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 <linux/sched/mm.h>
32 #include <asm/unaligned.h>
35 #include "transaction.h"
36 #include "btrfs_inode.h"
37 #include "print-tree.h"
38 #include "ordered-data.h"
42 #include "compression.h"
44 #include "free-space-cache.h"
45 #include "inode-map.h"
50 #include "delalloc-space.h"
52 struct btrfs_iget_args {
53 struct btrfs_key *location;
54 struct btrfs_root *root;
57 struct btrfs_dio_data {
59 u64 unsubmitted_oe_range_start;
60 u64 unsubmitted_oe_range_end;
64 static const struct inode_operations btrfs_dir_inode_operations;
65 static const struct inode_operations btrfs_symlink_inode_operations;
66 static const struct inode_operations btrfs_dir_ro_inode_operations;
67 static const struct inode_operations btrfs_special_inode_operations;
68 static const struct inode_operations btrfs_file_inode_operations;
69 static const struct address_space_operations btrfs_aops;
70 static const struct file_operations btrfs_dir_file_operations;
71 static const struct extent_io_ops btrfs_extent_io_ops;
73 static struct kmem_cache *btrfs_inode_cachep;
74 struct kmem_cache *btrfs_trans_handle_cachep;
75 struct kmem_cache *btrfs_path_cachep;
76 struct kmem_cache *btrfs_free_space_cachep;
78 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
79 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
80 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
81 static noinline int cow_file_range(struct inode *inode,
82 struct page *locked_page,
83 u64 start, u64 end, u64 delalloc_end,
84 int *page_started, unsigned long *nr_written,
85 int unlock, struct btrfs_dedupe_hash *hash);
86 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
87 u64 orig_start, u64 block_start,
88 u64 block_len, u64 orig_block_len,
89 u64 ram_bytes, int compress_type,
92 static void __endio_write_update_ordered(struct inode *inode,
93 const u64 offset, const u64 bytes,
97 * Cleanup all submitted ordered extents in specified range to handle errors
98 * from the btrfs_run_delalloc_range() callback.
100 * NOTE: caller must ensure that when an error happens, it can not call
101 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
102 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
103 * to be released, which we want to happen only when finishing the ordered
104 * extent (btrfs_finish_ordered_io()).
106 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
107 struct page *locked_page,
108 u64 offset, u64 bytes)
110 unsigned long index = offset >> PAGE_SHIFT;
111 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
112 u64 page_start = page_offset(locked_page);
113 u64 page_end = page_start + PAGE_SIZE - 1;
117 while (index <= end_index) {
118 page = find_get_page(inode->i_mapping, index);
122 ClearPagePrivate2(page);
127 * In case this page belongs to the delalloc range being instantiated
128 * then skip it, since the first page of a range is going to be
129 * properly cleaned up by the caller of run_delalloc_range
131 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
136 return __endio_write_update_ordered(inode, offset, bytes, false);
139 static int btrfs_dirty_inode(struct inode *inode);
141 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
142 void btrfs_test_inode_set_ops(struct inode *inode)
144 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
148 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
149 struct inode *inode, struct inode *dir,
150 const struct qstr *qstr)
154 err = btrfs_init_acl(trans, inode, dir);
156 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
161 * this does all the hard work for inserting an inline extent into
162 * the btree. The caller should have done a btrfs_drop_extents so that
163 * no overlapping inline items exist in the btree
165 static int insert_inline_extent(struct btrfs_trans_handle *trans,
166 struct btrfs_path *path, int extent_inserted,
167 struct btrfs_root *root, struct inode *inode,
168 u64 start, size_t size, size_t compressed_size,
170 struct page **compressed_pages)
172 struct extent_buffer *leaf;
173 struct page *page = NULL;
176 struct btrfs_file_extent_item *ei;
178 size_t cur_size = size;
179 unsigned long offset;
181 if (compressed_size && compressed_pages)
182 cur_size = compressed_size;
184 inode_add_bytes(inode, size);
186 if (!extent_inserted) {
187 struct btrfs_key key;
190 key.objectid = btrfs_ino(BTRFS_I(inode));
192 key.type = BTRFS_EXTENT_DATA_KEY;
194 datasize = btrfs_file_extent_calc_inline_size(cur_size);
195 path->leave_spinning = 1;
196 ret = btrfs_insert_empty_item(trans, root, path, &key,
201 leaf = path->nodes[0];
202 ei = btrfs_item_ptr(leaf, path->slots[0],
203 struct btrfs_file_extent_item);
204 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
205 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
206 btrfs_set_file_extent_encryption(leaf, ei, 0);
207 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
208 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
209 ptr = btrfs_file_extent_inline_start(ei);
211 if (compress_type != BTRFS_COMPRESS_NONE) {
214 while (compressed_size > 0) {
215 cpage = compressed_pages[i];
216 cur_size = min_t(unsigned long, compressed_size,
219 kaddr = kmap_atomic(cpage);
220 write_extent_buffer(leaf, kaddr, ptr, cur_size);
221 kunmap_atomic(kaddr);
225 compressed_size -= cur_size;
227 btrfs_set_file_extent_compression(leaf, ei,
230 page = find_get_page(inode->i_mapping,
231 start >> PAGE_SHIFT);
232 btrfs_set_file_extent_compression(leaf, ei, 0);
233 kaddr = kmap_atomic(page);
234 offset = offset_in_page(start);
235 write_extent_buffer(leaf, kaddr + offset, ptr, size);
236 kunmap_atomic(kaddr);
239 btrfs_mark_buffer_dirty(leaf);
240 btrfs_release_path(path);
243 * we're an inline extent, so nobody can
244 * extend the file past i_size without locking
245 * a page we already have locked.
247 * We must do any isize and inode updates
248 * before we unlock the pages. Otherwise we
249 * could end up racing with unlink.
251 BTRFS_I(inode)->disk_i_size = inode->i_size;
252 ret = btrfs_update_inode(trans, root, inode);
260 * conditionally insert an inline extent into the file. This
261 * does the checks required to make sure the data is small enough
262 * to fit as an inline extent.
264 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
265 u64 end, size_t compressed_size,
267 struct page **compressed_pages)
269 struct btrfs_root *root = BTRFS_I(inode)->root;
270 struct btrfs_fs_info *fs_info = root->fs_info;
271 struct btrfs_trans_handle *trans;
272 u64 isize = i_size_read(inode);
273 u64 actual_end = min(end + 1, isize);
274 u64 inline_len = actual_end - start;
275 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
276 u64 data_len = inline_len;
278 struct btrfs_path *path;
279 int extent_inserted = 0;
280 u32 extent_item_size;
283 data_len = compressed_size;
286 actual_end > fs_info->sectorsize ||
287 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
289 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
291 data_len > fs_info->max_inline) {
295 path = btrfs_alloc_path();
299 trans = btrfs_join_transaction(root);
301 btrfs_free_path(path);
302 return PTR_ERR(trans);
304 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
306 if (compressed_size && compressed_pages)
307 extent_item_size = btrfs_file_extent_calc_inline_size(
310 extent_item_size = btrfs_file_extent_calc_inline_size(
313 ret = __btrfs_drop_extents(trans, root, inode, path,
314 start, aligned_end, NULL,
315 1, 1, extent_item_size, &extent_inserted);
317 btrfs_abort_transaction(trans, ret);
321 if (isize > actual_end)
322 inline_len = min_t(u64, isize, actual_end);
323 ret = insert_inline_extent(trans, path, extent_inserted,
325 inline_len, compressed_size,
326 compress_type, compressed_pages);
327 if (ret && ret != -ENOSPC) {
328 btrfs_abort_transaction(trans, ret);
330 } else if (ret == -ENOSPC) {
335 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
336 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
339 * Don't forget to free the reserved space, as for inlined extent
340 * it won't count as data extent, free them directly here.
341 * And at reserve time, it's always aligned to page size, so
342 * just free one page here.
344 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
345 btrfs_free_path(path);
346 btrfs_end_transaction(trans);
350 struct async_extent {
355 unsigned long nr_pages;
357 struct list_head list;
362 struct page *locked_page;
365 unsigned int write_flags;
366 struct list_head extents;
367 struct btrfs_work work;
372 /* Number of chunks in flight; must be first in the structure */
374 struct async_chunk chunks[];
377 static noinline int add_async_extent(struct async_chunk *cow,
378 u64 start, u64 ram_size,
381 unsigned long nr_pages,
384 struct async_extent *async_extent;
386 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
387 BUG_ON(!async_extent); /* -ENOMEM */
388 async_extent->start = start;
389 async_extent->ram_size = ram_size;
390 async_extent->compressed_size = compressed_size;
391 async_extent->pages = pages;
392 async_extent->nr_pages = nr_pages;
393 async_extent->compress_type = compress_type;
394 list_add_tail(&async_extent->list, &cow->extents);
398 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
400 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
403 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
406 if (BTRFS_I(inode)->defrag_compress)
408 /* bad compression ratios */
409 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
411 if (btrfs_test_opt(fs_info, COMPRESS) ||
412 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
413 BTRFS_I(inode)->prop_compress)
414 return btrfs_compress_heuristic(inode, start, end);
418 static inline void inode_should_defrag(struct btrfs_inode *inode,
419 u64 start, u64 end, u64 num_bytes, u64 small_write)
421 /* If this is a small write inside eof, kick off a defrag */
422 if (num_bytes < small_write &&
423 (start > 0 || end + 1 < inode->disk_i_size))
424 btrfs_add_inode_defrag(NULL, inode);
428 * we create compressed extents in two phases. The first
429 * phase compresses a range of pages that have already been
430 * locked (both pages and state bits are locked).
432 * This is done inside an ordered work queue, and the compression
433 * is spread across many cpus. The actual IO submission is step
434 * two, and the ordered work queue takes care of making sure that
435 * happens in the same order things were put onto the queue by
436 * writepages and friends.
438 * If this code finds it can't get good compression, it puts an
439 * entry onto the work queue to write the uncompressed bytes. This
440 * makes sure that both compressed inodes and uncompressed inodes
441 * are written in the same order that the flusher thread sent them
444 static noinline void compress_file_range(struct async_chunk *async_chunk,
447 struct inode *inode = async_chunk->inode;
448 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
449 u64 blocksize = fs_info->sectorsize;
450 u64 start = async_chunk->start;
451 u64 end = async_chunk->end;
454 struct page **pages = NULL;
455 unsigned long nr_pages;
456 unsigned long total_compressed = 0;
457 unsigned long total_in = 0;
460 int compress_type = fs_info->compress_type;
463 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
466 actual_end = min_t(u64, i_size_read(inode), end + 1);
469 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
470 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
471 nr_pages = min_t(unsigned long, nr_pages,
472 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
475 * we don't want to send crud past the end of i_size through
476 * compression, that's just a waste of CPU time. So, if the
477 * end of the file is before the start of our current
478 * requested range of bytes, we bail out to the uncompressed
479 * cleanup code that can deal with all of this.
481 * It isn't really the fastest way to fix things, but this is a
482 * very uncommon corner.
484 if (actual_end <= start)
485 goto cleanup_and_bail_uncompressed;
487 total_compressed = actual_end - start;
490 * skip compression for a small file range(<=blocksize) that
491 * isn't an inline extent, since it doesn't save disk space at all.
493 if (total_compressed <= blocksize &&
494 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
495 goto cleanup_and_bail_uncompressed;
497 total_compressed = min_t(unsigned long, total_compressed,
498 BTRFS_MAX_UNCOMPRESSED);
503 * we do compression for mount -o compress and when the
504 * inode has not been flagged as nocompress. This flag can
505 * change at any time if we discover bad compression ratios.
507 if (inode_need_compress(inode, start, end)) {
509 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
511 /* just bail out to the uncompressed code */
516 if (BTRFS_I(inode)->defrag_compress)
517 compress_type = BTRFS_I(inode)->defrag_compress;
518 else if (BTRFS_I(inode)->prop_compress)
519 compress_type = BTRFS_I(inode)->prop_compress;
522 * we need to call clear_page_dirty_for_io on each
523 * page in the range. Otherwise applications with the file
524 * mmap'd can wander in and change the page contents while
525 * we are compressing them.
527 * If the compression fails for any reason, we set the pages
528 * dirty again later on.
530 * Note that the remaining part is redirtied, the start pointer
531 * has moved, the end is the original one.
534 extent_range_clear_dirty_for_io(inode, start, end);
538 /* Compression level is applied here and only here */
539 ret = btrfs_compress_pages(
540 compress_type | (fs_info->compress_level << 4),
541 inode->i_mapping, start,
548 unsigned long offset = offset_in_page(total_compressed);
549 struct page *page = pages[nr_pages - 1];
552 /* zero the tail end of the last page, we might be
553 * sending it down to disk
556 kaddr = kmap_atomic(page);
557 memset(kaddr + offset, 0,
559 kunmap_atomic(kaddr);
566 /* lets try to make an inline extent */
567 if (ret || total_in < actual_end) {
568 /* we didn't compress the entire range, try
569 * to make an uncompressed inline extent.
571 ret = cow_file_range_inline(inode, start, end, 0,
572 BTRFS_COMPRESS_NONE, NULL);
574 /* try making a compressed inline extent */
575 ret = cow_file_range_inline(inode, start, end,
577 compress_type, pages);
580 unsigned long clear_flags = EXTENT_DELALLOC |
581 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
582 EXTENT_DO_ACCOUNTING;
583 unsigned long page_error_op;
585 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
588 * inline extent creation worked or returned error,
589 * we don't need to create any more async work items.
590 * Unlock and free up our temp pages.
592 * We use DO_ACCOUNTING here because we need the
593 * delalloc_release_metadata to be done _after_ we drop
594 * our outstanding extent for clearing delalloc for this
597 extent_clear_unlock_delalloc(inode, start, end, end,
610 * we aren't doing an inline extent round the compressed size
611 * up to a block size boundary so the allocator does sane
614 total_compressed = ALIGN(total_compressed, blocksize);
617 * one last check to make sure the compression is really a
618 * win, compare the page count read with the blocks on disk,
619 * compression must free at least one sector size
621 total_in = ALIGN(total_in, PAGE_SIZE);
622 if (total_compressed + blocksize <= total_in) {
626 * The async work queues will take care of doing actual
627 * allocation on disk for these compressed pages, and
628 * will submit them to the elevator.
630 add_async_extent(async_chunk, start, total_in,
631 total_compressed, pages, nr_pages,
634 if (start + total_in < end) {
645 * the compression code ran but failed to make things smaller,
646 * free any pages it allocated and our page pointer array
648 for (i = 0; i < nr_pages; i++) {
649 WARN_ON(pages[i]->mapping);
654 total_compressed = 0;
657 /* flag the file so we don't compress in the future */
658 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
659 !(BTRFS_I(inode)->prop_compress)) {
660 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
663 cleanup_and_bail_uncompressed:
665 * No compression, but we still need to write the pages in the file
666 * we've been given so far. redirty the locked page if it corresponds
667 * to our extent and set things up for the async work queue to run
668 * cow_file_range to do the normal delalloc dance.
670 if (page_offset(async_chunk->locked_page) >= start &&
671 page_offset(async_chunk->locked_page) <= end)
672 __set_page_dirty_nobuffers(async_chunk->locked_page);
673 /* unlocked later on in the async handlers */
676 extent_range_redirty_for_io(inode, start, end);
677 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
678 BTRFS_COMPRESS_NONE);
684 for (i = 0; i < nr_pages; i++) {
685 WARN_ON(pages[i]->mapping);
691 static void free_async_extent_pages(struct async_extent *async_extent)
695 if (!async_extent->pages)
698 for (i = 0; i < async_extent->nr_pages; i++) {
699 WARN_ON(async_extent->pages[i]->mapping);
700 put_page(async_extent->pages[i]);
702 kfree(async_extent->pages);
703 async_extent->nr_pages = 0;
704 async_extent->pages = NULL;
708 * phase two of compressed writeback. This is the ordered portion
709 * of the code, which only gets called in the order the work was
710 * queued. We walk all the async extents created by compress_file_range
711 * and send them down to the disk.
713 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
715 struct inode *inode = async_chunk->inode;
716 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
717 struct async_extent *async_extent;
719 struct btrfs_key ins;
720 struct extent_map *em;
721 struct btrfs_root *root = BTRFS_I(inode)->root;
722 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
726 while (!list_empty(&async_chunk->extents)) {
727 async_extent = list_entry(async_chunk->extents.next,
728 struct async_extent, list);
729 list_del(&async_extent->list);
732 lock_extent(io_tree, async_extent->start,
733 async_extent->start + async_extent->ram_size - 1);
734 /* did the compression code fall back to uncompressed IO? */
735 if (!async_extent->pages) {
736 int page_started = 0;
737 unsigned long nr_written = 0;
739 /* allocate blocks */
740 ret = cow_file_range(inode, async_chunk->locked_page,
742 async_extent->start +
743 async_extent->ram_size - 1,
744 async_extent->start +
745 async_extent->ram_size - 1,
746 &page_started, &nr_written, 0,
752 * if page_started, cow_file_range inserted an
753 * inline extent and took care of all the unlocking
754 * and IO for us. Otherwise, we need to submit
755 * all those pages down to the drive.
757 if (!page_started && !ret)
758 extent_write_locked_range(inode,
760 async_extent->start +
761 async_extent->ram_size - 1,
764 unlock_page(async_chunk->locked_page);
770 ret = btrfs_reserve_extent(root, async_extent->ram_size,
771 async_extent->compressed_size,
772 async_extent->compressed_size,
773 0, alloc_hint, &ins, 1, 1);
775 free_async_extent_pages(async_extent);
777 if (ret == -ENOSPC) {
778 unlock_extent(io_tree, async_extent->start,
779 async_extent->start +
780 async_extent->ram_size - 1);
783 * we need to redirty the pages if we decide to
784 * fallback to uncompressed IO, otherwise we
785 * will not submit these pages down to lower
788 extent_range_redirty_for_io(inode,
790 async_extent->start +
791 async_extent->ram_size - 1);
798 * here we're doing allocation and writeback of the
801 em = create_io_em(inode, async_extent->start,
802 async_extent->ram_size, /* len */
803 async_extent->start, /* orig_start */
804 ins.objectid, /* block_start */
805 ins.offset, /* block_len */
806 ins.offset, /* orig_block_len */
807 async_extent->ram_size, /* ram_bytes */
808 async_extent->compress_type,
809 BTRFS_ORDERED_COMPRESSED);
811 /* ret value is not necessary due to void function */
812 goto out_free_reserve;
815 ret = btrfs_add_ordered_extent_compress(inode,
818 async_extent->ram_size,
820 BTRFS_ORDERED_COMPRESSED,
821 async_extent->compress_type);
823 btrfs_drop_extent_cache(BTRFS_I(inode),
825 async_extent->start +
826 async_extent->ram_size - 1, 0);
827 goto out_free_reserve;
829 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
832 * clear dirty, set writeback and unlock the pages.
834 extent_clear_unlock_delalloc(inode, async_extent->start,
835 async_extent->start +
836 async_extent->ram_size - 1,
837 async_extent->start +
838 async_extent->ram_size - 1,
839 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
840 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
842 if (btrfs_submit_compressed_write(inode,
844 async_extent->ram_size,
846 ins.offset, async_extent->pages,
847 async_extent->nr_pages,
848 async_chunk->write_flags)) {
849 struct page *p = async_extent->pages[0];
850 const u64 start = async_extent->start;
851 const u64 end = start + async_extent->ram_size - 1;
853 p->mapping = inode->i_mapping;
854 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
857 extent_clear_unlock_delalloc(inode, start, end, end,
861 free_async_extent_pages(async_extent);
863 alloc_hint = ins.objectid + ins.offset;
869 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
870 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
872 extent_clear_unlock_delalloc(inode, async_extent->start,
873 async_extent->start +
874 async_extent->ram_size - 1,
875 async_extent->start +
876 async_extent->ram_size - 1,
877 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
878 EXTENT_DELALLOC_NEW |
879 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
880 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
881 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
883 free_async_extent_pages(async_extent);
888 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
891 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
892 struct extent_map *em;
895 read_lock(&em_tree->lock);
896 em = search_extent_mapping(em_tree, start, num_bytes);
899 * if block start isn't an actual block number then find the
900 * first block in this inode and use that as a hint. If that
901 * block is also bogus then just don't worry about it.
903 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
905 em = search_extent_mapping(em_tree, 0, 0);
906 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
907 alloc_hint = em->block_start;
911 alloc_hint = em->block_start;
915 read_unlock(&em_tree->lock);
921 * when extent_io.c finds a delayed allocation range in the file,
922 * the call backs end up in this code. The basic idea is to
923 * allocate extents on disk for the range, and create ordered data structs
924 * in ram to track those extents.
926 * locked_page is the page that writepage had locked already. We use
927 * it to make sure we don't do extra locks or unlocks.
929 * *page_started is set to one if we unlock locked_page and do everything
930 * required to start IO on it. It may be clean and already done with
933 static noinline int cow_file_range(struct inode *inode,
934 struct page *locked_page,
935 u64 start, u64 end, u64 delalloc_end,
936 int *page_started, unsigned long *nr_written,
937 int unlock, struct btrfs_dedupe_hash *hash)
939 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
940 struct btrfs_root *root = BTRFS_I(inode)->root;
943 unsigned long ram_size;
944 u64 cur_alloc_size = 0;
945 u64 blocksize = fs_info->sectorsize;
946 struct btrfs_key ins;
947 struct extent_map *em;
949 unsigned long page_ops;
950 bool extent_reserved = false;
953 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
959 num_bytes = ALIGN(end - start + 1, blocksize);
960 num_bytes = max(blocksize, num_bytes);
961 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
963 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
966 /* lets try to make an inline extent */
967 ret = cow_file_range_inline(inode, start, end, 0,
968 BTRFS_COMPRESS_NONE, NULL);
971 * We use DO_ACCOUNTING here because we need the
972 * delalloc_release_metadata to be run _after_ we drop
973 * our outstanding extent for clearing delalloc for this
976 extent_clear_unlock_delalloc(inode, start, end,
978 EXTENT_LOCKED | EXTENT_DELALLOC |
979 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
980 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
981 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
983 *nr_written = *nr_written +
984 (end - start + PAGE_SIZE) / PAGE_SIZE;
987 } else if (ret < 0) {
992 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
993 btrfs_drop_extent_cache(BTRFS_I(inode), start,
994 start + num_bytes - 1, 0);
996 while (num_bytes > 0) {
997 cur_alloc_size = num_bytes;
998 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
999 fs_info->sectorsize, 0, alloc_hint,
1003 cur_alloc_size = ins.offset;
1004 extent_reserved = true;
1006 ram_size = ins.offset;
1007 em = create_io_em(inode, start, ins.offset, /* len */
1008 start, /* orig_start */
1009 ins.objectid, /* block_start */
1010 ins.offset, /* block_len */
1011 ins.offset, /* orig_block_len */
1012 ram_size, /* ram_bytes */
1013 BTRFS_COMPRESS_NONE, /* compress_type */
1014 BTRFS_ORDERED_REGULAR /* type */);
1019 free_extent_map(em);
1021 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1022 ram_size, cur_alloc_size, 0);
1024 goto out_drop_extent_cache;
1026 if (root->root_key.objectid ==
1027 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1028 ret = btrfs_reloc_clone_csums(inode, start,
1031 * Only drop cache here, and process as normal.
1033 * We must not allow extent_clear_unlock_delalloc()
1034 * at out_unlock label to free meta of this ordered
1035 * extent, as its meta should be freed by
1036 * btrfs_finish_ordered_io().
1038 * So we must continue until @start is increased to
1039 * skip current ordered extent.
1042 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1043 start + ram_size - 1, 0);
1046 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1048 /* we're not doing compressed IO, don't unlock the first
1049 * page (which the caller expects to stay locked), don't
1050 * clear any dirty bits and don't set any writeback bits
1052 * Do set the Private2 bit so we know this page was properly
1053 * setup for writepage
1055 page_ops = unlock ? PAGE_UNLOCK : 0;
1056 page_ops |= PAGE_SET_PRIVATE2;
1058 extent_clear_unlock_delalloc(inode, start,
1059 start + ram_size - 1,
1060 delalloc_end, locked_page,
1061 EXTENT_LOCKED | EXTENT_DELALLOC,
1063 if (num_bytes < cur_alloc_size)
1066 num_bytes -= cur_alloc_size;
1067 alloc_hint = ins.objectid + ins.offset;
1068 start += cur_alloc_size;
1069 extent_reserved = false;
1072 * btrfs_reloc_clone_csums() error, since start is increased
1073 * extent_clear_unlock_delalloc() at out_unlock label won't
1074 * free metadata of current ordered extent, we're OK to exit.
1082 out_drop_extent_cache:
1083 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1085 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1086 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1088 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1089 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1090 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1093 * If we reserved an extent for our delalloc range (or a subrange) and
1094 * failed to create the respective ordered extent, then it means that
1095 * when we reserved the extent we decremented the extent's size from
1096 * the data space_info's bytes_may_use counter and incremented the
1097 * space_info's bytes_reserved counter by the same amount. We must make
1098 * sure extent_clear_unlock_delalloc() does not try to decrement again
1099 * the data space_info's bytes_may_use counter, therefore we do not pass
1100 * it the flag EXTENT_CLEAR_DATA_RESV.
1102 if (extent_reserved) {
1103 extent_clear_unlock_delalloc(inode, start,
1104 start + cur_alloc_size,
1105 start + cur_alloc_size,
1109 start += cur_alloc_size;
1113 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1115 clear_bits | EXTENT_CLEAR_DATA_RESV,
1121 * work queue call back to started compression on a file and pages
1123 static noinline void async_cow_start(struct btrfs_work *work)
1125 struct async_chunk *async_chunk;
1128 async_chunk = container_of(work, struct async_chunk, work);
1130 compress_file_range(async_chunk, &num_added);
1131 if (num_added == 0) {
1132 btrfs_add_delayed_iput(async_chunk->inode);
1133 async_chunk->inode = NULL;
1138 * work queue call back to submit previously compressed pages
1140 static noinline void async_cow_submit(struct btrfs_work *work)
1142 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1144 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1145 unsigned long nr_pages;
1147 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1150 /* atomic_sub_return implies a barrier */
1151 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1153 cond_wake_up_nomb(&fs_info->async_submit_wait);
1156 * ->inode could be NULL if async_chunk_start has failed to compress,
1157 * in which case we don't have anything to submit, yet we need to
1158 * always adjust ->async_delalloc_pages as its paired with the init
1159 * happening in cow_file_range_async
1161 if (async_chunk->inode)
1162 submit_compressed_extents(async_chunk);
1165 static noinline void async_cow_free(struct btrfs_work *work)
1167 struct async_chunk *async_chunk;
1169 async_chunk = container_of(work, struct async_chunk, work);
1170 if (async_chunk->inode)
1171 btrfs_add_delayed_iput(async_chunk->inode);
1173 * Since the pointer to 'pending' is at the beginning of the array of
1174 * async_chunk's, freeing it ensures the whole array has been freed.
1176 if (atomic_dec_and_test(async_chunk->pending))
1177 kvfree(async_chunk->pending);
1180 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1181 u64 start, u64 end, int *page_started,
1182 unsigned long *nr_written,
1183 unsigned int write_flags)
1185 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1186 struct async_cow *ctx;
1187 struct async_chunk *async_chunk;
1188 unsigned long nr_pages;
1190 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1192 bool should_compress;
1195 unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1197 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1198 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1200 should_compress = false;
1202 should_compress = true;
1205 nofs_flag = memalloc_nofs_save();
1206 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1207 memalloc_nofs_restore(nofs_flag);
1210 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1211 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1212 EXTENT_DO_ACCOUNTING;
1213 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1214 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1217 extent_clear_unlock_delalloc(inode, start, end, 0, locked_page,
1218 clear_bits, page_ops);
1222 async_chunk = ctx->chunks;
1223 atomic_set(&ctx->num_chunks, num_chunks);
1225 for (i = 0; i < num_chunks; i++) {
1226 if (should_compress)
1227 cur_end = min(end, start + SZ_512K - 1);
1232 * igrab is called higher up in the call chain, take only the
1233 * lightweight reference for the callback lifetime
1236 async_chunk[i].pending = &ctx->num_chunks;
1237 async_chunk[i].inode = inode;
1238 async_chunk[i].start = start;
1239 async_chunk[i].end = cur_end;
1240 async_chunk[i].locked_page = locked_page;
1241 async_chunk[i].write_flags = write_flags;
1242 INIT_LIST_HEAD(&async_chunk[i].extents);
1244 btrfs_init_work(&async_chunk[i].work,
1245 btrfs_delalloc_helper,
1246 async_cow_start, async_cow_submit,
1249 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1250 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1252 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1254 *nr_written += nr_pages;
1255 start = cur_end + 1;
1261 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1262 u64 bytenr, u64 num_bytes)
1265 struct btrfs_ordered_sum *sums;
1268 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1269 bytenr + num_bytes - 1, &list, 0);
1270 if (ret == 0 && list_empty(&list))
1273 while (!list_empty(&list)) {
1274 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1275 list_del(&sums->list);
1284 * when nowcow writeback call back. This checks for snapshots or COW copies
1285 * of the extents that exist in the file, and COWs the file as required.
1287 * If no cow copies or snapshots exist, we write directly to the existing
1290 static noinline int run_delalloc_nocow(struct inode *inode,
1291 struct page *locked_page,
1292 u64 start, u64 end, int *page_started, int force,
1293 unsigned long *nr_written)
1295 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1296 struct btrfs_root *root = BTRFS_I(inode)->root;
1297 struct extent_buffer *leaf;
1298 struct btrfs_path *path;
1299 struct btrfs_file_extent_item *fi;
1300 struct btrfs_key found_key;
1301 struct extent_map *em;
1316 u64 ino = btrfs_ino(BTRFS_I(inode));
1318 path = btrfs_alloc_path();
1320 extent_clear_unlock_delalloc(inode, start, end, end,
1322 EXTENT_LOCKED | EXTENT_DELALLOC |
1323 EXTENT_DO_ACCOUNTING |
1324 EXTENT_DEFRAG, PAGE_UNLOCK |
1326 PAGE_SET_WRITEBACK |
1327 PAGE_END_WRITEBACK);
1331 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1333 cow_start = (u64)-1;
1336 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1340 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1341 leaf = path->nodes[0];
1342 btrfs_item_key_to_cpu(leaf, &found_key,
1343 path->slots[0] - 1);
1344 if (found_key.objectid == ino &&
1345 found_key.type == BTRFS_EXTENT_DATA_KEY)
1350 leaf = path->nodes[0];
1351 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1352 ret = btrfs_next_leaf(root, path);
1354 if (cow_start != (u64)-1)
1355 cur_offset = cow_start;
1360 leaf = path->nodes[0];
1366 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1368 if (found_key.objectid > ino)
1370 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1371 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1375 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1376 found_key.offset > end)
1379 if (found_key.offset > cur_offset) {
1380 extent_end = found_key.offset;
1385 fi = btrfs_item_ptr(leaf, path->slots[0],
1386 struct btrfs_file_extent_item);
1387 extent_type = btrfs_file_extent_type(leaf, fi);
1389 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1390 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1391 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1392 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1393 extent_offset = btrfs_file_extent_offset(leaf, fi);
1394 extent_end = found_key.offset +
1395 btrfs_file_extent_num_bytes(leaf, fi);
1397 btrfs_file_extent_disk_num_bytes(leaf, fi);
1398 if (extent_end <= start) {
1402 if (disk_bytenr == 0)
1404 if (btrfs_file_extent_compression(leaf, fi) ||
1405 btrfs_file_extent_encryption(leaf, fi) ||
1406 btrfs_file_extent_other_encoding(leaf, fi))
1409 * Do the same check as in btrfs_cross_ref_exist but
1410 * without the unnecessary search.
1413 btrfs_file_extent_generation(leaf, fi) <=
1414 btrfs_root_last_snapshot(&root->root_item))
1416 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1418 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1420 ret = btrfs_cross_ref_exist(root, ino,
1422 extent_offset, disk_bytenr);
1425 * ret could be -EIO if the above fails to read
1429 if (cow_start != (u64)-1)
1430 cur_offset = cow_start;
1434 WARN_ON_ONCE(nolock);
1437 disk_bytenr += extent_offset;
1438 disk_bytenr += cur_offset - found_key.offset;
1439 num_bytes = min(end + 1, extent_end) - cur_offset;
1441 * if there are pending snapshots for this root,
1442 * we fall into common COW way.
1444 if (!nolock && atomic_read(&root->snapshot_force_cow))
1447 * force cow if csum exists in the range.
1448 * this ensure that csum for a given extent are
1449 * either valid or do not exist.
1451 ret = csum_exist_in_range(fs_info, disk_bytenr,
1455 * ret could be -EIO if the above fails to read
1459 if (cow_start != (u64)-1)
1460 cur_offset = cow_start;
1463 WARN_ON_ONCE(nolock);
1466 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1469 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1470 extent_end = found_key.offset +
1471 btrfs_file_extent_ram_bytes(leaf, fi);
1472 extent_end = ALIGN(extent_end,
1473 fs_info->sectorsize);
1478 if (extent_end <= start) {
1481 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1485 if (cow_start == (u64)-1)
1486 cow_start = cur_offset;
1487 cur_offset = extent_end;
1488 if (cur_offset > end)
1494 btrfs_release_path(path);
1495 if (cow_start != (u64)-1) {
1496 ret = cow_file_range(inode, locked_page,
1497 cow_start, found_key.offset - 1,
1498 end, page_started, nr_written, 1,
1502 btrfs_dec_nocow_writers(fs_info,
1506 cow_start = (u64)-1;
1509 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1510 u64 orig_start = found_key.offset - extent_offset;
1512 em = create_io_em(inode, cur_offset, num_bytes,
1514 disk_bytenr, /* block_start */
1515 num_bytes, /* block_len */
1516 disk_num_bytes, /* orig_block_len */
1517 ram_bytes, BTRFS_COMPRESS_NONE,
1518 BTRFS_ORDERED_PREALLOC);
1521 btrfs_dec_nocow_writers(fs_info,
1526 free_extent_map(em);
1529 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1530 type = BTRFS_ORDERED_PREALLOC;
1532 type = BTRFS_ORDERED_NOCOW;
1535 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1536 num_bytes, num_bytes, type);
1538 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1539 BUG_ON(ret); /* -ENOMEM */
1541 if (root->root_key.objectid ==
1542 BTRFS_DATA_RELOC_TREE_OBJECTID)
1544 * Error handled later, as we must prevent
1545 * extent_clear_unlock_delalloc() in error handler
1546 * from freeing metadata of created ordered extent.
1548 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1551 extent_clear_unlock_delalloc(inode, cur_offset,
1552 cur_offset + num_bytes - 1, end,
1553 locked_page, EXTENT_LOCKED |
1555 EXTENT_CLEAR_DATA_RESV,
1556 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1558 cur_offset = extent_end;
1561 * btrfs_reloc_clone_csums() error, now we're OK to call error
1562 * handler, as metadata for created ordered extent will only
1563 * be freed by btrfs_finish_ordered_io().
1567 if (cur_offset > end)
1570 btrfs_release_path(path);
1572 if (cur_offset <= end && cow_start == (u64)-1)
1573 cow_start = cur_offset;
1575 if (cow_start != (u64)-1) {
1577 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1578 page_started, nr_written, 1, NULL);
1584 if (ret && cur_offset < end)
1585 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1586 locked_page, EXTENT_LOCKED |
1587 EXTENT_DELALLOC | EXTENT_DEFRAG |
1588 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1590 PAGE_SET_WRITEBACK |
1591 PAGE_END_WRITEBACK);
1592 btrfs_free_path(path);
1596 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1599 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1600 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1604 * @defrag_bytes is a hint value, no spinlock held here,
1605 * if is not zero, it means the file is defragging.
1606 * Force cow if given extent needs to be defragged.
1608 if (BTRFS_I(inode)->defrag_bytes &&
1609 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1610 EXTENT_DEFRAG, 0, NULL))
1617 * Function to process delayed allocation (create CoW) for ranges which are
1618 * being touched for the first time.
1620 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1621 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1622 struct writeback_control *wbc)
1625 int force_cow = need_force_cow(inode, start, end);
1626 unsigned int write_flags = wbc_to_write_flags(wbc);
1628 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1629 ret = run_delalloc_nocow(inode, locked_page, start, end,
1630 page_started, 1, nr_written);
1631 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1632 ret = run_delalloc_nocow(inode, locked_page, start, end,
1633 page_started, 0, nr_written);
1634 } else if (!inode_need_compress(inode, start, end)) {
1635 ret = cow_file_range(inode, locked_page, start, end, end,
1636 page_started, nr_written, 1, NULL);
1638 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1639 &BTRFS_I(inode)->runtime_flags);
1640 ret = cow_file_range_async(inode, locked_page, start, end,
1641 page_started, nr_written,
1645 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1650 void btrfs_split_delalloc_extent(struct inode *inode,
1651 struct extent_state *orig, u64 split)
1655 /* not delalloc, ignore it */
1656 if (!(orig->state & EXTENT_DELALLOC))
1659 size = orig->end - orig->start + 1;
1660 if (size > BTRFS_MAX_EXTENT_SIZE) {
1665 * See the explanation in btrfs_merge_delalloc_extent, the same
1666 * applies here, just in reverse.
1668 new_size = orig->end - split + 1;
1669 num_extents = count_max_extents(new_size);
1670 new_size = split - orig->start;
1671 num_extents += count_max_extents(new_size);
1672 if (count_max_extents(size) >= num_extents)
1676 spin_lock(&BTRFS_I(inode)->lock);
1677 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1678 spin_unlock(&BTRFS_I(inode)->lock);
1682 * Handle merged delayed allocation extents so we can keep track of new extents
1683 * that are just merged onto old extents, such as when we are doing sequential
1684 * writes, so we can properly account for the metadata space we'll need.
1686 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1687 struct extent_state *other)
1689 u64 new_size, old_size;
1692 /* not delalloc, ignore it */
1693 if (!(other->state & EXTENT_DELALLOC))
1696 if (new->start > other->start)
1697 new_size = new->end - other->start + 1;
1699 new_size = other->end - new->start + 1;
1701 /* we're not bigger than the max, unreserve the space and go */
1702 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1703 spin_lock(&BTRFS_I(inode)->lock);
1704 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1705 spin_unlock(&BTRFS_I(inode)->lock);
1710 * We have to add up either side to figure out how many extents were
1711 * accounted for before we merged into one big extent. If the number of
1712 * extents we accounted for is <= the amount we need for the new range
1713 * then we can return, otherwise drop. Think of it like this
1717 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1718 * need 2 outstanding extents, on one side we have 1 and the other side
1719 * we have 1 so they are == and we can return. But in this case
1721 * [MAX_SIZE+4k][MAX_SIZE+4k]
1723 * Each range on their own accounts for 2 extents, but merged together
1724 * they are only 3 extents worth of accounting, so we need to drop in
1727 old_size = other->end - other->start + 1;
1728 num_extents = count_max_extents(old_size);
1729 old_size = new->end - new->start + 1;
1730 num_extents += count_max_extents(old_size);
1731 if (count_max_extents(new_size) >= num_extents)
1734 spin_lock(&BTRFS_I(inode)->lock);
1735 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1736 spin_unlock(&BTRFS_I(inode)->lock);
1739 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1740 struct inode *inode)
1742 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1744 spin_lock(&root->delalloc_lock);
1745 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1746 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1747 &root->delalloc_inodes);
1748 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1749 &BTRFS_I(inode)->runtime_flags);
1750 root->nr_delalloc_inodes++;
1751 if (root->nr_delalloc_inodes == 1) {
1752 spin_lock(&fs_info->delalloc_root_lock);
1753 BUG_ON(!list_empty(&root->delalloc_root));
1754 list_add_tail(&root->delalloc_root,
1755 &fs_info->delalloc_roots);
1756 spin_unlock(&fs_info->delalloc_root_lock);
1759 spin_unlock(&root->delalloc_lock);
1763 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1764 struct btrfs_inode *inode)
1766 struct btrfs_fs_info *fs_info = root->fs_info;
1768 if (!list_empty(&inode->delalloc_inodes)) {
1769 list_del_init(&inode->delalloc_inodes);
1770 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1771 &inode->runtime_flags);
1772 root->nr_delalloc_inodes--;
1773 if (!root->nr_delalloc_inodes) {
1774 ASSERT(list_empty(&root->delalloc_inodes));
1775 spin_lock(&fs_info->delalloc_root_lock);
1776 BUG_ON(list_empty(&root->delalloc_root));
1777 list_del_init(&root->delalloc_root);
1778 spin_unlock(&fs_info->delalloc_root_lock);
1783 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1784 struct btrfs_inode *inode)
1786 spin_lock(&root->delalloc_lock);
1787 __btrfs_del_delalloc_inode(root, inode);
1788 spin_unlock(&root->delalloc_lock);
1792 * Properly track delayed allocation bytes in the inode and to maintain the
1793 * list of inodes that have pending delalloc work to be done.
1795 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1798 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1800 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1803 * set_bit and clear bit hooks normally require _irqsave/restore
1804 * but in this case, we are only testing for the DELALLOC
1805 * bit, which is only set or cleared with irqs on
1807 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1808 struct btrfs_root *root = BTRFS_I(inode)->root;
1809 u64 len = state->end + 1 - state->start;
1810 u32 num_extents = count_max_extents(len);
1811 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1813 spin_lock(&BTRFS_I(inode)->lock);
1814 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1815 spin_unlock(&BTRFS_I(inode)->lock);
1817 /* For sanity tests */
1818 if (btrfs_is_testing(fs_info))
1821 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1822 fs_info->delalloc_batch);
1823 spin_lock(&BTRFS_I(inode)->lock);
1824 BTRFS_I(inode)->delalloc_bytes += len;
1825 if (*bits & EXTENT_DEFRAG)
1826 BTRFS_I(inode)->defrag_bytes += len;
1827 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1828 &BTRFS_I(inode)->runtime_flags))
1829 btrfs_add_delalloc_inodes(root, inode);
1830 spin_unlock(&BTRFS_I(inode)->lock);
1833 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1834 (*bits & EXTENT_DELALLOC_NEW)) {
1835 spin_lock(&BTRFS_I(inode)->lock);
1836 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1838 spin_unlock(&BTRFS_I(inode)->lock);
1843 * Once a range is no longer delalloc this function ensures that proper
1844 * accounting happens.
1846 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1847 struct extent_state *state, unsigned *bits)
1849 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1850 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1851 u64 len = state->end + 1 - state->start;
1852 u32 num_extents = count_max_extents(len);
1854 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1855 spin_lock(&inode->lock);
1856 inode->defrag_bytes -= len;
1857 spin_unlock(&inode->lock);
1861 * set_bit and clear bit hooks normally require _irqsave/restore
1862 * but in this case, we are only testing for the DELALLOC
1863 * bit, which is only set or cleared with irqs on
1865 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1866 struct btrfs_root *root = inode->root;
1867 bool do_list = !btrfs_is_free_space_inode(inode);
1869 spin_lock(&inode->lock);
1870 btrfs_mod_outstanding_extents(inode, -num_extents);
1871 spin_unlock(&inode->lock);
1874 * We don't reserve metadata space for space cache inodes so we
1875 * don't need to call delalloc_release_metadata if there is an
1878 if (*bits & EXTENT_CLEAR_META_RESV &&
1879 root != fs_info->tree_root)
1880 btrfs_delalloc_release_metadata(inode, len, false);
1882 /* For sanity tests. */
1883 if (btrfs_is_testing(fs_info))
1886 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1887 do_list && !(state->state & EXTENT_NORESERVE) &&
1888 (*bits & EXTENT_CLEAR_DATA_RESV))
1889 btrfs_free_reserved_data_space_noquota(
1893 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1894 fs_info->delalloc_batch);
1895 spin_lock(&inode->lock);
1896 inode->delalloc_bytes -= len;
1897 if (do_list && inode->delalloc_bytes == 0 &&
1898 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1899 &inode->runtime_flags))
1900 btrfs_del_delalloc_inode(root, inode);
1901 spin_unlock(&inode->lock);
1904 if ((state->state & EXTENT_DELALLOC_NEW) &&
1905 (*bits & EXTENT_DELALLOC_NEW)) {
1906 spin_lock(&inode->lock);
1907 ASSERT(inode->new_delalloc_bytes >= len);
1908 inode->new_delalloc_bytes -= len;
1909 spin_unlock(&inode->lock);
1914 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1915 * in a chunk's stripe. This function ensures that bios do not span a
1918 * @page - The page we are about to add to the bio
1919 * @size - size we want to add to the bio
1920 * @bio - bio we want to ensure is smaller than a stripe
1921 * @bio_flags - flags of the bio
1923 * return 1 if page cannot be added to the bio
1924 * return 0 if page can be added to the bio
1925 * return error otherwise
1927 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
1928 unsigned long bio_flags)
1930 struct inode *inode = page->mapping->host;
1931 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1932 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1936 struct btrfs_io_geometry geom;
1938 if (bio_flags & EXTENT_BIO_COMPRESSED)
1941 length = bio->bi_iter.bi_size;
1942 map_length = length;
1943 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
1948 if (geom.len < length + size)
1954 * in order to insert checksums into the metadata in large chunks,
1955 * we wait until bio submission time. All the pages in the bio are
1956 * checksummed and sums are attached onto the ordered extent record.
1958 * At IO completion time the cums attached on the ordered extent record
1959 * are inserted into the btree
1961 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1964 struct inode *inode = private_data;
1965 blk_status_t ret = 0;
1967 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1968 BUG_ON(ret); /* -ENOMEM */
1973 * extent_io.c submission hook. This does the right thing for csum calculation
1974 * on write, or reading the csums from the tree before a read.
1976 * Rules about async/sync submit,
1977 * a) read: sync submit
1979 * b) write without checksum: sync submit
1981 * c) write with checksum:
1982 * c-1) if bio is issued by fsync: sync submit
1983 * (sync_writers != 0)
1985 * c-2) if root is reloc root: sync submit
1986 * (only in case of buffered IO)
1988 * c-3) otherwise: async submit
1990 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
1992 unsigned long bio_flags)
1995 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1996 struct btrfs_root *root = BTRFS_I(inode)->root;
1997 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1998 blk_status_t ret = 0;
2000 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2002 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2004 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2005 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2007 if (bio_op(bio) != REQ_OP_WRITE) {
2008 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2012 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2013 ret = btrfs_submit_compressed_read(inode, bio,
2017 } else if (!skip_sum) {
2018 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2023 } else if (async && !skip_sum) {
2024 /* csum items have already been cloned */
2025 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2027 /* we're doing a write, do the async checksumming */
2028 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2029 0, inode, btrfs_submit_bio_start);
2031 } else if (!skip_sum) {
2032 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2038 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2042 bio->bi_status = ret;
2049 * given a list of ordered sums record them in the inode. This happens
2050 * at IO completion time based on sums calculated at bio submission time.
2052 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2053 struct inode *inode, struct list_head *list)
2055 struct btrfs_ordered_sum *sum;
2058 list_for_each_entry(sum, list, list) {
2059 trans->adding_csums = true;
2060 ret = btrfs_csum_file_blocks(trans,
2061 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2062 trans->adding_csums = false;
2069 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2070 unsigned int extra_bits,
2071 struct extent_state **cached_state, int dedupe)
2073 WARN_ON(PAGE_ALIGNED(end));
2074 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2075 extra_bits, cached_state);
2078 /* see btrfs_writepage_start_hook for details on why this is required */
2079 struct btrfs_writepage_fixup {
2081 struct btrfs_work work;
2084 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2086 struct btrfs_writepage_fixup *fixup;
2087 struct btrfs_ordered_extent *ordered;
2088 struct extent_state *cached_state = NULL;
2089 struct extent_changeset *data_reserved = NULL;
2091 struct inode *inode;
2096 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2100 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2101 ClearPageChecked(page);
2105 inode = page->mapping->host;
2106 page_start = page_offset(page);
2107 page_end = page_offset(page) + PAGE_SIZE - 1;
2109 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2112 /* already ordered? We're done */
2113 if (PagePrivate2(page))
2116 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2119 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2120 page_end, &cached_state);
2122 btrfs_start_ordered_extent(inode, ordered, 1);
2123 btrfs_put_ordered_extent(ordered);
2127 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2130 mapping_set_error(page->mapping, ret);
2131 end_extent_writepage(page, ret, page_start, page_end);
2132 ClearPageChecked(page);
2136 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2139 mapping_set_error(page->mapping, ret);
2140 end_extent_writepage(page, ret, page_start, page_end);
2141 ClearPageChecked(page);
2145 ClearPageChecked(page);
2146 set_page_dirty(page);
2147 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2149 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2155 extent_changeset_free(data_reserved);
2159 * There are a few paths in the higher layers of the kernel that directly
2160 * set the page dirty bit without asking the filesystem if it is a
2161 * good idea. This causes problems because we want to make sure COW
2162 * properly happens and the data=ordered rules are followed.
2164 * In our case any range that doesn't have the ORDERED bit set
2165 * hasn't been properly setup for IO. We kick off an async process
2166 * to fix it up. The async helper will wait for ordered extents, set
2167 * the delalloc bit and make it safe to write the page.
2169 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2171 struct inode *inode = page->mapping->host;
2172 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2173 struct btrfs_writepage_fixup *fixup;
2175 /* this page is properly in the ordered list */
2176 if (TestClearPagePrivate2(page))
2179 if (PageChecked(page))
2182 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2186 SetPageChecked(page);
2188 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2189 btrfs_writepage_fixup_worker, NULL, NULL);
2191 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2195 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2196 struct inode *inode, u64 file_pos,
2197 u64 disk_bytenr, u64 disk_num_bytes,
2198 u64 num_bytes, u64 ram_bytes,
2199 u8 compression, u8 encryption,
2200 u16 other_encoding, int extent_type)
2202 struct btrfs_root *root = BTRFS_I(inode)->root;
2203 struct btrfs_file_extent_item *fi;
2204 struct btrfs_path *path;
2205 struct extent_buffer *leaf;
2206 struct btrfs_key ins;
2208 int extent_inserted = 0;
2211 path = btrfs_alloc_path();
2216 * we may be replacing one extent in the tree with another.
2217 * The new extent is pinned in the extent map, and we don't want
2218 * to drop it from the cache until it is completely in the btree.
2220 * So, tell btrfs_drop_extents to leave this extent in the cache.
2221 * the caller is expected to unpin it and allow it to be merged
2224 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2225 file_pos + num_bytes, NULL, 0,
2226 1, sizeof(*fi), &extent_inserted);
2230 if (!extent_inserted) {
2231 ins.objectid = btrfs_ino(BTRFS_I(inode));
2232 ins.offset = file_pos;
2233 ins.type = BTRFS_EXTENT_DATA_KEY;
2235 path->leave_spinning = 1;
2236 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2241 leaf = path->nodes[0];
2242 fi = btrfs_item_ptr(leaf, path->slots[0],
2243 struct btrfs_file_extent_item);
2244 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2245 btrfs_set_file_extent_type(leaf, fi, extent_type);
2246 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2247 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2248 btrfs_set_file_extent_offset(leaf, fi, 0);
2249 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2250 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2251 btrfs_set_file_extent_compression(leaf, fi, compression);
2252 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2253 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2255 btrfs_mark_buffer_dirty(leaf);
2256 btrfs_release_path(path);
2258 inode_add_bytes(inode, num_bytes);
2260 ins.objectid = disk_bytenr;
2261 ins.offset = disk_num_bytes;
2262 ins.type = BTRFS_EXTENT_ITEM_KEY;
2265 * Release the reserved range from inode dirty range map, as it is
2266 * already moved into delayed_ref_head
2268 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2272 ret = btrfs_alloc_reserved_file_extent(trans, root,
2273 btrfs_ino(BTRFS_I(inode)),
2274 file_pos, qg_released, &ins);
2276 btrfs_free_path(path);
2281 /* snapshot-aware defrag */
2282 struct sa_defrag_extent_backref {
2283 struct rb_node node;
2284 struct old_sa_defrag_extent *old;
2293 struct old_sa_defrag_extent {
2294 struct list_head list;
2295 struct new_sa_defrag_extent *new;
2304 struct new_sa_defrag_extent {
2305 struct rb_root root;
2306 struct list_head head;
2307 struct btrfs_path *path;
2308 struct inode *inode;
2316 static int backref_comp(struct sa_defrag_extent_backref *b1,
2317 struct sa_defrag_extent_backref *b2)
2319 if (b1->root_id < b2->root_id)
2321 else if (b1->root_id > b2->root_id)
2324 if (b1->inum < b2->inum)
2326 else if (b1->inum > b2->inum)
2329 if (b1->file_pos < b2->file_pos)
2331 else if (b1->file_pos > b2->file_pos)
2335 * [------------------------------] ===> (a range of space)
2336 * |<--->| |<---->| =============> (fs/file tree A)
2337 * |<---------------------------->| ===> (fs/file tree B)
2339 * A range of space can refer to two file extents in one tree while
2340 * refer to only one file extent in another tree.
2342 * So we may process a disk offset more than one time(two extents in A)
2343 * and locate at the same extent(one extent in B), then insert two same
2344 * backrefs(both refer to the extent in B).
2349 static void backref_insert(struct rb_root *root,
2350 struct sa_defrag_extent_backref *backref)
2352 struct rb_node **p = &root->rb_node;
2353 struct rb_node *parent = NULL;
2354 struct sa_defrag_extent_backref *entry;
2359 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2361 ret = backref_comp(backref, entry);
2365 p = &(*p)->rb_right;
2368 rb_link_node(&backref->node, parent, p);
2369 rb_insert_color(&backref->node, root);
2373 * Note the backref might has changed, and in this case we just return 0.
2375 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2378 struct btrfs_file_extent_item *extent;
2379 struct old_sa_defrag_extent *old = ctx;
2380 struct new_sa_defrag_extent *new = old->new;
2381 struct btrfs_path *path = new->path;
2382 struct btrfs_key key;
2383 struct btrfs_root *root;
2384 struct sa_defrag_extent_backref *backref;
2385 struct extent_buffer *leaf;
2386 struct inode *inode = new->inode;
2387 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2393 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2394 inum == btrfs_ino(BTRFS_I(inode)))
2397 key.objectid = root_id;
2398 key.type = BTRFS_ROOT_ITEM_KEY;
2399 key.offset = (u64)-1;
2401 root = btrfs_read_fs_root_no_name(fs_info, &key);
2403 if (PTR_ERR(root) == -ENOENT)
2406 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2407 inum, offset, root_id);
2408 return PTR_ERR(root);
2411 key.objectid = inum;
2412 key.type = BTRFS_EXTENT_DATA_KEY;
2413 if (offset > (u64)-1 << 32)
2416 key.offset = offset;
2418 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2419 if (WARN_ON(ret < 0))
2426 leaf = path->nodes[0];
2427 slot = path->slots[0];
2429 if (slot >= btrfs_header_nritems(leaf)) {
2430 ret = btrfs_next_leaf(root, path);
2433 } else if (ret > 0) {
2442 btrfs_item_key_to_cpu(leaf, &key, slot);
2444 if (key.objectid > inum)
2447 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2450 extent = btrfs_item_ptr(leaf, slot,
2451 struct btrfs_file_extent_item);
2453 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2457 * 'offset' refers to the exact key.offset,
2458 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2459 * (key.offset - extent_offset).
2461 if (key.offset != offset)
2464 extent_offset = btrfs_file_extent_offset(leaf, extent);
2465 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2467 if (extent_offset >= old->extent_offset + old->offset +
2468 old->len || extent_offset + num_bytes <=
2469 old->extent_offset + old->offset)
2474 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2480 backref->root_id = root_id;
2481 backref->inum = inum;
2482 backref->file_pos = offset;
2483 backref->num_bytes = num_bytes;
2484 backref->extent_offset = extent_offset;
2485 backref->generation = btrfs_file_extent_generation(leaf, extent);
2487 backref_insert(&new->root, backref);
2490 btrfs_release_path(path);
2495 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2496 struct new_sa_defrag_extent *new)
2498 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2499 struct old_sa_defrag_extent *old, *tmp;
2504 list_for_each_entry_safe(old, tmp, &new->head, list) {
2505 ret = iterate_inodes_from_logical(old->bytenr +
2506 old->extent_offset, fs_info,
2507 path, record_one_backref,
2509 if (ret < 0 && ret != -ENOENT)
2512 /* no backref to be processed for this extent */
2514 list_del(&old->list);
2519 if (list_empty(&new->head))
2525 static int relink_is_mergable(struct extent_buffer *leaf,
2526 struct btrfs_file_extent_item *fi,
2527 struct new_sa_defrag_extent *new)
2529 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2532 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2535 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2538 if (btrfs_file_extent_encryption(leaf, fi) ||
2539 btrfs_file_extent_other_encoding(leaf, fi))
2546 * Note the backref might has changed, and in this case we just return 0.
2548 static noinline int relink_extent_backref(struct btrfs_path *path,
2549 struct sa_defrag_extent_backref *prev,
2550 struct sa_defrag_extent_backref *backref)
2552 struct btrfs_file_extent_item *extent;
2553 struct btrfs_file_extent_item *item;
2554 struct btrfs_ordered_extent *ordered;
2555 struct btrfs_trans_handle *trans;
2556 struct btrfs_ref ref = { 0 };
2557 struct btrfs_root *root;
2558 struct btrfs_key key;
2559 struct extent_buffer *leaf;
2560 struct old_sa_defrag_extent *old = backref->old;
2561 struct new_sa_defrag_extent *new = old->new;
2562 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2563 struct inode *inode;
2564 struct extent_state *cached = NULL;
2573 if (prev && prev->root_id == backref->root_id &&
2574 prev->inum == backref->inum &&
2575 prev->file_pos + prev->num_bytes == backref->file_pos)
2578 /* step 1: get root */
2579 key.objectid = backref->root_id;
2580 key.type = BTRFS_ROOT_ITEM_KEY;
2581 key.offset = (u64)-1;
2583 index = srcu_read_lock(&fs_info->subvol_srcu);
2585 root = btrfs_read_fs_root_no_name(fs_info, &key);
2587 srcu_read_unlock(&fs_info->subvol_srcu, index);
2588 if (PTR_ERR(root) == -ENOENT)
2590 return PTR_ERR(root);
2593 if (btrfs_root_readonly(root)) {
2594 srcu_read_unlock(&fs_info->subvol_srcu, index);
2598 /* step 2: get inode */
2599 key.objectid = backref->inum;
2600 key.type = BTRFS_INODE_ITEM_KEY;
2603 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2604 if (IS_ERR(inode)) {
2605 srcu_read_unlock(&fs_info->subvol_srcu, index);
2609 srcu_read_unlock(&fs_info->subvol_srcu, index);
2611 /* step 3: relink backref */
2612 lock_start = backref->file_pos;
2613 lock_end = backref->file_pos + backref->num_bytes - 1;
2614 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2617 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2619 btrfs_put_ordered_extent(ordered);
2623 trans = btrfs_join_transaction(root);
2624 if (IS_ERR(trans)) {
2625 ret = PTR_ERR(trans);
2629 key.objectid = backref->inum;
2630 key.type = BTRFS_EXTENT_DATA_KEY;
2631 key.offset = backref->file_pos;
2633 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2636 } else if (ret > 0) {
2641 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2642 struct btrfs_file_extent_item);
2644 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2645 backref->generation)
2648 btrfs_release_path(path);
2650 start = backref->file_pos;
2651 if (backref->extent_offset < old->extent_offset + old->offset)
2652 start += old->extent_offset + old->offset -
2653 backref->extent_offset;
2655 len = min(backref->extent_offset + backref->num_bytes,
2656 old->extent_offset + old->offset + old->len);
2657 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2659 ret = btrfs_drop_extents(trans, root, inode, start,
2664 key.objectid = btrfs_ino(BTRFS_I(inode));
2665 key.type = BTRFS_EXTENT_DATA_KEY;
2668 path->leave_spinning = 1;
2670 struct btrfs_file_extent_item *fi;
2672 struct btrfs_key found_key;
2674 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2679 leaf = path->nodes[0];
2680 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2682 fi = btrfs_item_ptr(leaf, path->slots[0],
2683 struct btrfs_file_extent_item);
2684 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2686 if (extent_len + found_key.offset == start &&
2687 relink_is_mergable(leaf, fi, new)) {
2688 btrfs_set_file_extent_num_bytes(leaf, fi,
2690 btrfs_mark_buffer_dirty(leaf);
2691 inode_add_bytes(inode, len);
2697 btrfs_release_path(path);
2702 ret = btrfs_insert_empty_item(trans, root, path, &key,
2705 btrfs_abort_transaction(trans, ret);
2709 leaf = path->nodes[0];
2710 item = btrfs_item_ptr(leaf, path->slots[0],
2711 struct btrfs_file_extent_item);
2712 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2713 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2714 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2715 btrfs_set_file_extent_num_bytes(leaf, item, len);
2716 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2717 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2718 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2719 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2720 btrfs_set_file_extent_encryption(leaf, item, 0);
2721 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2723 btrfs_mark_buffer_dirty(leaf);
2724 inode_add_bytes(inode, len);
2725 btrfs_release_path(path);
2727 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2729 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2730 new->file_pos); /* start - extent_offset */
2731 ret = btrfs_inc_extent_ref(trans, &ref);
2733 btrfs_abort_transaction(trans, ret);
2739 btrfs_release_path(path);
2740 path->leave_spinning = 0;
2741 btrfs_end_transaction(trans);
2743 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2749 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2751 struct old_sa_defrag_extent *old, *tmp;
2756 list_for_each_entry_safe(old, tmp, &new->head, list) {
2762 static void relink_file_extents(struct new_sa_defrag_extent *new)
2764 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2765 struct btrfs_path *path;
2766 struct sa_defrag_extent_backref *backref;
2767 struct sa_defrag_extent_backref *prev = NULL;
2768 struct rb_node *node;
2771 path = btrfs_alloc_path();
2775 if (!record_extent_backrefs(path, new)) {
2776 btrfs_free_path(path);
2779 btrfs_release_path(path);
2782 node = rb_first(&new->root);
2785 rb_erase(node, &new->root);
2787 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2789 ret = relink_extent_backref(path, prev, backref);
2802 btrfs_free_path(path);
2804 free_sa_defrag_extent(new);
2806 atomic_dec(&fs_info->defrag_running);
2807 wake_up(&fs_info->transaction_wait);
2810 static struct new_sa_defrag_extent *
2811 record_old_file_extents(struct inode *inode,
2812 struct btrfs_ordered_extent *ordered)
2814 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2815 struct btrfs_root *root = BTRFS_I(inode)->root;
2816 struct btrfs_path *path;
2817 struct btrfs_key key;
2818 struct old_sa_defrag_extent *old;
2819 struct new_sa_defrag_extent *new;
2822 new = kmalloc(sizeof(*new), GFP_NOFS);
2827 new->file_pos = ordered->file_offset;
2828 new->len = ordered->len;
2829 new->bytenr = ordered->start;
2830 new->disk_len = ordered->disk_len;
2831 new->compress_type = ordered->compress_type;
2832 new->root = RB_ROOT;
2833 INIT_LIST_HEAD(&new->head);
2835 path = btrfs_alloc_path();
2839 key.objectid = btrfs_ino(BTRFS_I(inode));
2840 key.type = BTRFS_EXTENT_DATA_KEY;
2841 key.offset = new->file_pos;
2843 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2846 if (ret > 0 && path->slots[0] > 0)
2849 /* find out all the old extents for the file range */
2851 struct btrfs_file_extent_item *extent;
2852 struct extent_buffer *l;
2861 slot = path->slots[0];
2863 if (slot >= btrfs_header_nritems(l)) {
2864 ret = btrfs_next_leaf(root, path);
2872 btrfs_item_key_to_cpu(l, &key, slot);
2874 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2876 if (key.type != BTRFS_EXTENT_DATA_KEY)
2878 if (key.offset >= new->file_pos + new->len)
2881 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2883 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2884 if (key.offset + num_bytes < new->file_pos)
2887 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2891 extent_offset = btrfs_file_extent_offset(l, extent);
2893 old = kmalloc(sizeof(*old), GFP_NOFS);
2897 offset = max(new->file_pos, key.offset);
2898 end = min(new->file_pos + new->len, key.offset + num_bytes);
2900 old->bytenr = disk_bytenr;
2901 old->extent_offset = extent_offset;
2902 old->offset = offset - key.offset;
2903 old->len = end - offset;
2906 list_add_tail(&old->list, &new->head);
2912 btrfs_free_path(path);
2913 atomic_inc(&fs_info->defrag_running);
2918 btrfs_free_path(path);
2920 free_sa_defrag_extent(new);
2924 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2927 struct btrfs_block_group_cache *cache;
2929 cache = btrfs_lookup_block_group(fs_info, start);
2932 spin_lock(&cache->lock);
2933 cache->delalloc_bytes -= len;
2934 spin_unlock(&cache->lock);
2936 btrfs_put_block_group(cache);
2939 /* as ordered data IO finishes, this gets called so we can finish
2940 * an ordered extent if the range of bytes in the file it covers are
2943 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2945 struct inode *inode = ordered_extent->inode;
2946 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2947 struct btrfs_root *root = BTRFS_I(inode)->root;
2948 struct btrfs_trans_handle *trans = NULL;
2949 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2950 struct extent_state *cached_state = NULL;
2951 struct new_sa_defrag_extent *new = NULL;
2952 int compress_type = 0;
2954 u64 logical_len = ordered_extent->len;
2956 bool truncated = false;
2957 bool range_locked = false;
2958 bool clear_new_delalloc_bytes = false;
2959 bool clear_reserved_extent = true;
2961 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2962 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2963 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2964 clear_new_delalloc_bytes = true;
2966 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2968 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2973 btrfs_free_io_failure_record(BTRFS_I(inode),
2974 ordered_extent->file_offset,
2975 ordered_extent->file_offset +
2976 ordered_extent->len - 1);
2978 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2980 logical_len = ordered_extent->truncated_len;
2981 /* Truncated the entire extent, don't bother adding */
2986 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2987 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2990 * For mwrite(mmap + memset to write) case, we still reserve
2991 * space for NOCOW range.
2992 * As NOCOW won't cause a new delayed ref, just free the space
2994 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2995 ordered_extent->len);
2996 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2998 trans = btrfs_join_transaction_nolock(root);
3000 trans = btrfs_join_transaction(root);
3001 if (IS_ERR(trans)) {
3002 ret = PTR_ERR(trans);
3006 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3007 ret = btrfs_update_inode_fallback(trans, root, inode);
3008 if (ret) /* -ENOMEM or corruption */
3009 btrfs_abort_transaction(trans, ret);
3013 range_locked = true;
3014 lock_extent_bits(io_tree, ordered_extent->file_offset,
3015 ordered_extent->file_offset + ordered_extent->len - 1,
3018 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3019 ordered_extent->file_offset + ordered_extent->len - 1,
3020 EXTENT_DEFRAG, 0, cached_state);
3022 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3023 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3024 /* the inode is shared */
3025 new = record_old_file_extents(inode, ordered_extent);
3027 clear_extent_bit(io_tree, ordered_extent->file_offset,
3028 ordered_extent->file_offset + ordered_extent->len - 1,
3029 EXTENT_DEFRAG, 0, 0, &cached_state);
3033 trans = btrfs_join_transaction_nolock(root);
3035 trans = btrfs_join_transaction(root);
3036 if (IS_ERR(trans)) {
3037 ret = PTR_ERR(trans);
3042 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3044 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3045 compress_type = ordered_extent->compress_type;
3046 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3047 BUG_ON(compress_type);
3048 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3049 ordered_extent->len);
3050 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3051 ordered_extent->file_offset,
3052 ordered_extent->file_offset +
3055 BUG_ON(root == fs_info->tree_root);
3056 ret = insert_reserved_file_extent(trans, inode,
3057 ordered_extent->file_offset,
3058 ordered_extent->start,
3059 ordered_extent->disk_len,
3060 logical_len, logical_len,
3061 compress_type, 0, 0,
3062 BTRFS_FILE_EXTENT_REG);
3064 clear_reserved_extent = false;
3065 btrfs_release_delalloc_bytes(fs_info,
3066 ordered_extent->start,
3067 ordered_extent->disk_len);
3070 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3071 ordered_extent->file_offset, ordered_extent->len,
3074 btrfs_abort_transaction(trans, ret);
3078 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3080 btrfs_abort_transaction(trans, ret);
3084 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3085 ret = btrfs_update_inode_fallback(trans, root, inode);
3086 if (ret) { /* -ENOMEM or corruption */
3087 btrfs_abort_transaction(trans, ret);
3092 if (range_locked || clear_new_delalloc_bytes) {
3093 unsigned int clear_bits = 0;
3096 clear_bits |= EXTENT_LOCKED;
3097 if (clear_new_delalloc_bytes)
3098 clear_bits |= EXTENT_DELALLOC_NEW;
3099 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3100 ordered_extent->file_offset,
3101 ordered_extent->file_offset +
3102 ordered_extent->len - 1,
3104 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3109 btrfs_end_transaction(trans);
3111 if (ret || truncated) {
3115 start = ordered_extent->file_offset + logical_len;
3117 start = ordered_extent->file_offset;
3118 end = ordered_extent->file_offset + ordered_extent->len - 1;
3119 clear_extent_uptodate(io_tree, start, end, NULL);
3121 /* Drop the cache for the part of the extent we didn't write. */
3122 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3125 * If the ordered extent had an IOERR or something else went
3126 * wrong we need to return the space for this ordered extent
3127 * back to the allocator. We only free the extent in the
3128 * truncated case if we didn't write out the extent at all.
3130 * If we made it past insert_reserved_file_extent before we
3131 * errored out then we don't need to do this as the accounting
3132 * has already been done.
3134 if ((ret || !logical_len) &&
3135 clear_reserved_extent &&
3136 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3137 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3138 btrfs_free_reserved_extent(fs_info,
3139 ordered_extent->start,
3140 ordered_extent->disk_len, 1);
3145 * This needs to be done to make sure anybody waiting knows we are done
3146 * updating everything for this ordered extent.
3148 btrfs_remove_ordered_extent(inode, ordered_extent);
3150 /* for snapshot-aware defrag */
3153 free_sa_defrag_extent(new);
3154 atomic_dec(&fs_info->defrag_running);
3156 relink_file_extents(new);
3161 btrfs_put_ordered_extent(ordered_extent);
3162 /* once for the tree */
3163 btrfs_put_ordered_extent(ordered_extent);
3168 static void finish_ordered_fn(struct btrfs_work *work)
3170 struct btrfs_ordered_extent *ordered_extent;
3171 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3172 btrfs_finish_ordered_io(ordered_extent);
3175 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3176 u64 end, int uptodate)
3178 struct inode *inode = page->mapping->host;
3179 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3180 struct btrfs_ordered_extent *ordered_extent = NULL;
3181 struct btrfs_workqueue *wq;
3182 btrfs_work_func_t func;
3184 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3186 ClearPagePrivate2(page);
3187 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3188 end - start + 1, uptodate))
3191 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3192 wq = fs_info->endio_freespace_worker;
3193 func = btrfs_freespace_write_helper;
3195 wq = fs_info->endio_write_workers;
3196 func = btrfs_endio_write_helper;
3199 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3201 btrfs_queue_work(wq, &ordered_extent->work);
3204 static int __readpage_endio_check(struct inode *inode,
3205 struct btrfs_io_bio *io_bio,
3206 int icsum, struct page *page,
3207 int pgoff, u64 start, size_t len)
3209 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3210 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3212 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
3214 u8 csum[BTRFS_CSUM_SIZE];
3216 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
3218 kaddr = kmap_atomic(page);
3219 shash->tfm = fs_info->csum_shash;
3221 crypto_shash_init(shash);
3222 crypto_shash_update(shash, kaddr + pgoff, len);
3223 crypto_shash_final(shash, csum);
3225 if (memcmp(csum, csum_expected, csum_size))
3228 kunmap_atomic(kaddr);
3231 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3232 io_bio->mirror_num);
3233 memset(kaddr + pgoff, 1, len);
3234 flush_dcache_page(page);
3235 kunmap_atomic(kaddr);
3240 * when reads are done, we need to check csums to verify the data is correct
3241 * if there's a match, we allow the bio to finish. If not, the code in
3242 * extent_io.c will try to find good copies for us.
3244 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3245 u64 phy_offset, struct page *page,
3246 u64 start, u64 end, int mirror)
3248 size_t offset = start - page_offset(page);
3249 struct inode *inode = page->mapping->host;
3250 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3251 struct btrfs_root *root = BTRFS_I(inode)->root;
3253 if (PageChecked(page)) {
3254 ClearPageChecked(page);
3258 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3261 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3262 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3263 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3267 phy_offset >>= inode->i_sb->s_blocksize_bits;
3268 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3269 start, (size_t)(end - start + 1));
3273 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3275 * @inode: The inode we want to perform iput on
3277 * This function uses the generic vfs_inode::i_count to track whether we should
3278 * just decrement it (in case it's > 1) or if this is the last iput then link
3279 * the inode to the delayed iput machinery. Delayed iputs are processed at
3280 * transaction commit time/superblock commit/cleaner kthread.
3282 void btrfs_add_delayed_iput(struct inode *inode)
3284 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3285 struct btrfs_inode *binode = BTRFS_I(inode);
3287 if (atomic_add_unless(&inode->i_count, -1, 1))
3290 atomic_inc(&fs_info->nr_delayed_iputs);
3291 spin_lock(&fs_info->delayed_iput_lock);
3292 ASSERT(list_empty(&binode->delayed_iput));
3293 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3294 spin_unlock(&fs_info->delayed_iput_lock);
3295 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3296 wake_up_process(fs_info->cleaner_kthread);
3299 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3300 struct btrfs_inode *inode)
3302 list_del_init(&inode->delayed_iput);
3303 spin_unlock(&fs_info->delayed_iput_lock);
3304 iput(&inode->vfs_inode);
3305 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3306 wake_up(&fs_info->delayed_iputs_wait);
3307 spin_lock(&fs_info->delayed_iput_lock);
3310 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3311 struct btrfs_inode *inode)
3313 if (!list_empty(&inode->delayed_iput)) {
3314 spin_lock(&fs_info->delayed_iput_lock);
3315 if (!list_empty(&inode->delayed_iput))
3316 run_delayed_iput_locked(fs_info, inode);
3317 spin_unlock(&fs_info->delayed_iput_lock);
3321 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3324 spin_lock(&fs_info->delayed_iput_lock);
3325 while (!list_empty(&fs_info->delayed_iputs)) {
3326 struct btrfs_inode *inode;
3328 inode = list_first_entry(&fs_info->delayed_iputs,
3329 struct btrfs_inode, delayed_iput);
3330 run_delayed_iput_locked(fs_info, inode);
3332 spin_unlock(&fs_info->delayed_iput_lock);
3336 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3337 * @fs_info - the fs_info for this fs
3338 * @return - EINTR if we were killed, 0 if nothing's pending
3340 * This will wait on any delayed iputs that are currently running with KILLABLE
3341 * set. Once they are all done running we will return, unless we are killed in
3342 * which case we return EINTR. This helps in user operations like fallocate etc
3343 * that might get blocked on the iputs.
3345 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3347 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3348 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3355 * This creates an orphan entry for the given inode in case something goes wrong
3356 * in the middle of an unlink.
3358 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3359 struct btrfs_inode *inode)
3363 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3364 if (ret && ret != -EEXIST) {
3365 btrfs_abort_transaction(trans, ret);
3373 * We have done the delete so we can go ahead and remove the orphan item for
3374 * this particular inode.
3376 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3377 struct btrfs_inode *inode)
3379 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3383 * this cleans up any orphans that may be left on the list from the last use
3386 int btrfs_orphan_cleanup(struct btrfs_root *root)
3388 struct btrfs_fs_info *fs_info = root->fs_info;
3389 struct btrfs_path *path;
3390 struct extent_buffer *leaf;
3391 struct btrfs_key key, found_key;
3392 struct btrfs_trans_handle *trans;
3393 struct inode *inode;
3394 u64 last_objectid = 0;
3395 int ret = 0, nr_unlink = 0;
3397 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3400 path = btrfs_alloc_path();
3405 path->reada = READA_BACK;
3407 key.objectid = BTRFS_ORPHAN_OBJECTID;
3408 key.type = BTRFS_ORPHAN_ITEM_KEY;
3409 key.offset = (u64)-1;
3412 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3417 * if ret == 0 means we found what we were searching for, which
3418 * is weird, but possible, so only screw with path if we didn't
3419 * find the key and see if we have stuff that matches
3423 if (path->slots[0] == 0)
3428 /* pull out the item */
3429 leaf = path->nodes[0];
3430 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3432 /* make sure the item matches what we want */
3433 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3435 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3438 /* release the path since we're done with it */
3439 btrfs_release_path(path);
3442 * this is where we are basically btrfs_lookup, without the
3443 * crossing root thing. we store the inode number in the
3444 * offset of the orphan item.
3447 if (found_key.offset == last_objectid) {
3449 "Error removing orphan entry, stopping orphan cleanup");
3454 last_objectid = found_key.offset;
3456 found_key.objectid = found_key.offset;
3457 found_key.type = BTRFS_INODE_ITEM_KEY;
3458 found_key.offset = 0;
3459 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3460 ret = PTR_ERR_OR_ZERO(inode);
3461 if (ret && ret != -ENOENT)
3464 if (ret == -ENOENT && root == fs_info->tree_root) {
3465 struct btrfs_root *dead_root;
3466 struct btrfs_fs_info *fs_info = root->fs_info;
3467 int is_dead_root = 0;
3470 * this is an orphan in the tree root. Currently these
3471 * could come from 2 sources:
3472 * a) a snapshot deletion in progress
3473 * b) a free space cache inode
3474 * We need to distinguish those two, as the snapshot
3475 * orphan must not get deleted.
3476 * find_dead_roots already ran before us, so if this
3477 * is a snapshot deletion, we should find the root
3478 * in the dead_roots list
3480 spin_lock(&fs_info->trans_lock);
3481 list_for_each_entry(dead_root, &fs_info->dead_roots,
3483 if (dead_root->root_key.objectid ==
3484 found_key.objectid) {
3489 spin_unlock(&fs_info->trans_lock);
3491 /* prevent this orphan from being found again */
3492 key.offset = found_key.objectid - 1;
3499 * If we have an inode with links, there are a couple of
3500 * possibilities. Old kernels (before v3.12) used to create an
3501 * orphan item for truncate indicating that there were possibly
3502 * extent items past i_size that needed to be deleted. In v3.12,
3503 * truncate was changed to update i_size in sync with the extent
3504 * items, but the (useless) orphan item was still created. Since
3505 * v4.18, we don't create the orphan item for truncate at all.
3507 * So, this item could mean that we need to do a truncate, but
3508 * only if this filesystem was last used on a pre-v3.12 kernel
3509 * and was not cleanly unmounted. The odds of that are quite
3510 * slim, and it's a pain to do the truncate now, so just delete
3513 * It's also possible that this orphan item was supposed to be
3514 * deleted but wasn't. The inode number may have been reused,
3515 * but either way, we can delete the orphan item.
3517 if (ret == -ENOENT || inode->i_nlink) {
3520 trans = btrfs_start_transaction(root, 1);
3521 if (IS_ERR(trans)) {
3522 ret = PTR_ERR(trans);
3525 btrfs_debug(fs_info, "auto deleting %Lu",
3526 found_key.objectid);
3527 ret = btrfs_del_orphan_item(trans, root,
3528 found_key.objectid);
3529 btrfs_end_transaction(trans);
3537 /* this will do delete_inode and everything for us */
3540 /* release the path since we're done with it */
3541 btrfs_release_path(path);
3543 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3545 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3546 trans = btrfs_join_transaction(root);
3548 btrfs_end_transaction(trans);
3552 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3556 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3557 btrfs_free_path(path);
3562 * very simple check to peek ahead in the leaf looking for xattrs. If we
3563 * don't find any xattrs, we know there can't be any acls.
3565 * slot is the slot the inode is in, objectid is the objectid of the inode
3567 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3568 int slot, u64 objectid,
3569 int *first_xattr_slot)
3571 u32 nritems = btrfs_header_nritems(leaf);
3572 struct btrfs_key found_key;
3573 static u64 xattr_access = 0;
3574 static u64 xattr_default = 0;
3577 if (!xattr_access) {
3578 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3579 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3580 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3581 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3585 *first_xattr_slot = -1;
3586 while (slot < nritems) {
3587 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3589 /* we found a different objectid, there must not be acls */
3590 if (found_key.objectid != objectid)
3593 /* we found an xattr, assume we've got an acl */
3594 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3595 if (*first_xattr_slot == -1)
3596 *first_xattr_slot = slot;
3597 if (found_key.offset == xattr_access ||
3598 found_key.offset == xattr_default)
3603 * we found a key greater than an xattr key, there can't
3604 * be any acls later on
3606 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3613 * it goes inode, inode backrefs, xattrs, extents,
3614 * so if there are a ton of hard links to an inode there can
3615 * be a lot of backrefs. Don't waste time searching too hard,
3616 * this is just an optimization
3621 /* we hit the end of the leaf before we found an xattr or
3622 * something larger than an xattr. We have to assume the inode
3625 if (*first_xattr_slot == -1)
3626 *first_xattr_slot = slot;
3631 * read an inode from the btree into the in-memory inode
3633 static int btrfs_read_locked_inode(struct inode *inode,
3634 struct btrfs_path *in_path)
3636 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3637 struct btrfs_path *path = in_path;
3638 struct extent_buffer *leaf;
3639 struct btrfs_inode_item *inode_item;
3640 struct btrfs_root *root = BTRFS_I(inode)->root;
3641 struct btrfs_key location;
3646 bool filled = false;
3647 int first_xattr_slot;
3649 ret = btrfs_fill_inode(inode, &rdev);
3654 path = btrfs_alloc_path();
3659 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3661 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3663 if (path != in_path)
3664 btrfs_free_path(path);
3668 leaf = path->nodes[0];
3673 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3674 struct btrfs_inode_item);
3675 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3676 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3677 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3678 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3679 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3681 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3682 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3684 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3685 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3687 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3688 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3690 BTRFS_I(inode)->i_otime.tv_sec =
3691 btrfs_timespec_sec(leaf, &inode_item->otime);
3692 BTRFS_I(inode)->i_otime.tv_nsec =
3693 btrfs_timespec_nsec(leaf, &inode_item->otime);
3695 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3696 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3697 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3699 inode_set_iversion_queried(inode,
3700 btrfs_inode_sequence(leaf, inode_item));
3701 inode->i_generation = BTRFS_I(inode)->generation;
3703 rdev = btrfs_inode_rdev(leaf, inode_item);
3705 BTRFS_I(inode)->index_cnt = (u64)-1;
3706 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3710 * If we were modified in the current generation and evicted from memory
3711 * and then re-read we need to do a full sync since we don't have any
3712 * idea about which extents were modified before we were evicted from
3715 * This is required for both inode re-read from disk and delayed inode
3716 * in delayed_nodes_tree.
3718 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3719 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3720 &BTRFS_I(inode)->runtime_flags);
3723 * We don't persist the id of the transaction where an unlink operation
3724 * against the inode was last made. So here we assume the inode might
3725 * have been evicted, and therefore the exact value of last_unlink_trans
3726 * lost, and set it to last_trans to avoid metadata inconsistencies
3727 * between the inode and its parent if the inode is fsync'ed and the log
3728 * replayed. For example, in the scenario:
3731 * ln mydir/foo mydir/bar
3734 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3735 * xfs_io -c fsync mydir/foo
3737 * mount fs, triggers fsync log replay
3739 * We must make sure that when we fsync our inode foo we also log its
3740 * parent inode, otherwise after log replay the parent still has the
3741 * dentry with the "bar" name but our inode foo has a link count of 1
3742 * and doesn't have an inode ref with the name "bar" anymore.
3744 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3745 * but it guarantees correctness at the expense of occasional full
3746 * transaction commits on fsync if our inode is a directory, or if our
3747 * inode is not a directory, logging its parent unnecessarily.
3749 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3752 if (inode->i_nlink != 1 ||
3753 path->slots[0] >= btrfs_header_nritems(leaf))
3756 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3757 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3760 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3761 if (location.type == BTRFS_INODE_REF_KEY) {
3762 struct btrfs_inode_ref *ref;
3764 ref = (struct btrfs_inode_ref *)ptr;
3765 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3766 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3767 struct btrfs_inode_extref *extref;
3769 extref = (struct btrfs_inode_extref *)ptr;
3770 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3775 * try to precache a NULL acl entry for files that don't have
3776 * any xattrs or acls
3778 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3779 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3780 if (first_xattr_slot != -1) {
3781 path->slots[0] = first_xattr_slot;
3782 ret = btrfs_load_inode_props(inode, path);
3785 "error loading props for ino %llu (root %llu): %d",
3786 btrfs_ino(BTRFS_I(inode)),
3787 root->root_key.objectid, ret);
3789 if (path != in_path)
3790 btrfs_free_path(path);
3793 cache_no_acl(inode);
3795 switch (inode->i_mode & S_IFMT) {
3797 inode->i_mapping->a_ops = &btrfs_aops;
3798 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3799 inode->i_fop = &btrfs_file_operations;
3800 inode->i_op = &btrfs_file_inode_operations;
3803 inode->i_fop = &btrfs_dir_file_operations;
3804 inode->i_op = &btrfs_dir_inode_operations;
3807 inode->i_op = &btrfs_symlink_inode_operations;
3808 inode_nohighmem(inode);
3809 inode->i_mapping->a_ops = &btrfs_aops;
3812 inode->i_op = &btrfs_special_inode_operations;
3813 init_special_inode(inode, inode->i_mode, rdev);
3817 btrfs_sync_inode_flags_to_i_flags(inode);
3822 * given a leaf and an inode, copy the inode fields into the leaf
3824 static void fill_inode_item(struct btrfs_trans_handle *trans,
3825 struct extent_buffer *leaf,
3826 struct btrfs_inode_item *item,
3827 struct inode *inode)
3829 struct btrfs_map_token token;
3831 btrfs_init_map_token(&token);
3833 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3834 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3835 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3837 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3838 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3840 btrfs_set_token_timespec_sec(leaf, &item->atime,
3841 inode->i_atime.tv_sec, &token);
3842 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3843 inode->i_atime.tv_nsec, &token);
3845 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3846 inode->i_mtime.tv_sec, &token);
3847 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3848 inode->i_mtime.tv_nsec, &token);
3850 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3851 inode->i_ctime.tv_sec, &token);
3852 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3853 inode->i_ctime.tv_nsec, &token);
3855 btrfs_set_token_timespec_sec(leaf, &item->otime,
3856 BTRFS_I(inode)->i_otime.tv_sec, &token);
3857 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3858 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3860 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3862 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3864 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3866 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3867 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3868 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3869 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3873 * copy everything in the in-memory inode into the btree.
3875 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3876 struct btrfs_root *root, struct inode *inode)
3878 struct btrfs_inode_item *inode_item;
3879 struct btrfs_path *path;
3880 struct extent_buffer *leaf;
3883 path = btrfs_alloc_path();
3887 path->leave_spinning = 1;
3888 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3896 leaf = path->nodes[0];
3897 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3898 struct btrfs_inode_item);
3900 fill_inode_item(trans, leaf, inode_item, inode);
3901 btrfs_mark_buffer_dirty(leaf);
3902 btrfs_set_inode_last_trans(trans, inode);
3905 btrfs_free_path(path);
3910 * copy everything in the in-memory inode into the btree.
3912 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3913 struct btrfs_root *root, struct inode *inode)
3915 struct btrfs_fs_info *fs_info = root->fs_info;
3919 * If the inode is a free space inode, we can deadlock during commit
3920 * if we put it into the delayed code.
3922 * The data relocation inode should also be directly updated
3925 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3926 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3927 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3928 btrfs_update_root_times(trans, root);
3930 ret = btrfs_delayed_update_inode(trans, root, inode);
3932 btrfs_set_inode_last_trans(trans, inode);
3936 return btrfs_update_inode_item(trans, root, inode);
3939 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3940 struct btrfs_root *root,
3941 struct inode *inode)
3945 ret = btrfs_update_inode(trans, root, inode);
3947 return btrfs_update_inode_item(trans, root, inode);
3952 * unlink helper that gets used here in inode.c and in the tree logging
3953 * recovery code. It remove a link in a directory with a given name, and
3954 * also drops the back refs in the inode to the directory
3956 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3957 struct btrfs_root *root,
3958 struct btrfs_inode *dir,
3959 struct btrfs_inode *inode,
3960 const char *name, int name_len)
3962 struct btrfs_fs_info *fs_info = root->fs_info;
3963 struct btrfs_path *path;
3965 struct btrfs_dir_item *di;
3967 u64 ino = btrfs_ino(inode);
3968 u64 dir_ino = btrfs_ino(dir);
3970 path = btrfs_alloc_path();
3976 path->leave_spinning = 1;
3977 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3978 name, name_len, -1);
3979 if (IS_ERR_OR_NULL(di)) {
3980 ret = di ? PTR_ERR(di) : -ENOENT;
3983 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3986 btrfs_release_path(path);
3989 * If we don't have dir index, we have to get it by looking up
3990 * the inode ref, since we get the inode ref, remove it directly,
3991 * it is unnecessary to do delayed deletion.
3993 * But if we have dir index, needn't search inode ref to get it.
3994 * Since the inode ref is close to the inode item, it is better
3995 * that we delay to delete it, and just do this deletion when
3996 * we update the inode item.
3998 if (inode->dir_index) {
3999 ret = btrfs_delayed_delete_inode_ref(inode);
4001 index = inode->dir_index;
4006 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4010 "failed to delete reference to %.*s, inode %llu parent %llu",
4011 name_len, name, ino, dir_ino);
4012 btrfs_abort_transaction(trans, ret);
4016 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4018 btrfs_abort_transaction(trans, ret);
4022 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4024 if (ret != 0 && ret != -ENOENT) {
4025 btrfs_abort_transaction(trans, ret);
4029 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4034 btrfs_abort_transaction(trans, ret);
4037 * If we have a pending delayed iput we could end up with the final iput
4038 * being run in btrfs-cleaner context. If we have enough of these built
4039 * up we can end up burning a lot of time in btrfs-cleaner without any
4040 * way to throttle the unlinks. Since we're currently holding a ref on
4041 * the inode we can run the delayed iput here without any issues as the
4042 * final iput won't be done until after we drop the ref we're currently
4045 btrfs_run_delayed_iput(fs_info, inode);
4047 btrfs_free_path(path);
4051 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4052 inode_inc_iversion(&inode->vfs_inode);
4053 inode_inc_iversion(&dir->vfs_inode);
4054 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4055 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4056 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4061 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4062 struct btrfs_root *root,
4063 struct btrfs_inode *dir, struct btrfs_inode *inode,
4064 const char *name, int name_len)
4067 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4069 drop_nlink(&inode->vfs_inode);
4070 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4076 * helper to start transaction for unlink and rmdir.
4078 * unlink and rmdir are special in btrfs, they do not always free space, so
4079 * if we cannot make our reservations the normal way try and see if there is
4080 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4081 * allow the unlink to occur.
4083 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4085 struct btrfs_root *root = BTRFS_I(dir)->root;
4088 * 1 for the possible orphan item
4089 * 1 for the dir item
4090 * 1 for the dir index
4091 * 1 for the inode ref
4094 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4097 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4099 struct btrfs_root *root = BTRFS_I(dir)->root;
4100 struct btrfs_trans_handle *trans;
4101 struct inode *inode = d_inode(dentry);
4104 trans = __unlink_start_trans(dir);
4106 return PTR_ERR(trans);
4108 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4111 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4112 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4113 dentry->d_name.len);
4117 if (inode->i_nlink == 0) {
4118 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4124 btrfs_end_transaction(trans);
4125 btrfs_btree_balance_dirty(root->fs_info);
4129 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4130 struct inode *dir, u64 objectid,
4131 const char *name, int name_len)
4133 struct btrfs_root *root = BTRFS_I(dir)->root;
4134 struct btrfs_path *path;
4135 struct extent_buffer *leaf;
4136 struct btrfs_dir_item *di;
4137 struct btrfs_key key;
4140 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4142 path = btrfs_alloc_path();
4146 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4147 name, name_len, -1);
4148 if (IS_ERR_OR_NULL(di)) {
4149 ret = di ? PTR_ERR(di) : -ENOENT;
4153 leaf = path->nodes[0];
4154 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4155 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4156 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4158 btrfs_abort_transaction(trans, ret);
4161 btrfs_release_path(path);
4163 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4164 dir_ino, &index, name, name_len);
4166 if (ret != -ENOENT) {
4167 btrfs_abort_transaction(trans, ret);
4170 di = btrfs_search_dir_index_item(root, path, dir_ino,
4172 if (IS_ERR_OR_NULL(di)) {
4177 btrfs_abort_transaction(trans, ret);
4181 leaf = path->nodes[0];
4182 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4185 btrfs_release_path(path);
4187 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4189 btrfs_abort_transaction(trans, ret);
4193 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4194 inode_inc_iversion(dir);
4195 dir->i_mtime = dir->i_ctime = current_time(dir);
4196 ret = btrfs_update_inode_fallback(trans, root, dir);
4198 btrfs_abort_transaction(trans, ret);
4200 btrfs_free_path(path);
4205 * Helper to check if the subvolume references other subvolumes or if it's
4208 static noinline int may_destroy_subvol(struct btrfs_root *root)
4210 struct btrfs_fs_info *fs_info = root->fs_info;
4211 struct btrfs_path *path;
4212 struct btrfs_dir_item *di;
4213 struct btrfs_key key;
4217 path = btrfs_alloc_path();
4221 /* Make sure this root isn't set as the default subvol */
4222 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4223 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4224 dir_id, "default", 7, 0);
4225 if (di && !IS_ERR(di)) {
4226 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4227 if (key.objectid == root->root_key.objectid) {
4230 "deleting default subvolume %llu is not allowed",
4234 btrfs_release_path(path);
4237 key.objectid = root->root_key.objectid;
4238 key.type = BTRFS_ROOT_REF_KEY;
4239 key.offset = (u64)-1;
4241 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4247 if (path->slots[0] > 0) {
4249 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4250 if (key.objectid == root->root_key.objectid &&
4251 key.type == BTRFS_ROOT_REF_KEY)
4255 btrfs_free_path(path);
4259 /* Delete all dentries for inodes belonging to the root */
4260 static void btrfs_prune_dentries(struct btrfs_root *root)
4262 struct btrfs_fs_info *fs_info = root->fs_info;
4263 struct rb_node *node;
4264 struct rb_node *prev;
4265 struct btrfs_inode *entry;
4266 struct inode *inode;
4269 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4270 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4272 spin_lock(&root->inode_lock);
4274 node = root->inode_tree.rb_node;
4278 entry = rb_entry(node, struct btrfs_inode, rb_node);
4280 if (objectid < btrfs_ino(entry))
4281 node = node->rb_left;
4282 else if (objectid > btrfs_ino(entry))
4283 node = node->rb_right;
4289 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4290 if (objectid <= btrfs_ino(entry)) {
4294 prev = rb_next(prev);
4298 entry = rb_entry(node, struct btrfs_inode, rb_node);
4299 objectid = btrfs_ino(entry) + 1;
4300 inode = igrab(&entry->vfs_inode);
4302 spin_unlock(&root->inode_lock);
4303 if (atomic_read(&inode->i_count) > 1)
4304 d_prune_aliases(inode);
4306 * btrfs_drop_inode will have it removed from the inode
4307 * cache when its usage count hits zero.
4311 spin_lock(&root->inode_lock);
4315 if (cond_resched_lock(&root->inode_lock))
4318 node = rb_next(node);
4320 spin_unlock(&root->inode_lock);
4323 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4325 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4326 struct btrfs_root *root = BTRFS_I(dir)->root;
4327 struct inode *inode = d_inode(dentry);
4328 struct btrfs_root *dest = BTRFS_I(inode)->root;
4329 struct btrfs_trans_handle *trans;
4330 struct btrfs_block_rsv block_rsv;
4336 * Don't allow to delete a subvolume with send in progress. This is
4337 * inside the inode lock so the error handling that has to drop the bit
4338 * again is not run concurrently.
4340 spin_lock(&dest->root_item_lock);
4341 if (dest->send_in_progress) {
4342 spin_unlock(&dest->root_item_lock);
4344 "attempt to delete subvolume %llu during send",
4345 dest->root_key.objectid);
4348 root_flags = btrfs_root_flags(&dest->root_item);
4349 btrfs_set_root_flags(&dest->root_item,
4350 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4351 spin_unlock(&dest->root_item_lock);
4353 down_write(&fs_info->subvol_sem);
4355 err = may_destroy_subvol(dest);
4359 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4361 * One for dir inode,
4362 * two for dir entries,
4363 * two for root ref/backref.
4365 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4369 trans = btrfs_start_transaction(root, 0);
4370 if (IS_ERR(trans)) {
4371 err = PTR_ERR(trans);
4374 trans->block_rsv = &block_rsv;
4375 trans->bytes_reserved = block_rsv.size;
4377 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4379 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4380 dentry->d_name.name, dentry->d_name.len);
4383 btrfs_abort_transaction(trans, ret);
4387 btrfs_record_root_in_trans(trans, dest);
4389 memset(&dest->root_item.drop_progress, 0,
4390 sizeof(dest->root_item.drop_progress));
4391 dest->root_item.drop_level = 0;
4392 btrfs_set_root_refs(&dest->root_item, 0);
4394 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4395 ret = btrfs_insert_orphan_item(trans,
4397 dest->root_key.objectid);
4399 btrfs_abort_transaction(trans, ret);
4405 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4406 BTRFS_UUID_KEY_SUBVOL,
4407 dest->root_key.objectid);
4408 if (ret && ret != -ENOENT) {
4409 btrfs_abort_transaction(trans, ret);
4413 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4414 ret = btrfs_uuid_tree_remove(trans,
4415 dest->root_item.received_uuid,
4416 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4417 dest->root_key.objectid);
4418 if (ret && ret != -ENOENT) {
4419 btrfs_abort_transaction(trans, ret);
4426 trans->block_rsv = NULL;
4427 trans->bytes_reserved = 0;
4428 ret = btrfs_end_transaction(trans);
4431 inode->i_flags |= S_DEAD;
4433 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4435 up_write(&fs_info->subvol_sem);
4437 spin_lock(&dest->root_item_lock);
4438 root_flags = btrfs_root_flags(&dest->root_item);
4439 btrfs_set_root_flags(&dest->root_item,
4440 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4441 spin_unlock(&dest->root_item_lock);
4443 d_invalidate(dentry);
4444 btrfs_prune_dentries(dest);
4445 ASSERT(dest->send_in_progress == 0);
4448 if (dest->ino_cache_inode) {
4449 iput(dest->ino_cache_inode);
4450 dest->ino_cache_inode = NULL;
4457 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4459 struct inode *inode = d_inode(dentry);
4461 struct btrfs_root *root = BTRFS_I(dir)->root;
4462 struct btrfs_trans_handle *trans;
4463 u64 last_unlink_trans;
4465 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4467 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4468 return btrfs_delete_subvolume(dir, dentry);
4470 trans = __unlink_start_trans(dir);
4472 return PTR_ERR(trans);
4474 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4475 err = btrfs_unlink_subvol(trans, dir,
4476 BTRFS_I(inode)->location.objectid,
4477 dentry->d_name.name,
4478 dentry->d_name.len);
4482 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4486 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4488 /* now the directory is empty */
4489 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4490 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4491 dentry->d_name.len);
4493 btrfs_i_size_write(BTRFS_I(inode), 0);
4495 * Propagate the last_unlink_trans value of the deleted dir to
4496 * its parent directory. This is to prevent an unrecoverable
4497 * log tree in the case we do something like this:
4499 * 2) create snapshot under dir foo
4500 * 3) delete the snapshot
4503 * 6) fsync foo or some file inside foo
4505 if (last_unlink_trans >= trans->transid)
4506 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4509 btrfs_end_transaction(trans);
4510 btrfs_btree_balance_dirty(root->fs_info);
4516 * Return this if we need to call truncate_block for the last bit of the
4519 #define NEED_TRUNCATE_BLOCK 1
4522 * this can truncate away extent items, csum items and directory items.
4523 * It starts at a high offset and removes keys until it can't find
4524 * any higher than new_size
4526 * csum items that cross the new i_size are truncated to the new size
4529 * min_type is the minimum key type to truncate down to. If set to 0, this
4530 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4532 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4533 struct btrfs_root *root,
4534 struct inode *inode,
4535 u64 new_size, u32 min_type)
4537 struct btrfs_fs_info *fs_info = root->fs_info;
4538 struct btrfs_path *path;
4539 struct extent_buffer *leaf;
4540 struct btrfs_file_extent_item *fi;
4541 struct btrfs_key key;
4542 struct btrfs_key found_key;
4543 u64 extent_start = 0;
4544 u64 extent_num_bytes = 0;
4545 u64 extent_offset = 0;
4547 u64 last_size = new_size;
4548 u32 found_type = (u8)-1;
4551 int pending_del_nr = 0;
4552 int pending_del_slot = 0;
4553 int extent_type = -1;
4555 u64 ino = btrfs_ino(BTRFS_I(inode));
4556 u64 bytes_deleted = 0;
4557 bool be_nice = false;
4558 bool should_throttle = false;
4560 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4563 * for non-free space inodes and ref cows, we want to back off from
4566 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4567 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4570 path = btrfs_alloc_path();
4573 path->reada = READA_BACK;
4576 * We want to drop from the next block forward in case this new size is
4577 * not block aligned since we will be keeping the last block of the
4578 * extent just the way it is.
4580 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4581 root == fs_info->tree_root)
4582 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4583 fs_info->sectorsize),
4587 * This function is also used to drop the items in the log tree before
4588 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4589 * it is used to drop the logged items. So we shouldn't kill the delayed
4592 if (min_type == 0 && root == BTRFS_I(inode)->root)
4593 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4596 key.offset = (u64)-1;
4601 * with a 16K leaf size and 128MB extents, you can actually queue
4602 * up a huge file in a single leaf. Most of the time that
4603 * bytes_deleted is > 0, it will be huge by the time we get here
4605 if (be_nice && bytes_deleted > SZ_32M &&
4606 btrfs_should_end_transaction(trans)) {
4611 path->leave_spinning = 1;
4612 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4618 /* there are no items in the tree for us to truncate, we're
4621 if (path->slots[0] == 0)
4628 leaf = path->nodes[0];
4629 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4630 found_type = found_key.type;
4632 if (found_key.objectid != ino)
4635 if (found_type < min_type)
4638 item_end = found_key.offset;
4639 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4640 fi = btrfs_item_ptr(leaf, path->slots[0],
4641 struct btrfs_file_extent_item);
4642 extent_type = btrfs_file_extent_type(leaf, fi);
4643 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4645 btrfs_file_extent_num_bytes(leaf, fi);
4647 trace_btrfs_truncate_show_fi_regular(
4648 BTRFS_I(inode), leaf, fi,
4650 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4651 item_end += btrfs_file_extent_ram_bytes(leaf,
4654 trace_btrfs_truncate_show_fi_inline(
4655 BTRFS_I(inode), leaf, fi, path->slots[0],
4660 if (found_type > min_type) {
4663 if (item_end < new_size)
4665 if (found_key.offset >= new_size)
4671 /* FIXME, shrink the extent if the ref count is only 1 */
4672 if (found_type != BTRFS_EXTENT_DATA_KEY)
4675 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4677 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4679 u64 orig_num_bytes =
4680 btrfs_file_extent_num_bytes(leaf, fi);
4681 extent_num_bytes = ALIGN(new_size -
4683 fs_info->sectorsize);
4684 btrfs_set_file_extent_num_bytes(leaf, fi,
4686 num_dec = (orig_num_bytes -
4688 if (test_bit(BTRFS_ROOT_REF_COWS,
4691 inode_sub_bytes(inode, num_dec);
4692 btrfs_mark_buffer_dirty(leaf);
4695 btrfs_file_extent_disk_num_bytes(leaf,
4697 extent_offset = found_key.offset -
4698 btrfs_file_extent_offset(leaf, fi);
4700 /* FIXME blocksize != 4096 */
4701 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4702 if (extent_start != 0) {
4704 if (test_bit(BTRFS_ROOT_REF_COWS,
4706 inode_sub_bytes(inode, num_dec);
4709 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4711 * we can't truncate inline items that have had
4715 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4716 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4717 btrfs_file_extent_compression(leaf, fi) == 0) {
4718 u32 size = (u32)(new_size - found_key.offset);
4720 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4721 size = btrfs_file_extent_calc_inline_size(size);
4722 btrfs_truncate_item(path, size, 1);
4723 } else if (!del_item) {
4725 * We have to bail so the last_size is set to
4726 * just before this extent.
4728 ret = NEED_TRUNCATE_BLOCK;
4732 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4733 inode_sub_bytes(inode, item_end + 1 - new_size);
4737 last_size = found_key.offset;
4739 last_size = new_size;
4741 if (!pending_del_nr) {
4742 /* no pending yet, add ourselves */
4743 pending_del_slot = path->slots[0];
4745 } else if (pending_del_nr &&
4746 path->slots[0] + 1 == pending_del_slot) {
4747 /* hop on the pending chunk */
4749 pending_del_slot = path->slots[0];
4756 should_throttle = false;
4759 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4760 root == fs_info->tree_root)) {
4761 struct btrfs_ref ref = { 0 };
4763 btrfs_set_path_blocking(path);
4764 bytes_deleted += extent_num_bytes;
4766 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4767 extent_start, extent_num_bytes, 0);
4768 ref.real_root = root->root_key.objectid;
4769 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4770 ino, extent_offset);
4771 ret = btrfs_free_extent(trans, &ref);
4773 btrfs_abort_transaction(trans, ret);
4777 if (btrfs_should_throttle_delayed_refs(trans))
4778 should_throttle = true;
4782 if (found_type == BTRFS_INODE_ITEM_KEY)
4785 if (path->slots[0] == 0 ||
4786 path->slots[0] != pending_del_slot ||
4788 if (pending_del_nr) {
4789 ret = btrfs_del_items(trans, root, path,
4793 btrfs_abort_transaction(trans, ret);
4798 btrfs_release_path(path);
4801 * We can generate a lot of delayed refs, so we need to
4802 * throttle every once and a while and make sure we're
4803 * adding enough space to keep up with the work we are
4804 * generating. Since we hold a transaction here we
4805 * can't flush, and we don't want to FLUSH_LIMIT because
4806 * we could have generated too many delayed refs to
4807 * actually allocate, so just bail if we're short and
4808 * let the normal reservation dance happen higher up.
4810 if (should_throttle) {
4811 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4812 BTRFS_RESERVE_NO_FLUSH);
4824 if (ret >= 0 && pending_del_nr) {
4827 err = btrfs_del_items(trans, root, path, pending_del_slot,
4830 btrfs_abort_transaction(trans, err);
4834 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4835 ASSERT(last_size >= new_size);
4836 if (!ret && last_size > new_size)
4837 last_size = new_size;
4838 btrfs_ordered_update_i_size(inode, last_size, NULL);
4841 btrfs_free_path(path);
4846 * btrfs_truncate_block - read, zero a chunk and write a block
4847 * @inode - inode that we're zeroing
4848 * @from - the offset to start zeroing
4849 * @len - the length to zero, 0 to zero the entire range respective to the
4851 * @front - zero up to the offset instead of from the offset on
4853 * This will find the block for the "from" offset and cow the block and zero the
4854 * part we want to zero. This is used with truncate and hole punching.
4856 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4859 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4860 struct address_space *mapping = inode->i_mapping;
4861 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4862 struct btrfs_ordered_extent *ordered;
4863 struct extent_state *cached_state = NULL;
4864 struct extent_changeset *data_reserved = NULL;
4866 u32 blocksize = fs_info->sectorsize;
4867 pgoff_t index = from >> PAGE_SHIFT;
4868 unsigned offset = from & (blocksize - 1);
4870 gfp_t mask = btrfs_alloc_write_mask(mapping);
4875 if (IS_ALIGNED(offset, blocksize) &&
4876 (!len || IS_ALIGNED(len, blocksize)))
4879 block_start = round_down(from, blocksize);
4880 block_end = block_start + blocksize - 1;
4882 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4883 block_start, blocksize);
4888 page = find_or_create_page(mapping, index, mask);
4890 btrfs_delalloc_release_space(inode, data_reserved,
4891 block_start, blocksize, true);
4892 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4897 if (!PageUptodate(page)) {
4898 ret = btrfs_readpage(NULL, page);
4900 if (page->mapping != mapping) {
4905 if (!PageUptodate(page)) {
4910 wait_on_page_writeback(page);
4912 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4913 set_page_extent_mapped(page);
4915 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4917 unlock_extent_cached(io_tree, block_start, block_end,
4921 btrfs_start_ordered_extent(inode, ordered, 1);
4922 btrfs_put_ordered_extent(ordered);
4926 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4927 EXTENT_DIRTY | EXTENT_DELALLOC |
4928 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4929 0, 0, &cached_state);
4931 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4934 unlock_extent_cached(io_tree, block_start, block_end,
4939 if (offset != blocksize) {
4941 len = blocksize - offset;
4944 memset(kaddr + (block_start - page_offset(page)),
4947 memset(kaddr + (block_start - page_offset(page)) + offset,
4949 flush_dcache_page(page);
4952 ClearPageChecked(page);
4953 set_page_dirty(page);
4954 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4958 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4960 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4964 extent_changeset_free(data_reserved);
4968 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4969 u64 offset, u64 len)
4971 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4972 struct btrfs_trans_handle *trans;
4976 * Still need to make sure the inode looks like it's been updated so
4977 * that any holes get logged if we fsync.
4979 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4980 BTRFS_I(inode)->last_trans = fs_info->generation;
4981 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4982 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4987 * 1 - for the one we're dropping
4988 * 1 - for the one we're adding
4989 * 1 - for updating the inode.
4991 trans = btrfs_start_transaction(root, 3);
4993 return PTR_ERR(trans);
4995 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4997 btrfs_abort_transaction(trans, ret);
4998 btrfs_end_transaction(trans);
5002 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5003 offset, 0, 0, len, 0, len, 0, 0, 0);
5005 btrfs_abort_transaction(trans, ret);
5007 btrfs_update_inode(trans, root, inode);
5008 btrfs_end_transaction(trans);
5013 * This function puts in dummy file extents for the area we're creating a hole
5014 * for. So if we are truncating this file to a larger size we need to insert
5015 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5016 * the range between oldsize and size
5018 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5020 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5021 struct btrfs_root *root = BTRFS_I(inode)->root;
5022 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5023 struct extent_map *em = NULL;
5024 struct extent_state *cached_state = NULL;
5025 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5026 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5027 u64 block_end = ALIGN(size, fs_info->sectorsize);
5034 * If our size started in the middle of a block we need to zero out the
5035 * rest of the block before we expand the i_size, otherwise we could
5036 * expose stale data.
5038 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5042 if (size <= hole_start)
5045 btrfs_lock_and_flush_ordered_range(io_tree, BTRFS_I(inode), hole_start,
5046 block_end - 1, &cached_state);
5047 cur_offset = hole_start;
5049 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5050 block_end - cur_offset, 0);
5056 last_byte = min(extent_map_end(em), block_end);
5057 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5058 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5059 struct extent_map *hole_em;
5060 hole_size = last_byte - cur_offset;
5062 err = maybe_insert_hole(root, inode, cur_offset,
5066 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5067 cur_offset + hole_size - 1, 0);
5068 hole_em = alloc_extent_map();
5070 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5071 &BTRFS_I(inode)->runtime_flags);
5074 hole_em->start = cur_offset;
5075 hole_em->len = hole_size;
5076 hole_em->orig_start = cur_offset;
5078 hole_em->block_start = EXTENT_MAP_HOLE;
5079 hole_em->block_len = 0;
5080 hole_em->orig_block_len = 0;
5081 hole_em->ram_bytes = hole_size;
5082 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5083 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5084 hole_em->generation = fs_info->generation;
5087 write_lock(&em_tree->lock);
5088 err = add_extent_mapping(em_tree, hole_em, 1);
5089 write_unlock(&em_tree->lock);
5092 btrfs_drop_extent_cache(BTRFS_I(inode),
5097 free_extent_map(hole_em);
5100 free_extent_map(em);
5102 cur_offset = last_byte;
5103 if (cur_offset >= block_end)
5106 free_extent_map(em);
5107 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5111 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5113 struct btrfs_root *root = BTRFS_I(inode)->root;
5114 struct btrfs_trans_handle *trans;
5115 loff_t oldsize = i_size_read(inode);
5116 loff_t newsize = attr->ia_size;
5117 int mask = attr->ia_valid;
5121 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5122 * special case where we need to update the times despite not having
5123 * these flags set. For all other operations the VFS set these flags
5124 * explicitly if it wants a timestamp update.
5126 if (newsize != oldsize) {
5127 inode_inc_iversion(inode);
5128 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5129 inode->i_ctime = inode->i_mtime =
5130 current_time(inode);
5133 if (newsize > oldsize) {
5135 * Don't do an expanding truncate while snapshotting is ongoing.
5136 * This is to ensure the snapshot captures a fully consistent
5137 * state of this file - if the snapshot captures this expanding
5138 * truncation, it must capture all writes that happened before
5141 btrfs_wait_for_snapshot_creation(root);
5142 ret = btrfs_cont_expand(inode, oldsize, newsize);
5144 btrfs_end_write_no_snapshotting(root);
5148 trans = btrfs_start_transaction(root, 1);
5149 if (IS_ERR(trans)) {
5150 btrfs_end_write_no_snapshotting(root);
5151 return PTR_ERR(trans);
5154 i_size_write(inode, newsize);
5155 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5156 pagecache_isize_extended(inode, oldsize, newsize);
5157 ret = btrfs_update_inode(trans, root, inode);
5158 btrfs_end_write_no_snapshotting(root);
5159 btrfs_end_transaction(trans);
5163 * We're truncating a file that used to have good data down to
5164 * zero. Make sure it gets into the ordered flush list so that
5165 * any new writes get down to disk quickly.
5168 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5169 &BTRFS_I(inode)->runtime_flags);
5171 truncate_setsize(inode, newsize);
5173 /* Disable nonlocked read DIO to avoid the endless truncate */
5174 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5175 inode_dio_wait(inode);
5176 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5178 ret = btrfs_truncate(inode, newsize == oldsize);
5179 if (ret && inode->i_nlink) {
5183 * Truncate failed, so fix up the in-memory size. We
5184 * adjusted disk_i_size down as we removed extents, so
5185 * wait for disk_i_size to be stable and then update the
5186 * in-memory size to match.
5188 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5191 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5198 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5200 struct inode *inode = d_inode(dentry);
5201 struct btrfs_root *root = BTRFS_I(inode)->root;
5204 if (btrfs_root_readonly(root))
5207 err = setattr_prepare(dentry, attr);
5211 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5212 err = btrfs_setsize(inode, attr);
5217 if (attr->ia_valid) {
5218 setattr_copy(inode, attr);
5219 inode_inc_iversion(inode);
5220 err = btrfs_dirty_inode(inode);
5222 if (!err && attr->ia_valid & ATTR_MODE)
5223 err = posix_acl_chmod(inode, inode->i_mode);
5230 * While truncating the inode pages during eviction, we get the VFS calling
5231 * btrfs_invalidatepage() against each page of the inode. This is slow because
5232 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5233 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5234 * extent_state structures over and over, wasting lots of time.
5236 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5237 * those expensive operations on a per page basis and do only the ordered io
5238 * finishing, while we release here the extent_map and extent_state structures,
5239 * without the excessive merging and splitting.
5241 static void evict_inode_truncate_pages(struct inode *inode)
5243 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5244 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5245 struct rb_node *node;
5247 ASSERT(inode->i_state & I_FREEING);
5248 truncate_inode_pages_final(&inode->i_data);
5250 write_lock(&map_tree->lock);
5251 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5252 struct extent_map *em;
5254 node = rb_first_cached(&map_tree->map);
5255 em = rb_entry(node, struct extent_map, rb_node);
5256 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5257 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5258 remove_extent_mapping(map_tree, em);
5259 free_extent_map(em);
5260 if (need_resched()) {
5261 write_unlock(&map_tree->lock);
5263 write_lock(&map_tree->lock);
5266 write_unlock(&map_tree->lock);
5269 * Keep looping until we have no more ranges in the io tree.
5270 * We can have ongoing bios started by readpages (called from readahead)
5271 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5272 * still in progress (unlocked the pages in the bio but did not yet
5273 * unlocked the ranges in the io tree). Therefore this means some
5274 * ranges can still be locked and eviction started because before
5275 * submitting those bios, which are executed by a separate task (work
5276 * queue kthread), inode references (inode->i_count) were not taken
5277 * (which would be dropped in the end io callback of each bio).
5278 * Therefore here we effectively end up waiting for those bios and
5279 * anyone else holding locked ranges without having bumped the inode's
5280 * reference count - if we don't do it, when they access the inode's
5281 * io_tree to unlock a range it may be too late, leading to an
5282 * use-after-free issue.
5284 spin_lock(&io_tree->lock);
5285 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5286 struct extent_state *state;
5287 struct extent_state *cached_state = NULL;
5290 unsigned state_flags;
5292 node = rb_first(&io_tree->state);
5293 state = rb_entry(node, struct extent_state, rb_node);
5294 start = state->start;
5296 state_flags = state->state;
5297 spin_unlock(&io_tree->lock);
5299 lock_extent_bits(io_tree, start, end, &cached_state);
5302 * If still has DELALLOC flag, the extent didn't reach disk,
5303 * and its reserved space won't be freed by delayed_ref.
5304 * So we need to free its reserved space here.
5305 * (Refer to comment in btrfs_invalidatepage, case 2)
5307 * Note, end is the bytenr of last byte, so we need + 1 here.
5309 if (state_flags & EXTENT_DELALLOC)
5310 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5312 clear_extent_bit(io_tree, start, end,
5313 EXTENT_LOCKED | EXTENT_DIRTY |
5314 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5315 EXTENT_DEFRAG, 1, 1, &cached_state);
5318 spin_lock(&io_tree->lock);
5320 spin_unlock(&io_tree->lock);
5323 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5324 struct btrfs_block_rsv *rsv)
5326 struct btrfs_fs_info *fs_info = root->fs_info;
5327 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5328 u64 delayed_refs_extra = btrfs_calc_trans_metadata_size(fs_info, 1);
5332 struct btrfs_trans_handle *trans;
5335 ret = btrfs_block_rsv_refill(root, rsv,
5336 rsv->size + delayed_refs_extra,
5337 BTRFS_RESERVE_FLUSH_LIMIT);
5339 if (ret && ++failures > 2) {
5341 "could not allocate space for a delete; will truncate on mount");
5342 return ERR_PTR(-ENOSPC);
5346 * Evict can generate a large amount of delayed refs without
5347 * having a way to add space back since we exhaust our temporary
5348 * block rsv. We aren't allowed to do FLUSH_ALL in this case
5349 * because we could deadlock with so many things in the flushing
5350 * code, so we have to try and hold some extra space to
5351 * compensate for our delayed ref generation. If we can't get
5352 * that space then we need see if we can steal our minimum from
5353 * the global reserve. We will be ratelimited by the amount of
5354 * space we have for the delayed refs rsv, so we'll end up
5355 * committing and trying again.
5357 trans = btrfs_join_transaction(root);
5358 if (IS_ERR(trans) || !ret) {
5359 if (!IS_ERR(trans)) {
5360 trans->block_rsv = &fs_info->trans_block_rsv;
5361 trans->bytes_reserved = delayed_refs_extra;
5362 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5363 delayed_refs_extra, 1);
5369 * Try to steal from the global reserve if there is space for
5372 if (!btrfs_check_space_for_delayed_refs(fs_info) &&
5373 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0))
5376 /* If not, commit and try again. */
5377 ret = btrfs_commit_transaction(trans);
5379 return ERR_PTR(ret);
5383 void btrfs_evict_inode(struct inode *inode)
5385 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5386 struct btrfs_trans_handle *trans;
5387 struct btrfs_root *root = BTRFS_I(inode)->root;
5388 struct btrfs_block_rsv *rsv;
5391 trace_btrfs_inode_evict(inode);
5398 evict_inode_truncate_pages(inode);
5400 if (inode->i_nlink &&
5401 ((btrfs_root_refs(&root->root_item) != 0 &&
5402 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5403 btrfs_is_free_space_inode(BTRFS_I(inode))))
5406 if (is_bad_inode(inode))
5409 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5411 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5414 if (inode->i_nlink > 0) {
5415 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5416 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5420 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5424 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5427 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5430 btrfs_i_size_write(BTRFS_I(inode), 0);
5433 trans = evict_refill_and_join(root, rsv);
5437 trans->block_rsv = rsv;
5439 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5440 trans->block_rsv = &fs_info->trans_block_rsv;
5441 btrfs_end_transaction(trans);
5442 btrfs_btree_balance_dirty(fs_info);
5443 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5450 * Errors here aren't a big deal, it just means we leave orphan items in
5451 * the tree. They will be cleaned up on the next mount. If the inode
5452 * number gets reused, cleanup deletes the orphan item without doing
5453 * anything, and unlink reuses the existing orphan item.
5455 * If it turns out that we are dropping too many of these, we might want
5456 * to add a mechanism for retrying these after a commit.
5458 trans = evict_refill_and_join(root, rsv);
5459 if (!IS_ERR(trans)) {
5460 trans->block_rsv = rsv;
5461 btrfs_orphan_del(trans, BTRFS_I(inode));
5462 trans->block_rsv = &fs_info->trans_block_rsv;
5463 btrfs_end_transaction(trans);
5466 if (!(root == fs_info->tree_root ||
5467 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5468 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5471 btrfs_free_block_rsv(fs_info, rsv);
5474 * If we didn't successfully delete, the orphan item will still be in
5475 * the tree and we'll retry on the next mount. Again, we might also want
5476 * to retry these periodically in the future.
5478 btrfs_remove_delayed_node(BTRFS_I(inode));
5483 * Return the key found in the dir entry in the location pointer, fill @type
5484 * with BTRFS_FT_*, and return 0.
5486 * If no dir entries were found, returns -ENOENT.
5487 * If found a corrupted location in dir entry, returns -EUCLEAN.
5489 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5490 struct btrfs_key *location, u8 *type)
5492 const char *name = dentry->d_name.name;
5493 int namelen = dentry->d_name.len;
5494 struct btrfs_dir_item *di;
5495 struct btrfs_path *path;
5496 struct btrfs_root *root = BTRFS_I(dir)->root;
5499 path = btrfs_alloc_path();
5503 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5505 if (IS_ERR_OR_NULL(di)) {
5506 ret = di ? PTR_ERR(di) : -ENOENT;
5510 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5511 if (location->type != BTRFS_INODE_ITEM_KEY &&
5512 location->type != BTRFS_ROOT_ITEM_KEY) {
5514 btrfs_warn(root->fs_info,
5515 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5516 __func__, name, btrfs_ino(BTRFS_I(dir)),
5517 location->objectid, location->type, location->offset);
5520 *type = btrfs_dir_type(path->nodes[0], di);
5522 btrfs_free_path(path);
5527 * when we hit a tree root in a directory, the btrfs part of the inode
5528 * needs to be changed to reflect the root directory of the tree root. This
5529 * is kind of like crossing a mount point.
5531 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5533 struct dentry *dentry,
5534 struct btrfs_key *location,
5535 struct btrfs_root **sub_root)
5537 struct btrfs_path *path;
5538 struct btrfs_root *new_root;
5539 struct btrfs_root_ref *ref;
5540 struct extent_buffer *leaf;
5541 struct btrfs_key key;
5545 path = btrfs_alloc_path();
5552 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5553 key.type = BTRFS_ROOT_REF_KEY;
5554 key.offset = location->objectid;
5556 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5563 leaf = path->nodes[0];
5564 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5565 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5566 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5569 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5570 (unsigned long)(ref + 1),
5571 dentry->d_name.len);
5575 btrfs_release_path(path);
5577 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5578 if (IS_ERR(new_root)) {
5579 err = PTR_ERR(new_root);
5583 *sub_root = new_root;
5584 location->objectid = btrfs_root_dirid(&new_root->root_item);
5585 location->type = BTRFS_INODE_ITEM_KEY;
5586 location->offset = 0;
5589 btrfs_free_path(path);
5593 static void inode_tree_add(struct inode *inode)
5595 struct btrfs_root *root = BTRFS_I(inode)->root;
5596 struct btrfs_inode *entry;
5598 struct rb_node *parent;
5599 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5600 u64 ino = btrfs_ino(BTRFS_I(inode));
5602 if (inode_unhashed(inode))
5605 spin_lock(&root->inode_lock);
5606 p = &root->inode_tree.rb_node;
5609 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5611 if (ino < btrfs_ino(entry))
5612 p = &parent->rb_left;
5613 else if (ino > btrfs_ino(entry))
5614 p = &parent->rb_right;
5616 WARN_ON(!(entry->vfs_inode.i_state &
5617 (I_WILL_FREE | I_FREEING)));
5618 rb_replace_node(parent, new, &root->inode_tree);
5619 RB_CLEAR_NODE(parent);
5620 spin_unlock(&root->inode_lock);
5624 rb_link_node(new, parent, p);
5625 rb_insert_color(new, &root->inode_tree);
5626 spin_unlock(&root->inode_lock);
5629 static void inode_tree_del(struct inode *inode)
5631 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5632 struct btrfs_root *root = BTRFS_I(inode)->root;
5635 spin_lock(&root->inode_lock);
5636 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5637 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5638 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5639 empty = RB_EMPTY_ROOT(&root->inode_tree);
5641 spin_unlock(&root->inode_lock);
5643 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5644 synchronize_srcu(&fs_info->subvol_srcu);
5645 spin_lock(&root->inode_lock);
5646 empty = RB_EMPTY_ROOT(&root->inode_tree);
5647 spin_unlock(&root->inode_lock);
5649 btrfs_add_dead_root(root);
5654 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5656 struct btrfs_iget_args *args = p;
5657 inode->i_ino = args->location->objectid;
5658 memcpy(&BTRFS_I(inode)->location, args->location,
5659 sizeof(*args->location));
5660 BTRFS_I(inode)->root = args->root;
5664 static int btrfs_find_actor(struct inode *inode, void *opaque)
5666 struct btrfs_iget_args *args = opaque;
5667 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5668 args->root == BTRFS_I(inode)->root;
5671 static struct inode *btrfs_iget_locked(struct super_block *s,
5672 struct btrfs_key *location,
5673 struct btrfs_root *root)
5675 struct inode *inode;
5676 struct btrfs_iget_args args;
5677 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5679 args.location = location;
5682 inode = iget5_locked(s, hashval, btrfs_find_actor,
5683 btrfs_init_locked_inode,
5688 /* Get an inode object given its location and corresponding root.
5689 * Returns in *is_new if the inode was read from disk
5691 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5692 struct btrfs_root *root, int *new,
5693 struct btrfs_path *path)
5695 struct inode *inode;
5697 inode = btrfs_iget_locked(s, location, root);
5699 return ERR_PTR(-ENOMEM);
5701 if (inode->i_state & I_NEW) {
5704 ret = btrfs_read_locked_inode(inode, path);
5706 inode_tree_add(inode);
5707 unlock_new_inode(inode);
5713 * ret > 0 can come from btrfs_search_slot called by
5714 * btrfs_read_locked_inode, this means the inode item
5719 inode = ERR_PTR(ret);
5726 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5727 struct btrfs_root *root, int *new)
5729 return btrfs_iget_path(s, location, root, new, NULL);
5732 static struct inode *new_simple_dir(struct super_block *s,
5733 struct btrfs_key *key,
5734 struct btrfs_root *root)
5736 struct inode *inode = new_inode(s);
5739 return ERR_PTR(-ENOMEM);
5741 BTRFS_I(inode)->root = root;
5742 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5743 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5745 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5746 inode->i_op = &btrfs_dir_ro_inode_operations;
5747 inode->i_opflags &= ~IOP_XATTR;
5748 inode->i_fop = &simple_dir_operations;
5749 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5750 inode->i_mtime = current_time(inode);
5751 inode->i_atime = inode->i_mtime;
5752 inode->i_ctime = inode->i_mtime;
5753 BTRFS_I(inode)->i_otime = inode->i_mtime;
5758 static inline u8 btrfs_inode_type(struct inode *inode)
5761 * Compile-time asserts that generic FT_* types still match
5764 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5765 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5766 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5767 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5768 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5769 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5770 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5771 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5773 return fs_umode_to_ftype(inode->i_mode);
5776 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5778 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5779 struct inode *inode;
5780 struct btrfs_root *root = BTRFS_I(dir)->root;
5781 struct btrfs_root *sub_root = root;
5782 struct btrfs_key location;
5787 if (dentry->d_name.len > BTRFS_NAME_LEN)
5788 return ERR_PTR(-ENAMETOOLONG);
5790 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5792 return ERR_PTR(ret);
5794 if (location.type == BTRFS_INODE_ITEM_KEY) {
5795 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5799 /* Do extra check against inode mode with di_type */
5800 if (btrfs_inode_type(inode) != di_type) {
5802 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5803 inode->i_mode, btrfs_inode_type(inode),
5806 return ERR_PTR(-EUCLEAN);
5811 index = srcu_read_lock(&fs_info->subvol_srcu);
5812 ret = fixup_tree_root_location(fs_info, dir, dentry,
5813 &location, &sub_root);
5816 inode = ERR_PTR(ret);
5818 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5820 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5822 srcu_read_unlock(&fs_info->subvol_srcu, index);
5824 if (!IS_ERR(inode) && root != sub_root) {
5825 down_read(&fs_info->cleanup_work_sem);
5826 if (!sb_rdonly(inode->i_sb))
5827 ret = btrfs_orphan_cleanup(sub_root);
5828 up_read(&fs_info->cleanup_work_sem);
5831 inode = ERR_PTR(ret);
5838 static int btrfs_dentry_delete(const struct dentry *dentry)
5840 struct btrfs_root *root;
5841 struct inode *inode = d_inode(dentry);
5843 if (!inode && !IS_ROOT(dentry))
5844 inode = d_inode(dentry->d_parent);
5847 root = BTRFS_I(inode)->root;
5848 if (btrfs_root_refs(&root->root_item) == 0)
5851 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5857 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5860 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5862 if (inode == ERR_PTR(-ENOENT))
5864 return d_splice_alias(inode, dentry);
5868 * All this infrastructure exists because dir_emit can fault, and we are holding
5869 * the tree lock when doing readdir. For now just allocate a buffer and copy
5870 * our information into that, and then dir_emit from the buffer. This is
5871 * similar to what NFS does, only we don't keep the buffer around in pagecache
5872 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5873 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5876 static int btrfs_opendir(struct inode *inode, struct file *file)
5878 struct btrfs_file_private *private;
5880 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5883 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5884 if (!private->filldir_buf) {
5888 file->private_data = private;
5899 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5902 struct dir_entry *entry = addr;
5903 char *name = (char *)(entry + 1);
5905 ctx->pos = get_unaligned(&entry->offset);
5906 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5907 get_unaligned(&entry->ino),
5908 get_unaligned(&entry->type)))
5910 addr += sizeof(struct dir_entry) +
5911 get_unaligned(&entry->name_len);
5917 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5919 struct inode *inode = file_inode(file);
5920 struct btrfs_root *root = BTRFS_I(inode)->root;
5921 struct btrfs_file_private *private = file->private_data;
5922 struct btrfs_dir_item *di;
5923 struct btrfs_key key;
5924 struct btrfs_key found_key;
5925 struct btrfs_path *path;
5927 struct list_head ins_list;
5928 struct list_head del_list;
5930 struct extent_buffer *leaf;
5937 struct btrfs_key location;
5939 if (!dir_emit_dots(file, ctx))
5942 path = btrfs_alloc_path();
5946 addr = private->filldir_buf;
5947 path->reada = READA_FORWARD;
5949 INIT_LIST_HEAD(&ins_list);
5950 INIT_LIST_HEAD(&del_list);
5951 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5954 key.type = BTRFS_DIR_INDEX_KEY;
5955 key.offset = ctx->pos;
5956 key.objectid = btrfs_ino(BTRFS_I(inode));
5958 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5963 struct dir_entry *entry;
5965 leaf = path->nodes[0];
5966 slot = path->slots[0];
5967 if (slot >= btrfs_header_nritems(leaf)) {
5968 ret = btrfs_next_leaf(root, path);
5976 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5978 if (found_key.objectid != key.objectid)
5980 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5982 if (found_key.offset < ctx->pos)
5984 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5986 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5987 name_len = btrfs_dir_name_len(leaf, di);
5988 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5990 btrfs_release_path(path);
5991 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5994 addr = private->filldir_buf;
6001 put_unaligned(name_len, &entry->name_len);
6002 name_ptr = (char *)(entry + 1);
6003 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6005 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6007 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6008 put_unaligned(location.objectid, &entry->ino);
6009 put_unaligned(found_key.offset, &entry->offset);
6011 addr += sizeof(struct dir_entry) + name_len;
6012 total_len += sizeof(struct dir_entry) + name_len;
6016 btrfs_release_path(path);
6018 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6022 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6027 * Stop new entries from being returned after we return the last
6030 * New directory entries are assigned a strictly increasing
6031 * offset. This means that new entries created during readdir
6032 * are *guaranteed* to be seen in the future by that readdir.
6033 * This has broken buggy programs which operate on names as
6034 * they're returned by readdir. Until we re-use freed offsets
6035 * we have this hack to stop new entries from being returned
6036 * under the assumption that they'll never reach this huge
6039 * This is being careful not to overflow 32bit loff_t unless the
6040 * last entry requires it because doing so has broken 32bit apps
6043 if (ctx->pos >= INT_MAX)
6044 ctx->pos = LLONG_MAX;
6051 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6052 btrfs_free_path(path);
6057 * This is somewhat expensive, updating the tree every time the
6058 * inode changes. But, it is most likely to find the inode in cache.
6059 * FIXME, needs more benchmarking...there are no reasons other than performance
6060 * to keep or drop this code.
6062 static int btrfs_dirty_inode(struct inode *inode)
6064 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6065 struct btrfs_root *root = BTRFS_I(inode)->root;
6066 struct btrfs_trans_handle *trans;
6069 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6072 trans = btrfs_join_transaction(root);
6074 return PTR_ERR(trans);
6076 ret = btrfs_update_inode(trans, root, inode);
6077 if (ret && ret == -ENOSPC) {
6078 /* whoops, lets try again with the full transaction */
6079 btrfs_end_transaction(trans);
6080 trans = btrfs_start_transaction(root, 1);
6082 return PTR_ERR(trans);
6084 ret = btrfs_update_inode(trans, root, inode);
6086 btrfs_end_transaction(trans);
6087 if (BTRFS_I(inode)->delayed_node)
6088 btrfs_balance_delayed_items(fs_info);
6094 * This is a copy of file_update_time. We need this so we can return error on
6095 * ENOSPC for updating the inode in the case of file write and mmap writes.
6097 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6100 struct btrfs_root *root = BTRFS_I(inode)->root;
6101 bool dirty = flags & ~S_VERSION;
6103 if (btrfs_root_readonly(root))
6106 if (flags & S_VERSION)
6107 dirty |= inode_maybe_inc_iversion(inode, dirty);
6108 if (flags & S_CTIME)
6109 inode->i_ctime = *now;
6110 if (flags & S_MTIME)
6111 inode->i_mtime = *now;
6112 if (flags & S_ATIME)
6113 inode->i_atime = *now;
6114 return dirty ? btrfs_dirty_inode(inode) : 0;
6118 * find the highest existing sequence number in a directory
6119 * and then set the in-memory index_cnt variable to reflect
6120 * free sequence numbers
6122 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6124 struct btrfs_root *root = inode->root;
6125 struct btrfs_key key, found_key;
6126 struct btrfs_path *path;
6127 struct extent_buffer *leaf;
6130 key.objectid = btrfs_ino(inode);
6131 key.type = BTRFS_DIR_INDEX_KEY;
6132 key.offset = (u64)-1;
6134 path = btrfs_alloc_path();
6138 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6141 /* FIXME: we should be able to handle this */
6147 * MAGIC NUMBER EXPLANATION:
6148 * since we search a directory based on f_pos we have to start at 2
6149 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6150 * else has to start at 2
6152 if (path->slots[0] == 0) {
6153 inode->index_cnt = 2;
6159 leaf = path->nodes[0];
6160 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6162 if (found_key.objectid != btrfs_ino(inode) ||
6163 found_key.type != BTRFS_DIR_INDEX_KEY) {
6164 inode->index_cnt = 2;
6168 inode->index_cnt = found_key.offset + 1;
6170 btrfs_free_path(path);
6175 * helper to find a free sequence number in a given directory. This current
6176 * code is very simple, later versions will do smarter things in the btree
6178 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6182 if (dir->index_cnt == (u64)-1) {
6183 ret = btrfs_inode_delayed_dir_index_count(dir);
6185 ret = btrfs_set_inode_index_count(dir);
6191 *index = dir->index_cnt;
6197 static int btrfs_insert_inode_locked(struct inode *inode)
6199 struct btrfs_iget_args args;
6200 args.location = &BTRFS_I(inode)->location;
6201 args.root = BTRFS_I(inode)->root;
6203 return insert_inode_locked4(inode,
6204 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6205 btrfs_find_actor, &args);
6209 * Inherit flags from the parent inode.
6211 * Currently only the compression flags and the cow flags are inherited.
6213 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6220 flags = BTRFS_I(dir)->flags;
6222 if (flags & BTRFS_INODE_NOCOMPRESS) {
6223 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6224 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6225 } else if (flags & BTRFS_INODE_COMPRESS) {
6226 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6227 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6230 if (flags & BTRFS_INODE_NODATACOW) {
6231 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6232 if (S_ISREG(inode->i_mode))
6233 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6236 btrfs_sync_inode_flags_to_i_flags(inode);
6239 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6240 struct btrfs_root *root,
6242 const char *name, int name_len,
6243 u64 ref_objectid, u64 objectid,
6244 umode_t mode, u64 *index)
6246 struct btrfs_fs_info *fs_info = root->fs_info;
6247 struct inode *inode;
6248 struct btrfs_inode_item *inode_item;
6249 struct btrfs_key *location;
6250 struct btrfs_path *path;
6251 struct btrfs_inode_ref *ref;
6252 struct btrfs_key key[2];
6254 int nitems = name ? 2 : 1;
6258 path = btrfs_alloc_path();
6260 return ERR_PTR(-ENOMEM);
6262 inode = new_inode(fs_info->sb);
6264 btrfs_free_path(path);
6265 return ERR_PTR(-ENOMEM);
6269 * O_TMPFILE, set link count to 0, so that after this point,
6270 * we fill in an inode item with the correct link count.
6273 set_nlink(inode, 0);
6276 * we have to initialize this early, so we can reclaim the inode
6277 * number if we fail afterwards in this function.
6279 inode->i_ino = objectid;
6282 trace_btrfs_inode_request(dir);
6284 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6286 btrfs_free_path(path);
6288 return ERR_PTR(ret);
6294 * index_cnt is ignored for everything but a dir,
6295 * btrfs_set_inode_index_count has an explanation for the magic
6298 BTRFS_I(inode)->index_cnt = 2;
6299 BTRFS_I(inode)->dir_index = *index;
6300 BTRFS_I(inode)->root = root;
6301 BTRFS_I(inode)->generation = trans->transid;
6302 inode->i_generation = BTRFS_I(inode)->generation;
6305 * We could have gotten an inode number from somebody who was fsynced
6306 * and then removed in this same transaction, so let's just set full
6307 * sync since it will be a full sync anyway and this will blow away the
6308 * old info in the log.
6310 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6312 key[0].objectid = objectid;
6313 key[0].type = BTRFS_INODE_ITEM_KEY;
6316 sizes[0] = sizeof(struct btrfs_inode_item);
6320 * Start new inodes with an inode_ref. This is slightly more
6321 * efficient for small numbers of hard links since they will
6322 * be packed into one item. Extended refs will kick in if we
6323 * add more hard links than can fit in the ref item.
6325 key[1].objectid = objectid;
6326 key[1].type = BTRFS_INODE_REF_KEY;
6327 key[1].offset = ref_objectid;
6329 sizes[1] = name_len + sizeof(*ref);
6332 location = &BTRFS_I(inode)->location;
6333 location->objectid = objectid;
6334 location->offset = 0;
6335 location->type = BTRFS_INODE_ITEM_KEY;
6337 ret = btrfs_insert_inode_locked(inode);
6343 path->leave_spinning = 1;
6344 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6348 inode_init_owner(inode, dir, mode);
6349 inode_set_bytes(inode, 0);
6351 inode->i_mtime = current_time(inode);
6352 inode->i_atime = inode->i_mtime;
6353 inode->i_ctime = inode->i_mtime;
6354 BTRFS_I(inode)->i_otime = inode->i_mtime;
6356 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6357 struct btrfs_inode_item);
6358 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6359 sizeof(*inode_item));
6360 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6363 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6364 struct btrfs_inode_ref);
6365 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6366 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6367 ptr = (unsigned long)(ref + 1);
6368 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6371 btrfs_mark_buffer_dirty(path->nodes[0]);
6372 btrfs_free_path(path);
6374 btrfs_inherit_iflags(inode, dir);
6376 if (S_ISREG(mode)) {
6377 if (btrfs_test_opt(fs_info, NODATASUM))
6378 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6379 if (btrfs_test_opt(fs_info, NODATACOW))
6380 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6381 BTRFS_INODE_NODATASUM;
6384 inode_tree_add(inode);
6386 trace_btrfs_inode_new(inode);
6387 btrfs_set_inode_last_trans(trans, inode);
6389 btrfs_update_root_times(trans, root);
6391 ret = btrfs_inode_inherit_props(trans, inode, dir);
6394 "error inheriting props for ino %llu (root %llu): %d",
6395 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6400 discard_new_inode(inode);
6403 BTRFS_I(dir)->index_cnt--;
6404 btrfs_free_path(path);
6405 return ERR_PTR(ret);
6409 * utility function to add 'inode' into 'parent_inode' with
6410 * a give name and a given sequence number.
6411 * if 'add_backref' is true, also insert a backref from the
6412 * inode to the parent directory.
6414 int btrfs_add_link(struct btrfs_trans_handle *trans,
6415 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6416 const char *name, int name_len, int add_backref, u64 index)
6419 struct btrfs_key key;
6420 struct btrfs_root *root = parent_inode->root;
6421 u64 ino = btrfs_ino(inode);
6422 u64 parent_ino = btrfs_ino(parent_inode);
6424 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6425 memcpy(&key, &inode->root->root_key, sizeof(key));
6428 key.type = BTRFS_INODE_ITEM_KEY;
6432 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6433 ret = btrfs_add_root_ref(trans, key.objectid,
6434 root->root_key.objectid, parent_ino,
6435 index, name, name_len);
6436 } else if (add_backref) {
6437 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6441 /* Nothing to clean up yet */
6445 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6446 btrfs_inode_type(&inode->vfs_inode), index);
6447 if (ret == -EEXIST || ret == -EOVERFLOW)
6450 btrfs_abort_transaction(trans, ret);
6454 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6456 inode_inc_iversion(&parent_inode->vfs_inode);
6458 * If we are replaying a log tree, we do not want to update the mtime
6459 * and ctime of the parent directory with the current time, since the
6460 * log replay procedure is responsible for setting them to their correct
6461 * values (the ones it had when the fsync was done).
6463 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6464 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6466 parent_inode->vfs_inode.i_mtime = now;
6467 parent_inode->vfs_inode.i_ctime = now;
6469 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6471 btrfs_abort_transaction(trans, ret);
6475 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6478 err = btrfs_del_root_ref(trans, key.objectid,
6479 root->root_key.objectid, parent_ino,
6480 &local_index, name, name_len);
6482 btrfs_abort_transaction(trans, err);
6483 } else if (add_backref) {
6487 err = btrfs_del_inode_ref(trans, root, name, name_len,
6488 ino, parent_ino, &local_index);
6490 btrfs_abort_transaction(trans, err);
6493 /* Return the original error code */
6497 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6498 struct btrfs_inode *dir, struct dentry *dentry,
6499 struct btrfs_inode *inode, int backref, u64 index)
6501 int err = btrfs_add_link(trans, dir, inode,
6502 dentry->d_name.name, dentry->d_name.len,
6509 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6510 umode_t mode, dev_t rdev)
6512 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6513 struct btrfs_trans_handle *trans;
6514 struct btrfs_root *root = BTRFS_I(dir)->root;
6515 struct inode *inode = NULL;
6521 * 2 for inode item and ref
6523 * 1 for xattr if selinux is on
6525 trans = btrfs_start_transaction(root, 5);
6527 return PTR_ERR(trans);
6529 err = btrfs_find_free_ino(root, &objectid);
6533 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6534 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6536 if (IS_ERR(inode)) {
6537 err = PTR_ERR(inode);
6543 * If the active LSM wants to access the inode during
6544 * d_instantiate it needs these. Smack checks to see
6545 * if the filesystem supports xattrs by looking at the
6548 inode->i_op = &btrfs_special_inode_operations;
6549 init_special_inode(inode, inode->i_mode, rdev);
6551 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6555 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6560 btrfs_update_inode(trans, root, inode);
6561 d_instantiate_new(dentry, inode);
6564 btrfs_end_transaction(trans);
6565 btrfs_btree_balance_dirty(fs_info);
6567 inode_dec_link_count(inode);
6568 discard_new_inode(inode);
6573 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6574 umode_t mode, bool excl)
6576 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6577 struct btrfs_trans_handle *trans;
6578 struct btrfs_root *root = BTRFS_I(dir)->root;
6579 struct inode *inode = NULL;
6585 * 2 for inode item and ref
6587 * 1 for xattr if selinux is on
6589 trans = btrfs_start_transaction(root, 5);
6591 return PTR_ERR(trans);
6593 err = btrfs_find_free_ino(root, &objectid);
6597 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6598 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6600 if (IS_ERR(inode)) {
6601 err = PTR_ERR(inode);
6606 * If the active LSM wants to access the inode during
6607 * d_instantiate it needs these. Smack checks to see
6608 * if the filesystem supports xattrs by looking at the
6611 inode->i_fop = &btrfs_file_operations;
6612 inode->i_op = &btrfs_file_inode_operations;
6613 inode->i_mapping->a_ops = &btrfs_aops;
6615 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6619 err = btrfs_update_inode(trans, root, inode);
6623 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6628 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6629 d_instantiate_new(dentry, inode);
6632 btrfs_end_transaction(trans);
6634 inode_dec_link_count(inode);
6635 discard_new_inode(inode);
6637 btrfs_btree_balance_dirty(fs_info);
6641 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6642 struct dentry *dentry)
6644 struct btrfs_trans_handle *trans = NULL;
6645 struct btrfs_root *root = BTRFS_I(dir)->root;
6646 struct inode *inode = d_inode(old_dentry);
6647 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6652 /* do not allow sys_link's with other subvols of the same device */
6653 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6656 if (inode->i_nlink >= BTRFS_LINK_MAX)
6659 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6664 * 2 items for inode and inode ref
6665 * 2 items for dir items
6666 * 1 item for parent inode
6667 * 1 item for orphan item deletion if O_TMPFILE
6669 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6670 if (IS_ERR(trans)) {
6671 err = PTR_ERR(trans);
6676 /* There are several dir indexes for this inode, clear the cache. */
6677 BTRFS_I(inode)->dir_index = 0ULL;
6679 inode_inc_iversion(inode);
6680 inode->i_ctime = current_time(inode);
6682 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6684 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6690 struct dentry *parent = dentry->d_parent;
6693 err = btrfs_update_inode(trans, root, inode);
6696 if (inode->i_nlink == 1) {
6698 * If new hard link count is 1, it's a file created
6699 * with open(2) O_TMPFILE flag.
6701 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6705 d_instantiate(dentry, inode);
6706 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6708 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6709 err = btrfs_commit_transaction(trans);
6716 btrfs_end_transaction(trans);
6718 inode_dec_link_count(inode);
6721 btrfs_btree_balance_dirty(fs_info);
6725 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6727 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6728 struct inode *inode = NULL;
6729 struct btrfs_trans_handle *trans;
6730 struct btrfs_root *root = BTRFS_I(dir)->root;
6736 * 2 items for inode and ref
6737 * 2 items for dir items
6738 * 1 for xattr if selinux is on
6740 trans = btrfs_start_transaction(root, 5);
6742 return PTR_ERR(trans);
6744 err = btrfs_find_free_ino(root, &objectid);
6748 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6749 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6750 S_IFDIR | mode, &index);
6751 if (IS_ERR(inode)) {
6752 err = PTR_ERR(inode);
6757 /* these must be set before we unlock the inode */
6758 inode->i_op = &btrfs_dir_inode_operations;
6759 inode->i_fop = &btrfs_dir_file_operations;
6761 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6765 btrfs_i_size_write(BTRFS_I(inode), 0);
6766 err = btrfs_update_inode(trans, root, inode);
6770 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6771 dentry->d_name.name,
6772 dentry->d_name.len, 0, index);
6776 d_instantiate_new(dentry, inode);
6779 btrfs_end_transaction(trans);
6781 inode_dec_link_count(inode);
6782 discard_new_inode(inode);
6784 btrfs_btree_balance_dirty(fs_info);
6788 static noinline int uncompress_inline(struct btrfs_path *path,
6790 size_t pg_offset, u64 extent_offset,
6791 struct btrfs_file_extent_item *item)
6794 struct extent_buffer *leaf = path->nodes[0];
6797 unsigned long inline_size;
6801 WARN_ON(pg_offset != 0);
6802 compress_type = btrfs_file_extent_compression(leaf, item);
6803 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6804 inline_size = btrfs_file_extent_inline_item_len(leaf,
6805 btrfs_item_nr(path->slots[0]));
6806 tmp = kmalloc(inline_size, GFP_NOFS);
6809 ptr = btrfs_file_extent_inline_start(item);
6811 read_extent_buffer(leaf, tmp, ptr, inline_size);
6813 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6814 ret = btrfs_decompress(compress_type, tmp, page,
6815 extent_offset, inline_size, max_size);
6818 * decompression code contains a memset to fill in any space between the end
6819 * of the uncompressed data and the end of max_size in case the decompressed
6820 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6821 * the end of an inline extent and the beginning of the next block, so we
6822 * cover that region here.
6825 if (max_size + pg_offset < PAGE_SIZE) {
6826 char *map = kmap(page);
6827 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6835 * a bit scary, this does extent mapping from logical file offset to the disk.
6836 * the ugly parts come from merging extents from the disk with the in-ram
6837 * representation. This gets more complex because of the data=ordered code,
6838 * where the in-ram extents might be locked pending data=ordered completion.
6840 * This also copies inline extents directly into the page.
6842 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6844 size_t pg_offset, u64 start, u64 len,
6847 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6850 u64 extent_start = 0;
6852 u64 objectid = btrfs_ino(inode);
6853 int extent_type = -1;
6854 struct btrfs_path *path = NULL;
6855 struct btrfs_root *root = inode->root;
6856 struct btrfs_file_extent_item *item;
6857 struct extent_buffer *leaf;
6858 struct btrfs_key found_key;
6859 struct extent_map *em = NULL;
6860 struct extent_map_tree *em_tree = &inode->extent_tree;
6861 struct extent_io_tree *io_tree = &inode->io_tree;
6862 const bool new_inline = !page || create;
6864 read_lock(&em_tree->lock);
6865 em = lookup_extent_mapping(em_tree, start, len);
6867 em->bdev = fs_info->fs_devices->latest_bdev;
6868 read_unlock(&em_tree->lock);
6871 if (em->start > start || em->start + em->len <= start)
6872 free_extent_map(em);
6873 else if (em->block_start == EXTENT_MAP_INLINE && page)
6874 free_extent_map(em);
6878 em = alloc_extent_map();
6883 em->bdev = fs_info->fs_devices->latest_bdev;
6884 em->start = EXTENT_MAP_HOLE;
6885 em->orig_start = EXTENT_MAP_HOLE;
6887 em->block_len = (u64)-1;
6889 path = btrfs_alloc_path();
6895 /* Chances are we'll be called again, so go ahead and do readahead */
6896 path->reada = READA_FORWARD;
6899 * Unless we're going to uncompress the inline extent, no sleep would
6902 path->leave_spinning = 1;
6904 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6908 } else if (ret > 0) {
6909 if (path->slots[0] == 0)
6914 leaf = path->nodes[0];
6915 item = btrfs_item_ptr(leaf, path->slots[0],
6916 struct btrfs_file_extent_item);
6917 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6918 if (found_key.objectid != objectid ||
6919 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6921 * If we backup past the first extent we want to move forward
6922 * and see if there is an extent in front of us, otherwise we'll
6923 * say there is a hole for our whole search range which can
6930 extent_type = btrfs_file_extent_type(leaf, item);
6931 extent_start = found_key.offset;
6932 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6933 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6934 /* Only regular file could have regular/prealloc extent */
6935 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6938 "regular/prealloc extent found for non-regular inode %llu",
6942 extent_end = extent_start +
6943 btrfs_file_extent_num_bytes(leaf, item);
6945 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6947 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6950 size = btrfs_file_extent_ram_bytes(leaf, item);
6951 extent_end = ALIGN(extent_start + size,
6952 fs_info->sectorsize);
6954 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6959 if (start >= extent_end) {
6961 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6962 ret = btrfs_next_leaf(root, path);
6966 } else if (ret > 0) {
6969 leaf = path->nodes[0];
6971 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6972 if (found_key.objectid != objectid ||
6973 found_key.type != BTRFS_EXTENT_DATA_KEY)
6975 if (start + len <= found_key.offset)
6977 if (start > found_key.offset)
6980 /* New extent overlaps with existing one */
6982 em->orig_start = start;
6983 em->len = found_key.offset - start;
6984 em->block_start = EXTENT_MAP_HOLE;
6988 btrfs_extent_item_to_extent_map(inode, path, item,
6991 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6992 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6994 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6998 size_t extent_offset;
7004 size = btrfs_file_extent_ram_bytes(leaf, item);
7005 extent_offset = page_offset(page) + pg_offset - extent_start;
7006 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7007 size - extent_offset);
7008 em->start = extent_start + extent_offset;
7009 em->len = ALIGN(copy_size, fs_info->sectorsize);
7010 em->orig_block_len = em->len;
7011 em->orig_start = em->start;
7012 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7014 btrfs_set_path_blocking(path);
7015 if (!PageUptodate(page)) {
7016 if (btrfs_file_extent_compression(leaf, item) !=
7017 BTRFS_COMPRESS_NONE) {
7018 ret = uncompress_inline(path, page, pg_offset,
7019 extent_offset, item);
7026 read_extent_buffer(leaf, map + pg_offset, ptr,
7028 if (pg_offset + copy_size < PAGE_SIZE) {
7029 memset(map + pg_offset + copy_size, 0,
7030 PAGE_SIZE - pg_offset -
7035 flush_dcache_page(page);
7037 set_extent_uptodate(io_tree, em->start,
7038 extent_map_end(em) - 1, NULL, GFP_NOFS);
7043 em->orig_start = start;
7045 em->block_start = EXTENT_MAP_HOLE;
7047 btrfs_release_path(path);
7048 if (em->start > start || extent_map_end(em) <= start) {
7050 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7051 em->start, em->len, start, len);
7057 write_lock(&em_tree->lock);
7058 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7059 write_unlock(&em_tree->lock);
7061 btrfs_free_path(path);
7063 trace_btrfs_get_extent(root, inode, em);
7066 free_extent_map(em);
7067 return ERR_PTR(err);
7069 BUG_ON(!em); /* Error is always set */
7073 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7076 struct extent_map *em;
7077 struct extent_map *hole_em = NULL;
7078 u64 delalloc_start = start;
7084 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7088 * If our em maps to:
7090 * - a pre-alloc extent,
7091 * there might actually be delalloc bytes behind it.
7093 if (em->block_start != EXTENT_MAP_HOLE &&
7094 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7099 /* check to see if we've wrapped (len == -1 or similar) */
7108 /* ok, we didn't find anything, lets look for delalloc */
7109 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7110 end, len, EXTENT_DELALLOC, 1);
7111 delalloc_end = delalloc_start + delalloc_len;
7112 if (delalloc_end < delalloc_start)
7113 delalloc_end = (u64)-1;
7116 * We didn't find anything useful, return the original results from
7119 if (delalloc_start > end || delalloc_end <= start) {
7126 * Adjust the delalloc_start to make sure it doesn't go backwards from
7127 * the start they passed in
7129 delalloc_start = max(start, delalloc_start);
7130 delalloc_len = delalloc_end - delalloc_start;
7132 if (delalloc_len > 0) {
7135 const u64 hole_end = extent_map_end(hole_em);
7137 em = alloc_extent_map();
7146 * When btrfs_get_extent can't find anything it returns one
7149 * Make sure what it found really fits our range, and adjust to
7150 * make sure it is based on the start from the caller
7152 if (hole_end <= start || hole_em->start > end) {
7153 free_extent_map(hole_em);
7156 hole_start = max(hole_em->start, start);
7157 hole_len = hole_end - hole_start;
7160 if (hole_em && delalloc_start > hole_start) {
7162 * Our hole starts before our delalloc, so we have to
7163 * return just the parts of the hole that go until the
7166 em->len = min(hole_len, delalloc_start - hole_start);
7167 em->start = hole_start;
7168 em->orig_start = hole_start;
7170 * Don't adjust block start at all, it is fixed at
7173 em->block_start = hole_em->block_start;
7174 em->block_len = hole_len;
7175 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7176 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7179 * Hole is out of passed range or it starts after
7182 em->start = delalloc_start;
7183 em->len = delalloc_len;
7184 em->orig_start = delalloc_start;
7185 em->block_start = EXTENT_MAP_DELALLOC;
7186 em->block_len = delalloc_len;
7193 free_extent_map(hole_em);
7195 free_extent_map(em);
7196 return ERR_PTR(err);
7201 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7204 const u64 orig_start,
7205 const u64 block_start,
7206 const u64 block_len,
7207 const u64 orig_block_len,
7208 const u64 ram_bytes,
7211 struct extent_map *em = NULL;
7214 if (type != BTRFS_ORDERED_NOCOW) {
7215 em = create_io_em(inode, start, len, orig_start,
7216 block_start, block_len, orig_block_len,
7218 BTRFS_COMPRESS_NONE, /* compress_type */
7223 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7224 len, block_len, type);
7227 free_extent_map(em);
7228 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7229 start + len - 1, 0);
7238 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7241 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7242 struct btrfs_root *root = BTRFS_I(inode)->root;
7243 struct extent_map *em;
7244 struct btrfs_key ins;
7248 alloc_hint = get_extent_allocation_hint(inode, start, len);
7249 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7250 0, alloc_hint, &ins, 1, 1);
7252 return ERR_PTR(ret);
7254 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7255 ins.objectid, ins.offset, ins.offset,
7256 ins.offset, BTRFS_ORDERED_REGULAR);
7257 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7259 btrfs_free_reserved_extent(fs_info, ins.objectid,
7266 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7267 * block must be cow'd
7269 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7270 u64 *orig_start, u64 *orig_block_len,
7273 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7274 struct btrfs_path *path;
7276 struct extent_buffer *leaf;
7277 struct btrfs_root *root = BTRFS_I(inode)->root;
7278 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7279 struct btrfs_file_extent_item *fi;
7280 struct btrfs_key key;
7287 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7289 path = btrfs_alloc_path();
7293 ret = btrfs_lookup_file_extent(NULL, root, path,
7294 btrfs_ino(BTRFS_I(inode)), offset, 0);
7298 slot = path->slots[0];
7301 /* can't find the item, must cow */
7308 leaf = path->nodes[0];
7309 btrfs_item_key_to_cpu(leaf, &key, slot);
7310 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7311 key.type != BTRFS_EXTENT_DATA_KEY) {
7312 /* not our file or wrong item type, must cow */
7316 if (key.offset > offset) {
7317 /* Wrong offset, must cow */
7321 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7322 found_type = btrfs_file_extent_type(leaf, fi);
7323 if (found_type != BTRFS_FILE_EXTENT_REG &&
7324 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7325 /* not a regular extent, must cow */
7329 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7332 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7333 if (extent_end <= offset)
7336 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7337 if (disk_bytenr == 0)
7340 if (btrfs_file_extent_compression(leaf, fi) ||
7341 btrfs_file_extent_encryption(leaf, fi) ||
7342 btrfs_file_extent_other_encoding(leaf, fi))
7346 * Do the same check as in btrfs_cross_ref_exist but without the
7347 * unnecessary search.
7349 if (btrfs_file_extent_generation(leaf, fi) <=
7350 btrfs_root_last_snapshot(&root->root_item))
7353 backref_offset = btrfs_file_extent_offset(leaf, fi);
7356 *orig_start = key.offset - backref_offset;
7357 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7358 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7361 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7364 num_bytes = min(offset + *len, extent_end) - offset;
7365 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7368 range_end = round_up(offset + num_bytes,
7369 root->fs_info->sectorsize) - 1;
7370 ret = test_range_bit(io_tree, offset, range_end,
7371 EXTENT_DELALLOC, 0, NULL);
7378 btrfs_release_path(path);
7381 * look for other files referencing this extent, if we
7382 * find any we must cow
7385 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7386 key.offset - backref_offset, disk_bytenr);
7393 * adjust disk_bytenr and num_bytes to cover just the bytes
7394 * in this extent we are about to write. If there
7395 * are any csums in that range we have to cow in order
7396 * to keep the csums correct
7398 disk_bytenr += backref_offset;
7399 disk_bytenr += offset - key.offset;
7400 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7403 * all of the above have passed, it is safe to overwrite this extent
7409 btrfs_free_path(path);
7413 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7414 struct extent_state **cached_state, int writing)
7416 struct btrfs_ordered_extent *ordered;
7420 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7423 * We're concerned with the entire range that we're going to be
7424 * doing DIO to, so we need to make sure there's no ordered
7425 * extents in this range.
7427 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7428 lockend - lockstart + 1);
7431 * We need to make sure there are no buffered pages in this
7432 * range either, we could have raced between the invalidate in
7433 * generic_file_direct_write and locking the extent. The
7434 * invalidate needs to happen so that reads after a write do not
7438 (!writing || !filemap_range_has_page(inode->i_mapping,
7439 lockstart, lockend)))
7442 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7447 * If we are doing a DIO read and the ordered extent we
7448 * found is for a buffered write, we can not wait for it
7449 * to complete and retry, because if we do so we can
7450 * deadlock with concurrent buffered writes on page
7451 * locks. This happens only if our DIO read covers more
7452 * than one extent map, if at this point has already
7453 * created an ordered extent for a previous extent map
7454 * and locked its range in the inode's io tree, and a
7455 * concurrent write against that previous extent map's
7456 * range and this range started (we unlock the ranges
7457 * in the io tree only when the bios complete and
7458 * buffered writes always lock pages before attempting
7459 * to lock range in the io tree).
7462 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7463 btrfs_start_ordered_extent(inode, ordered, 1);
7466 btrfs_put_ordered_extent(ordered);
7469 * We could trigger writeback for this range (and wait
7470 * for it to complete) and then invalidate the pages for
7471 * this range (through invalidate_inode_pages2_range()),
7472 * but that can lead us to a deadlock with a concurrent
7473 * call to readpages() (a buffered read or a defrag call
7474 * triggered a readahead) on a page lock due to an
7475 * ordered dio extent we created before but did not have
7476 * yet a corresponding bio submitted (whence it can not
7477 * complete), which makes readpages() wait for that
7478 * ordered extent to complete while holding a lock on
7493 /* The callers of this must take lock_extent() */
7494 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7495 u64 orig_start, u64 block_start,
7496 u64 block_len, u64 orig_block_len,
7497 u64 ram_bytes, int compress_type,
7500 struct extent_map_tree *em_tree;
7501 struct extent_map *em;
7502 struct btrfs_root *root = BTRFS_I(inode)->root;
7505 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7506 type == BTRFS_ORDERED_COMPRESSED ||
7507 type == BTRFS_ORDERED_NOCOW ||
7508 type == BTRFS_ORDERED_REGULAR);
7510 em_tree = &BTRFS_I(inode)->extent_tree;
7511 em = alloc_extent_map();
7513 return ERR_PTR(-ENOMEM);
7516 em->orig_start = orig_start;
7518 em->block_len = block_len;
7519 em->block_start = block_start;
7520 em->bdev = root->fs_info->fs_devices->latest_bdev;
7521 em->orig_block_len = orig_block_len;
7522 em->ram_bytes = ram_bytes;
7523 em->generation = -1;
7524 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7525 if (type == BTRFS_ORDERED_PREALLOC) {
7526 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7527 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7528 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7529 em->compress_type = compress_type;
7533 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7534 em->start + em->len - 1, 0);
7535 write_lock(&em_tree->lock);
7536 ret = add_extent_mapping(em_tree, em, 1);
7537 write_unlock(&em_tree->lock);
7539 * The caller has taken lock_extent(), who could race with us
7542 } while (ret == -EEXIST);
7545 free_extent_map(em);
7546 return ERR_PTR(ret);
7549 /* em got 2 refs now, callers needs to do free_extent_map once. */
7554 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7555 struct buffer_head *bh_result,
7556 struct inode *inode,
7559 if (em->block_start == EXTENT_MAP_HOLE ||
7560 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7563 len = min(len, em->len - (start - em->start));
7565 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7567 bh_result->b_size = len;
7568 bh_result->b_bdev = em->bdev;
7569 set_buffer_mapped(bh_result);
7574 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7575 struct buffer_head *bh_result,
7576 struct inode *inode,
7577 struct btrfs_dio_data *dio_data,
7580 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7581 struct extent_map *em = *map;
7585 * We don't allocate a new extent in the following cases
7587 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7589 * 2) The extent is marked as PREALLOC. We're good to go here and can
7590 * just use the extent.
7593 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7594 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7595 em->block_start != EXTENT_MAP_HOLE)) {
7597 u64 block_start, orig_start, orig_block_len, ram_bytes;
7599 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7600 type = BTRFS_ORDERED_PREALLOC;
7602 type = BTRFS_ORDERED_NOCOW;
7603 len = min(len, em->len - (start - em->start));
7604 block_start = em->block_start + (start - em->start);
7606 if (can_nocow_extent(inode, start, &len, &orig_start,
7607 &orig_block_len, &ram_bytes) == 1 &&
7608 btrfs_inc_nocow_writers(fs_info, block_start)) {
7609 struct extent_map *em2;
7611 em2 = btrfs_create_dio_extent(inode, start, len,
7612 orig_start, block_start,
7613 len, orig_block_len,
7615 btrfs_dec_nocow_writers(fs_info, block_start);
7616 if (type == BTRFS_ORDERED_PREALLOC) {
7617 free_extent_map(em);
7621 if (em2 && IS_ERR(em2)) {
7626 * For inode marked NODATACOW or extent marked PREALLOC,
7627 * use the existing or preallocated extent, so does not
7628 * need to adjust btrfs_space_info's bytes_may_use.
7630 btrfs_free_reserved_data_space_noquota(inode, start,
7636 /* this will cow the extent */
7637 len = bh_result->b_size;
7638 free_extent_map(em);
7639 *map = em = btrfs_new_extent_direct(inode, start, len);
7645 len = min(len, em->len - (start - em->start));
7648 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7650 bh_result->b_size = len;
7651 bh_result->b_bdev = em->bdev;
7652 set_buffer_mapped(bh_result);
7654 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7655 set_buffer_new(bh_result);
7658 * Need to update the i_size under the extent lock so buffered
7659 * readers will get the updated i_size when we unlock.
7661 if (!dio_data->overwrite && start + len > i_size_read(inode))
7662 i_size_write(inode, start + len);
7664 WARN_ON(dio_data->reserve < len);
7665 dio_data->reserve -= len;
7666 dio_data->unsubmitted_oe_range_end = start + len;
7667 current->journal_info = dio_data;
7672 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7673 struct buffer_head *bh_result, int create)
7675 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7676 struct extent_map *em;
7677 struct extent_state *cached_state = NULL;
7678 struct btrfs_dio_data *dio_data = NULL;
7679 u64 start = iblock << inode->i_blkbits;
7680 u64 lockstart, lockend;
7681 u64 len = bh_result->b_size;
7682 int unlock_bits = EXTENT_LOCKED;
7686 unlock_bits |= EXTENT_DIRTY;
7688 len = min_t(u64, len, fs_info->sectorsize);
7691 lockend = start + len - 1;
7693 if (current->journal_info) {
7695 * Need to pull our outstanding extents and set journal_info to NULL so
7696 * that anything that needs to check if there's a transaction doesn't get
7699 dio_data = current->journal_info;
7700 current->journal_info = NULL;
7704 * If this errors out it's because we couldn't invalidate pagecache for
7705 * this range and we need to fallback to buffered.
7707 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7713 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7720 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7721 * io. INLINE is special, and we could probably kludge it in here, but
7722 * it's still buffered so for safety lets just fall back to the generic
7725 * For COMPRESSED we _have_ to read the entire extent in so we can
7726 * decompress it, so there will be buffering required no matter what we
7727 * do, so go ahead and fallback to buffered.
7729 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7730 * to buffered IO. Don't blame me, this is the price we pay for using
7733 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7734 em->block_start == EXTENT_MAP_INLINE) {
7735 free_extent_map(em);
7741 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7742 dio_data, start, len);
7746 /* clear and unlock the entire range */
7747 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7748 unlock_bits, 1, 0, &cached_state);
7750 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7752 /* Can be negative only if we read from a hole */
7755 free_extent_map(em);
7759 * We need to unlock only the end area that we aren't using.
7760 * The rest is going to be unlocked by the endio routine.
7762 lockstart = start + bh_result->b_size;
7763 if (lockstart < lockend) {
7764 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7765 lockend, unlock_bits, 1, 0,
7768 free_extent_state(cached_state);
7772 free_extent_map(em);
7777 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7778 unlock_bits, 1, 0, &cached_state);
7781 current->journal_info = dio_data;
7785 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7789 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7792 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7794 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7798 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7803 static int btrfs_check_dio_repairable(struct inode *inode,
7804 struct bio *failed_bio,
7805 struct io_failure_record *failrec,
7808 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7811 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7812 if (num_copies == 1) {
7814 * we only have a single copy of the data, so don't bother with
7815 * all the retry and error correction code that follows. no
7816 * matter what the error is, it is very likely to persist.
7818 btrfs_debug(fs_info,
7819 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7820 num_copies, failrec->this_mirror, failed_mirror);
7824 failrec->failed_mirror = failed_mirror;
7825 failrec->this_mirror++;
7826 if (failrec->this_mirror == failed_mirror)
7827 failrec->this_mirror++;
7829 if (failrec->this_mirror > num_copies) {
7830 btrfs_debug(fs_info,
7831 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7832 num_copies, failrec->this_mirror, failed_mirror);
7839 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7840 struct page *page, unsigned int pgoff,
7841 u64 start, u64 end, int failed_mirror,
7842 bio_end_io_t *repair_endio, void *repair_arg)
7844 struct io_failure_record *failrec;
7845 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7846 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7849 unsigned int read_mode = 0;
7852 blk_status_t status;
7853 struct bio_vec bvec;
7855 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7857 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7859 return errno_to_blk_status(ret);
7861 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7864 free_io_failure(failure_tree, io_tree, failrec);
7865 return BLK_STS_IOERR;
7868 segs = bio_segments(failed_bio);
7869 bio_get_first_bvec(failed_bio, &bvec);
7871 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7872 read_mode |= REQ_FAILFAST_DEV;
7874 isector = start - btrfs_io_bio(failed_bio)->logical;
7875 isector >>= inode->i_sb->s_blocksize_bits;
7876 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7877 pgoff, isector, repair_endio, repair_arg);
7878 bio->bi_opf = REQ_OP_READ | read_mode;
7880 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7881 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7882 read_mode, failrec->this_mirror, failrec->in_validation);
7884 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7886 free_io_failure(failure_tree, io_tree, failrec);
7893 struct btrfs_retry_complete {
7894 struct completion done;
7895 struct inode *inode;
7900 static void btrfs_retry_endio_nocsum(struct bio *bio)
7902 struct btrfs_retry_complete *done = bio->bi_private;
7903 struct inode *inode = done->inode;
7904 struct bio_vec *bvec;
7905 struct extent_io_tree *io_tree, *failure_tree;
7906 struct bvec_iter_all iter_all;
7911 ASSERT(bio->bi_vcnt == 1);
7912 io_tree = &BTRFS_I(inode)->io_tree;
7913 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7914 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7917 ASSERT(!bio_flagged(bio, BIO_CLONED));
7918 bio_for_each_segment_all(bvec, bio, iter_all)
7919 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7920 io_tree, done->start, bvec->bv_page,
7921 btrfs_ino(BTRFS_I(inode)), 0);
7923 complete(&done->done);
7927 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7928 struct btrfs_io_bio *io_bio)
7930 struct btrfs_fs_info *fs_info;
7931 struct bio_vec bvec;
7932 struct bvec_iter iter;
7933 struct btrfs_retry_complete done;
7939 blk_status_t err = BLK_STS_OK;
7941 fs_info = BTRFS_I(inode)->root->fs_info;
7942 sectorsize = fs_info->sectorsize;
7944 start = io_bio->logical;
7946 io_bio->bio.bi_iter = io_bio->iter;
7948 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7949 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7950 pgoff = bvec.bv_offset;
7952 next_block_or_try_again:
7955 init_completion(&done.done);
7957 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7958 pgoff, start, start + sectorsize - 1,
7960 btrfs_retry_endio_nocsum, &done);
7966 wait_for_completion_io(&done.done);
7968 if (!done.uptodate) {
7969 /* We might have another mirror, so try again */
7970 goto next_block_or_try_again;
7974 start += sectorsize;
7978 pgoff += sectorsize;
7979 ASSERT(pgoff < PAGE_SIZE);
7980 goto next_block_or_try_again;
7987 static void btrfs_retry_endio(struct bio *bio)
7989 struct btrfs_retry_complete *done = bio->bi_private;
7990 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7991 struct extent_io_tree *io_tree, *failure_tree;
7992 struct inode *inode = done->inode;
7993 struct bio_vec *bvec;
7997 struct bvec_iter_all iter_all;
8004 ASSERT(bio->bi_vcnt == 1);
8005 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8007 io_tree = &BTRFS_I(inode)->io_tree;
8008 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8010 ASSERT(!bio_flagged(bio, BIO_CLONED));
8011 bio_for_each_segment_all(bvec, bio, iter_all) {
8012 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8013 bvec->bv_offset, done->start,
8016 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8017 failure_tree, io_tree, done->start,
8019 btrfs_ino(BTRFS_I(inode)),
8026 done->uptodate = uptodate;
8028 complete(&done->done);
8032 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8033 struct btrfs_io_bio *io_bio, blk_status_t err)
8035 struct btrfs_fs_info *fs_info;
8036 struct bio_vec bvec;
8037 struct bvec_iter iter;
8038 struct btrfs_retry_complete done;
8045 bool uptodate = (err == 0);
8047 blk_status_t status;
8049 fs_info = BTRFS_I(inode)->root->fs_info;
8050 sectorsize = fs_info->sectorsize;
8053 start = io_bio->logical;
8055 io_bio->bio.bi_iter = io_bio->iter;
8057 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8058 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8060 pgoff = bvec.bv_offset;
8063 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8064 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8065 bvec.bv_page, pgoff, start, sectorsize);
8072 init_completion(&done.done);
8074 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8075 pgoff, start, start + sectorsize - 1,
8076 io_bio->mirror_num, btrfs_retry_endio,
8083 wait_for_completion_io(&done.done);
8085 if (!done.uptodate) {
8086 /* We might have another mirror, so try again */
8090 offset += sectorsize;
8091 start += sectorsize;
8097 pgoff += sectorsize;
8098 ASSERT(pgoff < PAGE_SIZE);
8106 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8107 struct btrfs_io_bio *io_bio, blk_status_t err)
8109 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8113 return __btrfs_correct_data_nocsum(inode, io_bio);
8117 return __btrfs_subio_endio_read(inode, io_bio, err);
8121 static void btrfs_endio_direct_read(struct bio *bio)
8123 struct btrfs_dio_private *dip = bio->bi_private;
8124 struct inode *inode = dip->inode;
8125 struct bio *dio_bio;
8126 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8127 blk_status_t err = bio->bi_status;
8129 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8130 err = btrfs_subio_endio_read(inode, io_bio, err);
8132 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8133 dip->logical_offset + dip->bytes - 1);
8134 dio_bio = dip->dio_bio;
8138 dio_bio->bi_status = err;
8139 dio_end_io(dio_bio);
8140 btrfs_io_bio_free_csum(io_bio);
8144 static void __endio_write_update_ordered(struct inode *inode,
8145 const u64 offset, const u64 bytes,
8146 const bool uptodate)
8148 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8149 struct btrfs_ordered_extent *ordered = NULL;
8150 struct btrfs_workqueue *wq;
8151 btrfs_work_func_t func;
8152 u64 ordered_offset = offset;
8153 u64 ordered_bytes = bytes;
8156 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8157 wq = fs_info->endio_freespace_worker;
8158 func = btrfs_freespace_write_helper;
8160 wq = fs_info->endio_write_workers;
8161 func = btrfs_endio_write_helper;
8164 while (ordered_offset < offset + bytes) {
8165 last_offset = ordered_offset;
8166 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8170 btrfs_init_work(&ordered->work, func,
8173 btrfs_queue_work(wq, &ordered->work);
8176 * If btrfs_dec_test_ordered_pending does not find any ordered
8177 * extent in the range, we can exit.
8179 if (ordered_offset == last_offset)
8182 * Our bio might span multiple ordered extents. In this case
8183 * we keep going until we have accounted the whole dio.
8185 if (ordered_offset < offset + bytes) {
8186 ordered_bytes = offset + bytes - ordered_offset;
8192 static void btrfs_endio_direct_write(struct bio *bio)
8194 struct btrfs_dio_private *dip = bio->bi_private;
8195 struct bio *dio_bio = dip->dio_bio;
8197 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8198 dip->bytes, !bio->bi_status);
8202 dio_bio->bi_status = bio->bi_status;
8203 dio_end_io(dio_bio);
8207 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8208 struct bio *bio, u64 offset)
8210 struct inode *inode = private_data;
8212 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8213 BUG_ON(ret); /* -ENOMEM */
8217 static void btrfs_end_dio_bio(struct bio *bio)
8219 struct btrfs_dio_private *dip = bio->bi_private;
8220 blk_status_t err = bio->bi_status;
8223 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8224 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8225 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8227 (unsigned long long)bio->bi_iter.bi_sector,
8228 bio->bi_iter.bi_size, err);
8230 if (dip->subio_endio)
8231 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8235 * We want to perceive the errors flag being set before
8236 * decrementing the reference count. We don't need a barrier
8237 * since atomic operations with a return value are fully
8238 * ordered as per atomic_t.txt
8243 /* if there are more bios still pending for this dio, just exit */
8244 if (!atomic_dec_and_test(&dip->pending_bios))
8248 bio_io_error(dip->orig_bio);
8250 dip->dio_bio->bi_status = BLK_STS_OK;
8251 bio_endio(dip->orig_bio);
8257 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8258 struct btrfs_dio_private *dip,
8262 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8263 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8267 * We load all the csum data we need when we submit
8268 * the first bio to reduce the csum tree search and
8271 if (dip->logical_offset == file_offset) {
8272 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8278 if (bio == dip->orig_bio)
8281 file_offset -= dip->logical_offset;
8282 file_offset >>= inode->i_sb->s_blocksize_bits;
8283 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8288 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8289 struct inode *inode, u64 file_offset, int async_submit)
8291 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8292 struct btrfs_dio_private *dip = bio->bi_private;
8293 bool write = bio_op(bio) == REQ_OP_WRITE;
8296 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8298 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8301 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8306 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8309 if (write && async_submit) {
8310 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8312 btrfs_submit_bio_start_direct_io);
8316 * If we aren't doing async submit, calculate the csum of the
8319 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8323 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8329 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8334 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8336 struct inode *inode = dip->inode;
8337 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8339 struct bio *orig_bio = dip->orig_bio;
8340 u64 start_sector = orig_bio->bi_iter.bi_sector;
8341 u64 file_offset = dip->logical_offset;
8342 int async_submit = 0;
8344 int clone_offset = 0;
8347 blk_status_t status;
8348 struct btrfs_io_geometry geom;
8350 submit_len = orig_bio->bi_iter.bi_size;
8351 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8352 start_sector << 9, submit_len, &geom);
8356 if (geom.len >= submit_len) {
8358 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8362 /* async crcs make it difficult to collect full stripe writes. */
8363 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8369 ASSERT(geom.len <= INT_MAX);
8370 atomic_inc(&dip->pending_bios);
8372 clone_len = min_t(int, submit_len, geom.len);
8375 * This will never fail as it's passing GPF_NOFS and
8376 * the allocation is backed by btrfs_bioset.
8378 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8380 bio->bi_private = dip;
8381 bio->bi_end_io = btrfs_end_dio_bio;
8382 btrfs_io_bio(bio)->logical = file_offset;
8384 ASSERT(submit_len >= clone_len);
8385 submit_len -= clone_len;
8386 if (submit_len == 0)
8390 * Increase the count before we submit the bio so we know
8391 * the end IO handler won't happen before we increase the
8392 * count. Otherwise, the dip might get freed before we're
8393 * done setting it up.
8395 atomic_inc(&dip->pending_bios);
8397 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8401 atomic_dec(&dip->pending_bios);
8405 clone_offset += clone_len;
8406 start_sector += clone_len >> 9;
8407 file_offset += clone_len;
8409 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8410 start_sector << 9, submit_len, &geom);
8413 } while (submit_len > 0);
8416 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8424 * Before atomic variable goto zero, we must make sure dip->errors is
8425 * perceived to be set. This ordering is ensured by the fact that an
8426 * atomic operations with a return value are fully ordered as per
8429 if (atomic_dec_and_test(&dip->pending_bios))
8430 bio_io_error(dip->orig_bio);
8432 /* bio_end_io() will handle error, so we needn't return it */
8436 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8439 struct btrfs_dio_private *dip = NULL;
8440 struct bio *bio = NULL;
8441 struct btrfs_io_bio *io_bio;
8442 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8445 bio = btrfs_bio_clone(dio_bio);
8447 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8453 dip->private = dio_bio->bi_private;
8455 dip->logical_offset = file_offset;
8456 dip->bytes = dio_bio->bi_iter.bi_size;
8457 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8458 bio->bi_private = dip;
8459 dip->orig_bio = bio;
8460 dip->dio_bio = dio_bio;
8461 atomic_set(&dip->pending_bios, 0);
8462 io_bio = btrfs_io_bio(bio);
8463 io_bio->logical = file_offset;
8466 bio->bi_end_io = btrfs_endio_direct_write;
8468 bio->bi_end_io = btrfs_endio_direct_read;
8469 dip->subio_endio = btrfs_subio_endio_read;
8473 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8474 * even if we fail to submit a bio, because in such case we do the
8475 * corresponding error handling below and it must not be done a second
8476 * time by btrfs_direct_IO().
8479 struct btrfs_dio_data *dio_data = current->journal_info;
8481 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8483 dio_data->unsubmitted_oe_range_start =
8484 dio_data->unsubmitted_oe_range_end;
8487 ret = btrfs_submit_direct_hook(dip);
8491 btrfs_io_bio_free_csum(io_bio);
8495 * If we arrived here it means either we failed to submit the dip
8496 * or we either failed to clone the dio_bio or failed to allocate the
8497 * dip. If we cloned the dio_bio and allocated the dip, we can just
8498 * call bio_endio against our io_bio so that we get proper resource
8499 * cleanup if we fail to submit the dip, otherwise, we must do the
8500 * same as btrfs_endio_direct_[write|read] because we can't call these
8501 * callbacks - they require an allocated dip and a clone of dio_bio.
8506 * The end io callbacks free our dip, do the final put on bio
8507 * and all the cleanup and final put for dio_bio (through
8514 __endio_write_update_ordered(inode,
8516 dio_bio->bi_iter.bi_size,
8519 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8520 file_offset + dio_bio->bi_iter.bi_size - 1);
8522 dio_bio->bi_status = BLK_STS_IOERR;
8524 * Releases and cleans up our dio_bio, no need to bio_put()
8525 * nor bio_endio()/bio_io_error() against dio_bio.
8527 dio_end_io(dio_bio);
8534 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8535 const struct iov_iter *iter, loff_t offset)
8539 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8540 ssize_t retval = -EINVAL;
8542 if (offset & blocksize_mask)
8545 if (iov_iter_alignment(iter) & blocksize_mask)
8548 /* If this is a write we don't need to check anymore */
8549 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8552 * Check to make sure we don't have duplicate iov_base's in this
8553 * iovec, if so return EINVAL, otherwise we'll get csum errors
8554 * when reading back.
8556 for (seg = 0; seg < iter->nr_segs; seg++) {
8557 for (i = seg + 1; i < iter->nr_segs; i++) {
8558 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8567 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8569 struct file *file = iocb->ki_filp;
8570 struct inode *inode = file->f_mapping->host;
8571 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8572 struct btrfs_dio_data dio_data = { 0 };
8573 struct extent_changeset *data_reserved = NULL;
8574 loff_t offset = iocb->ki_pos;
8578 bool relock = false;
8581 if (check_direct_IO(fs_info, iter, offset))
8584 inode_dio_begin(inode);
8587 * The generic stuff only does filemap_write_and_wait_range, which
8588 * isn't enough if we've written compressed pages to this area, so
8589 * we need to flush the dirty pages again to make absolutely sure
8590 * that any outstanding dirty pages are on disk.
8592 count = iov_iter_count(iter);
8593 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8594 &BTRFS_I(inode)->runtime_flags))
8595 filemap_fdatawrite_range(inode->i_mapping, offset,
8596 offset + count - 1);
8598 if (iov_iter_rw(iter) == WRITE) {
8600 * If the write DIO is beyond the EOF, we need update
8601 * the isize, but it is protected by i_mutex. So we can
8602 * not unlock the i_mutex at this case.
8604 if (offset + count <= inode->i_size) {
8605 dio_data.overwrite = 1;
8606 inode_unlock(inode);
8608 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8612 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8618 * We need to know how many extents we reserved so that we can
8619 * do the accounting properly if we go over the number we
8620 * originally calculated. Abuse current->journal_info for this.
8622 dio_data.reserve = round_up(count,
8623 fs_info->sectorsize);
8624 dio_data.unsubmitted_oe_range_start = (u64)offset;
8625 dio_data.unsubmitted_oe_range_end = (u64)offset;
8626 current->journal_info = &dio_data;
8627 down_read(&BTRFS_I(inode)->dio_sem);
8628 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8629 &BTRFS_I(inode)->runtime_flags)) {
8630 inode_dio_end(inode);
8631 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8635 ret = __blockdev_direct_IO(iocb, inode,
8636 fs_info->fs_devices->latest_bdev,
8637 iter, btrfs_get_blocks_direct, NULL,
8638 btrfs_submit_direct, flags);
8639 if (iov_iter_rw(iter) == WRITE) {
8640 up_read(&BTRFS_I(inode)->dio_sem);
8641 current->journal_info = NULL;
8642 if (ret < 0 && ret != -EIOCBQUEUED) {
8643 if (dio_data.reserve)
8644 btrfs_delalloc_release_space(inode, data_reserved,
8645 offset, dio_data.reserve, true);
8647 * On error we might have left some ordered extents
8648 * without submitting corresponding bios for them, so
8649 * cleanup them up to avoid other tasks getting them
8650 * and waiting for them to complete forever.
8652 if (dio_data.unsubmitted_oe_range_start <
8653 dio_data.unsubmitted_oe_range_end)
8654 __endio_write_update_ordered(inode,
8655 dio_data.unsubmitted_oe_range_start,
8656 dio_data.unsubmitted_oe_range_end -
8657 dio_data.unsubmitted_oe_range_start,
8659 } else if (ret >= 0 && (size_t)ret < count)
8660 btrfs_delalloc_release_space(inode, data_reserved,
8661 offset, count - (size_t)ret, true);
8662 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8666 inode_dio_end(inode);
8670 extent_changeset_free(data_reserved);
8674 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8676 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8677 __u64 start, __u64 len)
8681 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8685 return extent_fiemap(inode, fieinfo, start, len);
8688 int btrfs_readpage(struct file *file, struct page *page)
8690 struct extent_io_tree *tree;
8691 tree = &BTRFS_I(page->mapping->host)->io_tree;
8692 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8695 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8697 struct inode *inode = page->mapping->host;
8700 if (current->flags & PF_MEMALLOC) {
8701 redirty_page_for_writepage(wbc, page);
8707 * If we are under memory pressure we will call this directly from the
8708 * VM, we need to make sure we have the inode referenced for the ordered
8709 * extent. If not just return like we didn't do anything.
8711 if (!igrab(inode)) {
8712 redirty_page_for_writepage(wbc, page);
8713 return AOP_WRITEPAGE_ACTIVATE;
8715 ret = extent_write_full_page(page, wbc);
8716 btrfs_add_delayed_iput(inode);
8720 static int btrfs_writepages(struct address_space *mapping,
8721 struct writeback_control *wbc)
8723 return extent_writepages(mapping, wbc);
8727 btrfs_readpages(struct file *file, struct address_space *mapping,
8728 struct list_head *pages, unsigned nr_pages)
8730 return extent_readpages(mapping, pages, nr_pages);
8733 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8735 int ret = try_release_extent_mapping(page, gfp_flags);
8737 ClearPagePrivate(page);
8738 set_page_private(page, 0);
8744 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8746 if (PageWriteback(page) || PageDirty(page))
8748 return __btrfs_releasepage(page, gfp_flags);
8751 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8752 unsigned int length)
8754 struct inode *inode = page->mapping->host;
8755 struct extent_io_tree *tree;
8756 struct btrfs_ordered_extent *ordered;
8757 struct extent_state *cached_state = NULL;
8758 u64 page_start = page_offset(page);
8759 u64 page_end = page_start + PAGE_SIZE - 1;
8762 int inode_evicting = inode->i_state & I_FREEING;
8765 * we have the page locked, so new writeback can't start,
8766 * and the dirty bit won't be cleared while we are here.
8768 * Wait for IO on this page so that we can safely clear
8769 * the PagePrivate2 bit and do ordered accounting
8771 wait_on_page_writeback(page);
8773 tree = &BTRFS_I(inode)->io_tree;
8775 btrfs_releasepage(page, GFP_NOFS);
8779 if (!inode_evicting)
8780 lock_extent_bits(tree, page_start, page_end, &cached_state);
8783 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8784 page_end - start + 1);
8786 end = min(page_end, ordered->file_offset + ordered->len - 1);
8788 * IO on this page will never be started, so we need
8789 * to account for any ordered extents now
8791 if (!inode_evicting)
8792 clear_extent_bit(tree, start, end,
8793 EXTENT_DIRTY | EXTENT_DELALLOC |
8794 EXTENT_DELALLOC_NEW |
8795 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8796 EXTENT_DEFRAG, 1, 0, &cached_state);
8798 * whoever cleared the private bit is responsible
8799 * for the finish_ordered_io
8801 if (TestClearPagePrivate2(page)) {
8802 struct btrfs_ordered_inode_tree *tree;
8805 tree = &BTRFS_I(inode)->ordered_tree;
8807 spin_lock_irq(&tree->lock);
8808 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8809 new_len = start - ordered->file_offset;
8810 if (new_len < ordered->truncated_len)
8811 ordered->truncated_len = new_len;
8812 spin_unlock_irq(&tree->lock);
8814 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8816 end - start + 1, 1))
8817 btrfs_finish_ordered_io(ordered);
8819 btrfs_put_ordered_extent(ordered);
8820 if (!inode_evicting) {
8821 cached_state = NULL;
8822 lock_extent_bits(tree, start, end,
8827 if (start < page_end)
8832 * Qgroup reserved space handler
8833 * Page here will be either
8834 * 1) Already written to disk
8835 * In this case, its reserved space is released from data rsv map
8836 * and will be freed by delayed_ref handler finally.
8837 * So even we call qgroup_free_data(), it won't decrease reserved
8839 * 2) Not written to disk
8840 * This means the reserved space should be freed here. However,
8841 * if a truncate invalidates the page (by clearing PageDirty)
8842 * and the page is accounted for while allocating extent
8843 * in btrfs_check_data_free_space() we let delayed_ref to
8844 * free the entire extent.
8846 if (PageDirty(page))
8847 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8848 if (!inode_evicting) {
8849 clear_extent_bit(tree, page_start, page_end,
8850 EXTENT_LOCKED | EXTENT_DIRTY |
8851 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8852 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8855 __btrfs_releasepage(page, GFP_NOFS);
8858 ClearPageChecked(page);
8859 if (PagePrivate(page)) {
8860 ClearPagePrivate(page);
8861 set_page_private(page, 0);
8867 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8868 * called from a page fault handler when a page is first dirtied. Hence we must
8869 * be careful to check for EOF conditions here. We set the page up correctly
8870 * for a written page which means we get ENOSPC checking when writing into
8871 * holes and correct delalloc and unwritten extent mapping on filesystems that
8872 * support these features.
8874 * We are not allowed to take the i_mutex here so we have to play games to
8875 * protect against truncate races as the page could now be beyond EOF. Because
8876 * truncate_setsize() writes the inode size before removing pages, once we have
8877 * the page lock we can determine safely if the page is beyond EOF. If it is not
8878 * beyond EOF, then the page is guaranteed safe against truncation until we
8881 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8883 struct page *page = vmf->page;
8884 struct inode *inode = file_inode(vmf->vma->vm_file);
8885 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8886 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8887 struct btrfs_ordered_extent *ordered;
8888 struct extent_state *cached_state = NULL;
8889 struct extent_changeset *data_reserved = NULL;
8891 unsigned long zero_start;
8901 reserved_space = PAGE_SIZE;
8903 sb_start_pagefault(inode->i_sb);
8904 page_start = page_offset(page);
8905 page_end = page_start + PAGE_SIZE - 1;
8909 * Reserving delalloc space after obtaining the page lock can lead to
8910 * deadlock. For example, if a dirty page is locked by this function
8911 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8912 * dirty page write out, then the btrfs_writepage() function could
8913 * end up waiting indefinitely to get a lock on the page currently
8914 * being processed by btrfs_page_mkwrite() function.
8916 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8919 ret2 = file_update_time(vmf->vma->vm_file);
8923 ret = vmf_error(ret2);
8929 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8932 size = i_size_read(inode);
8934 if ((page->mapping != inode->i_mapping) ||
8935 (page_start >= size)) {
8936 /* page got truncated out from underneath us */
8939 wait_on_page_writeback(page);
8941 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8942 set_page_extent_mapped(page);
8945 * we can't set the delalloc bits if there are pending ordered
8946 * extents. Drop our locks and wait for them to finish
8948 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8951 unlock_extent_cached(io_tree, page_start, page_end,
8954 btrfs_start_ordered_extent(inode, ordered, 1);
8955 btrfs_put_ordered_extent(ordered);
8959 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8960 reserved_space = round_up(size - page_start,
8961 fs_info->sectorsize);
8962 if (reserved_space < PAGE_SIZE) {
8963 end = page_start + reserved_space - 1;
8964 btrfs_delalloc_release_space(inode, data_reserved,
8965 page_start, PAGE_SIZE - reserved_space,
8971 * page_mkwrite gets called when the page is firstly dirtied after it's
8972 * faulted in, but write(2) could also dirty a page and set delalloc
8973 * bits, thus in this case for space account reason, we still need to
8974 * clear any delalloc bits within this page range since we have to
8975 * reserve data&meta space before lock_page() (see above comments).
8977 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8978 EXTENT_DIRTY | EXTENT_DELALLOC |
8979 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8980 0, 0, &cached_state);
8982 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8985 unlock_extent_cached(io_tree, page_start, page_end,
8987 ret = VM_FAULT_SIGBUS;
8992 /* page is wholly or partially inside EOF */
8993 if (page_start + PAGE_SIZE > size)
8994 zero_start = offset_in_page(size);
8996 zero_start = PAGE_SIZE;
8998 if (zero_start != PAGE_SIZE) {
9000 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9001 flush_dcache_page(page);
9004 ClearPageChecked(page);
9005 set_page_dirty(page);
9006 SetPageUptodate(page);
9008 BTRFS_I(inode)->last_trans = fs_info->generation;
9009 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9010 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9012 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9015 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
9016 sb_end_pagefault(inode->i_sb);
9017 extent_changeset_free(data_reserved);
9018 return VM_FAULT_LOCKED;
9024 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
9025 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9026 reserved_space, (ret != 0));
9028 sb_end_pagefault(inode->i_sb);
9029 extent_changeset_free(data_reserved);
9033 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9035 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9036 struct btrfs_root *root = BTRFS_I(inode)->root;
9037 struct btrfs_block_rsv *rsv;
9039 struct btrfs_trans_handle *trans;
9040 u64 mask = fs_info->sectorsize - 1;
9041 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9043 if (!skip_writeback) {
9044 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9051 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9052 * things going on here:
9054 * 1) We need to reserve space to update our inode.
9056 * 2) We need to have something to cache all the space that is going to
9057 * be free'd up by the truncate operation, but also have some slack
9058 * space reserved in case it uses space during the truncate (thank you
9059 * very much snapshotting).
9061 * And we need these to be separate. The fact is we can use a lot of
9062 * space doing the truncate, and we have no earthly idea how much space
9063 * we will use, so we need the truncate reservation to be separate so it
9064 * doesn't end up using space reserved for updating the inode. We also
9065 * need to be able to stop the transaction and start a new one, which
9066 * means we need to be able to update the inode several times, and we
9067 * have no idea of knowing how many times that will be, so we can't just
9068 * reserve 1 item for the entirety of the operation, so that has to be
9069 * done separately as well.
9071 * So that leaves us with
9073 * 1) rsv - for the truncate reservation, which we will steal from the
9074 * transaction reservation.
9075 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9076 * updating the inode.
9078 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9081 rsv->size = min_size;
9085 * 1 for the truncate slack space
9086 * 1 for updating the inode.
9088 trans = btrfs_start_transaction(root, 2);
9089 if (IS_ERR(trans)) {
9090 ret = PTR_ERR(trans);
9094 /* Migrate the slack space for the truncate to our reserve */
9095 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9100 * So if we truncate and then write and fsync we normally would just
9101 * write the extents that changed, which is a problem if we need to
9102 * first truncate that entire inode. So set this flag so we write out
9103 * all of the extents in the inode to the sync log so we're completely
9106 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9107 trans->block_rsv = rsv;
9110 ret = btrfs_truncate_inode_items(trans, root, inode,
9112 BTRFS_EXTENT_DATA_KEY);
9113 trans->block_rsv = &fs_info->trans_block_rsv;
9114 if (ret != -ENOSPC && ret != -EAGAIN)
9117 ret = btrfs_update_inode(trans, root, inode);
9121 btrfs_end_transaction(trans);
9122 btrfs_btree_balance_dirty(fs_info);
9124 trans = btrfs_start_transaction(root, 2);
9125 if (IS_ERR(trans)) {
9126 ret = PTR_ERR(trans);
9131 btrfs_block_rsv_release(fs_info, rsv, -1);
9132 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9133 rsv, min_size, false);
9134 BUG_ON(ret); /* shouldn't happen */
9135 trans->block_rsv = rsv;
9139 * We can't call btrfs_truncate_block inside a trans handle as we could
9140 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9141 * we've truncated everything except the last little bit, and can do
9142 * btrfs_truncate_block and then update the disk_i_size.
9144 if (ret == NEED_TRUNCATE_BLOCK) {
9145 btrfs_end_transaction(trans);
9146 btrfs_btree_balance_dirty(fs_info);
9148 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9151 trans = btrfs_start_transaction(root, 1);
9152 if (IS_ERR(trans)) {
9153 ret = PTR_ERR(trans);
9156 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9162 trans->block_rsv = &fs_info->trans_block_rsv;
9163 ret2 = btrfs_update_inode(trans, root, inode);
9167 ret2 = btrfs_end_transaction(trans);
9170 btrfs_btree_balance_dirty(fs_info);
9173 btrfs_free_block_rsv(fs_info, rsv);
9179 * create a new subvolume directory/inode (helper for the ioctl).
9181 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9182 struct btrfs_root *new_root,
9183 struct btrfs_root *parent_root,
9186 struct inode *inode;
9190 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9191 new_dirid, new_dirid,
9192 S_IFDIR | (~current_umask() & S_IRWXUGO),
9195 return PTR_ERR(inode);
9196 inode->i_op = &btrfs_dir_inode_operations;
9197 inode->i_fop = &btrfs_dir_file_operations;
9199 set_nlink(inode, 1);
9200 btrfs_i_size_write(BTRFS_I(inode), 0);
9201 unlock_new_inode(inode);
9203 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9205 btrfs_err(new_root->fs_info,
9206 "error inheriting subvolume %llu properties: %d",
9207 new_root->root_key.objectid, err);
9209 err = btrfs_update_inode(trans, new_root, inode);
9215 struct inode *btrfs_alloc_inode(struct super_block *sb)
9217 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9218 struct btrfs_inode *ei;
9219 struct inode *inode;
9221 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9228 ei->last_sub_trans = 0;
9229 ei->logged_trans = 0;
9230 ei->delalloc_bytes = 0;
9231 ei->new_delalloc_bytes = 0;
9232 ei->defrag_bytes = 0;
9233 ei->disk_i_size = 0;
9236 ei->index_cnt = (u64)-1;
9238 ei->last_unlink_trans = 0;
9239 ei->last_log_commit = 0;
9241 spin_lock_init(&ei->lock);
9242 ei->outstanding_extents = 0;
9243 if (sb->s_magic != BTRFS_TEST_MAGIC)
9244 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9245 BTRFS_BLOCK_RSV_DELALLOC);
9246 ei->runtime_flags = 0;
9247 ei->prop_compress = BTRFS_COMPRESS_NONE;
9248 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9250 ei->delayed_node = NULL;
9252 ei->i_otime.tv_sec = 0;
9253 ei->i_otime.tv_nsec = 0;
9255 inode = &ei->vfs_inode;
9256 extent_map_tree_init(&ei->extent_tree);
9257 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9258 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9259 IO_TREE_INODE_IO_FAILURE, inode);
9260 ei->io_tree.track_uptodate = true;
9261 ei->io_failure_tree.track_uptodate = true;
9262 atomic_set(&ei->sync_writers, 0);
9263 mutex_init(&ei->log_mutex);
9264 mutex_init(&ei->delalloc_mutex);
9265 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9266 INIT_LIST_HEAD(&ei->delalloc_inodes);
9267 INIT_LIST_HEAD(&ei->delayed_iput);
9268 RB_CLEAR_NODE(&ei->rb_node);
9269 init_rwsem(&ei->dio_sem);
9274 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9275 void btrfs_test_destroy_inode(struct inode *inode)
9277 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9278 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9282 void btrfs_free_inode(struct inode *inode)
9284 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9287 void btrfs_destroy_inode(struct inode *inode)
9289 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9290 struct btrfs_ordered_extent *ordered;
9291 struct btrfs_root *root = BTRFS_I(inode)->root;
9293 WARN_ON(!hlist_empty(&inode->i_dentry));
9294 WARN_ON(inode->i_data.nrpages);
9295 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9296 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9297 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9298 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9299 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9300 WARN_ON(BTRFS_I(inode)->csum_bytes);
9301 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9304 * This can happen where we create an inode, but somebody else also
9305 * created the same inode and we need to destroy the one we already
9312 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9317 "found ordered extent %llu %llu on inode cleanup",
9318 ordered->file_offset, ordered->len);
9319 btrfs_remove_ordered_extent(inode, ordered);
9320 btrfs_put_ordered_extent(ordered);
9321 btrfs_put_ordered_extent(ordered);
9324 btrfs_qgroup_check_reserved_leak(inode);
9325 inode_tree_del(inode);
9326 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9329 int btrfs_drop_inode(struct inode *inode)
9331 struct btrfs_root *root = BTRFS_I(inode)->root;
9336 /* the snap/subvol tree is on deleting */
9337 if (btrfs_root_refs(&root->root_item) == 0)
9340 return generic_drop_inode(inode);
9343 static void init_once(void *foo)
9345 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9347 inode_init_once(&ei->vfs_inode);
9350 void __cold btrfs_destroy_cachep(void)
9353 * Make sure all delayed rcu free inodes are flushed before we
9357 kmem_cache_destroy(btrfs_inode_cachep);
9358 kmem_cache_destroy(btrfs_trans_handle_cachep);
9359 kmem_cache_destroy(btrfs_path_cachep);
9360 kmem_cache_destroy(btrfs_free_space_cachep);
9363 int __init btrfs_init_cachep(void)
9365 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9366 sizeof(struct btrfs_inode), 0,
9367 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9369 if (!btrfs_inode_cachep)
9372 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9373 sizeof(struct btrfs_trans_handle), 0,
9374 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9375 if (!btrfs_trans_handle_cachep)
9378 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9379 sizeof(struct btrfs_path), 0,
9380 SLAB_MEM_SPREAD, NULL);
9381 if (!btrfs_path_cachep)
9384 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9385 sizeof(struct btrfs_free_space), 0,
9386 SLAB_MEM_SPREAD, NULL);
9387 if (!btrfs_free_space_cachep)
9392 btrfs_destroy_cachep();
9396 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9397 u32 request_mask, unsigned int flags)
9400 struct inode *inode = d_inode(path->dentry);
9401 u32 blocksize = inode->i_sb->s_blocksize;
9402 u32 bi_flags = BTRFS_I(inode)->flags;
9404 stat->result_mask |= STATX_BTIME;
9405 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9406 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9407 if (bi_flags & BTRFS_INODE_APPEND)
9408 stat->attributes |= STATX_ATTR_APPEND;
9409 if (bi_flags & BTRFS_INODE_COMPRESS)
9410 stat->attributes |= STATX_ATTR_COMPRESSED;
9411 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9412 stat->attributes |= STATX_ATTR_IMMUTABLE;
9413 if (bi_flags & BTRFS_INODE_NODUMP)
9414 stat->attributes |= STATX_ATTR_NODUMP;
9416 stat->attributes_mask |= (STATX_ATTR_APPEND |
9417 STATX_ATTR_COMPRESSED |
9418 STATX_ATTR_IMMUTABLE |
9421 generic_fillattr(inode, stat);
9422 stat->dev = BTRFS_I(inode)->root->anon_dev;
9424 spin_lock(&BTRFS_I(inode)->lock);
9425 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9426 spin_unlock(&BTRFS_I(inode)->lock);
9427 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9428 ALIGN(delalloc_bytes, blocksize)) >> 9;
9432 static int btrfs_rename_exchange(struct inode *old_dir,
9433 struct dentry *old_dentry,
9434 struct inode *new_dir,
9435 struct dentry *new_dentry)
9437 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9438 struct btrfs_trans_handle *trans;
9439 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9440 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9441 struct inode *new_inode = new_dentry->d_inode;
9442 struct inode *old_inode = old_dentry->d_inode;
9443 struct timespec64 ctime = current_time(old_inode);
9444 struct dentry *parent;
9445 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9446 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9451 bool root_log_pinned = false;
9452 bool dest_log_pinned = false;
9453 struct btrfs_log_ctx ctx_root;
9454 struct btrfs_log_ctx ctx_dest;
9455 bool sync_log_root = false;
9456 bool sync_log_dest = false;
9457 bool commit_transaction = false;
9459 /* we only allow rename subvolume link between subvolumes */
9460 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9463 btrfs_init_log_ctx(&ctx_root, old_inode);
9464 btrfs_init_log_ctx(&ctx_dest, new_inode);
9466 /* close the race window with snapshot create/destroy ioctl */
9467 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9468 down_read(&fs_info->subvol_sem);
9469 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9470 down_read(&fs_info->subvol_sem);
9473 * We want to reserve the absolute worst case amount of items. So if
9474 * both inodes are subvols and we need to unlink them then that would
9475 * require 4 item modifications, but if they are both normal inodes it
9476 * would require 5 item modifications, so we'll assume their normal
9477 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9478 * should cover the worst case number of items we'll modify.
9480 trans = btrfs_start_transaction(root, 12);
9481 if (IS_ERR(trans)) {
9482 ret = PTR_ERR(trans);
9487 * We need to find a free sequence number both in the source and
9488 * in the destination directory for the exchange.
9490 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9493 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9497 BTRFS_I(old_inode)->dir_index = 0ULL;
9498 BTRFS_I(new_inode)->dir_index = 0ULL;
9500 /* Reference for the source. */
9501 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9502 /* force full log commit if subvolume involved. */
9503 btrfs_set_log_full_commit(trans);
9505 btrfs_pin_log_trans(root);
9506 root_log_pinned = true;
9507 ret = btrfs_insert_inode_ref(trans, dest,
9508 new_dentry->d_name.name,
9509 new_dentry->d_name.len,
9511 btrfs_ino(BTRFS_I(new_dir)),
9517 /* And now for the dest. */
9518 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9519 /* force full log commit if subvolume involved. */
9520 btrfs_set_log_full_commit(trans);
9522 btrfs_pin_log_trans(dest);
9523 dest_log_pinned = true;
9524 ret = btrfs_insert_inode_ref(trans, root,
9525 old_dentry->d_name.name,
9526 old_dentry->d_name.len,
9528 btrfs_ino(BTRFS_I(old_dir)),
9534 /* Update inode version and ctime/mtime. */
9535 inode_inc_iversion(old_dir);
9536 inode_inc_iversion(new_dir);
9537 inode_inc_iversion(old_inode);
9538 inode_inc_iversion(new_inode);
9539 old_dir->i_ctime = old_dir->i_mtime = ctime;
9540 new_dir->i_ctime = new_dir->i_mtime = ctime;
9541 old_inode->i_ctime = ctime;
9542 new_inode->i_ctime = ctime;
9544 if (old_dentry->d_parent != new_dentry->d_parent) {
9545 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9546 BTRFS_I(old_inode), 1);
9547 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9548 BTRFS_I(new_inode), 1);
9551 /* src is a subvolume */
9552 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9553 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9554 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9555 old_dentry->d_name.name,
9556 old_dentry->d_name.len);
9557 } else { /* src is an inode */
9558 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9559 BTRFS_I(old_dentry->d_inode),
9560 old_dentry->d_name.name,
9561 old_dentry->d_name.len);
9563 ret = btrfs_update_inode(trans, root, old_inode);
9566 btrfs_abort_transaction(trans, ret);
9570 /* dest is a subvolume */
9571 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9572 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9573 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9574 new_dentry->d_name.name,
9575 new_dentry->d_name.len);
9576 } else { /* dest is an inode */
9577 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9578 BTRFS_I(new_dentry->d_inode),
9579 new_dentry->d_name.name,
9580 new_dentry->d_name.len);
9582 ret = btrfs_update_inode(trans, dest, new_inode);
9585 btrfs_abort_transaction(trans, ret);
9589 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9590 new_dentry->d_name.name,
9591 new_dentry->d_name.len, 0, old_idx);
9593 btrfs_abort_transaction(trans, ret);
9597 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9598 old_dentry->d_name.name,
9599 old_dentry->d_name.len, 0, new_idx);
9601 btrfs_abort_transaction(trans, ret);
9605 if (old_inode->i_nlink == 1)
9606 BTRFS_I(old_inode)->dir_index = old_idx;
9607 if (new_inode->i_nlink == 1)
9608 BTRFS_I(new_inode)->dir_index = new_idx;
9610 if (root_log_pinned) {
9611 parent = new_dentry->d_parent;
9612 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9613 BTRFS_I(old_dir), parent,
9615 if (ret == BTRFS_NEED_LOG_SYNC)
9616 sync_log_root = true;
9617 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9618 commit_transaction = true;
9620 btrfs_end_log_trans(root);
9621 root_log_pinned = false;
9623 if (dest_log_pinned) {
9624 if (!commit_transaction) {
9625 parent = old_dentry->d_parent;
9626 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9627 BTRFS_I(new_dir), parent,
9629 if (ret == BTRFS_NEED_LOG_SYNC)
9630 sync_log_dest = true;
9631 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9632 commit_transaction = true;
9635 btrfs_end_log_trans(dest);
9636 dest_log_pinned = false;
9640 * If we have pinned a log and an error happened, we unpin tasks
9641 * trying to sync the log and force them to fallback to a transaction
9642 * commit if the log currently contains any of the inodes involved in
9643 * this rename operation (to ensure we do not persist a log with an
9644 * inconsistent state for any of these inodes or leading to any
9645 * inconsistencies when replayed). If the transaction was aborted, the
9646 * abortion reason is propagated to userspace when attempting to commit
9647 * the transaction. If the log does not contain any of these inodes, we
9648 * allow the tasks to sync it.
9650 if (ret && (root_log_pinned || dest_log_pinned)) {
9651 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9652 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9653 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9655 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9656 btrfs_set_log_full_commit(trans);
9658 if (root_log_pinned) {
9659 btrfs_end_log_trans(root);
9660 root_log_pinned = false;
9662 if (dest_log_pinned) {
9663 btrfs_end_log_trans(dest);
9664 dest_log_pinned = false;
9667 if (!ret && sync_log_root && !commit_transaction) {
9668 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9671 commit_transaction = true;
9673 if (!ret && sync_log_dest && !commit_transaction) {
9674 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9677 commit_transaction = true;
9679 if (commit_transaction) {
9680 ret = btrfs_commit_transaction(trans);
9684 ret2 = btrfs_end_transaction(trans);
9685 ret = ret ? ret : ret2;
9688 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9689 up_read(&fs_info->subvol_sem);
9690 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9691 up_read(&fs_info->subvol_sem);
9696 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9697 struct btrfs_root *root,
9699 struct dentry *dentry)
9702 struct inode *inode;
9706 ret = btrfs_find_free_ino(root, &objectid);
9710 inode = btrfs_new_inode(trans, root, dir,
9711 dentry->d_name.name,
9713 btrfs_ino(BTRFS_I(dir)),
9715 S_IFCHR | WHITEOUT_MODE,
9718 if (IS_ERR(inode)) {
9719 ret = PTR_ERR(inode);
9723 inode->i_op = &btrfs_special_inode_operations;
9724 init_special_inode(inode, inode->i_mode,
9727 ret = btrfs_init_inode_security(trans, inode, dir,
9732 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9733 BTRFS_I(inode), 0, index);
9737 ret = btrfs_update_inode(trans, root, inode);
9739 unlock_new_inode(inode);
9741 inode_dec_link_count(inode);
9747 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9748 struct inode *new_dir, struct dentry *new_dentry,
9751 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9752 struct btrfs_trans_handle *trans;
9753 unsigned int trans_num_items;
9754 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9755 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9756 struct inode *new_inode = d_inode(new_dentry);
9757 struct inode *old_inode = d_inode(old_dentry);
9761 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9762 bool log_pinned = false;
9763 struct btrfs_log_ctx ctx;
9764 bool sync_log = false;
9765 bool commit_transaction = false;
9767 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9770 /* we only allow rename subvolume link between subvolumes */
9771 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9774 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9775 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9778 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9779 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9783 /* check for collisions, even if the name isn't there */
9784 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9785 new_dentry->d_name.name,
9786 new_dentry->d_name.len);
9789 if (ret == -EEXIST) {
9791 * eexist without a new_inode */
9792 if (WARN_ON(!new_inode)) {
9796 /* maybe -EOVERFLOW */
9803 * we're using rename to replace one file with another. Start IO on it
9804 * now so we don't add too much work to the end of the transaction
9806 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9807 filemap_flush(old_inode->i_mapping);
9809 /* close the racy window with snapshot create/destroy ioctl */
9810 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9811 down_read(&fs_info->subvol_sem);
9813 * We want to reserve the absolute worst case amount of items. So if
9814 * both inodes are subvols and we need to unlink them then that would
9815 * require 4 item modifications, but if they are both normal inodes it
9816 * would require 5 item modifications, so we'll assume they are normal
9817 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9818 * should cover the worst case number of items we'll modify.
9819 * If our rename has the whiteout flag, we need more 5 units for the
9820 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9821 * when selinux is enabled).
9823 trans_num_items = 11;
9824 if (flags & RENAME_WHITEOUT)
9825 trans_num_items += 5;
9826 trans = btrfs_start_transaction(root, trans_num_items);
9827 if (IS_ERR(trans)) {
9828 ret = PTR_ERR(trans);
9833 btrfs_record_root_in_trans(trans, dest);
9835 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9839 BTRFS_I(old_inode)->dir_index = 0ULL;
9840 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9841 /* force full log commit if subvolume involved. */
9842 btrfs_set_log_full_commit(trans);
9844 btrfs_pin_log_trans(root);
9846 ret = btrfs_insert_inode_ref(trans, dest,
9847 new_dentry->d_name.name,
9848 new_dentry->d_name.len,
9850 btrfs_ino(BTRFS_I(new_dir)), index);
9855 inode_inc_iversion(old_dir);
9856 inode_inc_iversion(new_dir);
9857 inode_inc_iversion(old_inode);
9858 old_dir->i_ctime = old_dir->i_mtime =
9859 new_dir->i_ctime = new_dir->i_mtime =
9860 old_inode->i_ctime = current_time(old_dir);
9862 if (old_dentry->d_parent != new_dentry->d_parent)
9863 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9864 BTRFS_I(old_inode), 1);
9866 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9867 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9868 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9869 old_dentry->d_name.name,
9870 old_dentry->d_name.len);
9872 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9873 BTRFS_I(d_inode(old_dentry)),
9874 old_dentry->d_name.name,
9875 old_dentry->d_name.len);
9877 ret = btrfs_update_inode(trans, root, old_inode);
9880 btrfs_abort_transaction(trans, ret);
9885 inode_inc_iversion(new_inode);
9886 new_inode->i_ctime = current_time(new_inode);
9887 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9888 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9889 root_objectid = BTRFS_I(new_inode)->location.objectid;
9890 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9891 new_dentry->d_name.name,
9892 new_dentry->d_name.len);
9893 BUG_ON(new_inode->i_nlink == 0);
9895 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9896 BTRFS_I(d_inode(new_dentry)),
9897 new_dentry->d_name.name,
9898 new_dentry->d_name.len);
9900 if (!ret && new_inode->i_nlink == 0)
9901 ret = btrfs_orphan_add(trans,
9902 BTRFS_I(d_inode(new_dentry)));
9904 btrfs_abort_transaction(trans, ret);
9909 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9910 new_dentry->d_name.name,
9911 new_dentry->d_name.len, 0, index);
9913 btrfs_abort_transaction(trans, ret);
9917 if (old_inode->i_nlink == 1)
9918 BTRFS_I(old_inode)->dir_index = index;
9921 struct dentry *parent = new_dentry->d_parent;
9923 btrfs_init_log_ctx(&ctx, old_inode);
9924 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9925 BTRFS_I(old_dir), parent,
9927 if (ret == BTRFS_NEED_LOG_SYNC)
9929 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9930 commit_transaction = true;
9932 btrfs_end_log_trans(root);
9936 if (flags & RENAME_WHITEOUT) {
9937 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9941 btrfs_abort_transaction(trans, ret);
9947 * If we have pinned the log and an error happened, we unpin tasks
9948 * trying to sync the log and force them to fallback to a transaction
9949 * commit if the log currently contains any of the inodes involved in
9950 * this rename operation (to ensure we do not persist a log with an
9951 * inconsistent state for any of these inodes or leading to any
9952 * inconsistencies when replayed). If the transaction was aborted, the
9953 * abortion reason is propagated to userspace when attempting to commit
9954 * the transaction. If the log does not contain any of these inodes, we
9955 * allow the tasks to sync it.
9957 if (ret && log_pinned) {
9958 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9959 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9960 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9962 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9963 btrfs_set_log_full_commit(trans);
9965 btrfs_end_log_trans(root);
9968 if (!ret && sync_log) {
9969 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9971 commit_transaction = true;
9973 if (commit_transaction) {
9974 ret = btrfs_commit_transaction(trans);
9978 ret2 = btrfs_end_transaction(trans);
9979 ret = ret ? ret : ret2;
9982 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9983 up_read(&fs_info->subvol_sem);
9988 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9989 struct inode *new_dir, struct dentry *new_dentry,
9992 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9995 if (flags & RENAME_EXCHANGE)
9996 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9999 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10002 struct btrfs_delalloc_work {
10003 struct inode *inode;
10004 struct completion completion;
10005 struct list_head list;
10006 struct btrfs_work work;
10009 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10011 struct btrfs_delalloc_work *delalloc_work;
10012 struct inode *inode;
10014 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10016 inode = delalloc_work->inode;
10017 filemap_flush(inode->i_mapping);
10018 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10019 &BTRFS_I(inode)->runtime_flags))
10020 filemap_flush(inode->i_mapping);
10023 complete(&delalloc_work->completion);
10026 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
10028 struct btrfs_delalloc_work *work;
10030 work = kmalloc(sizeof(*work), GFP_NOFS);
10034 init_completion(&work->completion);
10035 INIT_LIST_HEAD(&work->list);
10036 work->inode = inode;
10037 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10038 btrfs_run_delalloc_work, NULL, NULL);
10044 * some fairly slow code that needs optimization. This walks the list
10045 * of all the inodes with pending delalloc and forces them to disk.
10047 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
10049 struct btrfs_inode *binode;
10050 struct inode *inode;
10051 struct btrfs_delalloc_work *work, *next;
10052 struct list_head works;
10053 struct list_head splice;
10056 INIT_LIST_HEAD(&works);
10057 INIT_LIST_HEAD(&splice);
10059 mutex_lock(&root->delalloc_mutex);
10060 spin_lock(&root->delalloc_lock);
10061 list_splice_init(&root->delalloc_inodes, &splice);
10062 while (!list_empty(&splice)) {
10063 binode = list_entry(splice.next, struct btrfs_inode,
10066 list_move_tail(&binode->delalloc_inodes,
10067 &root->delalloc_inodes);
10068 inode = igrab(&binode->vfs_inode);
10070 cond_resched_lock(&root->delalloc_lock);
10073 spin_unlock(&root->delalloc_lock);
10076 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10077 &binode->runtime_flags);
10078 work = btrfs_alloc_delalloc_work(inode);
10084 list_add_tail(&work->list, &works);
10085 btrfs_queue_work(root->fs_info->flush_workers,
10088 if (nr != -1 && ret >= nr)
10091 spin_lock(&root->delalloc_lock);
10093 spin_unlock(&root->delalloc_lock);
10096 list_for_each_entry_safe(work, next, &works, list) {
10097 list_del_init(&work->list);
10098 wait_for_completion(&work->completion);
10102 if (!list_empty(&splice)) {
10103 spin_lock(&root->delalloc_lock);
10104 list_splice_tail(&splice, &root->delalloc_inodes);
10105 spin_unlock(&root->delalloc_lock);
10107 mutex_unlock(&root->delalloc_mutex);
10111 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10113 struct btrfs_fs_info *fs_info = root->fs_info;
10116 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10119 ret = start_delalloc_inodes(root, -1, true);
10125 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10127 struct btrfs_root *root;
10128 struct list_head splice;
10131 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10134 INIT_LIST_HEAD(&splice);
10136 mutex_lock(&fs_info->delalloc_root_mutex);
10137 spin_lock(&fs_info->delalloc_root_lock);
10138 list_splice_init(&fs_info->delalloc_roots, &splice);
10139 while (!list_empty(&splice) && nr) {
10140 root = list_first_entry(&splice, struct btrfs_root,
10142 root = btrfs_grab_fs_root(root);
10144 list_move_tail(&root->delalloc_root,
10145 &fs_info->delalloc_roots);
10146 spin_unlock(&fs_info->delalloc_root_lock);
10148 ret = start_delalloc_inodes(root, nr, false);
10149 btrfs_put_fs_root(root);
10157 spin_lock(&fs_info->delalloc_root_lock);
10159 spin_unlock(&fs_info->delalloc_root_lock);
10163 if (!list_empty(&splice)) {
10164 spin_lock(&fs_info->delalloc_root_lock);
10165 list_splice_tail(&splice, &fs_info->delalloc_roots);
10166 spin_unlock(&fs_info->delalloc_root_lock);
10168 mutex_unlock(&fs_info->delalloc_root_mutex);
10172 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10173 const char *symname)
10175 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10176 struct btrfs_trans_handle *trans;
10177 struct btrfs_root *root = BTRFS_I(dir)->root;
10178 struct btrfs_path *path;
10179 struct btrfs_key key;
10180 struct inode *inode = NULL;
10187 struct btrfs_file_extent_item *ei;
10188 struct extent_buffer *leaf;
10190 name_len = strlen(symname);
10191 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10192 return -ENAMETOOLONG;
10195 * 2 items for inode item and ref
10196 * 2 items for dir items
10197 * 1 item for updating parent inode item
10198 * 1 item for the inline extent item
10199 * 1 item for xattr if selinux is on
10201 trans = btrfs_start_transaction(root, 7);
10203 return PTR_ERR(trans);
10205 err = btrfs_find_free_ino(root, &objectid);
10209 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10210 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10211 objectid, S_IFLNK|S_IRWXUGO, &index);
10212 if (IS_ERR(inode)) {
10213 err = PTR_ERR(inode);
10219 * If the active LSM wants to access the inode during
10220 * d_instantiate it needs these. Smack checks to see
10221 * if the filesystem supports xattrs by looking at the
10224 inode->i_fop = &btrfs_file_operations;
10225 inode->i_op = &btrfs_file_inode_operations;
10226 inode->i_mapping->a_ops = &btrfs_aops;
10227 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10229 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10233 path = btrfs_alloc_path();
10238 key.objectid = btrfs_ino(BTRFS_I(inode));
10240 key.type = BTRFS_EXTENT_DATA_KEY;
10241 datasize = btrfs_file_extent_calc_inline_size(name_len);
10242 err = btrfs_insert_empty_item(trans, root, path, &key,
10245 btrfs_free_path(path);
10248 leaf = path->nodes[0];
10249 ei = btrfs_item_ptr(leaf, path->slots[0],
10250 struct btrfs_file_extent_item);
10251 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10252 btrfs_set_file_extent_type(leaf, ei,
10253 BTRFS_FILE_EXTENT_INLINE);
10254 btrfs_set_file_extent_encryption(leaf, ei, 0);
10255 btrfs_set_file_extent_compression(leaf, ei, 0);
10256 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10257 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10259 ptr = btrfs_file_extent_inline_start(ei);
10260 write_extent_buffer(leaf, symname, ptr, name_len);
10261 btrfs_mark_buffer_dirty(leaf);
10262 btrfs_free_path(path);
10264 inode->i_op = &btrfs_symlink_inode_operations;
10265 inode_nohighmem(inode);
10266 inode_set_bytes(inode, name_len);
10267 btrfs_i_size_write(BTRFS_I(inode), name_len);
10268 err = btrfs_update_inode(trans, root, inode);
10270 * Last step, add directory indexes for our symlink inode. This is the
10271 * last step to avoid extra cleanup of these indexes if an error happens
10275 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10276 BTRFS_I(inode), 0, index);
10280 d_instantiate_new(dentry, inode);
10283 btrfs_end_transaction(trans);
10284 if (err && inode) {
10285 inode_dec_link_count(inode);
10286 discard_new_inode(inode);
10288 btrfs_btree_balance_dirty(fs_info);
10292 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10293 u64 start, u64 num_bytes, u64 min_size,
10294 loff_t actual_len, u64 *alloc_hint,
10295 struct btrfs_trans_handle *trans)
10297 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10298 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10299 struct extent_map *em;
10300 struct btrfs_root *root = BTRFS_I(inode)->root;
10301 struct btrfs_key ins;
10302 u64 cur_offset = start;
10305 u64 last_alloc = (u64)-1;
10307 bool own_trans = true;
10308 u64 end = start + num_bytes - 1;
10312 while (num_bytes > 0) {
10314 trans = btrfs_start_transaction(root, 3);
10315 if (IS_ERR(trans)) {
10316 ret = PTR_ERR(trans);
10321 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10322 cur_bytes = max(cur_bytes, min_size);
10324 * If we are severely fragmented we could end up with really
10325 * small allocations, so if the allocator is returning small
10326 * chunks lets make its job easier by only searching for those
10329 cur_bytes = min(cur_bytes, last_alloc);
10330 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10331 min_size, 0, *alloc_hint, &ins, 1, 0);
10334 btrfs_end_transaction(trans);
10337 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10339 last_alloc = ins.offset;
10340 ret = insert_reserved_file_extent(trans, inode,
10341 cur_offset, ins.objectid,
10342 ins.offset, ins.offset,
10343 ins.offset, 0, 0, 0,
10344 BTRFS_FILE_EXTENT_PREALLOC);
10346 btrfs_free_reserved_extent(fs_info, ins.objectid,
10348 btrfs_abort_transaction(trans, ret);
10350 btrfs_end_transaction(trans);
10354 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10355 cur_offset + ins.offset -1, 0);
10357 em = alloc_extent_map();
10359 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10360 &BTRFS_I(inode)->runtime_flags);
10364 em->start = cur_offset;
10365 em->orig_start = cur_offset;
10366 em->len = ins.offset;
10367 em->block_start = ins.objectid;
10368 em->block_len = ins.offset;
10369 em->orig_block_len = ins.offset;
10370 em->ram_bytes = ins.offset;
10371 em->bdev = fs_info->fs_devices->latest_bdev;
10372 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10373 em->generation = trans->transid;
10376 write_lock(&em_tree->lock);
10377 ret = add_extent_mapping(em_tree, em, 1);
10378 write_unlock(&em_tree->lock);
10379 if (ret != -EEXIST)
10381 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10382 cur_offset + ins.offset - 1,
10385 free_extent_map(em);
10387 num_bytes -= ins.offset;
10388 cur_offset += ins.offset;
10389 *alloc_hint = ins.objectid + ins.offset;
10391 inode_inc_iversion(inode);
10392 inode->i_ctime = current_time(inode);
10393 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10394 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10395 (actual_len > inode->i_size) &&
10396 (cur_offset > inode->i_size)) {
10397 if (cur_offset > actual_len)
10398 i_size = actual_len;
10400 i_size = cur_offset;
10401 i_size_write(inode, i_size);
10402 btrfs_ordered_update_i_size(inode, i_size, NULL);
10405 ret = btrfs_update_inode(trans, root, inode);
10408 btrfs_abort_transaction(trans, ret);
10410 btrfs_end_transaction(trans);
10415 btrfs_end_transaction(trans);
10417 if (cur_offset < end)
10418 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10419 end - cur_offset + 1);
10423 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10424 u64 start, u64 num_bytes, u64 min_size,
10425 loff_t actual_len, u64 *alloc_hint)
10427 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10428 min_size, actual_len, alloc_hint,
10432 int btrfs_prealloc_file_range_trans(struct inode *inode,
10433 struct btrfs_trans_handle *trans, int mode,
10434 u64 start, u64 num_bytes, u64 min_size,
10435 loff_t actual_len, u64 *alloc_hint)
10437 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10438 min_size, actual_len, alloc_hint, trans);
10441 static int btrfs_set_page_dirty(struct page *page)
10443 return __set_page_dirty_nobuffers(page);
10446 static int btrfs_permission(struct inode *inode, int mask)
10448 struct btrfs_root *root = BTRFS_I(inode)->root;
10449 umode_t mode = inode->i_mode;
10451 if (mask & MAY_WRITE &&
10452 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10453 if (btrfs_root_readonly(root))
10455 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10458 return generic_permission(inode, mask);
10461 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10463 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10464 struct btrfs_trans_handle *trans;
10465 struct btrfs_root *root = BTRFS_I(dir)->root;
10466 struct inode *inode = NULL;
10472 * 5 units required for adding orphan entry
10474 trans = btrfs_start_transaction(root, 5);
10476 return PTR_ERR(trans);
10478 ret = btrfs_find_free_ino(root, &objectid);
10482 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10483 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10484 if (IS_ERR(inode)) {
10485 ret = PTR_ERR(inode);
10490 inode->i_fop = &btrfs_file_operations;
10491 inode->i_op = &btrfs_file_inode_operations;
10493 inode->i_mapping->a_ops = &btrfs_aops;
10494 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10496 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10500 ret = btrfs_update_inode(trans, root, inode);
10503 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10508 * We set number of links to 0 in btrfs_new_inode(), and here we set
10509 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10512 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10514 set_nlink(inode, 1);
10515 d_tmpfile(dentry, inode);
10516 unlock_new_inode(inode);
10517 mark_inode_dirty(inode);
10519 btrfs_end_transaction(trans);
10521 discard_new_inode(inode);
10522 btrfs_btree_balance_dirty(fs_info);
10526 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10528 struct inode *inode = tree->private_data;
10529 unsigned long index = start >> PAGE_SHIFT;
10530 unsigned long end_index = end >> PAGE_SHIFT;
10533 while (index <= end_index) {
10534 page = find_get_page(inode->i_mapping, index);
10535 ASSERT(page); /* Pages should be in the extent_io_tree */
10536 set_page_writeback(page);
10544 * Add an entry indicating a block group or device which is pinned by a
10545 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10546 * negative errno on failure.
10548 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10549 bool is_block_group)
10551 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10552 struct btrfs_swapfile_pin *sp, *entry;
10553 struct rb_node **p;
10554 struct rb_node *parent = NULL;
10556 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10561 sp->is_block_group = is_block_group;
10563 spin_lock(&fs_info->swapfile_pins_lock);
10564 p = &fs_info->swapfile_pins.rb_node;
10567 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10568 if (sp->ptr < entry->ptr ||
10569 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10570 p = &(*p)->rb_left;
10571 } else if (sp->ptr > entry->ptr ||
10572 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10573 p = &(*p)->rb_right;
10575 spin_unlock(&fs_info->swapfile_pins_lock);
10580 rb_link_node(&sp->node, parent, p);
10581 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10582 spin_unlock(&fs_info->swapfile_pins_lock);
10586 /* Free all of the entries pinned by this swapfile. */
10587 static void btrfs_free_swapfile_pins(struct inode *inode)
10589 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10590 struct btrfs_swapfile_pin *sp;
10591 struct rb_node *node, *next;
10593 spin_lock(&fs_info->swapfile_pins_lock);
10594 node = rb_first(&fs_info->swapfile_pins);
10596 next = rb_next(node);
10597 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10598 if (sp->inode == inode) {
10599 rb_erase(&sp->node, &fs_info->swapfile_pins);
10600 if (sp->is_block_group)
10601 btrfs_put_block_group(sp->ptr);
10606 spin_unlock(&fs_info->swapfile_pins_lock);
10609 struct btrfs_swap_info {
10615 unsigned long nr_pages;
10619 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10620 struct btrfs_swap_info *bsi)
10622 unsigned long nr_pages;
10623 u64 first_ppage, first_ppage_reported, next_ppage;
10626 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10627 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10628 PAGE_SIZE) >> PAGE_SHIFT;
10630 if (first_ppage >= next_ppage)
10632 nr_pages = next_ppage - first_ppage;
10634 first_ppage_reported = first_ppage;
10635 if (bsi->start == 0)
10636 first_ppage_reported++;
10637 if (bsi->lowest_ppage > first_ppage_reported)
10638 bsi->lowest_ppage = first_ppage_reported;
10639 if (bsi->highest_ppage < (next_ppage - 1))
10640 bsi->highest_ppage = next_ppage - 1;
10642 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10645 bsi->nr_extents += ret;
10646 bsi->nr_pages += nr_pages;
10650 static void btrfs_swap_deactivate(struct file *file)
10652 struct inode *inode = file_inode(file);
10654 btrfs_free_swapfile_pins(inode);
10655 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10658 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10661 struct inode *inode = file_inode(file);
10662 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10663 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10664 struct extent_state *cached_state = NULL;
10665 struct extent_map *em = NULL;
10666 struct btrfs_device *device = NULL;
10667 struct btrfs_swap_info bsi = {
10668 .lowest_ppage = (sector_t)-1ULL,
10675 * If the swap file was just created, make sure delalloc is done. If the
10676 * file changes again after this, the user is doing something stupid and
10677 * we don't really care.
10679 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10684 * The inode is locked, so these flags won't change after we check them.
10686 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10687 btrfs_warn(fs_info, "swapfile must not be compressed");
10690 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10691 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10694 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10695 btrfs_warn(fs_info, "swapfile must not be checksummed");
10700 * Balance or device remove/replace/resize can move stuff around from
10701 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10702 * concurrently while we are mapping the swap extents, and
10703 * fs_info->swapfile_pins prevents them from running while the swap file
10704 * is active and moving the extents. Note that this also prevents a
10705 * concurrent device add which isn't actually necessary, but it's not
10706 * really worth the trouble to allow it.
10708 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10709 btrfs_warn(fs_info,
10710 "cannot activate swapfile while exclusive operation is running");
10714 * Snapshots can create extents which require COW even if NODATACOW is
10715 * set. We use this counter to prevent snapshots. We must increment it
10716 * before walking the extents because we don't want a concurrent
10717 * snapshot to run after we've already checked the extents.
10719 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10721 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10723 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10725 while (start < isize) {
10726 u64 logical_block_start, physical_block_start;
10727 struct btrfs_block_group_cache *bg;
10728 u64 len = isize - start;
10730 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10736 if (em->block_start == EXTENT_MAP_HOLE) {
10737 btrfs_warn(fs_info, "swapfile must not have holes");
10741 if (em->block_start == EXTENT_MAP_INLINE) {
10743 * It's unlikely we'll ever actually find ourselves
10744 * here, as a file small enough to fit inline won't be
10745 * big enough to store more than the swap header, but in
10746 * case something changes in the future, let's catch it
10747 * here rather than later.
10749 btrfs_warn(fs_info, "swapfile must not be inline");
10753 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10754 btrfs_warn(fs_info, "swapfile must not be compressed");
10759 logical_block_start = em->block_start + (start - em->start);
10760 len = min(len, em->len - (start - em->start));
10761 free_extent_map(em);
10764 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10770 btrfs_warn(fs_info,
10771 "swapfile must not be copy-on-write");
10776 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10782 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10783 btrfs_warn(fs_info,
10784 "swapfile must have single data profile");
10789 if (device == NULL) {
10790 device = em->map_lookup->stripes[0].dev;
10791 ret = btrfs_add_swapfile_pin(inode, device, false);
10796 } else if (device != em->map_lookup->stripes[0].dev) {
10797 btrfs_warn(fs_info, "swapfile must be on one device");
10802 physical_block_start = (em->map_lookup->stripes[0].physical +
10803 (logical_block_start - em->start));
10804 len = min(len, em->len - (logical_block_start - em->start));
10805 free_extent_map(em);
10808 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10810 btrfs_warn(fs_info,
10811 "could not find block group containing swapfile");
10816 ret = btrfs_add_swapfile_pin(inode, bg, true);
10818 btrfs_put_block_group(bg);
10825 if (bsi.block_len &&
10826 bsi.block_start + bsi.block_len == physical_block_start) {
10827 bsi.block_len += len;
10829 if (bsi.block_len) {
10830 ret = btrfs_add_swap_extent(sis, &bsi);
10835 bsi.block_start = physical_block_start;
10836 bsi.block_len = len;
10843 ret = btrfs_add_swap_extent(sis, &bsi);
10846 if (!IS_ERR_OR_NULL(em))
10847 free_extent_map(em);
10849 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10852 btrfs_swap_deactivate(file);
10854 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10860 sis->bdev = device->bdev;
10861 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10862 sis->max = bsi.nr_pages;
10863 sis->pages = bsi.nr_pages - 1;
10864 sis->highest_bit = bsi.nr_pages - 1;
10865 return bsi.nr_extents;
10868 static void btrfs_swap_deactivate(struct file *file)
10872 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10875 return -EOPNOTSUPP;
10879 static const struct inode_operations btrfs_dir_inode_operations = {
10880 .getattr = btrfs_getattr,
10881 .lookup = btrfs_lookup,
10882 .create = btrfs_create,
10883 .unlink = btrfs_unlink,
10884 .link = btrfs_link,
10885 .mkdir = btrfs_mkdir,
10886 .rmdir = btrfs_rmdir,
10887 .rename = btrfs_rename2,
10888 .symlink = btrfs_symlink,
10889 .setattr = btrfs_setattr,
10890 .mknod = btrfs_mknod,
10891 .listxattr = btrfs_listxattr,
10892 .permission = btrfs_permission,
10893 .get_acl = btrfs_get_acl,
10894 .set_acl = btrfs_set_acl,
10895 .update_time = btrfs_update_time,
10896 .tmpfile = btrfs_tmpfile,
10898 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10899 .lookup = btrfs_lookup,
10900 .permission = btrfs_permission,
10901 .update_time = btrfs_update_time,
10904 static const struct file_operations btrfs_dir_file_operations = {
10905 .llseek = generic_file_llseek,
10906 .read = generic_read_dir,
10907 .iterate_shared = btrfs_real_readdir,
10908 .open = btrfs_opendir,
10909 .unlocked_ioctl = btrfs_ioctl,
10910 #ifdef CONFIG_COMPAT
10911 .compat_ioctl = btrfs_compat_ioctl,
10913 .release = btrfs_release_file,
10914 .fsync = btrfs_sync_file,
10917 static const struct extent_io_ops btrfs_extent_io_ops = {
10918 /* mandatory callbacks */
10919 .submit_bio_hook = btrfs_submit_bio_hook,
10920 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10924 * btrfs doesn't support the bmap operation because swapfiles
10925 * use bmap to make a mapping of extents in the file. They assume
10926 * these extents won't change over the life of the file and they
10927 * use the bmap result to do IO directly to the drive.
10929 * the btrfs bmap call would return logical addresses that aren't
10930 * suitable for IO and they also will change frequently as COW
10931 * operations happen. So, swapfile + btrfs == corruption.
10933 * For now we're avoiding this by dropping bmap.
10935 static const struct address_space_operations btrfs_aops = {
10936 .readpage = btrfs_readpage,
10937 .writepage = btrfs_writepage,
10938 .writepages = btrfs_writepages,
10939 .readpages = btrfs_readpages,
10940 .direct_IO = btrfs_direct_IO,
10941 .invalidatepage = btrfs_invalidatepage,
10942 .releasepage = btrfs_releasepage,
10943 .set_page_dirty = btrfs_set_page_dirty,
10944 .error_remove_page = generic_error_remove_page,
10945 .swap_activate = btrfs_swap_activate,
10946 .swap_deactivate = btrfs_swap_deactivate,
10949 static const struct inode_operations btrfs_file_inode_operations = {
10950 .getattr = btrfs_getattr,
10951 .setattr = btrfs_setattr,
10952 .listxattr = btrfs_listxattr,
10953 .permission = btrfs_permission,
10954 .fiemap = btrfs_fiemap,
10955 .get_acl = btrfs_get_acl,
10956 .set_acl = btrfs_set_acl,
10957 .update_time = btrfs_update_time,
10959 static const struct inode_operations btrfs_special_inode_operations = {
10960 .getattr = btrfs_getattr,
10961 .setattr = btrfs_setattr,
10962 .permission = btrfs_permission,
10963 .listxattr = btrfs_listxattr,
10964 .get_acl = btrfs_get_acl,
10965 .set_acl = btrfs_set_acl,
10966 .update_time = btrfs_update_time,
10968 static const struct inode_operations btrfs_symlink_inode_operations = {
10969 .get_link = page_get_link,
10970 .getattr = btrfs_getattr,
10971 .setattr = btrfs_setattr,
10972 .permission = btrfs_permission,
10973 .listxattr = btrfs_listxattr,
10974 .update_time = btrfs_update_time,
10977 const struct dentry_operations btrfs_dentry_operations = {
10978 .d_delete = btrfs_dentry_delete,