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;
7832 struct bvec_iter_all iter_all;
7837 ASSERT(bio->bi_vcnt == 1);
7838 io_tree = &BTRFS_I(inode)->io_tree;
7839 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7840 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7843 ASSERT(!bio_flagged(bio, BIO_CLONED));
7844 bio_for_each_segment_all(bvec, bio, i, iter_all)
7845 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7846 io_tree, done->start, bvec->bv_page,
7847 btrfs_ino(BTRFS_I(inode)), 0);
7849 complete(&done->done);
7853 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7854 struct btrfs_io_bio *io_bio)
7856 struct btrfs_fs_info *fs_info;
7857 struct bio_vec bvec;
7858 struct bvec_iter iter;
7859 struct btrfs_retry_complete done;
7865 blk_status_t err = BLK_STS_OK;
7867 fs_info = BTRFS_I(inode)->root->fs_info;
7868 sectorsize = fs_info->sectorsize;
7870 start = io_bio->logical;
7872 io_bio->bio.bi_iter = io_bio->iter;
7874 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7875 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7876 pgoff = bvec.bv_offset;
7878 next_block_or_try_again:
7881 init_completion(&done.done);
7883 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7884 pgoff, start, start + sectorsize - 1,
7886 btrfs_retry_endio_nocsum, &done);
7892 wait_for_completion_io(&done.done);
7894 if (!done.uptodate) {
7895 /* We might have another mirror, so try again */
7896 goto next_block_or_try_again;
7900 start += sectorsize;
7904 pgoff += sectorsize;
7905 ASSERT(pgoff < PAGE_SIZE);
7906 goto next_block_or_try_again;
7913 static void btrfs_retry_endio(struct bio *bio)
7915 struct btrfs_retry_complete *done = bio->bi_private;
7916 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7917 struct extent_io_tree *io_tree, *failure_tree;
7918 struct inode *inode = done->inode;
7919 struct bio_vec *bvec;
7923 struct bvec_iter_all iter_all;
7930 ASSERT(bio->bi_vcnt == 1);
7931 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7933 io_tree = &BTRFS_I(inode)->io_tree;
7934 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7936 ASSERT(!bio_flagged(bio, BIO_CLONED));
7937 bio_for_each_segment_all(bvec, bio, i, iter_all) {
7938 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7939 bvec->bv_offset, done->start,
7942 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7943 failure_tree, io_tree, done->start,
7945 btrfs_ino(BTRFS_I(inode)),
7951 done->uptodate = uptodate;
7953 complete(&done->done);
7957 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
7958 struct btrfs_io_bio *io_bio, blk_status_t err)
7960 struct btrfs_fs_info *fs_info;
7961 struct bio_vec bvec;
7962 struct bvec_iter iter;
7963 struct btrfs_retry_complete done;
7970 bool uptodate = (err == 0);
7972 blk_status_t status;
7974 fs_info = BTRFS_I(inode)->root->fs_info;
7975 sectorsize = fs_info->sectorsize;
7978 start = io_bio->logical;
7980 io_bio->bio.bi_iter = io_bio->iter;
7982 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7983 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7985 pgoff = bvec.bv_offset;
7988 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
7989 ret = __readpage_endio_check(inode, io_bio, csum_pos,
7990 bvec.bv_page, pgoff, start, sectorsize);
7997 init_completion(&done.done);
7999 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8000 pgoff, start, start + sectorsize - 1,
8001 io_bio->mirror_num, btrfs_retry_endio,
8008 wait_for_completion_io(&done.done);
8010 if (!done.uptodate) {
8011 /* We might have another mirror, so try again */
8015 offset += sectorsize;
8016 start += sectorsize;
8022 pgoff += sectorsize;
8023 ASSERT(pgoff < PAGE_SIZE);
8031 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8032 struct btrfs_io_bio *io_bio, blk_status_t err)
8034 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8038 return __btrfs_correct_data_nocsum(inode, io_bio);
8042 return __btrfs_subio_endio_read(inode, io_bio, err);
8046 static void btrfs_endio_direct_read(struct bio *bio)
8048 struct btrfs_dio_private *dip = bio->bi_private;
8049 struct inode *inode = dip->inode;
8050 struct bio *dio_bio;
8051 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8052 blk_status_t err = bio->bi_status;
8054 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8055 err = btrfs_subio_endio_read(inode, io_bio, err);
8057 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8058 dip->logical_offset + dip->bytes - 1);
8059 dio_bio = dip->dio_bio;
8063 dio_bio->bi_status = err;
8064 dio_end_io(dio_bio);
8065 btrfs_io_bio_free_csum(io_bio);
8069 static void __endio_write_update_ordered(struct inode *inode,
8070 const u64 offset, const u64 bytes,
8071 const bool uptodate)
8073 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8074 struct btrfs_ordered_extent *ordered = NULL;
8075 struct btrfs_workqueue *wq;
8076 btrfs_work_func_t func;
8077 u64 ordered_offset = offset;
8078 u64 ordered_bytes = bytes;
8081 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8082 wq = fs_info->endio_freespace_worker;
8083 func = btrfs_freespace_write_helper;
8085 wq = fs_info->endio_write_workers;
8086 func = btrfs_endio_write_helper;
8089 while (ordered_offset < offset + bytes) {
8090 last_offset = ordered_offset;
8091 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8095 btrfs_init_work(&ordered->work, func,
8098 btrfs_queue_work(wq, &ordered->work);
8101 * If btrfs_dec_test_ordered_pending does not find any ordered
8102 * extent in the range, we can exit.
8104 if (ordered_offset == last_offset)
8107 * Our bio might span multiple ordered extents. In this case
8108 * we keep going until we have accounted the whole dio.
8110 if (ordered_offset < offset + bytes) {
8111 ordered_bytes = offset + bytes - ordered_offset;
8117 static void btrfs_endio_direct_write(struct bio *bio)
8119 struct btrfs_dio_private *dip = bio->bi_private;
8120 struct bio *dio_bio = dip->dio_bio;
8122 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8123 dip->bytes, !bio->bi_status);
8127 dio_bio->bi_status = bio->bi_status;
8128 dio_end_io(dio_bio);
8132 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8133 struct bio *bio, u64 offset)
8135 struct inode *inode = private_data;
8137 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8138 BUG_ON(ret); /* -ENOMEM */
8142 static void btrfs_end_dio_bio(struct bio *bio)
8144 struct btrfs_dio_private *dip = bio->bi_private;
8145 blk_status_t err = bio->bi_status;
8148 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8149 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8150 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8152 (unsigned long long)bio->bi_iter.bi_sector,
8153 bio->bi_iter.bi_size, err);
8155 if (dip->subio_endio)
8156 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8160 * We want to perceive the errors flag being set before
8161 * decrementing the reference count. We don't need a barrier
8162 * since atomic operations with a return value are fully
8163 * ordered as per atomic_t.txt
8168 /* if there are more bios still pending for this dio, just exit */
8169 if (!atomic_dec_and_test(&dip->pending_bios))
8173 bio_io_error(dip->orig_bio);
8175 dip->dio_bio->bi_status = BLK_STS_OK;
8176 bio_endio(dip->orig_bio);
8182 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8183 struct btrfs_dio_private *dip,
8187 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8188 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8192 * We load all the csum data we need when we submit
8193 * the first bio to reduce the csum tree search and
8196 if (dip->logical_offset == file_offset) {
8197 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8203 if (bio == dip->orig_bio)
8206 file_offset -= dip->logical_offset;
8207 file_offset >>= inode->i_sb->s_blocksize_bits;
8208 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8213 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8214 struct inode *inode, u64 file_offset, int async_submit)
8216 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8217 struct btrfs_dio_private *dip = bio->bi_private;
8218 bool write = bio_op(bio) == REQ_OP_WRITE;
8221 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8223 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8226 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8231 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8234 if (write && async_submit) {
8235 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8237 btrfs_submit_bio_start_direct_io);
8241 * If we aren't doing async submit, calculate the csum of the
8244 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8248 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8254 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8259 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8261 struct inode *inode = dip->inode;
8262 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8264 struct bio *orig_bio = dip->orig_bio;
8265 u64 start_sector = orig_bio->bi_iter.bi_sector;
8266 u64 file_offset = dip->logical_offset;
8268 int async_submit = 0;
8270 int clone_offset = 0;
8273 blk_status_t status;
8275 map_length = orig_bio->bi_iter.bi_size;
8276 submit_len = map_length;
8277 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8278 &map_length, NULL, 0);
8282 if (map_length >= submit_len) {
8284 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8288 /* async crcs make it difficult to collect full stripe writes. */
8289 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8295 ASSERT(map_length <= INT_MAX);
8296 atomic_inc(&dip->pending_bios);
8298 clone_len = min_t(int, submit_len, map_length);
8301 * This will never fail as it's passing GPF_NOFS and
8302 * the allocation is backed by btrfs_bioset.
8304 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8306 bio->bi_private = dip;
8307 bio->bi_end_io = btrfs_end_dio_bio;
8308 btrfs_io_bio(bio)->logical = file_offset;
8310 ASSERT(submit_len >= clone_len);
8311 submit_len -= clone_len;
8312 if (submit_len == 0)
8316 * Increase the count before we submit the bio so we know
8317 * the end IO handler won't happen before we increase the
8318 * count. Otherwise, the dip might get freed before we're
8319 * done setting it up.
8321 atomic_inc(&dip->pending_bios);
8323 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8327 atomic_dec(&dip->pending_bios);
8331 clone_offset += clone_len;
8332 start_sector += clone_len >> 9;
8333 file_offset += clone_len;
8335 map_length = submit_len;
8336 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8337 start_sector << 9, &map_length, NULL, 0);
8340 } while (submit_len > 0);
8343 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8351 * Before atomic variable goto zero, we must make sure dip->errors is
8352 * perceived to be set. This ordering is ensured by the fact that an
8353 * atomic operations with a return value are fully ordered as per
8356 if (atomic_dec_and_test(&dip->pending_bios))
8357 bio_io_error(dip->orig_bio);
8359 /* bio_end_io() will handle error, so we needn't return it */
8363 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8366 struct btrfs_dio_private *dip = NULL;
8367 struct bio *bio = NULL;
8368 struct btrfs_io_bio *io_bio;
8369 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8372 bio = btrfs_bio_clone(dio_bio);
8374 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8380 dip->private = dio_bio->bi_private;
8382 dip->logical_offset = file_offset;
8383 dip->bytes = dio_bio->bi_iter.bi_size;
8384 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8385 bio->bi_private = dip;
8386 dip->orig_bio = bio;
8387 dip->dio_bio = dio_bio;
8388 atomic_set(&dip->pending_bios, 0);
8389 io_bio = btrfs_io_bio(bio);
8390 io_bio->logical = file_offset;
8393 bio->bi_end_io = btrfs_endio_direct_write;
8395 bio->bi_end_io = btrfs_endio_direct_read;
8396 dip->subio_endio = btrfs_subio_endio_read;
8400 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8401 * even if we fail to submit a bio, because in such case we do the
8402 * corresponding error handling below and it must not be done a second
8403 * time by btrfs_direct_IO().
8406 struct btrfs_dio_data *dio_data = current->journal_info;
8408 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8410 dio_data->unsubmitted_oe_range_start =
8411 dio_data->unsubmitted_oe_range_end;
8414 ret = btrfs_submit_direct_hook(dip);
8418 btrfs_io_bio_free_csum(io_bio);
8422 * If we arrived here it means either we failed to submit the dip
8423 * or we either failed to clone the dio_bio or failed to allocate the
8424 * dip. If we cloned the dio_bio and allocated the dip, we can just
8425 * call bio_endio against our io_bio so that we get proper resource
8426 * cleanup if we fail to submit the dip, otherwise, we must do the
8427 * same as btrfs_endio_direct_[write|read] because we can't call these
8428 * callbacks - they require an allocated dip and a clone of dio_bio.
8433 * The end io callbacks free our dip, do the final put on bio
8434 * and all the cleanup and final put for dio_bio (through
8441 __endio_write_update_ordered(inode,
8443 dio_bio->bi_iter.bi_size,
8446 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8447 file_offset + dio_bio->bi_iter.bi_size - 1);
8449 dio_bio->bi_status = BLK_STS_IOERR;
8451 * Releases and cleans up our dio_bio, no need to bio_put()
8452 * nor bio_endio()/bio_io_error() against dio_bio.
8454 dio_end_io(dio_bio);
8461 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8462 const struct iov_iter *iter, loff_t offset)
8466 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8467 ssize_t retval = -EINVAL;
8469 if (offset & blocksize_mask)
8472 if (iov_iter_alignment(iter) & blocksize_mask)
8475 /* If this is a write we don't need to check anymore */
8476 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8479 * Check to make sure we don't have duplicate iov_base's in this
8480 * iovec, if so return EINVAL, otherwise we'll get csum errors
8481 * when reading back.
8483 for (seg = 0; seg < iter->nr_segs; seg++) {
8484 for (i = seg + 1; i < iter->nr_segs; i++) {
8485 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8494 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8496 struct file *file = iocb->ki_filp;
8497 struct inode *inode = file->f_mapping->host;
8498 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8499 struct btrfs_dio_data dio_data = { 0 };
8500 struct extent_changeset *data_reserved = NULL;
8501 loff_t offset = iocb->ki_pos;
8505 bool relock = false;
8508 if (check_direct_IO(fs_info, iter, offset))
8511 inode_dio_begin(inode);
8514 * The generic stuff only does filemap_write_and_wait_range, which
8515 * isn't enough if we've written compressed pages to this area, so
8516 * we need to flush the dirty pages again to make absolutely sure
8517 * that any outstanding dirty pages are on disk.
8519 count = iov_iter_count(iter);
8520 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8521 &BTRFS_I(inode)->runtime_flags))
8522 filemap_fdatawrite_range(inode->i_mapping, offset,
8523 offset + count - 1);
8525 if (iov_iter_rw(iter) == WRITE) {
8527 * If the write DIO is beyond the EOF, we need update
8528 * the isize, but it is protected by i_mutex. So we can
8529 * not unlock the i_mutex at this case.
8531 if (offset + count <= inode->i_size) {
8532 dio_data.overwrite = 1;
8533 inode_unlock(inode);
8535 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8539 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8545 * We need to know how many extents we reserved so that we can
8546 * do the accounting properly if we go over the number we
8547 * originally calculated. Abuse current->journal_info for this.
8549 dio_data.reserve = round_up(count,
8550 fs_info->sectorsize);
8551 dio_data.unsubmitted_oe_range_start = (u64)offset;
8552 dio_data.unsubmitted_oe_range_end = (u64)offset;
8553 current->journal_info = &dio_data;
8554 down_read(&BTRFS_I(inode)->dio_sem);
8555 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8556 &BTRFS_I(inode)->runtime_flags)) {
8557 inode_dio_end(inode);
8558 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8562 ret = __blockdev_direct_IO(iocb, inode,
8563 fs_info->fs_devices->latest_bdev,
8564 iter, btrfs_get_blocks_direct, NULL,
8565 btrfs_submit_direct, flags);
8566 if (iov_iter_rw(iter) == WRITE) {
8567 up_read(&BTRFS_I(inode)->dio_sem);
8568 current->journal_info = NULL;
8569 if (ret < 0 && ret != -EIOCBQUEUED) {
8570 if (dio_data.reserve)
8571 btrfs_delalloc_release_space(inode, data_reserved,
8572 offset, dio_data.reserve, true);
8574 * On error we might have left some ordered extents
8575 * without submitting corresponding bios for them, so
8576 * cleanup them up to avoid other tasks getting them
8577 * and waiting for them to complete forever.
8579 if (dio_data.unsubmitted_oe_range_start <
8580 dio_data.unsubmitted_oe_range_end)
8581 __endio_write_update_ordered(inode,
8582 dio_data.unsubmitted_oe_range_start,
8583 dio_data.unsubmitted_oe_range_end -
8584 dio_data.unsubmitted_oe_range_start,
8586 } else if (ret >= 0 && (size_t)ret < count)
8587 btrfs_delalloc_release_space(inode, data_reserved,
8588 offset, count - (size_t)ret, true);
8589 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8593 inode_dio_end(inode);
8597 extent_changeset_free(data_reserved);
8601 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8603 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8604 __u64 start, __u64 len)
8608 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8612 return extent_fiemap(inode, fieinfo, start, len);
8615 int btrfs_readpage(struct file *file, struct page *page)
8617 struct extent_io_tree *tree;
8618 tree = &BTRFS_I(page->mapping->host)->io_tree;
8619 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8622 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8624 struct inode *inode = page->mapping->host;
8627 if (current->flags & PF_MEMALLOC) {
8628 redirty_page_for_writepage(wbc, page);
8634 * If we are under memory pressure we will call this directly from the
8635 * VM, we need to make sure we have the inode referenced for the ordered
8636 * extent. If not just return like we didn't do anything.
8638 if (!igrab(inode)) {
8639 redirty_page_for_writepage(wbc, page);
8640 return AOP_WRITEPAGE_ACTIVATE;
8642 ret = extent_write_full_page(page, wbc);
8643 btrfs_add_delayed_iput(inode);
8647 static int btrfs_writepages(struct address_space *mapping,
8648 struct writeback_control *wbc)
8650 return extent_writepages(mapping, wbc);
8654 btrfs_readpages(struct file *file, struct address_space *mapping,
8655 struct list_head *pages, unsigned nr_pages)
8657 return extent_readpages(mapping, pages, nr_pages);
8660 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8662 int ret = try_release_extent_mapping(page, gfp_flags);
8664 ClearPagePrivate(page);
8665 set_page_private(page, 0);
8671 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8673 if (PageWriteback(page) || PageDirty(page))
8675 return __btrfs_releasepage(page, gfp_flags);
8678 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8679 unsigned int length)
8681 struct inode *inode = page->mapping->host;
8682 struct extent_io_tree *tree;
8683 struct btrfs_ordered_extent *ordered;
8684 struct extent_state *cached_state = NULL;
8685 u64 page_start = page_offset(page);
8686 u64 page_end = page_start + PAGE_SIZE - 1;
8689 int inode_evicting = inode->i_state & I_FREEING;
8692 * we have the page locked, so new writeback can't start,
8693 * and the dirty bit won't be cleared while we are here.
8695 * Wait for IO on this page so that we can safely clear
8696 * the PagePrivate2 bit and do ordered accounting
8698 wait_on_page_writeback(page);
8700 tree = &BTRFS_I(inode)->io_tree;
8702 btrfs_releasepage(page, GFP_NOFS);
8706 if (!inode_evicting)
8707 lock_extent_bits(tree, page_start, page_end, &cached_state);
8710 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8711 page_end - start + 1);
8713 end = min(page_end, ordered->file_offset + ordered->len - 1);
8715 * IO on this page will never be started, so we need
8716 * to account for any ordered extents now
8718 if (!inode_evicting)
8719 clear_extent_bit(tree, start, end,
8720 EXTENT_DIRTY | EXTENT_DELALLOC |
8721 EXTENT_DELALLOC_NEW |
8722 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8723 EXTENT_DEFRAG, 1, 0, &cached_state);
8725 * whoever cleared the private bit is responsible
8726 * for the finish_ordered_io
8728 if (TestClearPagePrivate2(page)) {
8729 struct btrfs_ordered_inode_tree *tree;
8732 tree = &BTRFS_I(inode)->ordered_tree;
8734 spin_lock_irq(&tree->lock);
8735 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8736 new_len = start - ordered->file_offset;
8737 if (new_len < ordered->truncated_len)
8738 ordered->truncated_len = new_len;
8739 spin_unlock_irq(&tree->lock);
8741 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8743 end - start + 1, 1))
8744 btrfs_finish_ordered_io(ordered);
8746 btrfs_put_ordered_extent(ordered);
8747 if (!inode_evicting) {
8748 cached_state = NULL;
8749 lock_extent_bits(tree, start, end,
8754 if (start < page_end)
8759 * Qgroup reserved space handler
8760 * Page here will be either
8761 * 1) Already written to disk
8762 * In this case, its reserved space is released from data rsv map
8763 * and will be freed by delayed_ref handler finally.
8764 * So even we call qgroup_free_data(), it won't decrease reserved
8766 * 2) Not written to disk
8767 * This means the reserved space should be freed here. However,
8768 * if a truncate invalidates the page (by clearing PageDirty)
8769 * and the page is accounted for while allocating extent
8770 * in btrfs_check_data_free_space() we let delayed_ref to
8771 * free the entire extent.
8773 if (PageDirty(page))
8774 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8775 if (!inode_evicting) {
8776 clear_extent_bit(tree, page_start, page_end,
8777 EXTENT_LOCKED | EXTENT_DIRTY |
8778 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8779 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8782 __btrfs_releasepage(page, GFP_NOFS);
8785 ClearPageChecked(page);
8786 if (PagePrivate(page)) {
8787 ClearPagePrivate(page);
8788 set_page_private(page, 0);
8794 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8795 * called from a page fault handler when a page is first dirtied. Hence we must
8796 * be careful to check for EOF conditions here. We set the page up correctly
8797 * for a written page which means we get ENOSPC checking when writing into
8798 * holes and correct delalloc and unwritten extent mapping on filesystems that
8799 * support these features.
8801 * We are not allowed to take the i_mutex here so we have to play games to
8802 * protect against truncate races as the page could now be beyond EOF. Because
8803 * truncate_setsize() writes the inode size before removing pages, once we have
8804 * the page lock we can determine safely if the page is beyond EOF. If it is not
8805 * beyond EOF, then the page is guaranteed safe against truncation until we
8808 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8810 struct page *page = vmf->page;
8811 struct inode *inode = file_inode(vmf->vma->vm_file);
8812 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8813 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8814 struct btrfs_ordered_extent *ordered;
8815 struct extent_state *cached_state = NULL;
8816 struct extent_changeset *data_reserved = NULL;
8818 unsigned long zero_start;
8828 reserved_space = PAGE_SIZE;
8830 sb_start_pagefault(inode->i_sb);
8831 page_start = page_offset(page);
8832 page_end = page_start + PAGE_SIZE - 1;
8836 * Reserving delalloc space after obtaining the page lock can lead to
8837 * deadlock. For example, if a dirty page is locked by this function
8838 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8839 * dirty page write out, then the btrfs_writepage() function could
8840 * end up waiting indefinitely to get a lock on the page currently
8841 * being processed by btrfs_page_mkwrite() function.
8843 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8846 ret2 = file_update_time(vmf->vma->vm_file);
8850 ret = vmf_error(ret2);
8856 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8859 size = i_size_read(inode);
8861 if ((page->mapping != inode->i_mapping) ||
8862 (page_start >= size)) {
8863 /* page got truncated out from underneath us */
8866 wait_on_page_writeback(page);
8868 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8869 set_page_extent_mapped(page);
8872 * we can't set the delalloc bits if there are pending ordered
8873 * extents. Drop our locks and wait for them to finish
8875 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8878 unlock_extent_cached(io_tree, page_start, page_end,
8881 btrfs_start_ordered_extent(inode, ordered, 1);
8882 btrfs_put_ordered_extent(ordered);
8886 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8887 reserved_space = round_up(size - page_start,
8888 fs_info->sectorsize);
8889 if (reserved_space < PAGE_SIZE) {
8890 end = page_start + reserved_space - 1;
8891 btrfs_delalloc_release_space(inode, data_reserved,
8892 page_start, PAGE_SIZE - reserved_space,
8898 * page_mkwrite gets called when the page is firstly dirtied after it's
8899 * faulted in, but write(2) could also dirty a page and set delalloc
8900 * bits, thus in this case for space account reason, we still need to
8901 * clear any delalloc bits within this page range since we have to
8902 * reserve data&meta space before lock_page() (see above comments).
8904 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8905 EXTENT_DIRTY | EXTENT_DELALLOC |
8906 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8907 0, 0, &cached_state);
8909 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8912 unlock_extent_cached(io_tree, page_start, page_end,
8914 ret = VM_FAULT_SIGBUS;
8919 /* page is wholly or partially inside EOF */
8920 if (page_start + PAGE_SIZE > size)
8921 zero_start = offset_in_page(size);
8923 zero_start = PAGE_SIZE;
8925 if (zero_start != PAGE_SIZE) {
8927 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8928 flush_dcache_page(page);
8931 ClearPageChecked(page);
8932 set_page_dirty(page);
8933 SetPageUptodate(page);
8935 BTRFS_I(inode)->last_trans = fs_info->generation;
8936 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8937 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8939 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8942 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8943 sb_end_pagefault(inode->i_sb);
8944 extent_changeset_free(data_reserved);
8945 return VM_FAULT_LOCKED;
8951 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
8952 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8953 reserved_space, (ret != 0));
8955 sb_end_pagefault(inode->i_sb);
8956 extent_changeset_free(data_reserved);
8960 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8962 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8963 struct btrfs_root *root = BTRFS_I(inode)->root;
8964 struct btrfs_block_rsv *rsv;
8966 struct btrfs_trans_handle *trans;
8967 u64 mask = fs_info->sectorsize - 1;
8968 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
8970 if (!skip_writeback) {
8971 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8978 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8979 * things going on here:
8981 * 1) We need to reserve space to update our inode.
8983 * 2) We need to have something to cache all the space that is going to
8984 * be free'd up by the truncate operation, but also have some slack
8985 * space reserved in case it uses space during the truncate (thank you
8986 * very much snapshotting).
8988 * And we need these to be separate. The fact is we can use a lot of
8989 * space doing the truncate, and we have no earthly idea how much space
8990 * we will use, so we need the truncate reservation to be separate so it
8991 * doesn't end up using space reserved for updating the inode. We also
8992 * need to be able to stop the transaction and start a new one, which
8993 * means we need to be able to update the inode several times, and we
8994 * have no idea of knowing how many times that will be, so we can't just
8995 * reserve 1 item for the entirety of the operation, so that has to be
8996 * done separately as well.
8998 * So that leaves us with
9000 * 1) rsv - for the truncate reservation, which we will steal from the
9001 * transaction reservation.
9002 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9003 * updating the inode.
9005 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9008 rsv->size = min_size;
9012 * 1 for the truncate slack space
9013 * 1 for updating the inode.
9015 trans = btrfs_start_transaction(root, 2);
9016 if (IS_ERR(trans)) {
9017 ret = PTR_ERR(trans);
9021 /* Migrate the slack space for the truncate to our reserve */
9022 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9027 * So if we truncate and then write and fsync we normally would just
9028 * write the extents that changed, which is a problem if we need to
9029 * first truncate that entire inode. So set this flag so we write out
9030 * all of the extents in the inode to the sync log so we're completely
9033 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9034 trans->block_rsv = rsv;
9037 ret = btrfs_truncate_inode_items(trans, root, inode,
9039 BTRFS_EXTENT_DATA_KEY);
9040 trans->block_rsv = &fs_info->trans_block_rsv;
9041 if (ret != -ENOSPC && ret != -EAGAIN)
9044 ret = btrfs_update_inode(trans, root, inode);
9048 btrfs_end_transaction(trans);
9049 btrfs_btree_balance_dirty(fs_info);
9051 trans = btrfs_start_transaction(root, 2);
9052 if (IS_ERR(trans)) {
9053 ret = PTR_ERR(trans);
9058 btrfs_block_rsv_release(fs_info, rsv, -1);
9059 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9060 rsv, min_size, false);
9061 BUG_ON(ret); /* shouldn't happen */
9062 trans->block_rsv = rsv;
9066 * We can't call btrfs_truncate_block inside a trans handle as we could
9067 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9068 * we've truncated everything except the last little bit, and can do
9069 * btrfs_truncate_block and then update the disk_i_size.
9071 if (ret == NEED_TRUNCATE_BLOCK) {
9072 btrfs_end_transaction(trans);
9073 btrfs_btree_balance_dirty(fs_info);
9075 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9078 trans = btrfs_start_transaction(root, 1);
9079 if (IS_ERR(trans)) {
9080 ret = PTR_ERR(trans);
9083 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9089 trans->block_rsv = &fs_info->trans_block_rsv;
9090 ret2 = btrfs_update_inode(trans, root, inode);
9094 ret2 = btrfs_end_transaction(trans);
9097 btrfs_btree_balance_dirty(fs_info);
9100 btrfs_free_block_rsv(fs_info, rsv);
9106 * create a new subvolume directory/inode (helper for the ioctl).
9108 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9109 struct btrfs_root *new_root,
9110 struct btrfs_root *parent_root,
9113 struct inode *inode;
9117 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9118 new_dirid, new_dirid,
9119 S_IFDIR | (~current_umask() & S_IRWXUGO),
9122 return PTR_ERR(inode);
9123 inode->i_op = &btrfs_dir_inode_operations;
9124 inode->i_fop = &btrfs_dir_file_operations;
9126 set_nlink(inode, 1);
9127 btrfs_i_size_write(BTRFS_I(inode), 0);
9128 unlock_new_inode(inode);
9130 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9132 btrfs_err(new_root->fs_info,
9133 "error inheriting subvolume %llu properties: %d",
9134 new_root->root_key.objectid, err);
9136 err = btrfs_update_inode(trans, new_root, inode);
9142 struct inode *btrfs_alloc_inode(struct super_block *sb)
9144 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9145 struct btrfs_inode *ei;
9146 struct inode *inode;
9148 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9155 ei->last_sub_trans = 0;
9156 ei->logged_trans = 0;
9157 ei->delalloc_bytes = 0;
9158 ei->new_delalloc_bytes = 0;
9159 ei->defrag_bytes = 0;
9160 ei->disk_i_size = 0;
9163 ei->index_cnt = (u64)-1;
9165 ei->last_unlink_trans = 0;
9166 ei->last_link_trans = 0;
9167 ei->last_log_commit = 0;
9169 spin_lock_init(&ei->lock);
9170 ei->outstanding_extents = 0;
9171 if (sb->s_magic != BTRFS_TEST_MAGIC)
9172 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9173 BTRFS_BLOCK_RSV_DELALLOC);
9174 ei->runtime_flags = 0;
9175 ei->prop_compress = BTRFS_COMPRESS_NONE;
9176 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9178 ei->delayed_node = NULL;
9180 ei->i_otime.tv_sec = 0;
9181 ei->i_otime.tv_nsec = 0;
9183 inode = &ei->vfs_inode;
9184 extent_map_tree_init(&ei->extent_tree);
9185 extent_io_tree_init(&ei->io_tree, inode);
9186 extent_io_tree_init(&ei->io_failure_tree, inode);
9187 ei->io_tree.track_uptodate = 1;
9188 ei->io_failure_tree.track_uptodate = 1;
9189 atomic_set(&ei->sync_writers, 0);
9190 mutex_init(&ei->log_mutex);
9191 mutex_init(&ei->delalloc_mutex);
9192 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9193 INIT_LIST_HEAD(&ei->delalloc_inodes);
9194 INIT_LIST_HEAD(&ei->delayed_iput);
9195 RB_CLEAR_NODE(&ei->rb_node);
9196 init_rwsem(&ei->dio_sem);
9201 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9202 void btrfs_test_destroy_inode(struct inode *inode)
9204 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9205 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9209 static void btrfs_i_callback(struct rcu_head *head)
9211 struct inode *inode = container_of(head, struct inode, i_rcu);
9212 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9215 void btrfs_destroy_inode(struct inode *inode)
9217 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9218 struct btrfs_ordered_extent *ordered;
9219 struct btrfs_root *root = BTRFS_I(inode)->root;
9221 WARN_ON(!hlist_empty(&inode->i_dentry));
9222 WARN_ON(inode->i_data.nrpages);
9223 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9224 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9225 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9226 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9227 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9228 WARN_ON(BTRFS_I(inode)->csum_bytes);
9229 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9232 * This can happen where we create an inode, but somebody else also
9233 * created the same inode and we need to destroy the one we already
9240 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9245 "found ordered extent %llu %llu on inode cleanup",
9246 ordered->file_offset, ordered->len);
9247 btrfs_remove_ordered_extent(inode, ordered);
9248 btrfs_put_ordered_extent(ordered);
9249 btrfs_put_ordered_extent(ordered);
9252 btrfs_qgroup_check_reserved_leak(inode);
9253 inode_tree_del(inode);
9254 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9256 call_rcu(&inode->i_rcu, btrfs_i_callback);
9259 int btrfs_drop_inode(struct inode *inode)
9261 struct btrfs_root *root = BTRFS_I(inode)->root;
9266 /* the snap/subvol tree is on deleting */
9267 if (btrfs_root_refs(&root->root_item) == 0)
9270 return generic_drop_inode(inode);
9273 static void init_once(void *foo)
9275 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9277 inode_init_once(&ei->vfs_inode);
9280 void __cold btrfs_destroy_cachep(void)
9283 * Make sure all delayed rcu free inodes are flushed before we
9287 kmem_cache_destroy(btrfs_inode_cachep);
9288 kmem_cache_destroy(btrfs_trans_handle_cachep);
9289 kmem_cache_destroy(btrfs_path_cachep);
9290 kmem_cache_destroy(btrfs_free_space_cachep);
9293 int __init btrfs_init_cachep(void)
9295 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9296 sizeof(struct btrfs_inode), 0,
9297 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9299 if (!btrfs_inode_cachep)
9302 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9303 sizeof(struct btrfs_trans_handle), 0,
9304 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9305 if (!btrfs_trans_handle_cachep)
9308 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9309 sizeof(struct btrfs_path), 0,
9310 SLAB_MEM_SPREAD, NULL);
9311 if (!btrfs_path_cachep)
9314 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9315 sizeof(struct btrfs_free_space), 0,
9316 SLAB_MEM_SPREAD, NULL);
9317 if (!btrfs_free_space_cachep)
9322 btrfs_destroy_cachep();
9326 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9327 u32 request_mask, unsigned int flags)
9330 struct inode *inode = d_inode(path->dentry);
9331 u32 blocksize = inode->i_sb->s_blocksize;
9332 u32 bi_flags = BTRFS_I(inode)->flags;
9334 stat->result_mask |= STATX_BTIME;
9335 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9336 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9337 if (bi_flags & BTRFS_INODE_APPEND)
9338 stat->attributes |= STATX_ATTR_APPEND;
9339 if (bi_flags & BTRFS_INODE_COMPRESS)
9340 stat->attributes |= STATX_ATTR_COMPRESSED;
9341 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9342 stat->attributes |= STATX_ATTR_IMMUTABLE;
9343 if (bi_flags & BTRFS_INODE_NODUMP)
9344 stat->attributes |= STATX_ATTR_NODUMP;
9346 stat->attributes_mask |= (STATX_ATTR_APPEND |
9347 STATX_ATTR_COMPRESSED |
9348 STATX_ATTR_IMMUTABLE |
9351 generic_fillattr(inode, stat);
9352 stat->dev = BTRFS_I(inode)->root->anon_dev;
9354 spin_lock(&BTRFS_I(inode)->lock);
9355 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9356 spin_unlock(&BTRFS_I(inode)->lock);
9357 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9358 ALIGN(delalloc_bytes, blocksize)) >> 9;
9362 static int btrfs_rename_exchange(struct inode *old_dir,
9363 struct dentry *old_dentry,
9364 struct inode *new_dir,
9365 struct dentry *new_dentry)
9367 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9368 struct btrfs_trans_handle *trans;
9369 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9370 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9371 struct inode *new_inode = new_dentry->d_inode;
9372 struct inode *old_inode = old_dentry->d_inode;
9373 struct timespec64 ctime = current_time(old_inode);
9374 struct dentry *parent;
9375 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9376 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9381 bool root_log_pinned = false;
9382 bool dest_log_pinned = false;
9383 struct btrfs_log_ctx ctx_root;
9384 struct btrfs_log_ctx ctx_dest;
9385 bool sync_log_root = false;
9386 bool sync_log_dest = false;
9387 bool commit_transaction = false;
9389 /* we only allow rename subvolume link between subvolumes */
9390 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9393 btrfs_init_log_ctx(&ctx_root, old_inode);
9394 btrfs_init_log_ctx(&ctx_dest, new_inode);
9396 /* close the race window with snapshot create/destroy ioctl */
9397 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9398 down_read(&fs_info->subvol_sem);
9399 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9400 down_read(&fs_info->subvol_sem);
9403 * We want to reserve the absolute worst case amount of items. So if
9404 * both inodes are subvols and we need to unlink them then that would
9405 * require 4 item modifications, but if they are both normal inodes it
9406 * would require 5 item modifications, so we'll assume their normal
9407 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9408 * should cover the worst case number of items we'll modify.
9410 trans = btrfs_start_transaction(root, 12);
9411 if (IS_ERR(trans)) {
9412 ret = PTR_ERR(trans);
9417 * We need to find a free sequence number both in the source and
9418 * in the destination directory for the exchange.
9420 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9423 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9427 BTRFS_I(old_inode)->dir_index = 0ULL;
9428 BTRFS_I(new_inode)->dir_index = 0ULL;
9430 /* Reference for the source. */
9431 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9432 /* force full log commit if subvolume involved. */
9433 btrfs_set_log_full_commit(fs_info, trans);
9435 btrfs_pin_log_trans(root);
9436 root_log_pinned = true;
9437 ret = btrfs_insert_inode_ref(trans, dest,
9438 new_dentry->d_name.name,
9439 new_dentry->d_name.len,
9441 btrfs_ino(BTRFS_I(new_dir)),
9447 /* And now for the dest. */
9448 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9449 /* force full log commit if subvolume involved. */
9450 btrfs_set_log_full_commit(fs_info, trans);
9452 btrfs_pin_log_trans(dest);
9453 dest_log_pinned = true;
9454 ret = btrfs_insert_inode_ref(trans, root,
9455 old_dentry->d_name.name,
9456 old_dentry->d_name.len,
9458 btrfs_ino(BTRFS_I(old_dir)),
9464 /* Update inode version and ctime/mtime. */
9465 inode_inc_iversion(old_dir);
9466 inode_inc_iversion(new_dir);
9467 inode_inc_iversion(old_inode);
9468 inode_inc_iversion(new_inode);
9469 old_dir->i_ctime = old_dir->i_mtime = ctime;
9470 new_dir->i_ctime = new_dir->i_mtime = ctime;
9471 old_inode->i_ctime = ctime;
9472 new_inode->i_ctime = ctime;
9474 if (old_dentry->d_parent != new_dentry->d_parent) {
9475 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9476 BTRFS_I(old_inode), 1);
9477 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9478 BTRFS_I(new_inode), 1);
9481 /* src is a subvolume */
9482 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9483 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9484 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9485 old_dentry->d_name.name,
9486 old_dentry->d_name.len);
9487 } else { /* src is an inode */
9488 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9489 BTRFS_I(old_dentry->d_inode),
9490 old_dentry->d_name.name,
9491 old_dentry->d_name.len);
9493 ret = btrfs_update_inode(trans, root, old_inode);
9496 btrfs_abort_transaction(trans, ret);
9500 /* dest is a subvolume */
9501 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9502 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9503 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9504 new_dentry->d_name.name,
9505 new_dentry->d_name.len);
9506 } else { /* dest is an inode */
9507 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9508 BTRFS_I(new_dentry->d_inode),
9509 new_dentry->d_name.name,
9510 new_dentry->d_name.len);
9512 ret = btrfs_update_inode(trans, dest, new_inode);
9515 btrfs_abort_transaction(trans, ret);
9519 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9520 new_dentry->d_name.name,
9521 new_dentry->d_name.len, 0, old_idx);
9523 btrfs_abort_transaction(trans, ret);
9527 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9528 old_dentry->d_name.name,
9529 old_dentry->d_name.len, 0, new_idx);
9531 btrfs_abort_transaction(trans, ret);
9535 if (old_inode->i_nlink == 1)
9536 BTRFS_I(old_inode)->dir_index = old_idx;
9537 if (new_inode->i_nlink == 1)
9538 BTRFS_I(new_inode)->dir_index = new_idx;
9540 if (root_log_pinned) {
9541 parent = new_dentry->d_parent;
9542 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9543 BTRFS_I(old_dir), parent,
9545 if (ret == BTRFS_NEED_LOG_SYNC)
9546 sync_log_root = true;
9547 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9548 commit_transaction = true;
9550 btrfs_end_log_trans(root);
9551 root_log_pinned = false;
9553 if (dest_log_pinned) {
9554 if (!commit_transaction) {
9555 parent = old_dentry->d_parent;
9556 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9557 BTRFS_I(new_dir), parent,
9559 if (ret == BTRFS_NEED_LOG_SYNC)
9560 sync_log_dest = true;
9561 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9562 commit_transaction = true;
9565 btrfs_end_log_trans(dest);
9566 dest_log_pinned = false;
9570 * If we have pinned a log and an error happened, we unpin tasks
9571 * trying to sync the log and force them to fallback to a transaction
9572 * commit if the log currently contains any of the inodes involved in
9573 * this rename operation (to ensure we do not persist a log with an
9574 * inconsistent state for any of these inodes or leading to any
9575 * inconsistencies when replayed). If the transaction was aborted, the
9576 * abortion reason is propagated to userspace when attempting to commit
9577 * the transaction. If the log does not contain any of these inodes, we
9578 * allow the tasks to sync it.
9580 if (ret && (root_log_pinned || dest_log_pinned)) {
9581 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9582 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9583 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9585 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9586 btrfs_set_log_full_commit(fs_info, trans);
9588 if (root_log_pinned) {
9589 btrfs_end_log_trans(root);
9590 root_log_pinned = false;
9592 if (dest_log_pinned) {
9593 btrfs_end_log_trans(dest);
9594 dest_log_pinned = false;
9597 if (!ret && sync_log_root && !commit_transaction) {
9598 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9601 commit_transaction = true;
9603 if (!ret && sync_log_dest && !commit_transaction) {
9604 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9607 commit_transaction = true;
9609 if (commit_transaction) {
9610 ret = btrfs_commit_transaction(trans);
9614 ret2 = btrfs_end_transaction(trans);
9615 ret = ret ? ret : ret2;
9618 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9619 up_read(&fs_info->subvol_sem);
9620 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9621 up_read(&fs_info->subvol_sem);
9626 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9627 struct btrfs_root *root,
9629 struct dentry *dentry)
9632 struct inode *inode;
9636 ret = btrfs_find_free_ino(root, &objectid);
9640 inode = btrfs_new_inode(trans, root, dir,
9641 dentry->d_name.name,
9643 btrfs_ino(BTRFS_I(dir)),
9645 S_IFCHR | WHITEOUT_MODE,
9648 if (IS_ERR(inode)) {
9649 ret = PTR_ERR(inode);
9653 inode->i_op = &btrfs_special_inode_operations;
9654 init_special_inode(inode, inode->i_mode,
9657 ret = btrfs_init_inode_security(trans, inode, dir,
9662 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9663 BTRFS_I(inode), 0, index);
9667 ret = btrfs_update_inode(trans, root, inode);
9669 unlock_new_inode(inode);
9671 inode_dec_link_count(inode);
9677 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9678 struct inode *new_dir, struct dentry *new_dentry,
9681 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9682 struct btrfs_trans_handle *trans;
9683 unsigned int trans_num_items;
9684 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9685 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9686 struct inode *new_inode = d_inode(new_dentry);
9687 struct inode *old_inode = d_inode(old_dentry);
9691 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9692 bool log_pinned = false;
9693 struct btrfs_log_ctx ctx;
9694 bool sync_log = false;
9695 bool commit_transaction = false;
9697 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9700 /* we only allow rename subvolume link between subvolumes */
9701 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9704 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9705 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9708 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9709 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9713 /* check for collisions, even if the name isn't there */
9714 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9715 new_dentry->d_name.name,
9716 new_dentry->d_name.len);
9719 if (ret == -EEXIST) {
9721 * eexist without a new_inode */
9722 if (WARN_ON(!new_inode)) {
9726 /* maybe -EOVERFLOW */
9733 * we're using rename to replace one file with another. Start IO on it
9734 * now so we don't add too much work to the end of the transaction
9736 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9737 filemap_flush(old_inode->i_mapping);
9739 /* close the racy window with snapshot create/destroy ioctl */
9740 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9741 down_read(&fs_info->subvol_sem);
9743 * We want to reserve the absolute worst case amount of items. So if
9744 * both inodes are subvols and we need to unlink them then that would
9745 * require 4 item modifications, but if they are both normal inodes it
9746 * would require 5 item modifications, so we'll assume they are normal
9747 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9748 * should cover the worst case number of items we'll modify.
9749 * If our rename has the whiteout flag, we need more 5 units for the
9750 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9751 * when selinux is enabled).
9753 trans_num_items = 11;
9754 if (flags & RENAME_WHITEOUT)
9755 trans_num_items += 5;
9756 trans = btrfs_start_transaction(root, trans_num_items);
9757 if (IS_ERR(trans)) {
9758 ret = PTR_ERR(trans);
9763 btrfs_record_root_in_trans(trans, dest);
9765 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9769 BTRFS_I(old_inode)->dir_index = 0ULL;
9770 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9771 /* force full log commit if subvolume involved. */
9772 btrfs_set_log_full_commit(fs_info, trans);
9774 btrfs_pin_log_trans(root);
9776 ret = btrfs_insert_inode_ref(trans, dest,
9777 new_dentry->d_name.name,
9778 new_dentry->d_name.len,
9780 btrfs_ino(BTRFS_I(new_dir)), index);
9785 inode_inc_iversion(old_dir);
9786 inode_inc_iversion(new_dir);
9787 inode_inc_iversion(old_inode);
9788 old_dir->i_ctime = old_dir->i_mtime =
9789 new_dir->i_ctime = new_dir->i_mtime =
9790 old_inode->i_ctime = current_time(old_dir);
9792 if (old_dentry->d_parent != new_dentry->d_parent)
9793 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9794 BTRFS_I(old_inode), 1);
9796 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9797 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9798 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9799 old_dentry->d_name.name,
9800 old_dentry->d_name.len);
9802 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9803 BTRFS_I(d_inode(old_dentry)),
9804 old_dentry->d_name.name,
9805 old_dentry->d_name.len);
9807 ret = btrfs_update_inode(trans, root, old_inode);
9810 btrfs_abort_transaction(trans, ret);
9815 inode_inc_iversion(new_inode);
9816 new_inode->i_ctime = current_time(new_inode);
9817 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9818 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9819 root_objectid = BTRFS_I(new_inode)->location.objectid;
9820 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9821 new_dentry->d_name.name,
9822 new_dentry->d_name.len);
9823 BUG_ON(new_inode->i_nlink == 0);
9825 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9826 BTRFS_I(d_inode(new_dentry)),
9827 new_dentry->d_name.name,
9828 new_dentry->d_name.len);
9830 if (!ret && new_inode->i_nlink == 0)
9831 ret = btrfs_orphan_add(trans,
9832 BTRFS_I(d_inode(new_dentry)));
9834 btrfs_abort_transaction(trans, ret);
9839 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9840 new_dentry->d_name.name,
9841 new_dentry->d_name.len, 0, index);
9843 btrfs_abort_transaction(trans, ret);
9847 if (old_inode->i_nlink == 1)
9848 BTRFS_I(old_inode)->dir_index = index;
9851 struct dentry *parent = new_dentry->d_parent;
9853 btrfs_init_log_ctx(&ctx, old_inode);
9854 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9855 BTRFS_I(old_dir), parent,
9857 if (ret == BTRFS_NEED_LOG_SYNC)
9859 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9860 commit_transaction = true;
9862 btrfs_end_log_trans(root);
9866 if (flags & RENAME_WHITEOUT) {
9867 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9871 btrfs_abort_transaction(trans, ret);
9877 * If we have pinned the log and an error happened, we unpin tasks
9878 * trying to sync the log and force them to fallback to a transaction
9879 * commit if the log currently contains any of the inodes involved in
9880 * this rename operation (to ensure we do not persist a log with an
9881 * inconsistent state for any of these inodes or leading to any
9882 * inconsistencies when replayed). If the transaction was aborted, the
9883 * abortion reason is propagated to userspace when attempting to commit
9884 * the transaction. If the log does not contain any of these inodes, we
9885 * allow the tasks to sync it.
9887 if (ret && log_pinned) {
9888 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9889 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9890 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9892 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9893 btrfs_set_log_full_commit(fs_info, trans);
9895 btrfs_end_log_trans(root);
9898 if (!ret && sync_log) {
9899 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9901 commit_transaction = true;
9903 if (commit_transaction) {
9904 ret = btrfs_commit_transaction(trans);
9908 ret2 = btrfs_end_transaction(trans);
9909 ret = ret ? ret : ret2;
9912 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9913 up_read(&fs_info->subvol_sem);
9918 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9919 struct inode *new_dir, struct dentry *new_dentry,
9922 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9925 if (flags & RENAME_EXCHANGE)
9926 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9929 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9932 struct btrfs_delalloc_work {
9933 struct inode *inode;
9934 struct completion completion;
9935 struct list_head list;
9936 struct btrfs_work work;
9939 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9941 struct btrfs_delalloc_work *delalloc_work;
9942 struct inode *inode;
9944 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9946 inode = delalloc_work->inode;
9947 filemap_flush(inode->i_mapping);
9948 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9949 &BTRFS_I(inode)->runtime_flags))
9950 filemap_flush(inode->i_mapping);
9953 complete(&delalloc_work->completion);
9956 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9958 struct btrfs_delalloc_work *work;
9960 work = kmalloc(sizeof(*work), GFP_NOFS);
9964 init_completion(&work->completion);
9965 INIT_LIST_HEAD(&work->list);
9966 work->inode = inode;
9967 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9968 btrfs_run_delalloc_work, NULL, NULL);
9974 * some fairly slow code that needs optimization. This walks the list
9975 * of all the inodes with pending delalloc and forces them to disk.
9977 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9979 struct btrfs_inode *binode;
9980 struct inode *inode;
9981 struct btrfs_delalloc_work *work, *next;
9982 struct list_head works;
9983 struct list_head splice;
9986 INIT_LIST_HEAD(&works);
9987 INIT_LIST_HEAD(&splice);
9989 mutex_lock(&root->delalloc_mutex);
9990 spin_lock(&root->delalloc_lock);
9991 list_splice_init(&root->delalloc_inodes, &splice);
9992 while (!list_empty(&splice)) {
9993 binode = list_entry(splice.next, struct btrfs_inode,
9996 list_move_tail(&binode->delalloc_inodes,
9997 &root->delalloc_inodes);
9998 inode = igrab(&binode->vfs_inode);
10000 cond_resched_lock(&root->delalloc_lock);
10003 spin_unlock(&root->delalloc_lock);
10006 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10007 &binode->runtime_flags);
10008 work = btrfs_alloc_delalloc_work(inode);
10014 list_add_tail(&work->list, &works);
10015 btrfs_queue_work(root->fs_info->flush_workers,
10018 if (nr != -1 && ret >= nr)
10021 spin_lock(&root->delalloc_lock);
10023 spin_unlock(&root->delalloc_lock);
10026 list_for_each_entry_safe(work, next, &works, list) {
10027 list_del_init(&work->list);
10028 wait_for_completion(&work->completion);
10032 if (!list_empty(&splice)) {
10033 spin_lock(&root->delalloc_lock);
10034 list_splice_tail(&splice, &root->delalloc_inodes);
10035 spin_unlock(&root->delalloc_lock);
10037 mutex_unlock(&root->delalloc_mutex);
10041 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10043 struct btrfs_fs_info *fs_info = root->fs_info;
10046 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10049 ret = start_delalloc_inodes(root, -1, true);
10055 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10057 struct btrfs_root *root;
10058 struct list_head splice;
10061 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10064 INIT_LIST_HEAD(&splice);
10066 mutex_lock(&fs_info->delalloc_root_mutex);
10067 spin_lock(&fs_info->delalloc_root_lock);
10068 list_splice_init(&fs_info->delalloc_roots, &splice);
10069 while (!list_empty(&splice) && nr) {
10070 root = list_first_entry(&splice, struct btrfs_root,
10072 root = btrfs_grab_fs_root(root);
10074 list_move_tail(&root->delalloc_root,
10075 &fs_info->delalloc_roots);
10076 spin_unlock(&fs_info->delalloc_root_lock);
10078 ret = start_delalloc_inodes(root, nr, false);
10079 btrfs_put_fs_root(root);
10087 spin_lock(&fs_info->delalloc_root_lock);
10089 spin_unlock(&fs_info->delalloc_root_lock);
10093 if (!list_empty(&splice)) {
10094 spin_lock(&fs_info->delalloc_root_lock);
10095 list_splice_tail(&splice, &fs_info->delalloc_roots);
10096 spin_unlock(&fs_info->delalloc_root_lock);
10098 mutex_unlock(&fs_info->delalloc_root_mutex);
10102 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10103 const char *symname)
10105 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10106 struct btrfs_trans_handle *trans;
10107 struct btrfs_root *root = BTRFS_I(dir)->root;
10108 struct btrfs_path *path;
10109 struct btrfs_key key;
10110 struct inode *inode = NULL;
10117 struct btrfs_file_extent_item *ei;
10118 struct extent_buffer *leaf;
10120 name_len = strlen(symname);
10121 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10122 return -ENAMETOOLONG;
10125 * 2 items for inode item and ref
10126 * 2 items for dir items
10127 * 1 item for updating parent inode item
10128 * 1 item for the inline extent item
10129 * 1 item for xattr if selinux is on
10131 trans = btrfs_start_transaction(root, 7);
10133 return PTR_ERR(trans);
10135 err = btrfs_find_free_ino(root, &objectid);
10139 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10140 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10141 objectid, S_IFLNK|S_IRWXUGO, &index);
10142 if (IS_ERR(inode)) {
10143 err = PTR_ERR(inode);
10149 * If the active LSM wants to access the inode during
10150 * d_instantiate it needs these. Smack checks to see
10151 * if the filesystem supports xattrs by looking at the
10154 inode->i_fop = &btrfs_file_operations;
10155 inode->i_op = &btrfs_file_inode_operations;
10156 inode->i_mapping->a_ops = &btrfs_aops;
10157 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10159 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10163 path = btrfs_alloc_path();
10168 key.objectid = btrfs_ino(BTRFS_I(inode));
10170 key.type = BTRFS_EXTENT_DATA_KEY;
10171 datasize = btrfs_file_extent_calc_inline_size(name_len);
10172 err = btrfs_insert_empty_item(trans, root, path, &key,
10175 btrfs_free_path(path);
10178 leaf = path->nodes[0];
10179 ei = btrfs_item_ptr(leaf, path->slots[0],
10180 struct btrfs_file_extent_item);
10181 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10182 btrfs_set_file_extent_type(leaf, ei,
10183 BTRFS_FILE_EXTENT_INLINE);
10184 btrfs_set_file_extent_encryption(leaf, ei, 0);
10185 btrfs_set_file_extent_compression(leaf, ei, 0);
10186 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10187 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10189 ptr = btrfs_file_extent_inline_start(ei);
10190 write_extent_buffer(leaf, symname, ptr, name_len);
10191 btrfs_mark_buffer_dirty(leaf);
10192 btrfs_free_path(path);
10194 inode->i_op = &btrfs_symlink_inode_operations;
10195 inode_nohighmem(inode);
10196 inode->i_mapping->a_ops = &btrfs_aops;
10197 inode_set_bytes(inode, name_len);
10198 btrfs_i_size_write(BTRFS_I(inode), name_len);
10199 err = btrfs_update_inode(trans, root, inode);
10201 * Last step, add directory indexes for our symlink inode. This is the
10202 * last step to avoid extra cleanup of these indexes if an error happens
10206 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10207 BTRFS_I(inode), 0, index);
10211 d_instantiate_new(dentry, inode);
10214 btrfs_end_transaction(trans);
10215 if (err && inode) {
10216 inode_dec_link_count(inode);
10217 discard_new_inode(inode);
10219 btrfs_btree_balance_dirty(fs_info);
10223 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10224 u64 start, u64 num_bytes, u64 min_size,
10225 loff_t actual_len, u64 *alloc_hint,
10226 struct btrfs_trans_handle *trans)
10228 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10229 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10230 struct extent_map *em;
10231 struct btrfs_root *root = BTRFS_I(inode)->root;
10232 struct btrfs_key ins;
10233 u64 cur_offset = start;
10236 u64 last_alloc = (u64)-1;
10238 bool own_trans = true;
10239 u64 end = start + num_bytes - 1;
10243 while (num_bytes > 0) {
10245 trans = btrfs_start_transaction(root, 3);
10246 if (IS_ERR(trans)) {
10247 ret = PTR_ERR(trans);
10252 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10253 cur_bytes = max(cur_bytes, min_size);
10255 * If we are severely fragmented we could end up with really
10256 * small allocations, so if the allocator is returning small
10257 * chunks lets make its job easier by only searching for those
10260 cur_bytes = min(cur_bytes, last_alloc);
10261 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10262 min_size, 0, *alloc_hint, &ins, 1, 0);
10265 btrfs_end_transaction(trans);
10268 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10270 last_alloc = ins.offset;
10271 ret = insert_reserved_file_extent(trans, inode,
10272 cur_offset, ins.objectid,
10273 ins.offset, ins.offset,
10274 ins.offset, 0, 0, 0,
10275 BTRFS_FILE_EXTENT_PREALLOC);
10277 btrfs_free_reserved_extent(fs_info, ins.objectid,
10279 btrfs_abort_transaction(trans, ret);
10281 btrfs_end_transaction(trans);
10285 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10286 cur_offset + ins.offset -1, 0);
10288 em = alloc_extent_map();
10290 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10291 &BTRFS_I(inode)->runtime_flags);
10295 em->start = cur_offset;
10296 em->orig_start = cur_offset;
10297 em->len = ins.offset;
10298 em->block_start = ins.objectid;
10299 em->block_len = ins.offset;
10300 em->orig_block_len = ins.offset;
10301 em->ram_bytes = ins.offset;
10302 em->bdev = fs_info->fs_devices->latest_bdev;
10303 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10304 em->generation = trans->transid;
10307 write_lock(&em_tree->lock);
10308 ret = add_extent_mapping(em_tree, em, 1);
10309 write_unlock(&em_tree->lock);
10310 if (ret != -EEXIST)
10312 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10313 cur_offset + ins.offset - 1,
10316 free_extent_map(em);
10318 num_bytes -= ins.offset;
10319 cur_offset += ins.offset;
10320 *alloc_hint = ins.objectid + ins.offset;
10322 inode_inc_iversion(inode);
10323 inode->i_ctime = current_time(inode);
10324 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10325 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10326 (actual_len > inode->i_size) &&
10327 (cur_offset > inode->i_size)) {
10328 if (cur_offset > actual_len)
10329 i_size = actual_len;
10331 i_size = cur_offset;
10332 i_size_write(inode, i_size);
10333 btrfs_ordered_update_i_size(inode, i_size, NULL);
10336 ret = btrfs_update_inode(trans, root, inode);
10339 btrfs_abort_transaction(trans, ret);
10341 btrfs_end_transaction(trans);
10346 btrfs_end_transaction(trans);
10348 if (cur_offset < end)
10349 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10350 end - cur_offset + 1);
10354 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10355 u64 start, u64 num_bytes, u64 min_size,
10356 loff_t actual_len, u64 *alloc_hint)
10358 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10359 min_size, actual_len, alloc_hint,
10363 int btrfs_prealloc_file_range_trans(struct inode *inode,
10364 struct btrfs_trans_handle *trans, int mode,
10365 u64 start, u64 num_bytes, u64 min_size,
10366 loff_t actual_len, u64 *alloc_hint)
10368 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10369 min_size, actual_len, alloc_hint, trans);
10372 static int btrfs_set_page_dirty(struct page *page)
10374 return __set_page_dirty_nobuffers(page);
10377 static int btrfs_permission(struct inode *inode, int mask)
10379 struct btrfs_root *root = BTRFS_I(inode)->root;
10380 umode_t mode = inode->i_mode;
10382 if (mask & MAY_WRITE &&
10383 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10384 if (btrfs_root_readonly(root))
10386 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10389 return generic_permission(inode, mask);
10392 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10394 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10395 struct btrfs_trans_handle *trans;
10396 struct btrfs_root *root = BTRFS_I(dir)->root;
10397 struct inode *inode = NULL;
10403 * 5 units required for adding orphan entry
10405 trans = btrfs_start_transaction(root, 5);
10407 return PTR_ERR(trans);
10409 ret = btrfs_find_free_ino(root, &objectid);
10413 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10414 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10415 if (IS_ERR(inode)) {
10416 ret = PTR_ERR(inode);
10421 inode->i_fop = &btrfs_file_operations;
10422 inode->i_op = &btrfs_file_inode_operations;
10424 inode->i_mapping->a_ops = &btrfs_aops;
10425 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10427 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10431 ret = btrfs_update_inode(trans, root, inode);
10434 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10439 * We set number of links to 0 in btrfs_new_inode(), and here we set
10440 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10443 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10445 set_nlink(inode, 1);
10446 d_tmpfile(dentry, inode);
10447 unlock_new_inode(inode);
10448 mark_inode_dirty(inode);
10450 btrfs_end_transaction(trans);
10452 discard_new_inode(inode);
10453 btrfs_btree_balance_dirty(fs_info);
10457 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10459 struct inode *inode = tree->private_data;
10460 unsigned long index = start >> PAGE_SHIFT;
10461 unsigned long end_index = end >> PAGE_SHIFT;
10464 while (index <= end_index) {
10465 page = find_get_page(inode->i_mapping, index);
10466 ASSERT(page); /* Pages should be in the extent_io_tree */
10467 set_page_writeback(page);
10475 * Add an entry indicating a block group or device which is pinned by a
10476 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10477 * negative errno on failure.
10479 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10480 bool is_block_group)
10482 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10483 struct btrfs_swapfile_pin *sp, *entry;
10484 struct rb_node **p;
10485 struct rb_node *parent = NULL;
10487 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10492 sp->is_block_group = is_block_group;
10494 spin_lock(&fs_info->swapfile_pins_lock);
10495 p = &fs_info->swapfile_pins.rb_node;
10498 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10499 if (sp->ptr < entry->ptr ||
10500 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10501 p = &(*p)->rb_left;
10502 } else if (sp->ptr > entry->ptr ||
10503 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10504 p = &(*p)->rb_right;
10506 spin_unlock(&fs_info->swapfile_pins_lock);
10511 rb_link_node(&sp->node, parent, p);
10512 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10513 spin_unlock(&fs_info->swapfile_pins_lock);
10517 /* Free all of the entries pinned by this swapfile. */
10518 static void btrfs_free_swapfile_pins(struct inode *inode)
10520 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10521 struct btrfs_swapfile_pin *sp;
10522 struct rb_node *node, *next;
10524 spin_lock(&fs_info->swapfile_pins_lock);
10525 node = rb_first(&fs_info->swapfile_pins);
10527 next = rb_next(node);
10528 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10529 if (sp->inode == inode) {
10530 rb_erase(&sp->node, &fs_info->swapfile_pins);
10531 if (sp->is_block_group)
10532 btrfs_put_block_group(sp->ptr);
10537 spin_unlock(&fs_info->swapfile_pins_lock);
10540 struct btrfs_swap_info {
10546 unsigned long nr_pages;
10550 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10551 struct btrfs_swap_info *bsi)
10553 unsigned long nr_pages;
10554 u64 first_ppage, first_ppage_reported, next_ppage;
10557 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10558 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10559 PAGE_SIZE) >> PAGE_SHIFT;
10561 if (first_ppage >= next_ppage)
10563 nr_pages = next_ppage - first_ppage;
10565 first_ppage_reported = first_ppage;
10566 if (bsi->start == 0)
10567 first_ppage_reported++;
10568 if (bsi->lowest_ppage > first_ppage_reported)
10569 bsi->lowest_ppage = first_ppage_reported;
10570 if (bsi->highest_ppage < (next_ppage - 1))
10571 bsi->highest_ppage = next_ppage - 1;
10573 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10576 bsi->nr_extents += ret;
10577 bsi->nr_pages += nr_pages;
10581 static void btrfs_swap_deactivate(struct file *file)
10583 struct inode *inode = file_inode(file);
10585 btrfs_free_swapfile_pins(inode);
10586 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10589 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10592 struct inode *inode = file_inode(file);
10593 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10594 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10595 struct extent_state *cached_state = NULL;
10596 struct extent_map *em = NULL;
10597 struct btrfs_device *device = NULL;
10598 struct btrfs_swap_info bsi = {
10599 .lowest_ppage = (sector_t)-1ULL,
10606 * If the swap file was just created, make sure delalloc is done. If the
10607 * file changes again after this, the user is doing something stupid and
10608 * we don't really care.
10610 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10615 * The inode is locked, so these flags won't change after we check them.
10617 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10618 btrfs_warn(fs_info, "swapfile must not be compressed");
10621 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10622 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10625 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10626 btrfs_warn(fs_info, "swapfile must not be checksummed");
10631 * Balance or device remove/replace/resize can move stuff around from
10632 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10633 * concurrently while we are mapping the swap extents, and
10634 * fs_info->swapfile_pins prevents them from running while the swap file
10635 * is active and moving the extents. Note that this also prevents a
10636 * concurrent device add which isn't actually necessary, but it's not
10637 * really worth the trouble to allow it.
10639 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10640 btrfs_warn(fs_info,
10641 "cannot activate swapfile while exclusive operation is running");
10645 * Snapshots can create extents which require COW even if NODATACOW is
10646 * set. We use this counter to prevent snapshots. We must increment it
10647 * before walking the extents because we don't want a concurrent
10648 * snapshot to run after we've already checked the extents.
10650 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10652 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10654 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10656 while (start < isize) {
10657 u64 logical_block_start, physical_block_start;
10658 struct btrfs_block_group_cache *bg;
10659 u64 len = isize - start;
10661 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10667 if (em->block_start == EXTENT_MAP_HOLE) {
10668 btrfs_warn(fs_info, "swapfile must not have holes");
10672 if (em->block_start == EXTENT_MAP_INLINE) {
10674 * It's unlikely we'll ever actually find ourselves
10675 * here, as a file small enough to fit inline won't be
10676 * big enough to store more than the swap header, but in
10677 * case something changes in the future, let's catch it
10678 * here rather than later.
10680 btrfs_warn(fs_info, "swapfile must not be inline");
10684 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10685 btrfs_warn(fs_info, "swapfile must not be compressed");
10690 logical_block_start = em->block_start + (start - em->start);
10691 len = min(len, em->len - (start - em->start));
10692 free_extent_map(em);
10695 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10701 btrfs_warn(fs_info,
10702 "swapfile must not be copy-on-write");
10707 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10713 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10714 btrfs_warn(fs_info,
10715 "swapfile must have single data profile");
10720 if (device == NULL) {
10721 device = em->map_lookup->stripes[0].dev;
10722 ret = btrfs_add_swapfile_pin(inode, device, false);
10727 } else if (device != em->map_lookup->stripes[0].dev) {
10728 btrfs_warn(fs_info, "swapfile must be on one device");
10733 physical_block_start = (em->map_lookup->stripes[0].physical +
10734 (logical_block_start - em->start));
10735 len = min(len, em->len - (logical_block_start - em->start));
10736 free_extent_map(em);
10739 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10741 btrfs_warn(fs_info,
10742 "could not find block group containing swapfile");
10747 ret = btrfs_add_swapfile_pin(inode, bg, true);
10749 btrfs_put_block_group(bg);
10756 if (bsi.block_len &&
10757 bsi.block_start + bsi.block_len == physical_block_start) {
10758 bsi.block_len += len;
10760 if (bsi.block_len) {
10761 ret = btrfs_add_swap_extent(sis, &bsi);
10766 bsi.block_start = physical_block_start;
10767 bsi.block_len = len;
10774 ret = btrfs_add_swap_extent(sis, &bsi);
10777 if (!IS_ERR_OR_NULL(em))
10778 free_extent_map(em);
10780 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10783 btrfs_swap_deactivate(file);
10785 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10791 sis->bdev = device->bdev;
10792 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10793 sis->max = bsi.nr_pages;
10794 sis->pages = bsi.nr_pages - 1;
10795 sis->highest_bit = bsi.nr_pages - 1;
10796 return bsi.nr_extents;
10799 static void btrfs_swap_deactivate(struct file *file)
10803 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10806 return -EOPNOTSUPP;
10810 static const struct inode_operations btrfs_dir_inode_operations = {
10811 .getattr = btrfs_getattr,
10812 .lookup = btrfs_lookup,
10813 .create = btrfs_create,
10814 .unlink = btrfs_unlink,
10815 .link = btrfs_link,
10816 .mkdir = btrfs_mkdir,
10817 .rmdir = btrfs_rmdir,
10818 .rename = btrfs_rename2,
10819 .symlink = btrfs_symlink,
10820 .setattr = btrfs_setattr,
10821 .mknod = btrfs_mknod,
10822 .listxattr = btrfs_listxattr,
10823 .permission = btrfs_permission,
10824 .get_acl = btrfs_get_acl,
10825 .set_acl = btrfs_set_acl,
10826 .update_time = btrfs_update_time,
10827 .tmpfile = btrfs_tmpfile,
10829 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10830 .lookup = btrfs_lookup,
10831 .permission = btrfs_permission,
10832 .update_time = btrfs_update_time,
10835 static const struct file_operations btrfs_dir_file_operations = {
10836 .llseek = generic_file_llseek,
10837 .read = generic_read_dir,
10838 .iterate_shared = btrfs_real_readdir,
10839 .open = btrfs_opendir,
10840 .unlocked_ioctl = btrfs_ioctl,
10841 #ifdef CONFIG_COMPAT
10842 .compat_ioctl = btrfs_compat_ioctl,
10844 .release = btrfs_release_file,
10845 .fsync = btrfs_sync_file,
10848 static const struct extent_io_ops btrfs_extent_io_ops = {
10849 /* mandatory callbacks */
10850 .submit_bio_hook = btrfs_submit_bio_hook,
10851 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10855 * btrfs doesn't support the bmap operation because swapfiles
10856 * use bmap to make a mapping of extents in the file. They assume
10857 * these extents won't change over the life of the file and they
10858 * use the bmap result to do IO directly to the drive.
10860 * the btrfs bmap call would return logical addresses that aren't
10861 * suitable for IO and they also will change frequently as COW
10862 * operations happen. So, swapfile + btrfs == corruption.
10864 * For now we're avoiding this by dropping bmap.
10866 static const struct address_space_operations btrfs_aops = {
10867 .readpage = btrfs_readpage,
10868 .writepage = btrfs_writepage,
10869 .writepages = btrfs_writepages,
10870 .readpages = btrfs_readpages,
10871 .direct_IO = btrfs_direct_IO,
10872 .invalidatepage = btrfs_invalidatepage,
10873 .releasepage = btrfs_releasepage,
10874 .set_page_dirty = btrfs_set_page_dirty,
10875 .error_remove_page = generic_error_remove_page,
10876 .swap_activate = btrfs_swap_activate,
10877 .swap_deactivate = btrfs_swap_deactivate,
10880 static const struct inode_operations btrfs_file_inode_operations = {
10881 .getattr = btrfs_getattr,
10882 .setattr = btrfs_setattr,
10883 .listxattr = btrfs_listxattr,
10884 .permission = btrfs_permission,
10885 .fiemap = btrfs_fiemap,
10886 .get_acl = btrfs_get_acl,
10887 .set_acl = btrfs_set_acl,
10888 .update_time = btrfs_update_time,
10890 static const struct inode_operations btrfs_special_inode_operations = {
10891 .getattr = btrfs_getattr,
10892 .setattr = btrfs_setattr,
10893 .permission = btrfs_permission,
10894 .listxattr = btrfs_listxattr,
10895 .get_acl = btrfs_get_acl,
10896 .set_acl = btrfs_set_acl,
10897 .update_time = btrfs_update_time,
10899 static const struct inode_operations btrfs_symlink_inode_operations = {
10900 .get_link = page_get_link,
10901 .getattr = btrfs_getattr,
10902 .setattr = btrfs_setattr,
10903 .permission = btrfs_permission,
10904 .listxattr = btrfs_listxattr,
10905 .update_time = btrfs_update_time,
10908 const struct dentry_operations btrfs_dentry_operations = {
10909 .d_delete = btrfs_dentry_delete,