1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <asm/unaligned.h>
34 #include "transaction.h"
35 #include "btrfs_inode.h"
36 #include "print-tree.h"
37 #include "ordered-data.h"
41 #include "compression.h"
43 #include "free-space-cache.h"
44 #include "inode-map.h"
50 struct btrfs_iget_args {
51 struct btrfs_key *location;
52 struct btrfs_root *root;
55 struct btrfs_dio_data {
57 u64 unsubmitted_oe_range_start;
58 u64 unsubmitted_oe_range_end;
62 static const struct inode_operations btrfs_dir_inode_operations;
63 static const struct inode_operations btrfs_symlink_inode_operations;
64 static const struct inode_operations btrfs_dir_ro_inode_operations;
65 static const struct inode_operations btrfs_special_inode_operations;
66 static const struct inode_operations btrfs_file_inode_operations;
67 static const struct address_space_operations btrfs_aops;
68 static const struct file_operations btrfs_dir_file_operations;
69 static const struct extent_io_ops btrfs_extent_io_ops;
71 static struct kmem_cache *btrfs_inode_cachep;
72 struct kmem_cache *btrfs_trans_handle_cachep;
73 struct kmem_cache *btrfs_path_cachep;
74 struct kmem_cache *btrfs_free_space_cachep;
76 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
77 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
78 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
79 static noinline int cow_file_range(struct inode *inode,
80 struct page *locked_page,
81 u64 start, u64 end, u64 delalloc_end,
82 int *page_started, unsigned long *nr_written,
83 int unlock, struct btrfs_dedupe_hash *hash);
84 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
85 u64 orig_start, u64 block_start,
86 u64 block_len, u64 orig_block_len,
87 u64 ram_bytes, int compress_type,
90 static void __endio_write_update_ordered(struct inode *inode,
91 const u64 offset, const u64 bytes,
95 * Cleanup all submitted ordered extents in specified range to handle errors
96 * from the btrfs_run_delalloc_range() callback.
98 * NOTE: caller must ensure that when an error happens, it can not call
99 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
100 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
101 * to be released, which we want to happen only when finishing the ordered
102 * extent (btrfs_finish_ordered_io()).
104 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
105 struct page *locked_page,
106 u64 offset, u64 bytes)
108 unsigned long index = offset >> PAGE_SHIFT;
109 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
110 u64 page_start = page_offset(locked_page);
111 u64 page_end = page_start + PAGE_SIZE - 1;
115 while (index <= end_index) {
116 page = find_get_page(inode->i_mapping, index);
120 ClearPagePrivate2(page);
125 * In case this page belongs to the delalloc range being instantiated
126 * then skip it, since the first page of a range is going to be
127 * properly cleaned up by the caller of run_delalloc_range
129 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
134 return __endio_write_update_ordered(inode, offset, bytes, false);
137 static int btrfs_dirty_inode(struct inode *inode);
139 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
140 void btrfs_test_inode_set_ops(struct inode *inode)
142 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
146 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
147 struct inode *inode, struct inode *dir,
148 const struct qstr *qstr)
152 err = btrfs_init_acl(trans, inode, dir);
154 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
159 * this does all the hard work for inserting an inline extent into
160 * the btree. The caller should have done a btrfs_drop_extents so that
161 * no overlapping inline items exist in the btree
163 static int insert_inline_extent(struct btrfs_trans_handle *trans,
164 struct btrfs_path *path, int extent_inserted,
165 struct btrfs_root *root, struct inode *inode,
166 u64 start, size_t size, size_t compressed_size,
168 struct page **compressed_pages)
170 struct extent_buffer *leaf;
171 struct page *page = NULL;
174 struct btrfs_file_extent_item *ei;
176 size_t cur_size = size;
177 unsigned long offset;
179 if (compressed_size && compressed_pages)
180 cur_size = compressed_size;
182 inode_add_bytes(inode, size);
184 if (!extent_inserted) {
185 struct btrfs_key key;
188 key.objectid = btrfs_ino(BTRFS_I(inode));
190 key.type = BTRFS_EXTENT_DATA_KEY;
192 datasize = btrfs_file_extent_calc_inline_size(cur_size);
193 path->leave_spinning = 1;
194 ret = btrfs_insert_empty_item(trans, root, path, &key,
199 leaf = path->nodes[0];
200 ei = btrfs_item_ptr(leaf, path->slots[0],
201 struct btrfs_file_extent_item);
202 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
203 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
204 btrfs_set_file_extent_encryption(leaf, ei, 0);
205 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
206 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
207 ptr = btrfs_file_extent_inline_start(ei);
209 if (compress_type != BTRFS_COMPRESS_NONE) {
212 while (compressed_size > 0) {
213 cpage = compressed_pages[i];
214 cur_size = min_t(unsigned long, compressed_size,
217 kaddr = kmap_atomic(cpage);
218 write_extent_buffer(leaf, kaddr, ptr, cur_size);
219 kunmap_atomic(kaddr);
223 compressed_size -= cur_size;
225 btrfs_set_file_extent_compression(leaf, ei,
228 page = find_get_page(inode->i_mapping,
229 start >> PAGE_SHIFT);
230 btrfs_set_file_extent_compression(leaf, ei, 0);
231 kaddr = kmap_atomic(page);
232 offset = offset_in_page(start);
233 write_extent_buffer(leaf, kaddr + offset, ptr, size);
234 kunmap_atomic(kaddr);
237 btrfs_mark_buffer_dirty(leaf);
238 btrfs_release_path(path);
241 * we're an inline extent, so nobody can
242 * extend the file past i_size without locking
243 * a page we already have locked.
245 * We must do any isize and inode updates
246 * before we unlock the pages. Otherwise we
247 * could end up racing with unlink.
249 BTRFS_I(inode)->disk_i_size = inode->i_size;
250 ret = btrfs_update_inode(trans, root, inode);
258 * conditionally insert an inline extent into the file. This
259 * does the checks required to make sure the data is small enough
260 * to fit as an inline extent.
262 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
263 u64 end, size_t compressed_size,
265 struct page **compressed_pages)
267 struct btrfs_root *root = BTRFS_I(inode)->root;
268 struct btrfs_fs_info *fs_info = root->fs_info;
269 struct btrfs_trans_handle *trans;
270 u64 isize = i_size_read(inode);
271 u64 actual_end = min(end + 1, isize);
272 u64 inline_len = actual_end - start;
273 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
274 u64 data_len = inline_len;
276 struct btrfs_path *path;
277 int extent_inserted = 0;
278 u32 extent_item_size;
281 data_len = compressed_size;
284 actual_end > fs_info->sectorsize ||
285 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
287 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
289 data_len > fs_info->max_inline) {
293 path = btrfs_alloc_path();
297 trans = btrfs_join_transaction(root);
299 btrfs_free_path(path);
300 return PTR_ERR(trans);
302 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
304 if (compressed_size && compressed_pages)
305 extent_item_size = btrfs_file_extent_calc_inline_size(
308 extent_item_size = btrfs_file_extent_calc_inline_size(
311 ret = __btrfs_drop_extents(trans, root, inode, path,
312 start, aligned_end, NULL,
313 1, 1, extent_item_size, &extent_inserted);
315 btrfs_abort_transaction(trans, ret);
319 if (isize > actual_end)
320 inline_len = min_t(u64, isize, actual_end);
321 ret = insert_inline_extent(trans, path, extent_inserted,
323 inline_len, compressed_size,
324 compress_type, compressed_pages);
325 if (ret && ret != -ENOSPC) {
326 btrfs_abort_transaction(trans, ret);
328 } else if (ret == -ENOSPC) {
333 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
334 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
337 * Don't forget to free the reserved space, as for inlined extent
338 * it won't count as data extent, free them directly here.
339 * And at reserve time, it's always aligned to page size, so
340 * just free one page here.
342 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
343 btrfs_free_path(path);
344 btrfs_end_transaction(trans);
348 struct async_extent {
353 unsigned long nr_pages;
355 struct list_head list;
360 struct btrfs_fs_info *fs_info;
361 struct page *locked_page;
364 unsigned int write_flags;
365 struct list_head extents;
366 struct btrfs_work work;
371 /* Number of chunks in flight; must be first in the structure */
373 struct async_chunk chunks[];
376 static noinline int add_async_extent(struct async_chunk *cow,
377 u64 start, u64 ram_size,
380 unsigned long nr_pages,
383 struct async_extent *async_extent;
385 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
386 BUG_ON(!async_extent); /* -ENOMEM */
387 async_extent->start = start;
388 async_extent->ram_size = ram_size;
389 async_extent->compressed_size = compressed_size;
390 async_extent->pages = pages;
391 async_extent->nr_pages = nr_pages;
392 async_extent->compress_type = compress_type;
393 list_add_tail(&async_extent->list, &cow->extents);
397 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
399 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
402 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
405 if (BTRFS_I(inode)->defrag_compress)
407 /* bad compression ratios */
408 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
410 if (btrfs_test_opt(fs_info, COMPRESS) ||
411 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
412 BTRFS_I(inode)->prop_compress)
413 return btrfs_compress_heuristic(inode, start, end);
417 static inline void inode_should_defrag(struct btrfs_inode *inode,
418 u64 start, u64 end, u64 num_bytes, u64 small_write)
420 /* If this is a small write inside eof, kick off a defrag */
421 if (num_bytes < small_write &&
422 (start > 0 || end + 1 < inode->disk_i_size))
423 btrfs_add_inode_defrag(NULL, inode);
427 * we create compressed extents in two phases. The first
428 * phase compresses a range of pages that have already been
429 * locked (both pages and state bits are locked).
431 * This is done inside an ordered work queue, and the compression
432 * is spread across many cpus. The actual IO submission is step
433 * two, and the ordered work queue takes care of making sure that
434 * happens in the same order things were put onto the queue by
435 * writepages and friends.
437 * If this code finds it can't get good compression, it puts an
438 * entry onto the work queue to write the uncompressed bytes. This
439 * makes sure that both compressed inodes and uncompressed inodes
440 * are written in the same order that the flusher thread sent them
443 static noinline void compress_file_range(struct inode *inode,
444 struct page *locked_page,
446 struct async_chunk *async_cow,
449 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
450 u64 blocksize = fs_info->sectorsize;
453 struct page **pages = NULL;
454 unsigned long nr_pages;
455 unsigned long total_compressed = 0;
456 unsigned long total_in = 0;
459 int compress_type = fs_info->compress_type;
462 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
465 actual_end = min_t(u64, i_size_read(inode), end + 1);
468 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
469 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
470 nr_pages = min_t(unsigned long, nr_pages,
471 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
474 * we don't want to send crud past the end of i_size through
475 * compression, that's just a waste of CPU time. So, if the
476 * end of the file is before the start of our current
477 * requested range of bytes, we bail out to the uncompressed
478 * cleanup code that can deal with all of this.
480 * It isn't really the fastest way to fix things, but this is a
481 * very uncommon corner.
483 if (actual_end <= start)
484 goto cleanup_and_bail_uncompressed;
486 total_compressed = actual_end - start;
489 * skip compression for a small file range(<=blocksize) that
490 * isn't an inline extent, since it doesn't save disk space at all.
492 if (total_compressed <= blocksize &&
493 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
494 goto cleanup_and_bail_uncompressed;
496 total_compressed = min_t(unsigned long, total_compressed,
497 BTRFS_MAX_UNCOMPRESSED);
502 * we do compression for mount -o compress and when the
503 * inode has not been flagged as nocompress. This flag can
504 * change at any time if we discover bad compression ratios.
506 if (inode_need_compress(inode, start, end)) {
508 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
510 /* just bail out to the uncompressed code */
515 if (BTRFS_I(inode)->defrag_compress)
516 compress_type = BTRFS_I(inode)->defrag_compress;
517 else if (BTRFS_I(inode)->prop_compress)
518 compress_type = BTRFS_I(inode)->prop_compress;
521 * we need to call clear_page_dirty_for_io on each
522 * page in the range. Otherwise applications with the file
523 * mmap'd can wander in and change the page contents while
524 * we are compressing them.
526 * If the compression fails for any reason, we set the pages
527 * dirty again later on.
529 * Note that the remaining part is redirtied, the start pointer
530 * has moved, the end is the original one.
533 extent_range_clear_dirty_for_io(inode, start, end);
537 /* Compression level is applied here and only here */
538 ret = btrfs_compress_pages(
539 compress_type | (fs_info->compress_level << 4),
540 inode->i_mapping, start,
547 unsigned long offset = offset_in_page(total_compressed);
548 struct page *page = pages[nr_pages - 1];
551 /* zero the tail end of the last page, we might be
552 * sending it down to disk
555 kaddr = kmap_atomic(page);
556 memset(kaddr + offset, 0,
558 kunmap_atomic(kaddr);
565 /* lets try to make an inline extent */
566 if (ret || total_in < actual_end) {
567 /* we didn't compress the entire range, try
568 * to make an uncompressed inline extent.
570 ret = cow_file_range_inline(inode, start, end, 0,
571 BTRFS_COMPRESS_NONE, NULL);
573 /* try making a compressed inline extent */
574 ret = cow_file_range_inline(inode, start, end,
576 compress_type, pages);
579 unsigned long clear_flags = EXTENT_DELALLOC |
580 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
581 EXTENT_DO_ACCOUNTING;
582 unsigned long page_error_op;
584 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
587 * inline extent creation worked or returned error,
588 * we don't need to create any more async work items.
589 * Unlock and free up our temp pages.
591 * We use DO_ACCOUNTING here because we need the
592 * delalloc_release_metadata to be done _after_ we drop
593 * our outstanding extent for clearing delalloc for this
596 extent_clear_unlock_delalloc(inode, start, end, end,
609 * we aren't doing an inline extent round the compressed size
610 * up to a block size boundary so the allocator does sane
613 total_compressed = ALIGN(total_compressed, blocksize);
616 * one last check to make sure the compression is really a
617 * win, compare the page count read with the blocks on disk,
618 * compression must free at least one sector size
620 total_in = ALIGN(total_in, PAGE_SIZE);
621 if (total_compressed + blocksize <= total_in) {
625 * The async work queues will take care of doing actual
626 * allocation on disk for these compressed pages, and
627 * will submit them to the elevator.
629 add_async_extent(async_cow, start, total_in,
630 total_compressed, pages, nr_pages,
633 if (start + total_in < end) {
644 * the compression code ran but failed to make things smaller,
645 * free any pages it allocated and our page pointer array
647 for (i = 0; i < nr_pages; i++) {
648 WARN_ON(pages[i]->mapping);
653 total_compressed = 0;
656 /* flag the file so we don't compress in the future */
657 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
658 !(BTRFS_I(inode)->prop_compress)) {
659 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
662 cleanup_and_bail_uncompressed:
664 * No compression, but we still need to write the pages in the file
665 * we've been given so far. redirty the locked page if it corresponds
666 * to our extent and set things up for the async work queue to run
667 * cow_file_range to do the normal delalloc dance.
669 if (page_offset(locked_page) >= start &&
670 page_offset(locked_page) <= end)
671 __set_page_dirty_nobuffers(locked_page);
672 /* unlocked later on in the async handlers */
675 extent_range_redirty_for_io(inode, start, end);
676 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
677 BTRFS_COMPRESS_NONE);
683 for (i = 0; i < nr_pages; i++) {
684 WARN_ON(pages[i]->mapping);
690 static void free_async_extent_pages(struct async_extent *async_extent)
694 if (!async_extent->pages)
697 for (i = 0; i < async_extent->nr_pages; i++) {
698 WARN_ON(async_extent->pages[i]->mapping);
699 put_page(async_extent->pages[i]);
701 kfree(async_extent->pages);
702 async_extent->nr_pages = 0;
703 async_extent->pages = NULL;
707 * phase two of compressed writeback. This is the ordered portion
708 * of the code, which only gets called in the order the work was
709 * queued. We walk all the async extents created by compress_file_range
710 * and send them down to the disk.
712 static noinline void submit_compressed_extents(struct async_chunk *async_cow)
714 struct inode *inode = async_cow->inode;
715 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
716 struct async_extent *async_extent;
718 struct btrfs_key ins;
719 struct extent_map *em;
720 struct btrfs_root *root = BTRFS_I(inode)->root;
721 struct extent_io_tree *io_tree;
725 while (!list_empty(&async_cow->extents)) {
726 async_extent = list_entry(async_cow->extents.next,
727 struct async_extent, list);
728 list_del(&async_extent->list);
730 io_tree = &BTRFS_I(inode)->io_tree;
733 /* did the compression code fall back to uncompressed IO? */
734 if (!async_extent->pages) {
735 int page_started = 0;
736 unsigned long nr_written = 0;
738 lock_extent(io_tree, async_extent->start,
739 async_extent->start +
740 async_extent->ram_size - 1);
742 /* allocate blocks */
743 ret = cow_file_range(inode, async_cow->locked_page,
745 async_extent->start +
746 async_extent->ram_size - 1,
747 async_extent->start +
748 async_extent->ram_size - 1,
749 &page_started, &nr_written, 0,
755 * if page_started, cow_file_range inserted an
756 * inline extent and took care of all the unlocking
757 * and IO for us. Otherwise, we need to submit
758 * all those pages down to the drive.
760 if (!page_started && !ret)
761 extent_write_locked_range(inode,
763 async_extent->start +
764 async_extent->ram_size - 1,
767 unlock_page(async_cow->locked_page);
773 lock_extent(io_tree, async_extent->start,
774 async_extent->start + async_extent->ram_size - 1);
776 ret = btrfs_reserve_extent(root, async_extent->ram_size,
777 async_extent->compressed_size,
778 async_extent->compressed_size,
779 0, alloc_hint, &ins, 1, 1);
781 free_async_extent_pages(async_extent);
783 if (ret == -ENOSPC) {
784 unlock_extent(io_tree, async_extent->start,
785 async_extent->start +
786 async_extent->ram_size - 1);
789 * we need to redirty the pages if we decide to
790 * fallback to uncompressed IO, otherwise we
791 * will not submit these pages down to lower
794 extent_range_redirty_for_io(inode,
796 async_extent->start +
797 async_extent->ram_size - 1);
804 * here we're doing allocation and writeback of the
807 em = create_io_em(inode, async_extent->start,
808 async_extent->ram_size, /* len */
809 async_extent->start, /* orig_start */
810 ins.objectid, /* block_start */
811 ins.offset, /* block_len */
812 ins.offset, /* orig_block_len */
813 async_extent->ram_size, /* ram_bytes */
814 async_extent->compress_type,
815 BTRFS_ORDERED_COMPRESSED);
817 /* ret value is not necessary due to void function */
818 goto out_free_reserve;
821 ret = btrfs_add_ordered_extent_compress(inode,
824 async_extent->ram_size,
826 BTRFS_ORDERED_COMPRESSED,
827 async_extent->compress_type);
829 btrfs_drop_extent_cache(BTRFS_I(inode),
831 async_extent->start +
832 async_extent->ram_size - 1, 0);
833 goto out_free_reserve;
835 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
838 * clear dirty, set writeback and unlock the pages.
840 extent_clear_unlock_delalloc(inode, async_extent->start,
841 async_extent->start +
842 async_extent->ram_size - 1,
843 async_extent->start +
844 async_extent->ram_size - 1,
845 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
846 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
848 if (btrfs_submit_compressed_write(inode,
850 async_extent->ram_size,
852 ins.offset, async_extent->pages,
853 async_extent->nr_pages,
854 async_cow->write_flags)) {
855 struct page *p = async_extent->pages[0];
856 const u64 start = async_extent->start;
857 const u64 end = start + async_extent->ram_size - 1;
859 p->mapping = inode->i_mapping;
860 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
863 extent_clear_unlock_delalloc(inode, start, end, end,
867 free_async_extent_pages(async_extent);
869 alloc_hint = ins.objectid + ins.offset;
875 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
876 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
878 extent_clear_unlock_delalloc(inode, async_extent->start,
879 async_extent->start +
880 async_extent->ram_size - 1,
881 async_extent->start +
882 async_extent->ram_size - 1,
883 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
884 EXTENT_DELALLOC_NEW |
885 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
886 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
887 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
889 free_async_extent_pages(async_extent);
894 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
897 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
898 struct extent_map *em;
901 read_lock(&em_tree->lock);
902 em = search_extent_mapping(em_tree, start, num_bytes);
905 * if block start isn't an actual block number then find the
906 * first block in this inode and use that as a hint. If that
907 * block is also bogus then just don't worry about it.
909 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
911 em = search_extent_mapping(em_tree, 0, 0);
912 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
913 alloc_hint = em->block_start;
917 alloc_hint = em->block_start;
921 read_unlock(&em_tree->lock);
927 * when extent_io.c finds a delayed allocation range in the file,
928 * the call backs end up in this code. The basic idea is to
929 * allocate extents on disk for the range, and create ordered data structs
930 * in ram to track those extents.
932 * locked_page is the page that writepage had locked already. We use
933 * it to make sure we don't do extra locks or unlocks.
935 * *page_started is set to one if we unlock locked_page and do everything
936 * required to start IO on it. It may be clean and already done with
939 static noinline int cow_file_range(struct inode *inode,
940 struct page *locked_page,
941 u64 start, u64 end, u64 delalloc_end,
942 int *page_started, unsigned long *nr_written,
943 int unlock, struct btrfs_dedupe_hash *hash)
945 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
946 struct btrfs_root *root = BTRFS_I(inode)->root;
949 unsigned long ram_size;
950 u64 cur_alloc_size = 0;
951 u64 blocksize = fs_info->sectorsize;
952 struct btrfs_key ins;
953 struct extent_map *em;
955 unsigned long page_ops;
956 bool extent_reserved = false;
959 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
965 num_bytes = ALIGN(end - start + 1, blocksize);
966 num_bytes = max(blocksize, num_bytes);
967 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
969 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
972 /* lets try to make an inline extent */
973 ret = cow_file_range_inline(inode, start, end, 0,
974 BTRFS_COMPRESS_NONE, NULL);
977 * We use DO_ACCOUNTING here because we need the
978 * delalloc_release_metadata to be run _after_ we drop
979 * our outstanding extent for clearing delalloc for this
982 extent_clear_unlock_delalloc(inode, start, end,
984 EXTENT_LOCKED | EXTENT_DELALLOC |
985 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
986 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
987 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
989 *nr_written = *nr_written +
990 (end - start + PAGE_SIZE) / PAGE_SIZE;
993 } else if (ret < 0) {
998 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
999 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1000 start + num_bytes - 1, 0);
1002 while (num_bytes > 0) {
1003 cur_alloc_size = num_bytes;
1004 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1005 fs_info->sectorsize, 0, alloc_hint,
1009 cur_alloc_size = ins.offset;
1010 extent_reserved = true;
1012 ram_size = ins.offset;
1013 em = create_io_em(inode, start, ins.offset, /* len */
1014 start, /* orig_start */
1015 ins.objectid, /* block_start */
1016 ins.offset, /* block_len */
1017 ins.offset, /* orig_block_len */
1018 ram_size, /* ram_bytes */
1019 BTRFS_COMPRESS_NONE, /* compress_type */
1020 BTRFS_ORDERED_REGULAR /* type */);
1025 free_extent_map(em);
1027 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1028 ram_size, cur_alloc_size, 0);
1030 goto out_drop_extent_cache;
1032 if (root->root_key.objectid ==
1033 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1034 ret = btrfs_reloc_clone_csums(inode, start,
1037 * Only drop cache here, and process as normal.
1039 * We must not allow extent_clear_unlock_delalloc()
1040 * at out_unlock label to free meta of this ordered
1041 * extent, as its meta should be freed by
1042 * btrfs_finish_ordered_io().
1044 * So we must continue until @start is increased to
1045 * skip current ordered extent.
1048 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1049 start + ram_size - 1, 0);
1052 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1054 /* we're not doing compressed IO, don't unlock the first
1055 * page (which the caller expects to stay locked), don't
1056 * clear any dirty bits and don't set any writeback bits
1058 * Do set the Private2 bit so we know this page was properly
1059 * setup for writepage
1061 page_ops = unlock ? PAGE_UNLOCK : 0;
1062 page_ops |= PAGE_SET_PRIVATE2;
1064 extent_clear_unlock_delalloc(inode, start,
1065 start + ram_size - 1,
1066 delalloc_end, locked_page,
1067 EXTENT_LOCKED | EXTENT_DELALLOC,
1069 if (num_bytes < cur_alloc_size)
1072 num_bytes -= cur_alloc_size;
1073 alloc_hint = ins.objectid + ins.offset;
1074 start += cur_alloc_size;
1075 extent_reserved = false;
1078 * btrfs_reloc_clone_csums() error, since start is increased
1079 * extent_clear_unlock_delalloc() at out_unlock label won't
1080 * free metadata of current ordered extent, we're OK to exit.
1088 out_drop_extent_cache:
1089 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1091 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1092 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1094 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1095 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1096 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1099 * If we reserved an extent for our delalloc range (or a subrange) and
1100 * failed to create the respective ordered extent, then it means that
1101 * when we reserved the extent we decremented the extent's size from
1102 * the data space_info's bytes_may_use counter and incremented the
1103 * space_info's bytes_reserved counter by the same amount. We must make
1104 * sure extent_clear_unlock_delalloc() does not try to decrement again
1105 * the data space_info's bytes_may_use counter, therefore we do not pass
1106 * it the flag EXTENT_CLEAR_DATA_RESV.
1108 if (extent_reserved) {
1109 extent_clear_unlock_delalloc(inode, start,
1110 start + cur_alloc_size,
1111 start + cur_alloc_size,
1115 start += cur_alloc_size;
1119 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1121 clear_bits | EXTENT_CLEAR_DATA_RESV,
1127 * work queue call back to started compression on a file and pages
1129 static noinline void async_cow_start(struct btrfs_work *work)
1131 struct async_chunk *async_cow;
1134 async_cow = container_of(work, struct async_chunk, work);
1136 compress_file_range(async_cow->inode, async_cow->locked_page,
1137 async_cow->start, async_cow->end, async_cow,
1139 if (num_added == 0) {
1140 btrfs_add_delayed_iput(async_cow->inode);
1141 async_cow->inode = NULL;
1146 * work queue call back to submit previously compressed pages
1148 static noinline void async_cow_submit(struct btrfs_work *work)
1150 struct btrfs_fs_info *fs_info;
1151 struct async_chunk *async_cow;
1152 unsigned long nr_pages;
1154 async_cow = container_of(work, struct async_chunk, work);
1156 fs_info = async_cow->fs_info;
1157 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1160 /* atomic_sub_return implies a barrier */
1161 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1163 cond_wake_up_nomb(&fs_info->async_submit_wait);
1166 * ->inode could be NULL if async_cow_start has failed to compress,
1167 * in which case we don't have anything to submit, yet we need to
1168 * always adjust ->async_delalloc_pages as its paired with the init
1169 * happening in cow_file_range_async
1171 if (async_cow->inode)
1172 submit_compressed_extents(async_cow);
1175 static noinline void async_cow_free(struct btrfs_work *work)
1177 struct async_chunk *async_cow;
1179 async_cow = container_of(work, struct async_chunk, work);
1180 if (async_cow->inode)
1181 btrfs_add_delayed_iput(async_cow->inode);
1183 * Since the pointer to 'pending' is at the beginning of the array of
1184 * async_cow's, freeing it ensures the whole array has been freed.
1186 if (atomic_dec_and_test(async_cow->pending))
1187 kfree(async_cow->pending);
1190 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1191 u64 start, u64 end, int *page_started,
1192 unsigned long *nr_written,
1193 unsigned int write_flags)
1195 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1196 struct async_cow *ctx;
1197 struct async_chunk *async_chunk;
1198 unsigned long nr_pages;
1200 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1202 bool should_compress;
1204 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1207 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1208 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1210 should_compress = false;
1212 should_compress = true;
1215 ctx = kmalloc(struct_size(ctx, chunks, num_chunks), GFP_NOFS);
1217 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1218 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1219 EXTENT_DO_ACCOUNTING;
1220 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1221 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1224 extent_clear_unlock_delalloc(inode, start, end, 0, locked_page,
1225 clear_bits, page_ops);
1229 async_chunk = ctx->chunks;
1230 atomic_set(&ctx->num_chunks, num_chunks);
1232 for (i = 0; i < num_chunks; i++) {
1233 if (should_compress)
1234 cur_end = min(end, start + SZ_512K - 1);
1239 * igrab is called higher up in the call chain, take only the
1240 * lightweight reference for the callback lifetime
1243 async_chunk[i].pending = &ctx->num_chunks;
1244 async_chunk[i].inode = inode;
1245 async_chunk[i].start = start;
1246 async_chunk[i].end = cur_end;
1247 async_chunk[i].fs_info = fs_info;
1248 async_chunk[i].locked_page = locked_page;
1249 async_chunk[i].write_flags = write_flags;
1250 INIT_LIST_HEAD(&async_chunk[i].extents);
1252 btrfs_init_work(&async_chunk[i].work,
1253 btrfs_delalloc_helper,
1254 async_cow_start, async_cow_submit,
1257 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1258 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1260 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1262 *nr_written += nr_pages;
1263 start = cur_end + 1;
1269 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1270 u64 bytenr, u64 num_bytes)
1273 struct btrfs_ordered_sum *sums;
1276 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1277 bytenr + num_bytes - 1, &list, 0);
1278 if (ret == 0 && list_empty(&list))
1281 while (!list_empty(&list)) {
1282 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1283 list_del(&sums->list);
1292 * when nowcow writeback call back. This checks for snapshots or COW copies
1293 * of the extents that exist in the file, and COWs the file as required.
1295 * If no cow copies or snapshots exist, we write directly to the existing
1298 static noinline int run_delalloc_nocow(struct inode *inode,
1299 struct page *locked_page,
1300 u64 start, u64 end, int *page_started, int force,
1301 unsigned long *nr_written)
1303 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1304 struct btrfs_root *root = BTRFS_I(inode)->root;
1305 struct extent_buffer *leaf;
1306 struct btrfs_path *path;
1307 struct btrfs_file_extent_item *fi;
1308 struct btrfs_key found_key;
1309 struct extent_map *em;
1324 u64 ino = btrfs_ino(BTRFS_I(inode));
1326 path = btrfs_alloc_path();
1328 extent_clear_unlock_delalloc(inode, start, end, end,
1330 EXTENT_LOCKED | EXTENT_DELALLOC |
1331 EXTENT_DO_ACCOUNTING |
1332 EXTENT_DEFRAG, PAGE_UNLOCK |
1334 PAGE_SET_WRITEBACK |
1335 PAGE_END_WRITEBACK);
1339 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1341 cow_start = (u64)-1;
1344 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1348 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1349 leaf = path->nodes[0];
1350 btrfs_item_key_to_cpu(leaf, &found_key,
1351 path->slots[0] - 1);
1352 if (found_key.objectid == ino &&
1353 found_key.type == BTRFS_EXTENT_DATA_KEY)
1358 leaf = path->nodes[0];
1359 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1360 ret = btrfs_next_leaf(root, path);
1362 if (cow_start != (u64)-1)
1363 cur_offset = cow_start;
1368 leaf = path->nodes[0];
1374 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1376 if (found_key.objectid > ino)
1378 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1379 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1383 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1384 found_key.offset > end)
1387 if (found_key.offset > cur_offset) {
1388 extent_end = found_key.offset;
1393 fi = btrfs_item_ptr(leaf, path->slots[0],
1394 struct btrfs_file_extent_item);
1395 extent_type = btrfs_file_extent_type(leaf, fi);
1397 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1398 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1399 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1400 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1401 extent_offset = btrfs_file_extent_offset(leaf, fi);
1402 extent_end = found_key.offset +
1403 btrfs_file_extent_num_bytes(leaf, fi);
1405 btrfs_file_extent_disk_num_bytes(leaf, fi);
1406 if (extent_end <= start) {
1410 if (disk_bytenr == 0)
1412 if (btrfs_file_extent_compression(leaf, fi) ||
1413 btrfs_file_extent_encryption(leaf, fi) ||
1414 btrfs_file_extent_other_encoding(leaf, fi))
1417 * Do the same check as in btrfs_cross_ref_exist but
1418 * without the unnecessary search.
1421 btrfs_file_extent_generation(leaf, fi) <=
1422 btrfs_root_last_snapshot(&root->root_item))
1424 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1426 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1428 ret = btrfs_cross_ref_exist(root, ino,
1430 extent_offset, disk_bytenr);
1433 * ret could be -EIO if the above fails to read
1437 if (cow_start != (u64)-1)
1438 cur_offset = cow_start;
1442 WARN_ON_ONCE(nolock);
1445 disk_bytenr += extent_offset;
1446 disk_bytenr += cur_offset - found_key.offset;
1447 num_bytes = min(end + 1, extent_end) - cur_offset;
1449 * if there are pending snapshots for this root,
1450 * we fall into common COW way.
1452 if (!nolock && atomic_read(&root->snapshot_force_cow))
1455 * force cow if csum exists in the range.
1456 * this ensure that csum for a given extent are
1457 * either valid or do not exist.
1459 ret = csum_exist_in_range(fs_info, disk_bytenr,
1463 * ret could be -EIO if the above fails to read
1467 if (cow_start != (u64)-1)
1468 cur_offset = cow_start;
1471 WARN_ON_ONCE(nolock);
1474 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1477 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1478 extent_end = found_key.offset +
1479 btrfs_file_extent_ram_bytes(leaf, fi);
1480 extent_end = ALIGN(extent_end,
1481 fs_info->sectorsize);
1486 if (extent_end <= start) {
1489 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1493 if (cow_start == (u64)-1)
1494 cow_start = cur_offset;
1495 cur_offset = extent_end;
1496 if (cur_offset > end)
1502 btrfs_release_path(path);
1503 if (cow_start != (u64)-1) {
1504 ret = cow_file_range(inode, locked_page,
1505 cow_start, found_key.offset - 1,
1506 end, page_started, nr_written, 1,
1510 btrfs_dec_nocow_writers(fs_info,
1514 cow_start = (u64)-1;
1517 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1518 u64 orig_start = found_key.offset - extent_offset;
1520 em = create_io_em(inode, cur_offset, num_bytes,
1522 disk_bytenr, /* block_start */
1523 num_bytes, /* block_len */
1524 disk_num_bytes, /* orig_block_len */
1525 ram_bytes, BTRFS_COMPRESS_NONE,
1526 BTRFS_ORDERED_PREALLOC);
1529 btrfs_dec_nocow_writers(fs_info,
1534 free_extent_map(em);
1537 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1538 type = BTRFS_ORDERED_PREALLOC;
1540 type = BTRFS_ORDERED_NOCOW;
1543 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1544 num_bytes, num_bytes, type);
1546 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1547 BUG_ON(ret); /* -ENOMEM */
1549 if (root->root_key.objectid ==
1550 BTRFS_DATA_RELOC_TREE_OBJECTID)
1552 * Error handled later, as we must prevent
1553 * extent_clear_unlock_delalloc() in error handler
1554 * from freeing metadata of created ordered extent.
1556 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1559 extent_clear_unlock_delalloc(inode, cur_offset,
1560 cur_offset + num_bytes - 1, end,
1561 locked_page, EXTENT_LOCKED |
1563 EXTENT_CLEAR_DATA_RESV,
1564 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1566 cur_offset = extent_end;
1569 * btrfs_reloc_clone_csums() error, now we're OK to call error
1570 * handler, as metadata for created ordered extent will only
1571 * be freed by btrfs_finish_ordered_io().
1575 if (cur_offset > end)
1578 btrfs_release_path(path);
1580 if (cur_offset <= end && cow_start == (u64)-1)
1581 cow_start = cur_offset;
1583 if (cow_start != (u64)-1) {
1585 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1586 page_started, nr_written, 1, NULL);
1592 if (ret && cur_offset < end)
1593 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1594 locked_page, EXTENT_LOCKED |
1595 EXTENT_DELALLOC | EXTENT_DEFRAG |
1596 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1598 PAGE_SET_WRITEBACK |
1599 PAGE_END_WRITEBACK);
1600 btrfs_free_path(path);
1604 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1607 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1608 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1612 * @defrag_bytes is a hint value, no spinlock held here,
1613 * if is not zero, it means the file is defragging.
1614 * Force cow if given extent needs to be defragged.
1616 if (BTRFS_I(inode)->defrag_bytes &&
1617 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1618 EXTENT_DEFRAG, 0, NULL))
1625 * Function to process delayed allocation (create CoW) for ranges which are
1626 * being touched for the first time.
1628 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1629 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1630 struct writeback_control *wbc)
1633 int force_cow = need_force_cow(inode, start, end);
1634 unsigned int write_flags = wbc_to_write_flags(wbc);
1636 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1637 ret = run_delalloc_nocow(inode, locked_page, start, end,
1638 page_started, 1, nr_written);
1639 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1640 ret = run_delalloc_nocow(inode, locked_page, start, end,
1641 page_started, 0, nr_written);
1642 } else if (!inode_need_compress(inode, start, end)) {
1643 ret = cow_file_range(inode, locked_page, start, end, end,
1644 page_started, nr_written, 1, NULL);
1646 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1647 &BTRFS_I(inode)->runtime_flags);
1648 ret = cow_file_range_async(inode, locked_page, start, end,
1649 page_started, nr_written,
1653 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1658 void btrfs_split_delalloc_extent(struct inode *inode,
1659 struct extent_state *orig, u64 split)
1663 /* not delalloc, ignore it */
1664 if (!(orig->state & EXTENT_DELALLOC))
1667 size = orig->end - orig->start + 1;
1668 if (size > BTRFS_MAX_EXTENT_SIZE) {
1673 * See the explanation in btrfs_merge_delalloc_extent, the same
1674 * applies here, just in reverse.
1676 new_size = orig->end - split + 1;
1677 num_extents = count_max_extents(new_size);
1678 new_size = split - orig->start;
1679 num_extents += count_max_extents(new_size);
1680 if (count_max_extents(size) >= num_extents)
1684 spin_lock(&BTRFS_I(inode)->lock);
1685 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1686 spin_unlock(&BTRFS_I(inode)->lock);
1690 * Handle merged delayed allocation extents so we can keep track of new extents
1691 * that are just merged onto old extents, such as when we are doing sequential
1692 * writes, so we can properly account for the metadata space we'll need.
1694 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1695 struct extent_state *other)
1697 u64 new_size, old_size;
1700 /* not delalloc, ignore it */
1701 if (!(other->state & EXTENT_DELALLOC))
1704 if (new->start > other->start)
1705 new_size = new->end - other->start + 1;
1707 new_size = other->end - new->start + 1;
1709 /* we're not bigger than the max, unreserve the space and go */
1710 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1711 spin_lock(&BTRFS_I(inode)->lock);
1712 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1713 spin_unlock(&BTRFS_I(inode)->lock);
1718 * We have to add up either side to figure out how many extents were
1719 * accounted for before we merged into one big extent. If the number of
1720 * extents we accounted for is <= the amount we need for the new range
1721 * then we can return, otherwise drop. Think of it like this
1725 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1726 * need 2 outstanding extents, on one side we have 1 and the other side
1727 * we have 1 so they are == and we can return. But in this case
1729 * [MAX_SIZE+4k][MAX_SIZE+4k]
1731 * Each range on their own accounts for 2 extents, but merged together
1732 * they are only 3 extents worth of accounting, so we need to drop in
1735 old_size = other->end - other->start + 1;
1736 num_extents = count_max_extents(old_size);
1737 old_size = new->end - new->start + 1;
1738 num_extents += count_max_extents(old_size);
1739 if (count_max_extents(new_size) >= num_extents)
1742 spin_lock(&BTRFS_I(inode)->lock);
1743 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1744 spin_unlock(&BTRFS_I(inode)->lock);
1747 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1748 struct inode *inode)
1750 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1752 spin_lock(&root->delalloc_lock);
1753 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1754 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1755 &root->delalloc_inodes);
1756 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1757 &BTRFS_I(inode)->runtime_flags);
1758 root->nr_delalloc_inodes++;
1759 if (root->nr_delalloc_inodes == 1) {
1760 spin_lock(&fs_info->delalloc_root_lock);
1761 BUG_ON(!list_empty(&root->delalloc_root));
1762 list_add_tail(&root->delalloc_root,
1763 &fs_info->delalloc_roots);
1764 spin_unlock(&fs_info->delalloc_root_lock);
1767 spin_unlock(&root->delalloc_lock);
1771 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1772 struct btrfs_inode *inode)
1774 struct btrfs_fs_info *fs_info = root->fs_info;
1776 if (!list_empty(&inode->delalloc_inodes)) {
1777 list_del_init(&inode->delalloc_inodes);
1778 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1779 &inode->runtime_flags);
1780 root->nr_delalloc_inodes--;
1781 if (!root->nr_delalloc_inodes) {
1782 ASSERT(list_empty(&root->delalloc_inodes));
1783 spin_lock(&fs_info->delalloc_root_lock);
1784 BUG_ON(list_empty(&root->delalloc_root));
1785 list_del_init(&root->delalloc_root);
1786 spin_unlock(&fs_info->delalloc_root_lock);
1791 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1792 struct btrfs_inode *inode)
1794 spin_lock(&root->delalloc_lock);
1795 __btrfs_del_delalloc_inode(root, inode);
1796 spin_unlock(&root->delalloc_lock);
1800 * Properly track delayed allocation bytes in the inode and to maintain the
1801 * list of inodes that have pending delalloc work to be done.
1803 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1806 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1808 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1811 * set_bit and clear bit hooks normally require _irqsave/restore
1812 * but in this case, we are only testing for the DELALLOC
1813 * bit, which is only set or cleared with irqs on
1815 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1816 struct btrfs_root *root = BTRFS_I(inode)->root;
1817 u64 len = state->end + 1 - state->start;
1818 u32 num_extents = count_max_extents(len);
1819 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1821 spin_lock(&BTRFS_I(inode)->lock);
1822 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1823 spin_unlock(&BTRFS_I(inode)->lock);
1825 /* For sanity tests */
1826 if (btrfs_is_testing(fs_info))
1829 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1830 fs_info->delalloc_batch);
1831 spin_lock(&BTRFS_I(inode)->lock);
1832 BTRFS_I(inode)->delalloc_bytes += len;
1833 if (*bits & EXTENT_DEFRAG)
1834 BTRFS_I(inode)->defrag_bytes += len;
1835 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1836 &BTRFS_I(inode)->runtime_flags))
1837 btrfs_add_delalloc_inodes(root, inode);
1838 spin_unlock(&BTRFS_I(inode)->lock);
1841 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1842 (*bits & EXTENT_DELALLOC_NEW)) {
1843 spin_lock(&BTRFS_I(inode)->lock);
1844 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1846 spin_unlock(&BTRFS_I(inode)->lock);
1851 * Once a range is no longer delalloc this function ensures that proper
1852 * accounting happens.
1854 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1855 struct extent_state *state, unsigned *bits)
1857 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1858 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1859 u64 len = state->end + 1 - state->start;
1860 u32 num_extents = count_max_extents(len);
1862 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1863 spin_lock(&inode->lock);
1864 inode->defrag_bytes -= len;
1865 spin_unlock(&inode->lock);
1869 * set_bit and clear bit hooks normally require _irqsave/restore
1870 * but in this case, we are only testing for the DELALLOC
1871 * bit, which is only set or cleared with irqs on
1873 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1874 struct btrfs_root *root = inode->root;
1875 bool do_list = !btrfs_is_free_space_inode(inode);
1877 spin_lock(&inode->lock);
1878 btrfs_mod_outstanding_extents(inode, -num_extents);
1879 spin_unlock(&inode->lock);
1882 * We don't reserve metadata space for space cache inodes so we
1883 * don't need to call delalloc_release_metadata if there is an
1886 if (*bits & EXTENT_CLEAR_META_RESV &&
1887 root != fs_info->tree_root)
1888 btrfs_delalloc_release_metadata(inode, len, false);
1890 /* For sanity tests. */
1891 if (btrfs_is_testing(fs_info))
1894 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1895 do_list && !(state->state & EXTENT_NORESERVE) &&
1896 (*bits & EXTENT_CLEAR_DATA_RESV))
1897 btrfs_free_reserved_data_space_noquota(
1901 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1902 fs_info->delalloc_batch);
1903 spin_lock(&inode->lock);
1904 inode->delalloc_bytes -= len;
1905 if (do_list && inode->delalloc_bytes == 0 &&
1906 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1907 &inode->runtime_flags))
1908 btrfs_del_delalloc_inode(root, inode);
1909 spin_unlock(&inode->lock);
1912 if ((state->state & EXTENT_DELALLOC_NEW) &&
1913 (*bits & EXTENT_DELALLOC_NEW)) {
1914 spin_lock(&inode->lock);
1915 ASSERT(inode->new_delalloc_bytes >= len);
1916 inode->new_delalloc_bytes -= len;
1917 spin_unlock(&inode->lock);
1922 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1923 * in a chunk's stripe. This function ensures that bios do not span a
1926 * @page - The page we are about to add to the bio
1927 * @size - size we want to add to the bio
1928 * @bio - bio we want to ensure is smaller than a stripe
1929 * @bio_flags - flags of the bio
1931 * return 1 if page cannot be added to the bio
1932 * return 0 if page can be added to the bio
1933 * return error otherwise
1935 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
1936 unsigned long bio_flags)
1938 struct inode *inode = page->mapping->host;
1939 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1940 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1945 if (bio_flags & EXTENT_BIO_COMPRESSED)
1948 length = bio->bi_iter.bi_size;
1949 map_length = length;
1950 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1954 if (map_length < length + size)
1960 * in order to insert checksums into the metadata in large chunks,
1961 * we wait until bio submission time. All the pages in the bio are
1962 * checksummed and sums are attached onto the ordered extent record.
1964 * At IO completion time the cums attached on the ordered extent record
1965 * are inserted into the btree
1967 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1970 struct inode *inode = private_data;
1971 blk_status_t ret = 0;
1973 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1974 BUG_ON(ret); /* -ENOMEM */
1979 * extent_io.c submission hook. This does the right thing for csum calculation
1980 * on write, or reading the csums from the tree before a read.
1982 * Rules about async/sync submit,
1983 * a) read: sync submit
1985 * b) write without checksum: sync submit
1987 * c) write with checksum:
1988 * c-1) if bio is issued by fsync: sync submit
1989 * (sync_writers != 0)
1991 * c-2) if root is reloc root: sync submit
1992 * (only in case of buffered IO)
1994 * c-3) otherwise: async submit
1996 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
1998 unsigned long bio_flags)
2001 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2002 struct btrfs_root *root = BTRFS_I(inode)->root;
2003 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2004 blk_status_t ret = 0;
2006 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2008 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2010 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2011 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2013 if (bio_op(bio) != REQ_OP_WRITE) {
2014 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2018 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2019 ret = btrfs_submit_compressed_read(inode, bio,
2023 } else if (!skip_sum) {
2024 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2029 } else if (async && !skip_sum) {
2030 /* csum items have already been cloned */
2031 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2033 /* we're doing a write, do the async checksumming */
2034 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2035 0, inode, btrfs_submit_bio_start);
2037 } else if (!skip_sum) {
2038 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2044 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2048 bio->bi_status = ret;
2055 * given a list of ordered sums record them in the inode. This happens
2056 * at IO completion time based on sums calculated at bio submission time.
2058 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2059 struct inode *inode, struct list_head *list)
2061 struct btrfs_ordered_sum *sum;
2064 list_for_each_entry(sum, list, list) {
2065 trans->adding_csums = true;
2066 ret = btrfs_csum_file_blocks(trans,
2067 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2068 trans->adding_csums = false;
2075 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2076 unsigned int extra_bits,
2077 struct extent_state **cached_state, int dedupe)
2079 WARN_ON(PAGE_ALIGNED(end));
2080 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2081 extra_bits, cached_state);
2084 /* see btrfs_writepage_start_hook for details on why this is required */
2085 struct btrfs_writepage_fixup {
2087 struct btrfs_work work;
2090 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2092 struct btrfs_writepage_fixup *fixup;
2093 struct btrfs_ordered_extent *ordered;
2094 struct extent_state *cached_state = NULL;
2095 struct extent_changeset *data_reserved = NULL;
2097 struct inode *inode;
2102 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2106 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2107 ClearPageChecked(page);
2111 inode = page->mapping->host;
2112 page_start = page_offset(page);
2113 page_end = page_offset(page) + PAGE_SIZE - 1;
2115 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2118 /* already ordered? We're done */
2119 if (PagePrivate2(page))
2122 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2125 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2126 page_end, &cached_state);
2128 btrfs_start_ordered_extent(inode, ordered, 1);
2129 btrfs_put_ordered_extent(ordered);
2133 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2136 mapping_set_error(page->mapping, ret);
2137 end_extent_writepage(page, ret, page_start, page_end);
2138 ClearPageChecked(page);
2142 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2145 mapping_set_error(page->mapping, ret);
2146 end_extent_writepage(page, ret, page_start, page_end);
2147 ClearPageChecked(page);
2151 ClearPageChecked(page);
2152 set_page_dirty(page);
2153 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2155 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2161 extent_changeset_free(data_reserved);
2165 * There are a few paths in the higher layers of the kernel that directly
2166 * set the page dirty bit without asking the filesystem if it is a
2167 * good idea. This causes problems because we want to make sure COW
2168 * properly happens and the data=ordered rules are followed.
2170 * In our case any range that doesn't have the ORDERED bit set
2171 * hasn't been properly setup for IO. We kick off an async process
2172 * to fix it up. The async helper will wait for ordered extents, set
2173 * the delalloc bit and make it safe to write the page.
2175 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2177 struct inode *inode = page->mapping->host;
2178 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2179 struct btrfs_writepage_fixup *fixup;
2181 /* this page is properly in the ordered list */
2182 if (TestClearPagePrivate2(page))
2185 if (PageChecked(page))
2188 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2192 SetPageChecked(page);
2194 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2195 btrfs_writepage_fixup_worker, NULL, NULL);
2197 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2201 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2202 struct inode *inode, u64 file_pos,
2203 u64 disk_bytenr, u64 disk_num_bytes,
2204 u64 num_bytes, u64 ram_bytes,
2205 u8 compression, u8 encryption,
2206 u16 other_encoding, int extent_type)
2208 struct btrfs_root *root = BTRFS_I(inode)->root;
2209 struct btrfs_file_extent_item *fi;
2210 struct btrfs_path *path;
2211 struct extent_buffer *leaf;
2212 struct btrfs_key ins;
2214 int extent_inserted = 0;
2217 path = btrfs_alloc_path();
2222 * we may be replacing one extent in the tree with another.
2223 * The new extent is pinned in the extent map, and we don't want
2224 * to drop it from the cache until it is completely in the btree.
2226 * So, tell btrfs_drop_extents to leave this extent in the cache.
2227 * the caller is expected to unpin it and allow it to be merged
2230 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2231 file_pos + num_bytes, NULL, 0,
2232 1, sizeof(*fi), &extent_inserted);
2236 if (!extent_inserted) {
2237 ins.objectid = btrfs_ino(BTRFS_I(inode));
2238 ins.offset = file_pos;
2239 ins.type = BTRFS_EXTENT_DATA_KEY;
2241 path->leave_spinning = 1;
2242 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2247 leaf = path->nodes[0];
2248 fi = btrfs_item_ptr(leaf, path->slots[0],
2249 struct btrfs_file_extent_item);
2250 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2251 btrfs_set_file_extent_type(leaf, fi, extent_type);
2252 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2253 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2254 btrfs_set_file_extent_offset(leaf, fi, 0);
2255 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2256 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2257 btrfs_set_file_extent_compression(leaf, fi, compression);
2258 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2259 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2261 btrfs_mark_buffer_dirty(leaf);
2262 btrfs_release_path(path);
2264 inode_add_bytes(inode, num_bytes);
2266 ins.objectid = disk_bytenr;
2267 ins.offset = disk_num_bytes;
2268 ins.type = BTRFS_EXTENT_ITEM_KEY;
2271 * Release the reserved range from inode dirty range map, as it is
2272 * already moved into delayed_ref_head
2274 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2278 ret = btrfs_alloc_reserved_file_extent(trans, root,
2279 btrfs_ino(BTRFS_I(inode)),
2280 file_pos, qg_released, &ins);
2282 btrfs_free_path(path);
2287 /* snapshot-aware defrag */
2288 struct sa_defrag_extent_backref {
2289 struct rb_node node;
2290 struct old_sa_defrag_extent *old;
2299 struct old_sa_defrag_extent {
2300 struct list_head list;
2301 struct new_sa_defrag_extent *new;
2310 struct new_sa_defrag_extent {
2311 struct rb_root root;
2312 struct list_head head;
2313 struct btrfs_path *path;
2314 struct inode *inode;
2322 static int backref_comp(struct sa_defrag_extent_backref *b1,
2323 struct sa_defrag_extent_backref *b2)
2325 if (b1->root_id < b2->root_id)
2327 else if (b1->root_id > b2->root_id)
2330 if (b1->inum < b2->inum)
2332 else if (b1->inum > b2->inum)
2335 if (b1->file_pos < b2->file_pos)
2337 else if (b1->file_pos > b2->file_pos)
2341 * [------------------------------] ===> (a range of space)
2342 * |<--->| |<---->| =============> (fs/file tree A)
2343 * |<---------------------------->| ===> (fs/file tree B)
2345 * A range of space can refer to two file extents in one tree while
2346 * refer to only one file extent in another tree.
2348 * So we may process a disk offset more than one time(two extents in A)
2349 * and locate at the same extent(one extent in B), then insert two same
2350 * backrefs(both refer to the extent in B).
2355 static void backref_insert(struct rb_root *root,
2356 struct sa_defrag_extent_backref *backref)
2358 struct rb_node **p = &root->rb_node;
2359 struct rb_node *parent = NULL;
2360 struct sa_defrag_extent_backref *entry;
2365 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2367 ret = backref_comp(backref, entry);
2371 p = &(*p)->rb_right;
2374 rb_link_node(&backref->node, parent, p);
2375 rb_insert_color(&backref->node, root);
2379 * Note the backref might has changed, and in this case we just return 0.
2381 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2384 struct btrfs_file_extent_item *extent;
2385 struct old_sa_defrag_extent *old = ctx;
2386 struct new_sa_defrag_extent *new = old->new;
2387 struct btrfs_path *path = new->path;
2388 struct btrfs_key key;
2389 struct btrfs_root *root;
2390 struct sa_defrag_extent_backref *backref;
2391 struct extent_buffer *leaf;
2392 struct inode *inode = new->inode;
2393 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2399 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2400 inum == btrfs_ino(BTRFS_I(inode)))
2403 key.objectid = root_id;
2404 key.type = BTRFS_ROOT_ITEM_KEY;
2405 key.offset = (u64)-1;
2407 root = btrfs_read_fs_root_no_name(fs_info, &key);
2409 if (PTR_ERR(root) == -ENOENT)
2412 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2413 inum, offset, root_id);
2414 return PTR_ERR(root);
2417 key.objectid = inum;
2418 key.type = BTRFS_EXTENT_DATA_KEY;
2419 if (offset > (u64)-1 << 32)
2422 key.offset = offset;
2424 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2425 if (WARN_ON(ret < 0))
2432 leaf = path->nodes[0];
2433 slot = path->slots[0];
2435 if (slot >= btrfs_header_nritems(leaf)) {
2436 ret = btrfs_next_leaf(root, path);
2439 } else if (ret > 0) {
2448 btrfs_item_key_to_cpu(leaf, &key, slot);
2450 if (key.objectid > inum)
2453 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2456 extent = btrfs_item_ptr(leaf, slot,
2457 struct btrfs_file_extent_item);
2459 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2463 * 'offset' refers to the exact key.offset,
2464 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2465 * (key.offset - extent_offset).
2467 if (key.offset != offset)
2470 extent_offset = btrfs_file_extent_offset(leaf, extent);
2471 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2473 if (extent_offset >= old->extent_offset + old->offset +
2474 old->len || extent_offset + num_bytes <=
2475 old->extent_offset + old->offset)
2480 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2486 backref->root_id = root_id;
2487 backref->inum = inum;
2488 backref->file_pos = offset;
2489 backref->num_bytes = num_bytes;
2490 backref->extent_offset = extent_offset;
2491 backref->generation = btrfs_file_extent_generation(leaf, extent);
2493 backref_insert(&new->root, backref);
2496 btrfs_release_path(path);
2501 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2502 struct new_sa_defrag_extent *new)
2504 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2505 struct old_sa_defrag_extent *old, *tmp;
2510 list_for_each_entry_safe(old, tmp, &new->head, list) {
2511 ret = iterate_inodes_from_logical(old->bytenr +
2512 old->extent_offset, fs_info,
2513 path, record_one_backref,
2515 if (ret < 0 && ret != -ENOENT)
2518 /* no backref to be processed for this extent */
2520 list_del(&old->list);
2525 if (list_empty(&new->head))
2531 static int relink_is_mergable(struct extent_buffer *leaf,
2532 struct btrfs_file_extent_item *fi,
2533 struct new_sa_defrag_extent *new)
2535 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2538 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2541 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2544 if (btrfs_file_extent_encryption(leaf, fi) ||
2545 btrfs_file_extent_other_encoding(leaf, fi))
2552 * Note the backref might has changed, and in this case we just return 0.
2554 static noinline int relink_extent_backref(struct btrfs_path *path,
2555 struct sa_defrag_extent_backref *prev,
2556 struct sa_defrag_extent_backref *backref)
2558 struct btrfs_file_extent_item *extent;
2559 struct btrfs_file_extent_item *item;
2560 struct btrfs_ordered_extent *ordered;
2561 struct btrfs_trans_handle *trans;
2562 struct btrfs_ref ref = { 0 };
2563 struct btrfs_root *root;
2564 struct btrfs_key key;
2565 struct extent_buffer *leaf;
2566 struct old_sa_defrag_extent *old = backref->old;
2567 struct new_sa_defrag_extent *new = old->new;
2568 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2569 struct inode *inode;
2570 struct extent_state *cached = NULL;
2579 if (prev && prev->root_id == backref->root_id &&
2580 prev->inum == backref->inum &&
2581 prev->file_pos + prev->num_bytes == backref->file_pos)
2584 /* step 1: get root */
2585 key.objectid = backref->root_id;
2586 key.type = BTRFS_ROOT_ITEM_KEY;
2587 key.offset = (u64)-1;
2589 index = srcu_read_lock(&fs_info->subvol_srcu);
2591 root = btrfs_read_fs_root_no_name(fs_info, &key);
2593 srcu_read_unlock(&fs_info->subvol_srcu, index);
2594 if (PTR_ERR(root) == -ENOENT)
2596 return PTR_ERR(root);
2599 if (btrfs_root_readonly(root)) {
2600 srcu_read_unlock(&fs_info->subvol_srcu, index);
2604 /* step 2: get inode */
2605 key.objectid = backref->inum;
2606 key.type = BTRFS_INODE_ITEM_KEY;
2609 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2610 if (IS_ERR(inode)) {
2611 srcu_read_unlock(&fs_info->subvol_srcu, index);
2615 srcu_read_unlock(&fs_info->subvol_srcu, index);
2617 /* step 3: relink backref */
2618 lock_start = backref->file_pos;
2619 lock_end = backref->file_pos + backref->num_bytes - 1;
2620 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2623 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2625 btrfs_put_ordered_extent(ordered);
2629 trans = btrfs_join_transaction(root);
2630 if (IS_ERR(trans)) {
2631 ret = PTR_ERR(trans);
2635 key.objectid = backref->inum;
2636 key.type = BTRFS_EXTENT_DATA_KEY;
2637 key.offset = backref->file_pos;
2639 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2642 } else if (ret > 0) {
2647 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2648 struct btrfs_file_extent_item);
2650 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2651 backref->generation)
2654 btrfs_release_path(path);
2656 start = backref->file_pos;
2657 if (backref->extent_offset < old->extent_offset + old->offset)
2658 start += old->extent_offset + old->offset -
2659 backref->extent_offset;
2661 len = min(backref->extent_offset + backref->num_bytes,
2662 old->extent_offset + old->offset + old->len);
2663 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2665 ret = btrfs_drop_extents(trans, root, inode, start,
2670 key.objectid = btrfs_ino(BTRFS_I(inode));
2671 key.type = BTRFS_EXTENT_DATA_KEY;
2674 path->leave_spinning = 1;
2676 struct btrfs_file_extent_item *fi;
2678 struct btrfs_key found_key;
2680 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2685 leaf = path->nodes[0];
2686 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2688 fi = btrfs_item_ptr(leaf, path->slots[0],
2689 struct btrfs_file_extent_item);
2690 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2692 if (extent_len + found_key.offset == start &&
2693 relink_is_mergable(leaf, fi, new)) {
2694 btrfs_set_file_extent_num_bytes(leaf, fi,
2696 btrfs_mark_buffer_dirty(leaf);
2697 inode_add_bytes(inode, len);
2703 btrfs_release_path(path);
2708 ret = btrfs_insert_empty_item(trans, root, path, &key,
2711 btrfs_abort_transaction(trans, ret);
2715 leaf = path->nodes[0];
2716 item = btrfs_item_ptr(leaf, path->slots[0],
2717 struct btrfs_file_extent_item);
2718 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2719 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2720 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2721 btrfs_set_file_extent_num_bytes(leaf, item, len);
2722 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2723 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2724 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2725 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2726 btrfs_set_file_extent_encryption(leaf, item, 0);
2727 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2729 btrfs_mark_buffer_dirty(leaf);
2730 inode_add_bytes(inode, len);
2731 btrfs_release_path(path);
2733 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2735 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2736 new->file_pos); /* start - extent_offset */
2737 ret = btrfs_inc_extent_ref(trans, &ref);
2739 btrfs_abort_transaction(trans, ret);
2745 btrfs_release_path(path);
2746 path->leave_spinning = 0;
2747 btrfs_end_transaction(trans);
2749 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2755 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2757 struct old_sa_defrag_extent *old, *tmp;
2762 list_for_each_entry_safe(old, tmp, &new->head, list) {
2768 static void relink_file_extents(struct new_sa_defrag_extent *new)
2770 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2771 struct btrfs_path *path;
2772 struct sa_defrag_extent_backref *backref;
2773 struct sa_defrag_extent_backref *prev = NULL;
2774 struct rb_node *node;
2777 path = btrfs_alloc_path();
2781 if (!record_extent_backrefs(path, new)) {
2782 btrfs_free_path(path);
2785 btrfs_release_path(path);
2788 node = rb_first(&new->root);
2791 rb_erase(node, &new->root);
2793 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2795 ret = relink_extent_backref(path, prev, backref);
2808 btrfs_free_path(path);
2810 free_sa_defrag_extent(new);
2812 atomic_dec(&fs_info->defrag_running);
2813 wake_up(&fs_info->transaction_wait);
2816 static struct new_sa_defrag_extent *
2817 record_old_file_extents(struct inode *inode,
2818 struct btrfs_ordered_extent *ordered)
2820 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2821 struct btrfs_root *root = BTRFS_I(inode)->root;
2822 struct btrfs_path *path;
2823 struct btrfs_key key;
2824 struct old_sa_defrag_extent *old;
2825 struct new_sa_defrag_extent *new;
2828 new = kmalloc(sizeof(*new), GFP_NOFS);
2833 new->file_pos = ordered->file_offset;
2834 new->len = ordered->len;
2835 new->bytenr = ordered->start;
2836 new->disk_len = ordered->disk_len;
2837 new->compress_type = ordered->compress_type;
2838 new->root = RB_ROOT;
2839 INIT_LIST_HEAD(&new->head);
2841 path = btrfs_alloc_path();
2845 key.objectid = btrfs_ino(BTRFS_I(inode));
2846 key.type = BTRFS_EXTENT_DATA_KEY;
2847 key.offset = new->file_pos;
2849 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2852 if (ret > 0 && path->slots[0] > 0)
2855 /* find out all the old extents for the file range */
2857 struct btrfs_file_extent_item *extent;
2858 struct extent_buffer *l;
2867 slot = path->slots[0];
2869 if (slot >= btrfs_header_nritems(l)) {
2870 ret = btrfs_next_leaf(root, path);
2878 btrfs_item_key_to_cpu(l, &key, slot);
2880 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2882 if (key.type != BTRFS_EXTENT_DATA_KEY)
2884 if (key.offset >= new->file_pos + new->len)
2887 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2889 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2890 if (key.offset + num_bytes < new->file_pos)
2893 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2897 extent_offset = btrfs_file_extent_offset(l, extent);
2899 old = kmalloc(sizeof(*old), GFP_NOFS);
2903 offset = max(new->file_pos, key.offset);
2904 end = min(new->file_pos + new->len, key.offset + num_bytes);
2906 old->bytenr = disk_bytenr;
2907 old->extent_offset = extent_offset;
2908 old->offset = offset - key.offset;
2909 old->len = end - offset;
2912 list_add_tail(&old->list, &new->head);
2918 btrfs_free_path(path);
2919 atomic_inc(&fs_info->defrag_running);
2924 btrfs_free_path(path);
2926 free_sa_defrag_extent(new);
2930 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2933 struct btrfs_block_group_cache *cache;
2935 cache = btrfs_lookup_block_group(fs_info, start);
2938 spin_lock(&cache->lock);
2939 cache->delalloc_bytes -= len;
2940 spin_unlock(&cache->lock);
2942 btrfs_put_block_group(cache);
2945 /* as ordered data IO finishes, this gets called so we can finish
2946 * an ordered extent if the range of bytes in the file it covers are
2949 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2951 struct inode *inode = ordered_extent->inode;
2952 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2953 struct btrfs_root *root = BTRFS_I(inode)->root;
2954 struct btrfs_trans_handle *trans = NULL;
2955 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2956 struct extent_state *cached_state = NULL;
2957 struct new_sa_defrag_extent *new = NULL;
2958 int compress_type = 0;
2960 u64 logical_len = ordered_extent->len;
2962 bool truncated = false;
2963 bool range_locked = false;
2964 bool clear_new_delalloc_bytes = false;
2965 bool clear_reserved_extent = true;
2967 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2968 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2969 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2970 clear_new_delalloc_bytes = true;
2972 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2974 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2979 btrfs_free_io_failure_record(BTRFS_I(inode),
2980 ordered_extent->file_offset,
2981 ordered_extent->file_offset +
2982 ordered_extent->len - 1);
2984 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2986 logical_len = ordered_extent->truncated_len;
2987 /* Truncated the entire extent, don't bother adding */
2992 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2993 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2996 * For mwrite(mmap + memset to write) case, we still reserve
2997 * space for NOCOW range.
2998 * As NOCOW won't cause a new delayed ref, just free the space
3000 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3001 ordered_extent->len);
3002 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3004 trans = btrfs_join_transaction_nolock(root);
3006 trans = btrfs_join_transaction(root);
3007 if (IS_ERR(trans)) {
3008 ret = PTR_ERR(trans);
3012 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3013 ret = btrfs_update_inode_fallback(trans, root, inode);
3014 if (ret) /* -ENOMEM or corruption */
3015 btrfs_abort_transaction(trans, ret);
3019 range_locked = true;
3020 lock_extent_bits(io_tree, ordered_extent->file_offset,
3021 ordered_extent->file_offset + ordered_extent->len - 1,
3024 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3025 ordered_extent->file_offset + ordered_extent->len - 1,
3026 EXTENT_DEFRAG, 0, cached_state);
3028 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3029 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3030 /* the inode is shared */
3031 new = record_old_file_extents(inode, ordered_extent);
3033 clear_extent_bit(io_tree, ordered_extent->file_offset,
3034 ordered_extent->file_offset + ordered_extent->len - 1,
3035 EXTENT_DEFRAG, 0, 0, &cached_state);
3039 trans = btrfs_join_transaction_nolock(root);
3041 trans = btrfs_join_transaction(root);
3042 if (IS_ERR(trans)) {
3043 ret = PTR_ERR(trans);
3048 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3050 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3051 compress_type = ordered_extent->compress_type;
3052 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3053 BUG_ON(compress_type);
3054 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3055 ordered_extent->len);
3056 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3057 ordered_extent->file_offset,
3058 ordered_extent->file_offset +
3061 BUG_ON(root == fs_info->tree_root);
3062 ret = insert_reserved_file_extent(trans, inode,
3063 ordered_extent->file_offset,
3064 ordered_extent->start,
3065 ordered_extent->disk_len,
3066 logical_len, logical_len,
3067 compress_type, 0, 0,
3068 BTRFS_FILE_EXTENT_REG);
3070 clear_reserved_extent = false;
3071 btrfs_release_delalloc_bytes(fs_info,
3072 ordered_extent->start,
3073 ordered_extent->disk_len);
3076 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3077 ordered_extent->file_offset, ordered_extent->len,
3080 btrfs_abort_transaction(trans, ret);
3084 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3086 btrfs_abort_transaction(trans, ret);
3090 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3091 ret = btrfs_update_inode_fallback(trans, root, inode);
3092 if (ret) { /* -ENOMEM or corruption */
3093 btrfs_abort_transaction(trans, ret);
3098 if (range_locked || clear_new_delalloc_bytes) {
3099 unsigned int clear_bits = 0;
3102 clear_bits |= EXTENT_LOCKED;
3103 if (clear_new_delalloc_bytes)
3104 clear_bits |= EXTENT_DELALLOC_NEW;
3105 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3106 ordered_extent->file_offset,
3107 ordered_extent->file_offset +
3108 ordered_extent->len - 1,
3110 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3115 btrfs_end_transaction(trans);
3117 if (ret || truncated) {
3121 start = ordered_extent->file_offset + logical_len;
3123 start = ordered_extent->file_offset;
3124 end = ordered_extent->file_offset + ordered_extent->len - 1;
3125 clear_extent_uptodate(io_tree, start, end, NULL);
3127 /* Drop the cache for the part of the extent we didn't write. */
3128 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3131 * If the ordered extent had an IOERR or something else went
3132 * wrong we need to return the space for this ordered extent
3133 * back to the allocator. We only free the extent in the
3134 * truncated case if we didn't write out the extent at all.
3136 * If we made it past insert_reserved_file_extent before we
3137 * errored out then we don't need to do this as the accounting
3138 * has already been done.
3140 if ((ret || !logical_len) &&
3141 clear_reserved_extent &&
3142 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3143 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3144 btrfs_free_reserved_extent(fs_info,
3145 ordered_extent->start,
3146 ordered_extent->disk_len, 1);
3151 * This needs to be done to make sure anybody waiting knows we are done
3152 * updating everything for this ordered extent.
3154 btrfs_remove_ordered_extent(inode, ordered_extent);
3156 /* for snapshot-aware defrag */
3159 free_sa_defrag_extent(new);
3160 atomic_dec(&fs_info->defrag_running);
3162 relink_file_extents(new);
3167 btrfs_put_ordered_extent(ordered_extent);
3168 /* once for the tree */
3169 btrfs_put_ordered_extent(ordered_extent);
3174 static void finish_ordered_fn(struct btrfs_work *work)
3176 struct btrfs_ordered_extent *ordered_extent;
3177 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3178 btrfs_finish_ordered_io(ordered_extent);
3181 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3182 u64 end, int uptodate)
3184 struct inode *inode = page->mapping->host;
3185 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3186 struct btrfs_ordered_extent *ordered_extent = NULL;
3187 struct btrfs_workqueue *wq;
3188 btrfs_work_func_t func;
3190 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3192 ClearPagePrivate2(page);
3193 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3194 end - start + 1, uptodate))
3197 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3198 wq = fs_info->endio_freespace_worker;
3199 func = btrfs_freespace_write_helper;
3201 wq = fs_info->endio_write_workers;
3202 func = btrfs_endio_write_helper;
3205 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3207 btrfs_queue_work(wq, &ordered_extent->work);
3210 static int __readpage_endio_check(struct inode *inode,
3211 struct btrfs_io_bio *io_bio,
3212 int icsum, struct page *page,
3213 int pgoff, u64 start, size_t len)
3219 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3221 kaddr = kmap_atomic(page);
3222 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3223 btrfs_csum_final(csum, (u8 *)&csum);
3224 if (csum != csum_expected)
3227 kunmap_atomic(kaddr);
3230 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3231 io_bio->mirror_num);
3232 memset(kaddr + pgoff, 1, len);
3233 flush_dcache_page(page);
3234 kunmap_atomic(kaddr);
3239 * when reads are done, we need to check csums to verify the data is correct
3240 * if there's a match, we allow the bio to finish. If not, the code in
3241 * extent_io.c will try to find good copies for us.
3243 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3244 u64 phy_offset, struct page *page,
3245 u64 start, u64 end, int mirror)
3247 size_t offset = start - page_offset(page);
3248 struct inode *inode = page->mapping->host;
3249 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3250 struct btrfs_root *root = BTRFS_I(inode)->root;
3252 if (PageChecked(page)) {
3253 ClearPageChecked(page);
3257 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3260 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3261 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3262 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3266 phy_offset >>= inode->i_sb->s_blocksize_bits;
3267 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3268 start, (size_t)(end - start + 1));
3272 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3274 * @inode: The inode we want to perform iput on
3276 * This function uses the generic vfs_inode::i_count to track whether we should
3277 * just decrement it (in case it's > 1) or if this is the last iput then link
3278 * the inode to the delayed iput machinery. Delayed iputs are processed at
3279 * transaction commit time/superblock commit/cleaner kthread.
3281 void btrfs_add_delayed_iput(struct inode *inode)
3283 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3284 struct btrfs_inode *binode = BTRFS_I(inode);
3286 if (atomic_add_unless(&inode->i_count, -1, 1))
3289 atomic_inc(&fs_info->nr_delayed_iputs);
3290 spin_lock(&fs_info->delayed_iput_lock);
3291 ASSERT(list_empty(&binode->delayed_iput));
3292 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3293 spin_unlock(&fs_info->delayed_iput_lock);
3294 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3295 wake_up_process(fs_info->cleaner_kthread);
3298 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3301 spin_lock(&fs_info->delayed_iput_lock);
3302 while (!list_empty(&fs_info->delayed_iputs)) {
3303 struct btrfs_inode *inode;
3305 inode = list_first_entry(&fs_info->delayed_iputs,
3306 struct btrfs_inode, delayed_iput);
3307 list_del_init(&inode->delayed_iput);
3308 spin_unlock(&fs_info->delayed_iput_lock);
3309 iput(&inode->vfs_inode);
3310 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3311 wake_up(&fs_info->delayed_iputs_wait);
3312 spin_lock(&fs_info->delayed_iput_lock);
3314 spin_unlock(&fs_info->delayed_iput_lock);
3318 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3319 * @fs_info - the fs_info for this fs
3320 * @return - EINTR if we were killed, 0 if nothing's pending
3322 * This will wait on any delayed iputs that are currently running with KILLABLE
3323 * set. Once they are all done running we will return, unless we are killed in
3324 * which case we return EINTR. This helps in user operations like fallocate etc
3325 * that might get blocked on the iputs.
3327 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3329 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3330 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3337 * This creates an orphan entry for the given inode in case something goes wrong
3338 * in the middle of an unlink.
3340 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3341 struct btrfs_inode *inode)
3345 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3346 if (ret && ret != -EEXIST) {
3347 btrfs_abort_transaction(trans, ret);
3355 * We have done the delete so we can go ahead and remove the orphan item for
3356 * this particular inode.
3358 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3359 struct btrfs_inode *inode)
3361 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3365 * this cleans up any orphans that may be left on the list from the last use
3368 int btrfs_orphan_cleanup(struct btrfs_root *root)
3370 struct btrfs_fs_info *fs_info = root->fs_info;
3371 struct btrfs_path *path;
3372 struct extent_buffer *leaf;
3373 struct btrfs_key key, found_key;
3374 struct btrfs_trans_handle *trans;
3375 struct inode *inode;
3376 u64 last_objectid = 0;
3377 int ret = 0, nr_unlink = 0;
3379 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3382 path = btrfs_alloc_path();
3387 path->reada = READA_BACK;
3389 key.objectid = BTRFS_ORPHAN_OBJECTID;
3390 key.type = BTRFS_ORPHAN_ITEM_KEY;
3391 key.offset = (u64)-1;
3394 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3399 * if ret == 0 means we found what we were searching for, which
3400 * is weird, but possible, so only screw with path if we didn't
3401 * find the key and see if we have stuff that matches
3405 if (path->slots[0] == 0)
3410 /* pull out the item */
3411 leaf = path->nodes[0];
3412 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3414 /* make sure the item matches what we want */
3415 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3417 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3420 /* release the path since we're done with it */
3421 btrfs_release_path(path);
3424 * this is where we are basically btrfs_lookup, without the
3425 * crossing root thing. we store the inode number in the
3426 * offset of the orphan item.
3429 if (found_key.offset == last_objectid) {
3431 "Error removing orphan entry, stopping orphan cleanup");
3436 last_objectid = found_key.offset;
3438 found_key.objectid = found_key.offset;
3439 found_key.type = BTRFS_INODE_ITEM_KEY;
3440 found_key.offset = 0;
3441 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3442 ret = PTR_ERR_OR_ZERO(inode);
3443 if (ret && ret != -ENOENT)
3446 if (ret == -ENOENT && root == fs_info->tree_root) {
3447 struct btrfs_root *dead_root;
3448 struct btrfs_fs_info *fs_info = root->fs_info;
3449 int is_dead_root = 0;
3452 * this is an orphan in the tree root. Currently these
3453 * could come from 2 sources:
3454 * a) a snapshot deletion in progress
3455 * b) a free space cache inode
3456 * We need to distinguish those two, as the snapshot
3457 * orphan must not get deleted.
3458 * find_dead_roots already ran before us, so if this
3459 * is a snapshot deletion, we should find the root
3460 * in the dead_roots list
3462 spin_lock(&fs_info->trans_lock);
3463 list_for_each_entry(dead_root, &fs_info->dead_roots,
3465 if (dead_root->root_key.objectid ==
3466 found_key.objectid) {
3471 spin_unlock(&fs_info->trans_lock);
3473 /* prevent this orphan from being found again */
3474 key.offset = found_key.objectid - 1;
3481 * If we have an inode with links, there are a couple of
3482 * possibilities. Old kernels (before v3.12) used to create an
3483 * orphan item for truncate indicating that there were possibly
3484 * extent items past i_size that needed to be deleted. In v3.12,
3485 * truncate was changed to update i_size in sync with the extent
3486 * items, but the (useless) orphan item was still created. Since
3487 * v4.18, we don't create the orphan item for truncate at all.
3489 * So, this item could mean that we need to do a truncate, but
3490 * only if this filesystem was last used on a pre-v3.12 kernel
3491 * and was not cleanly unmounted. The odds of that are quite
3492 * slim, and it's a pain to do the truncate now, so just delete
3495 * It's also possible that this orphan item was supposed to be
3496 * deleted but wasn't. The inode number may have been reused,
3497 * but either way, we can delete the orphan item.
3499 if (ret == -ENOENT || inode->i_nlink) {
3502 trans = btrfs_start_transaction(root, 1);
3503 if (IS_ERR(trans)) {
3504 ret = PTR_ERR(trans);
3507 btrfs_debug(fs_info, "auto deleting %Lu",
3508 found_key.objectid);
3509 ret = btrfs_del_orphan_item(trans, root,
3510 found_key.objectid);
3511 btrfs_end_transaction(trans);
3519 /* this will do delete_inode and everything for us */
3522 /* release the path since we're done with it */
3523 btrfs_release_path(path);
3525 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3527 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3528 trans = btrfs_join_transaction(root);
3530 btrfs_end_transaction(trans);
3534 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3538 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3539 btrfs_free_path(path);
3544 * very simple check to peek ahead in the leaf looking for xattrs. If we
3545 * don't find any xattrs, we know there can't be any acls.
3547 * slot is the slot the inode is in, objectid is the objectid of the inode
3549 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3550 int slot, u64 objectid,
3551 int *first_xattr_slot)
3553 u32 nritems = btrfs_header_nritems(leaf);
3554 struct btrfs_key found_key;
3555 static u64 xattr_access = 0;
3556 static u64 xattr_default = 0;
3559 if (!xattr_access) {
3560 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3561 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3562 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3563 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3567 *first_xattr_slot = -1;
3568 while (slot < nritems) {
3569 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3571 /* we found a different objectid, there must not be acls */
3572 if (found_key.objectid != objectid)
3575 /* we found an xattr, assume we've got an acl */
3576 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3577 if (*first_xattr_slot == -1)
3578 *first_xattr_slot = slot;
3579 if (found_key.offset == xattr_access ||
3580 found_key.offset == xattr_default)
3585 * we found a key greater than an xattr key, there can't
3586 * be any acls later on
3588 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3595 * it goes inode, inode backrefs, xattrs, extents,
3596 * so if there are a ton of hard links to an inode there can
3597 * be a lot of backrefs. Don't waste time searching too hard,
3598 * this is just an optimization
3603 /* we hit the end of the leaf before we found an xattr or
3604 * something larger than an xattr. We have to assume the inode
3607 if (*first_xattr_slot == -1)
3608 *first_xattr_slot = slot;
3613 * read an inode from the btree into the in-memory inode
3615 static int btrfs_read_locked_inode(struct inode *inode,
3616 struct btrfs_path *in_path)
3618 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3619 struct btrfs_path *path = in_path;
3620 struct extent_buffer *leaf;
3621 struct btrfs_inode_item *inode_item;
3622 struct btrfs_root *root = BTRFS_I(inode)->root;
3623 struct btrfs_key location;
3628 bool filled = false;
3629 int first_xattr_slot;
3631 ret = btrfs_fill_inode(inode, &rdev);
3636 path = btrfs_alloc_path();
3641 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3643 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3645 if (path != in_path)
3646 btrfs_free_path(path);
3650 leaf = path->nodes[0];
3655 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3656 struct btrfs_inode_item);
3657 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3658 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3659 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3660 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3661 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3663 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3664 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3666 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3667 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3669 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3670 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3672 BTRFS_I(inode)->i_otime.tv_sec =
3673 btrfs_timespec_sec(leaf, &inode_item->otime);
3674 BTRFS_I(inode)->i_otime.tv_nsec =
3675 btrfs_timespec_nsec(leaf, &inode_item->otime);
3677 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3678 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3679 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3681 inode_set_iversion_queried(inode,
3682 btrfs_inode_sequence(leaf, inode_item));
3683 inode->i_generation = BTRFS_I(inode)->generation;
3685 rdev = btrfs_inode_rdev(leaf, inode_item);
3687 BTRFS_I(inode)->index_cnt = (u64)-1;
3688 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3692 * If we were modified in the current generation and evicted from memory
3693 * and then re-read we need to do a full sync since we don't have any
3694 * idea about which extents were modified before we were evicted from
3697 * This is required for both inode re-read from disk and delayed inode
3698 * in delayed_nodes_tree.
3700 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3701 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3702 &BTRFS_I(inode)->runtime_flags);
3705 * We don't persist the id of the transaction where an unlink operation
3706 * against the inode was last made. So here we assume the inode might
3707 * have been evicted, and therefore the exact value of last_unlink_trans
3708 * lost, and set it to last_trans to avoid metadata inconsistencies
3709 * between the inode and its parent if the inode is fsync'ed and the log
3710 * replayed. For example, in the scenario:
3713 * ln mydir/foo mydir/bar
3716 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3717 * xfs_io -c fsync mydir/foo
3719 * mount fs, triggers fsync log replay
3721 * We must make sure that when we fsync our inode foo we also log its
3722 * parent inode, otherwise after log replay the parent still has the
3723 * dentry with the "bar" name but our inode foo has a link count of 1
3724 * and doesn't have an inode ref with the name "bar" anymore.
3726 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3727 * but it guarantees correctness at the expense of occasional full
3728 * transaction commits on fsync if our inode is a directory, or if our
3729 * inode is not a directory, logging its parent unnecessarily.
3731 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3734 if (inode->i_nlink != 1 ||
3735 path->slots[0] >= btrfs_header_nritems(leaf))
3738 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3739 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3742 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3743 if (location.type == BTRFS_INODE_REF_KEY) {
3744 struct btrfs_inode_ref *ref;
3746 ref = (struct btrfs_inode_ref *)ptr;
3747 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3748 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3749 struct btrfs_inode_extref *extref;
3751 extref = (struct btrfs_inode_extref *)ptr;
3752 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3757 * try to precache a NULL acl entry for files that don't have
3758 * any xattrs or acls
3760 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3761 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3762 if (first_xattr_slot != -1) {
3763 path->slots[0] = first_xattr_slot;
3764 ret = btrfs_load_inode_props(inode, path);
3767 "error loading props for ino %llu (root %llu): %d",
3768 btrfs_ino(BTRFS_I(inode)),
3769 root->root_key.objectid, ret);
3771 if (path != in_path)
3772 btrfs_free_path(path);
3775 cache_no_acl(inode);
3777 switch (inode->i_mode & S_IFMT) {
3779 inode->i_mapping->a_ops = &btrfs_aops;
3780 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3781 inode->i_fop = &btrfs_file_operations;
3782 inode->i_op = &btrfs_file_inode_operations;
3785 inode->i_fop = &btrfs_dir_file_operations;
3786 inode->i_op = &btrfs_dir_inode_operations;
3789 inode->i_op = &btrfs_symlink_inode_operations;
3790 inode_nohighmem(inode);
3791 inode->i_mapping->a_ops = &btrfs_aops;
3794 inode->i_op = &btrfs_special_inode_operations;
3795 init_special_inode(inode, inode->i_mode, rdev);
3799 btrfs_sync_inode_flags_to_i_flags(inode);
3804 * given a leaf and an inode, copy the inode fields into the leaf
3806 static void fill_inode_item(struct btrfs_trans_handle *trans,
3807 struct extent_buffer *leaf,
3808 struct btrfs_inode_item *item,
3809 struct inode *inode)
3811 struct btrfs_map_token token;
3813 btrfs_init_map_token(&token);
3815 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3816 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3817 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3819 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3820 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3822 btrfs_set_token_timespec_sec(leaf, &item->atime,
3823 inode->i_atime.tv_sec, &token);
3824 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3825 inode->i_atime.tv_nsec, &token);
3827 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3828 inode->i_mtime.tv_sec, &token);
3829 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3830 inode->i_mtime.tv_nsec, &token);
3832 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3833 inode->i_ctime.tv_sec, &token);
3834 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3835 inode->i_ctime.tv_nsec, &token);
3837 btrfs_set_token_timespec_sec(leaf, &item->otime,
3838 BTRFS_I(inode)->i_otime.tv_sec, &token);
3839 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3840 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3842 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3844 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3846 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3848 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3849 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3850 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3851 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3855 * copy everything in the in-memory inode into the btree.
3857 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3858 struct btrfs_root *root, struct inode *inode)
3860 struct btrfs_inode_item *inode_item;
3861 struct btrfs_path *path;
3862 struct extent_buffer *leaf;
3865 path = btrfs_alloc_path();
3869 path->leave_spinning = 1;
3870 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3878 leaf = path->nodes[0];
3879 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3880 struct btrfs_inode_item);
3882 fill_inode_item(trans, leaf, inode_item, inode);
3883 btrfs_mark_buffer_dirty(leaf);
3884 btrfs_set_inode_last_trans(trans, inode);
3887 btrfs_free_path(path);
3892 * copy everything in the in-memory inode into the btree.
3894 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3895 struct btrfs_root *root, struct inode *inode)
3897 struct btrfs_fs_info *fs_info = root->fs_info;
3901 * If the inode is a free space inode, we can deadlock during commit
3902 * if we put it into the delayed code.
3904 * The data relocation inode should also be directly updated
3907 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3908 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3909 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3910 btrfs_update_root_times(trans, root);
3912 ret = btrfs_delayed_update_inode(trans, root, inode);
3914 btrfs_set_inode_last_trans(trans, inode);
3918 return btrfs_update_inode_item(trans, root, inode);
3921 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3922 struct btrfs_root *root,
3923 struct inode *inode)
3927 ret = btrfs_update_inode(trans, root, inode);
3929 return btrfs_update_inode_item(trans, root, inode);
3934 * unlink helper that gets used here in inode.c and in the tree logging
3935 * recovery code. It remove a link in a directory with a given name, and
3936 * also drops the back refs in the inode to the directory
3938 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3939 struct btrfs_root *root,
3940 struct btrfs_inode *dir,
3941 struct btrfs_inode *inode,
3942 const char *name, int name_len)
3944 struct btrfs_fs_info *fs_info = root->fs_info;
3945 struct btrfs_path *path;
3947 struct extent_buffer *leaf;
3948 struct btrfs_dir_item *di;
3949 struct btrfs_key key;
3951 u64 ino = btrfs_ino(inode);
3952 u64 dir_ino = btrfs_ino(dir);
3954 path = btrfs_alloc_path();
3960 path->leave_spinning = 1;
3961 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3962 name, name_len, -1);
3963 if (IS_ERR_OR_NULL(di)) {
3964 ret = di ? PTR_ERR(di) : -ENOENT;
3967 leaf = path->nodes[0];
3968 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3969 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3972 btrfs_release_path(path);
3975 * If we don't have dir index, we have to get it by looking up
3976 * the inode ref, since we get the inode ref, remove it directly,
3977 * it is unnecessary to do delayed deletion.
3979 * But if we have dir index, needn't search inode ref to get it.
3980 * Since the inode ref is close to the inode item, it is better
3981 * that we delay to delete it, and just do this deletion when
3982 * we update the inode item.
3984 if (inode->dir_index) {
3985 ret = btrfs_delayed_delete_inode_ref(inode);
3987 index = inode->dir_index;
3992 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3996 "failed to delete reference to %.*s, inode %llu parent %llu",
3997 name_len, name, ino, dir_ino);
3998 btrfs_abort_transaction(trans, ret);
4002 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4004 btrfs_abort_transaction(trans, ret);
4008 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4010 if (ret != 0 && ret != -ENOENT) {
4011 btrfs_abort_transaction(trans, ret);
4015 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4020 btrfs_abort_transaction(trans, ret);
4022 btrfs_free_path(path);
4026 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4027 inode_inc_iversion(&inode->vfs_inode);
4028 inode_inc_iversion(&dir->vfs_inode);
4029 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4030 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4031 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4036 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4037 struct btrfs_root *root,
4038 struct btrfs_inode *dir, struct btrfs_inode *inode,
4039 const char *name, int name_len)
4042 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4044 drop_nlink(&inode->vfs_inode);
4045 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4051 * helper to start transaction for unlink and rmdir.
4053 * unlink and rmdir are special in btrfs, they do not always free space, so
4054 * if we cannot make our reservations the normal way try and see if there is
4055 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4056 * allow the unlink to occur.
4058 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4060 struct btrfs_root *root = BTRFS_I(dir)->root;
4063 * 1 for the possible orphan item
4064 * 1 for the dir item
4065 * 1 for the dir index
4066 * 1 for the inode ref
4069 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4072 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4074 struct btrfs_root *root = BTRFS_I(dir)->root;
4075 struct btrfs_trans_handle *trans;
4076 struct inode *inode = d_inode(dentry);
4079 trans = __unlink_start_trans(dir);
4081 return PTR_ERR(trans);
4083 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4086 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4087 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4088 dentry->d_name.len);
4092 if (inode->i_nlink == 0) {
4093 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4099 btrfs_end_transaction(trans);
4100 btrfs_btree_balance_dirty(root->fs_info);
4104 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4105 struct inode *dir, u64 objectid,
4106 const char *name, int name_len)
4108 struct btrfs_root *root = BTRFS_I(dir)->root;
4109 struct btrfs_path *path;
4110 struct extent_buffer *leaf;
4111 struct btrfs_dir_item *di;
4112 struct btrfs_key key;
4115 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4117 path = btrfs_alloc_path();
4121 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4122 name, name_len, -1);
4123 if (IS_ERR_OR_NULL(di)) {
4124 ret = di ? PTR_ERR(di) : -ENOENT;
4128 leaf = path->nodes[0];
4129 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4130 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4131 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4133 btrfs_abort_transaction(trans, ret);
4136 btrfs_release_path(path);
4138 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4139 dir_ino, &index, name, name_len);
4141 if (ret != -ENOENT) {
4142 btrfs_abort_transaction(trans, ret);
4145 di = btrfs_search_dir_index_item(root, path, dir_ino,
4147 if (IS_ERR_OR_NULL(di)) {
4152 btrfs_abort_transaction(trans, ret);
4156 leaf = path->nodes[0];
4157 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4160 btrfs_release_path(path);
4162 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4164 btrfs_abort_transaction(trans, ret);
4168 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4169 inode_inc_iversion(dir);
4170 dir->i_mtime = dir->i_ctime = current_time(dir);
4171 ret = btrfs_update_inode_fallback(trans, root, dir);
4173 btrfs_abort_transaction(trans, ret);
4175 btrfs_free_path(path);
4180 * Helper to check if the subvolume references other subvolumes or if it's
4183 static noinline int may_destroy_subvol(struct btrfs_root *root)
4185 struct btrfs_fs_info *fs_info = root->fs_info;
4186 struct btrfs_path *path;
4187 struct btrfs_dir_item *di;
4188 struct btrfs_key key;
4192 path = btrfs_alloc_path();
4196 /* Make sure this root isn't set as the default subvol */
4197 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4198 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4199 dir_id, "default", 7, 0);
4200 if (di && !IS_ERR(di)) {
4201 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4202 if (key.objectid == root->root_key.objectid) {
4205 "deleting default subvolume %llu is not allowed",
4209 btrfs_release_path(path);
4212 key.objectid = root->root_key.objectid;
4213 key.type = BTRFS_ROOT_REF_KEY;
4214 key.offset = (u64)-1;
4216 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4222 if (path->slots[0] > 0) {
4224 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4225 if (key.objectid == root->root_key.objectid &&
4226 key.type == BTRFS_ROOT_REF_KEY)
4230 btrfs_free_path(path);
4234 /* Delete all dentries for inodes belonging to the root */
4235 static void btrfs_prune_dentries(struct btrfs_root *root)
4237 struct btrfs_fs_info *fs_info = root->fs_info;
4238 struct rb_node *node;
4239 struct rb_node *prev;
4240 struct btrfs_inode *entry;
4241 struct inode *inode;
4244 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4245 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4247 spin_lock(&root->inode_lock);
4249 node = root->inode_tree.rb_node;
4253 entry = rb_entry(node, struct btrfs_inode, rb_node);
4255 if (objectid < btrfs_ino(entry))
4256 node = node->rb_left;
4257 else if (objectid > btrfs_ino(entry))
4258 node = node->rb_right;
4264 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4265 if (objectid <= btrfs_ino(entry)) {
4269 prev = rb_next(prev);
4273 entry = rb_entry(node, struct btrfs_inode, rb_node);
4274 objectid = btrfs_ino(entry) + 1;
4275 inode = igrab(&entry->vfs_inode);
4277 spin_unlock(&root->inode_lock);
4278 if (atomic_read(&inode->i_count) > 1)
4279 d_prune_aliases(inode);
4281 * btrfs_drop_inode will have it removed from the inode
4282 * cache when its usage count hits zero.
4286 spin_lock(&root->inode_lock);
4290 if (cond_resched_lock(&root->inode_lock))
4293 node = rb_next(node);
4295 spin_unlock(&root->inode_lock);
4298 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4300 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4301 struct btrfs_root *root = BTRFS_I(dir)->root;
4302 struct inode *inode = d_inode(dentry);
4303 struct btrfs_root *dest = BTRFS_I(inode)->root;
4304 struct btrfs_trans_handle *trans;
4305 struct btrfs_block_rsv block_rsv;
4311 * Don't allow to delete a subvolume with send in progress. This is
4312 * inside the inode lock so the error handling that has to drop the bit
4313 * again is not run concurrently.
4315 spin_lock(&dest->root_item_lock);
4316 if (dest->send_in_progress) {
4317 spin_unlock(&dest->root_item_lock);
4319 "attempt to delete subvolume %llu during send",
4320 dest->root_key.objectid);
4323 root_flags = btrfs_root_flags(&dest->root_item);
4324 btrfs_set_root_flags(&dest->root_item,
4325 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4326 spin_unlock(&dest->root_item_lock);
4328 down_write(&fs_info->subvol_sem);
4330 err = may_destroy_subvol(dest);
4334 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4336 * One for dir inode,
4337 * two for dir entries,
4338 * two for root ref/backref.
4340 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4344 trans = btrfs_start_transaction(root, 0);
4345 if (IS_ERR(trans)) {
4346 err = PTR_ERR(trans);
4349 trans->block_rsv = &block_rsv;
4350 trans->bytes_reserved = block_rsv.size;
4352 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4354 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4355 dentry->d_name.name, dentry->d_name.len);
4358 btrfs_abort_transaction(trans, ret);
4362 btrfs_record_root_in_trans(trans, dest);
4364 memset(&dest->root_item.drop_progress, 0,
4365 sizeof(dest->root_item.drop_progress));
4366 dest->root_item.drop_level = 0;
4367 btrfs_set_root_refs(&dest->root_item, 0);
4369 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4370 ret = btrfs_insert_orphan_item(trans,
4372 dest->root_key.objectid);
4374 btrfs_abort_transaction(trans, ret);
4380 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4381 BTRFS_UUID_KEY_SUBVOL,
4382 dest->root_key.objectid);
4383 if (ret && ret != -ENOENT) {
4384 btrfs_abort_transaction(trans, ret);
4388 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4389 ret = btrfs_uuid_tree_remove(trans,
4390 dest->root_item.received_uuid,
4391 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4392 dest->root_key.objectid);
4393 if (ret && ret != -ENOENT) {
4394 btrfs_abort_transaction(trans, ret);
4401 trans->block_rsv = NULL;
4402 trans->bytes_reserved = 0;
4403 ret = btrfs_end_transaction(trans);
4406 inode->i_flags |= S_DEAD;
4408 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4410 up_write(&fs_info->subvol_sem);
4412 spin_lock(&dest->root_item_lock);
4413 root_flags = btrfs_root_flags(&dest->root_item);
4414 btrfs_set_root_flags(&dest->root_item,
4415 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4416 spin_unlock(&dest->root_item_lock);
4418 d_invalidate(dentry);
4419 btrfs_prune_dentries(dest);
4420 ASSERT(dest->send_in_progress == 0);
4423 if (dest->ino_cache_inode) {
4424 iput(dest->ino_cache_inode);
4425 dest->ino_cache_inode = NULL;
4432 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4434 struct inode *inode = d_inode(dentry);
4436 struct btrfs_root *root = BTRFS_I(dir)->root;
4437 struct btrfs_trans_handle *trans;
4438 u64 last_unlink_trans;
4440 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4442 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4443 return btrfs_delete_subvolume(dir, dentry);
4445 trans = __unlink_start_trans(dir);
4447 return PTR_ERR(trans);
4449 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4450 err = btrfs_unlink_subvol(trans, dir,
4451 BTRFS_I(inode)->location.objectid,
4452 dentry->d_name.name,
4453 dentry->d_name.len);
4457 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4461 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4463 /* now the directory is empty */
4464 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4465 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4466 dentry->d_name.len);
4468 btrfs_i_size_write(BTRFS_I(inode), 0);
4470 * Propagate the last_unlink_trans value of the deleted dir to
4471 * its parent directory. This is to prevent an unrecoverable
4472 * log tree in the case we do something like this:
4474 * 2) create snapshot under dir foo
4475 * 3) delete the snapshot
4478 * 6) fsync foo or some file inside foo
4480 if (last_unlink_trans >= trans->transid)
4481 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4484 btrfs_end_transaction(trans);
4485 btrfs_btree_balance_dirty(root->fs_info);
4491 * Return this if we need to call truncate_block for the last bit of the
4494 #define NEED_TRUNCATE_BLOCK 1
4497 * this can truncate away extent items, csum items and directory items.
4498 * It starts at a high offset and removes keys until it can't find
4499 * any higher than new_size
4501 * csum items that cross the new i_size are truncated to the new size
4504 * min_type is the minimum key type to truncate down to. If set to 0, this
4505 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4507 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4508 struct btrfs_root *root,
4509 struct inode *inode,
4510 u64 new_size, u32 min_type)
4512 struct btrfs_fs_info *fs_info = root->fs_info;
4513 struct btrfs_path *path;
4514 struct extent_buffer *leaf;
4515 struct btrfs_file_extent_item *fi;
4516 struct btrfs_key key;
4517 struct btrfs_key found_key;
4518 u64 extent_start = 0;
4519 u64 extent_num_bytes = 0;
4520 u64 extent_offset = 0;
4522 u64 last_size = new_size;
4523 u32 found_type = (u8)-1;
4526 int pending_del_nr = 0;
4527 int pending_del_slot = 0;
4528 int extent_type = -1;
4530 u64 ino = btrfs_ino(BTRFS_I(inode));
4531 u64 bytes_deleted = 0;
4532 bool be_nice = false;
4533 bool should_throttle = false;
4535 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4538 * for non-free space inodes and ref cows, we want to back off from
4541 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4542 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4545 path = btrfs_alloc_path();
4548 path->reada = READA_BACK;
4551 * We want to drop from the next block forward in case this new size is
4552 * not block aligned since we will be keeping the last block of the
4553 * extent just the way it is.
4555 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4556 root == fs_info->tree_root)
4557 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4558 fs_info->sectorsize),
4562 * This function is also used to drop the items in the log tree before
4563 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4564 * it is used to drop the logged items. So we shouldn't kill the delayed
4567 if (min_type == 0 && root == BTRFS_I(inode)->root)
4568 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4571 key.offset = (u64)-1;
4576 * with a 16K leaf size and 128MB extents, you can actually queue
4577 * up a huge file in a single leaf. Most of the time that
4578 * bytes_deleted is > 0, it will be huge by the time we get here
4580 if (be_nice && bytes_deleted > SZ_32M &&
4581 btrfs_should_end_transaction(trans)) {
4586 path->leave_spinning = 1;
4587 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4593 /* there are no items in the tree for us to truncate, we're
4596 if (path->slots[0] == 0)
4603 leaf = path->nodes[0];
4604 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4605 found_type = found_key.type;
4607 if (found_key.objectid != ino)
4610 if (found_type < min_type)
4613 item_end = found_key.offset;
4614 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4615 fi = btrfs_item_ptr(leaf, path->slots[0],
4616 struct btrfs_file_extent_item);
4617 extent_type = btrfs_file_extent_type(leaf, fi);
4618 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4620 btrfs_file_extent_num_bytes(leaf, fi);
4622 trace_btrfs_truncate_show_fi_regular(
4623 BTRFS_I(inode), leaf, fi,
4625 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4626 item_end += btrfs_file_extent_ram_bytes(leaf,
4629 trace_btrfs_truncate_show_fi_inline(
4630 BTRFS_I(inode), leaf, fi, path->slots[0],
4635 if (found_type > min_type) {
4638 if (item_end < new_size)
4640 if (found_key.offset >= new_size)
4646 /* FIXME, shrink the extent if the ref count is only 1 */
4647 if (found_type != BTRFS_EXTENT_DATA_KEY)
4650 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4652 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4654 u64 orig_num_bytes =
4655 btrfs_file_extent_num_bytes(leaf, fi);
4656 extent_num_bytes = ALIGN(new_size -
4658 fs_info->sectorsize);
4659 btrfs_set_file_extent_num_bytes(leaf, fi,
4661 num_dec = (orig_num_bytes -
4663 if (test_bit(BTRFS_ROOT_REF_COWS,
4666 inode_sub_bytes(inode, num_dec);
4667 btrfs_mark_buffer_dirty(leaf);
4670 btrfs_file_extent_disk_num_bytes(leaf,
4672 extent_offset = found_key.offset -
4673 btrfs_file_extent_offset(leaf, fi);
4675 /* FIXME blocksize != 4096 */
4676 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4677 if (extent_start != 0) {
4679 if (test_bit(BTRFS_ROOT_REF_COWS,
4681 inode_sub_bytes(inode, num_dec);
4684 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4686 * we can't truncate inline items that have had
4690 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4691 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4692 btrfs_file_extent_compression(leaf, fi) == 0) {
4693 u32 size = (u32)(new_size - found_key.offset);
4695 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4696 size = btrfs_file_extent_calc_inline_size(size);
4697 btrfs_truncate_item(path, size, 1);
4698 } else if (!del_item) {
4700 * We have to bail so the last_size is set to
4701 * just before this extent.
4703 ret = NEED_TRUNCATE_BLOCK;
4707 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4708 inode_sub_bytes(inode, item_end + 1 - new_size);
4712 last_size = found_key.offset;
4714 last_size = new_size;
4716 if (!pending_del_nr) {
4717 /* no pending yet, add ourselves */
4718 pending_del_slot = path->slots[0];
4720 } else if (pending_del_nr &&
4721 path->slots[0] + 1 == pending_del_slot) {
4722 /* hop on the pending chunk */
4724 pending_del_slot = path->slots[0];
4731 should_throttle = false;
4734 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4735 root == fs_info->tree_root)) {
4736 struct btrfs_ref ref = { 0 };
4738 btrfs_set_path_blocking(path);
4739 bytes_deleted += extent_num_bytes;
4741 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4742 extent_start, extent_num_bytes, 0);
4743 ref.real_root = root->root_key.objectid;
4744 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4745 ino, extent_offset);
4746 ret = btrfs_free_extent(trans, &ref);
4748 btrfs_abort_transaction(trans, ret);
4752 if (btrfs_should_throttle_delayed_refs(trans))
4753 should_throttle = true;
4757 if (found_type == BTRFS_INODE_ITEM_KEY)
4760 if (path->slots[0] == 0 ||
4761 path->slots[0] != pending_del_slot ||
4763 if (pending_del_nr) {
4764 ret = btrfs_del_items(trans, root, path,
4768 btrfs_abort_transaction(trans, ret);
4773 btrfs_release_path(path);
4776 * We can generate a lot of delayed refs, so we need to
4777 * throttle every once and a while and make sure we're
4778 * adding enough space to keep up with the work we are
4779 * generating. Since we hold a transaction here we
4780 * can't flush, and we don't want to FLUSH_LIMIT because
4781 * we could have generated too many delayed refs to
4782 * actually allocate, so just bail if we're short and
4783 * let the normal reservation dance happen higher up.
4785 if (should_throttle) {
4786 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4787 BTRFS_RESERVE_NO_FLUSH);
4799 if (ret >= 0 && pending_del_nr) {
4802 err = btrfs_del_items(trans, root, path, pending_del_slot,
4805 btrfs_abort_transaction(trans, err);
4809 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4810 ASSERT(last_size >= new_size);
4811 if (!ret && last_size > new_size)
4812 last_size = new_size;
4813 btrfs_ordered_update_i_size(inode, last_size, NULL);
4816 btrfs_free_path(path);
4821 * btrfs_truncate_block - read, zero a chunk and write a block
4822 * @inode - inode that we're zeroing
4823 * @from - the offset to start zeroing
4824 * @len - the length to zero, 0 to zero the entire range respective to the
4826 * @front - zero up to the offset instead of from the offset on
4828 * This will find the block for the "from" offset and cow the block and zero the
4829 * part we want to zero. This is used with truncate and hole punching.
4831 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4834 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4835 struct address_space *mapping = inode->i_mapping;
4836 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4837 struct btrfs_ordered_extent *ordered;
4838 struct extent_state *cached_state = NULL;
4839 struct extent_changeset *data_reserved = NULL;
4841 u32 blocksize = fs_info->sectorsize;
4842 pgoff_t index = from >> PAGE_SHIFT;
4843 unsigned offset = from & (blocksize - 1);
4845 gfp_t mask = btrfs_alloc_write_mask(mapping);
4850 if (IS_ALIGNED(offset, blocksize) &&
4851 (!len || IS_ALIGNED(len, blocksize)))
4854 block_start = round_down(from, blocksize);
4855 block_end = block_start + blocksize - 1;
4857 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4858 block_start, blocksize);
4863 page = find_or_create_page(mapping, index, mask);
4865 btrfs_delalloc_release_space(inode, data_reserved,
4866 block_start, blocksize, true);
4867 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4872 if (!PageUptodate(page)) {
4873 ret = btrfs_readpage(NULL, page);
4875 if (page->mapping != mapping) {
4880 if (!PageUptodate(page)) {
4885 wait_on_page_writeback(page);
4887 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4888 set_page_extent_mapped(page);
4890 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4892 unlock_extent_cached(io_tree, block_start, block_end,
4896 btrfs_start_ordered_extent(inode, ordered, 1);
4897 btrfs_put_ordered_extent(ordered);
4901 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4902 EXTENT_DIRTY | EXTENT_DELALLOC |
4903 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4904 0, 0, &cached_state);
4906 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4909 unlock_extent_cached(io_tree, block_start, block_end,
4914 if (offset != blocksize) {
4916 len = blocksize - offset;
4919 memset(kaddr + (block_start - page_offset(page)),
4922 memset(kaddr + (block_start - page_offset(page)) + offset,
4924 flush_dcache_page(page);
4927 ClearPageChecked(page);
4928 set_page_dirty(page);
4929 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4933 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4935 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4939 extent_changeset_free(data_reserved);
4943 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4944 u64 offset, u64 len)
4946 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4947 struct btrfs_trans_handle *trans;
4951 * Still need to make sure the inode looks like it's been updated so
4952 * that any holes get logged if we fsync.
4954 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4955 BTRFS_I(inode)->last_trans = fs_info->generation;
4956 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4957 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4962 * 1 - for the one we're dropping
4963 * 1 - for the one we're adding
4964 * 1 - for updating the inode.
4966 trans = btrfs_start_transaction(root, 3);
4968 return PTR_ERR(trans);
4970 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4972 btrfs_abort_transaction(trans, ret);
4973 btrfs_end_transaction(trans);
4977 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4978 offset, 0, 0, len, 0, len, 0, 0, 0);
4980 btrfs_abort_transaction(trans, ret);
4982 btrfs_update_inode(trans, root, inode);
4983 btrfs_end_transaction(trans);
4988 * This function puts in dummy file extents for the area we're creating a hole
4989 * for. So if we are truncating this file to a larger size we need to insert
4990 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4991 * the range between oldsize and size
4993 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4995 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4996 struct btrfs_root *root = BTRFS_I(inode)->root;
4997 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4998 struct extent_map *em = NULL;
4999 struct extent_state *cached_state = NULL;
5000 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5001 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5002 u64 block_end = ALIGN(size, fs_info->sectorsize);
5009 * If our size started in the middle of a block we need to zero out the
5010 * rest of the block before we expand the i_size, otherwise we could
5011 * expose stale data.
5013 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5017 if (size <= hole_start)
5021 struct btrfs_ordered_extent *ordered;
5023 lock_extent_bits(io_tree, hole_start, block_end - 1,
5025 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5026 block_end - hole_start);
5029 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5031 btrfs_start_ordered_extent(inode, ordered, 1);
5032 btrfs_put_ordered_extent(ordered);
5035 cur_offset = hole_start;
5037 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5038 block_end - cur_offset, 0);
5044 last_byte = min(extent_map_end(em), block_end);
5045 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5046 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5047 struct extent_map *hole_em;
5048 hole_size = last_byte - cur_offset;
5050 err = maybe_insert_hole(root, inode, cur_offset,
5054 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5055 cur_offset + hole_size - 1, 0);
5056 hole_em = alloc_extent_map();
5058 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5059 &BTRFS_I(inode)->runtime_flags);
5062 hole_em->start = cur_offset;
5063 hole_em->len = hole_size;
5064 hole_em->orig_start = cur_offset;
5066 hole_em->block_start = EXTENT_MAP_HOLE;
5067 hole_em->block_len = 0;
5068 hole_em->orig_block_len = 0;
5069 hole_em->ram_bytes = hole_size;
5070 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5071 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5072 hole_em->generation = fs_info->generation;
5075 write_lock(&em_tree->lock);
5076 err = add_extent_mapping(em_tree, hole_em, 1);
5077 write_unlock(&em_tree->lock);
5080 btrfs_drop_extent_cache(BTRFS_I(inode),
5085 free_extent_map(hole_em);
5088 free_extent_map(em);
5090 cur_offset = last_byte;
5091 if (cur_offset >= block_end)
5094 free_extent_map(em);
5095 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5099 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5101 struct btrfs_root *root = BTRFS_I(inode)->root;
5102 struct btrfs_trans_handle *trans;
5103 loff_t oldsize = i_size_read(inode);
5104 loff_t newsize = attr->ia_size;
5105 int mask = attr->ia_valid;
5109 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5110 * special case where we need to update the times despite not having
5111 * these flags set. For all other operations the VFS set these flags
5112 * explicitly if it wants a timestamp update.
5114 if (newsize != oldsize) {
5115 inode_inc_iversion(inode);
5116 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5117 inode->i_ctime = inode->i_mtime =
5118 current_time(inode);
5121 if (newsize > oldsize) {
5123 * Don't do an expanding truncate while snapshotting is ongoing.
5124 * This is to ensure the snapshot captures a fully consistent
5125 * state of this file - if the snapshot captures this expanding
5126 * truncation, it must capture all writes that happened before
5129 btrfs_wait_for_snapshot_creation(root);
5130 ret = btrfs_cont_expand(inode, oldsize, newsize);
5132 btrfs_end_write_no_snapshotting(root);
5136 trans = btrfs_start_transaction(root, 1);
5137 if (IS_ERR(trans)) {
5138 btrfs_end_write_no_snapshotting(root);
5139 return PTR_ERR(trans);
5142 i_size_write(inode, newsize);
5143 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5144 pagecache_isize_extended(inode, oldsize, newsize);
5145 ret = btrfs_update_inode(trans, root, inode);
5146 btrfs_end_write_no_snapshotting(root);
5147 btrfs_end_transaction(trans);
5151 * We're truncating a file that used to have good data down to
5152 * zero. Make sure it gets into the ordered flush list so that
5153 * any new writes get down to disk quickly.
5156 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5157 &BTRFS_I(inode)->runtime_flags);
5159 truncate_setsize(inode, newsize);
5161 /* Disable nonlocked read DIO to avoid the endless truncate */
5162 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5163 inode_dio_wait(inode);
5164 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5166 ret = btrfs_truncate(inode, newsize == oldsize);
5167 if (ret && inode->i_nlink) {
5171 * Truncate failed, so fix up the in-memory size. We
5172 * adjusted disk_i_size down as we removed extents, so
5173 * wait for disk_i_size to be stable and then update the
5174 * in-memory size to match.
5176 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5179 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5186 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5188 struct inode *inode = d_inode(dentry);
5189 struct btrfs_root *root = BTRFS_I(inode)->root;
5192 if (btrfs_root_readonly(root))
5195 err = setattr_prepare(dentry, attr);
5199 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5200 err = btrfs_setsize(inode, attr);
5205 if (attr->ia_valid) {
5206 setattr_copy(inode, attr);
5207 inode_inc_iversion(inode);
5208 err = btrfs_dirty_inode(inode);
5210 if (!err && attr->ia_valid & ATTR_MODE)
5211 err = posix_acl_chmod(inode, inode->i_mode);
5218 * While truncating the inode pages during eviction, we get the VFS calling
5219 * btrfs_invalidatepage() against each page of the inode. This is slow because
5220 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5221 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5222 * extent_state structures over and over, wasting lots of time.
5224 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5225 * those expensive operations on a per page basis and do only the ordered io
5226 * finishing, while we release here the extent_map and extent_state structures,
5227 * without the excessive merging and splitting.
5229 static void evict_inode_truncate_pages(struct inode *inode)
5231 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5232 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5233 struct rb_node *node;
5235 ASSERT(inode->i_state & I_FREEING);
5236 truncate_inode_pages_final(&inode->i_data);
5238 write_lock(&map_tree->lock);
5239 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5240 struct extent_map *em;
5242 node = rb_first_cached(&map_tree->map);
5243 em = rb_entry(node, struct extent_map, rb_node);
5244 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5245 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5246 remove_extent_mapping(map_tree, em);
5247 free_extent_map(em);
5248 if (need_resched()) {
5249 write_unlock(&map_tree->lock);
5251 write_lock(&map_tree->lock);
5254 write_unlock(&map_tree->lock);
5257 * Keep looping until we have no more ranges in the io tree.
5258 * We can have ongoing bios started by readpages (called from readahead)
5259 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5260 * still in progress (unlocked the pages in the bio but did not yet
5261 * unlocked the ranges in the io tree). Therefore this means some
5262 * ranges can still be locked and eviction started because before
5263 * submitting those bios, which are executed by a separate task (work
5264 * queue kthread), inode references (inode->i_count) were not taken
5265 * (which would be dropped in the end io callback of each bio).
5266 * Therefore here we effectively end up waiting for those bios and
5267 * anyone else holding locked ranges without having bumped the inode's
5268 * reference count - if we don't do it, when they access the inode's
5269 * io_tree to unlock a range it may be too late, leading to an
5270 * use-after-free issue.
5272 spin_lock(&io_tree->lock);
5273 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5274 struct extent_state *state;
5275 struct extent_state *cached_state = NULL;
5278 unsigned state_flags;
5280 node = rb_first(&io_tree->state);
5281 state = rb_entry(node, struct extent_state, rb_node);
5282 start = state->start;
5284 state_flags = state->state;
5285 spin_unlock(&io_tree->lock);
5287 lock_extent_bits(io_tree, start, end, &cached_state);
5290 * If still has DELALLOC flag, the extent didn't reach disk,
5291 * and its reserved space won't be freed by delayed_ref.
5292 * So we need to free its reserved space here.
5293 * (Refer to comment in btrfs_invalidatepage, case 2)
5295 * Note, end is the bytenr of last byte, so we need + 1 here.
5297 if (state_flags & EXTENT_DELALLOC)
5298 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5300 clear_extent_bit(io_tree, start, end,
5301 EXTENT_LOCKED | EXTENT_DIRTY |
5302 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5303 EXTENT_DEFRAG, 1, 1, &cached_state);
5306 spin_lock(&io_tree->lock);
5308 spin_unlock(&io_tree->lock);
5311 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5312 struct btrfs_block_rsv *rsv)
5314 struct btrfs_fs_info *fs_info = root->fs_info;
5315 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5316 u64 delayed_refs_extra = btrfs_calc_trans_metadata_size(fs_info, 1);
5320 struct btrfs_trans_handle *trans;
5323 ret = btrfs_block_rsv_refill(root, rsv,
5324 rsv->size + delayed_refs_extra,
5325 BTRFS_RESERVE_FLUSH_LIMIT);
5327 if (ret && ++failures > 2) {
5329 "could not allocate space for a delete; will truncate on mount");
5330 return ERR_PTR(-ENOSPC);
5334 * Evict can generate a large amount of delayed refs without
5335 * having a way to add space back since we exhaust our temporary
5336 * block rsv. We aren't allowed to do FLUSH_ALL in this case
5337 * because we could deadlock with so many things in the flushing
5338 * code, so we have to try and hold some extra space to
5339 * compensate for our delayed ref generation. If we can't get
5340 * that space then we need see if we can steal our minimum from
5341 * the global reserve. We will be ratelimited by the amount of
5342 * space we have for the delayed refs rsv, so we'll end up
5343 * committing and trying again.
5345 trans = btrfs_join_transaction(root);
5346 if (IS_ERR(trans) || !ret) {
5347 if (!IS_ERR(trans)) {
5348 trans->block_rsv = &fs_info->trans_block_rsv;
5349 trans->bytes_reserved = delayed_refs_extra;
5350 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5351 delayed_refs_extra, 1);
5357 * Try to steal from the global reserve if there is space for
5360 if (!btrfs_check_space_for_delayed_refs(fs_info) &&
5361 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0))
5364 /* If not, commit and try again. */
5365 ret = btrfs_commit_transaction(trans);
5367 return ERR_PTR(ret);
5371 void btrfs_evict_inode(struct inode *inode)
5373 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5374 struct btrfs_trans_handle *trans;
5375 struct btrfs_root *root = BTRFS_I(inode)->root;
5376 struct btrfs_block_rsv *rsv;
5379 trace_btrfs_inode_evict(inode);
5386 evict_inode_truncate_pages(inode);
5388 if (inode->i_nlink &&
5389 ((btrfs_root_refs(&root->root_item) != 0 &&
5390 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5391 btrfs_is_free_space_inode(BTRFS_I(inode))))
5394 if (is_bad_inode(inode))
5397 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5399 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5402 if (inode->i_nlink > 0) {
5403 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5404 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5408 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5412 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5415 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5418 btrfs_i_size_write(BTRFS_I(inode), 0);
5421 trans = evict_refill_and_join(root, rsv);
5425 trans->block_rsv = rsv;
5427 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5428 trans->block_rsv = &fs_info->trans_block_rsv;
5429 btrfs_end_transaction(trans);
5430 btrfs_btree_balance_dirty(fs_info);
5431 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5438 * Errors here aren't a big deal, it just means we leave orphan items in
5439 * the tree. They will be cleaned up on the next mount. If the inode
5440 * number gets reused, cleanup deletes the orphan item without doing
5441 * anything, and unlink reuses the existing orphan item.
5443 * If it turns out that we are dropping too many of these, we might want
5444 * to add a mechanism for retrying these after a commit.
5446 trans = evict_refill_and_join(root, rsv);
5447 if (!IS_ERR(trans)) {
5448 trans->block_rsv = rsv;
5449 btrfs_orphan_del(trans, BTRFS_I(inode));
5450 trans->block_rsv = &fs_info->trans_block_rsv;
5451 btrfs_end_transaction(trans);
5454 if (!(root == fs_info->tree_root ||
5455 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5456 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5459 btrfs_free_block_rsv(fs_info, rsv);
5462 * If we didn't successfully delete, the orphan item will still be in
5463 * the tree and we'll retry on the next mount. Again, we might also want
5464 * to retry these periodically in the future.
5466 btrfs_remove_delayed_node(BTRFS_I(inode));
5471 * Return the key found in the dir entry in the location pointer, fill @type
5472 * with BTRFS_FT_*, and return 0.
5474 * If no dir entries were found, returns -ENOENT.
5475 * If found a corrupted location in dir entry, returns -EUCLEAN.
5477 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5478 struct btrfs_key *location, u8 *type)
5480 const char *name = dentry->d_name.name;
5481 int namelen = dentry->d_name.len;
5482 struct btrfs_dir_item *di;
5483 struct btrfs_path *path;
5484 struct btrfs_root *root = BTRFS_I(dir)->root;
5487 path = btrfs_alloc_path();
5491 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5493 if (IS_ERR_OR_NULL(di)) {
5494 ret = di ? PTR_ERR(di) : -ENOENT;
5498 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5499 if (location->type != BTRFS_INODE_ITEM_KEY &&
5500 location->type != BTRFS_ROOT_ITEM_KEY) {
5502 btrfs_warn(root->fs_info,
5503 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5504 __func__, name, btrfs_ino(BTRFS_I(dir)),
5505 location->objectid, location->type, location->offset);
5508 *type = btrfs_dir_type(path->nodes[0], di);
5510 btrfs_free_path(path);
5515 * when we hit a tree root in a directory, the btrfs part of the inode
5516 * needs to be changed to reflect the root directory of the tree root. This
5517 * is kind of like crossing a mount point.
5519 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5521 struct dentry *dentry,
5522 struct btrfs_key *location,
5523 struct btrfs_root **sub_root)
5525 struct btrfs_path *path;
5526 struct btrfs_root *new_root;
5527 struct btrfs_root_ref *ref;
5528 struct extent_buffer *leaf;
5529 struct btrfs_key key;
5533 path = btrfs_alloc_path();
5540 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5541 key.type = BTRFS_ROOT_REF_KEY;
5542 key.offset = location->objectid;
5544 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5551 leaf = path->nodes[0];
5552 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5553 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5554 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5557 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5558 (unsigned long)(ref + 1),
5559 dentry->d_name.len);
5563 btrfs_release_path(path);
5565 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5566 if (IS_ERR(new_root)) {
5567 err = PTR_ERR(new_root);
5571 *sub_root = new_root;
5572 location->objectid = btrfs_root_dirid(&new_root->root_item);
5573 location->type = BTRFS_INODE_ITEM_KEY;
5574 location->offset = 0;
5577 btrfs_free_path(path);
5581 static void inode_tree_add(struct inode *inode)
5583 struct btrfs_root *root = BTRFS_I(inode)->root;
5584 struct btrfs_inode *entry;
5586 struct rb_node *parent;
5587 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5588 u64 ino = btrfs_ino(BTRFS_I(inode));
5590 if (inode_unhashed(inode))
5593 spin_lock(&root->inode_lock);
5594 p = &root->inode_tree.rb_node;
5597 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5599 if (ino < btrfs_ino(entry))
5600 p = &parent->rb_left;
5601 else if (ino > btrfs_ino(entry))
5602 p = &parent->rb_right;
5604 WARN_ON(!(entry->vfs_inode.i_state &
5605 (I_WILL_FREE | I_FREEING)));
5606 rb_replace_node(parent, new, &root->inode_tree);
5607 RB_CLEAR_NODE(parent);
5608 spin_unlock(&root->inode_lock);
5612 rb_link_node(new, parent, p);
5613 rb_insert_color(new, &root->inode_tree);
5614 spin_unlock(&root->inode_lock);
5617 static void inode_tree_del(struct inode *inode)
5619 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5620 struct btrfs_root *root = BTRFS_I(inode)->root;
5623 spin_lock(&root->inode_lock);
5624 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5625 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5626 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5627 empty = RB_EMPTY_ROOT(&root->inode_tree);
5629 spin_unlock(&root->inode_lock);
5631 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5632 synchronize_srcu(&fs_info->subvol_srcu);
5633 spin_lock(&root->inode_lock);
5634 empty = RB_EMPTY_ROOT(&root->inode_tree);
5635 spin_unlock(&root->inode_lock);
5637 btrfs_add_dead_root(root);
5642 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5644 struct btrfs_iget_args *args = p;
5645 inode->i_ino = args->location->objectid;
5646 memcpy(&BTRFS_I(inode)->location, args->location,
5647 sizeof(*args->location));
5648 BTRFS_I(inode)->root = args->root;
5652 static int btrfs_find_actor(struct inode *inode, void *opaque)
5654 struct btrfs_iget_args *args = opaque;
5655 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5656 args->root == BTRFS_I(inode)->root;
5659 static struct inode *btrfs_iget_locked(struct super_block *s,
5660 struct btrfs_key *location,
5661 struct btrfs_root *root)
5663 struct inode *inode;
5664 struct btrfs_iget_args args;
5665 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5667 args.location = location;
5670 inode = iget5_locked(s, hashval, btrfs_find_actor,
5671 btrfs_init_locked_inode,
5676 /* Get an inode object given its location and corresponding root.
5677 * Returns in *is_new if the inode was read from disk
5679 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5680 struct btrfs_root *root, int *new,
5681 struct btrfs_path *path)
5683 struct inode *inode;
5685 inode = btrfs_iget_locked(s, location, root);
5687 return ERR_PTR(-ENOMEM);
5689 if (inode->i_state & I_NEW) {
5692 ret = btrfs_read_locked_inode(inode, path);
5694 inode_tree_add(inode);
5695 unlock_new_inode(inode);
5701 * ret > 0 can come from btrfs_search_slot called by
5702 * btrfs_read_locked_inode, this means the inode item
5707 inode = ERR_PTR(ret);
5714 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5715 struct btrfs_root *root, int *new)
5717 return btrfs_iget_path(s, location, root, new, NULL);
5720 static struct inode *new_simple_dir(struct super_block *s,
5721 struct btrfs_key *key,
5722 struct btrfs_root *root)
5724 struct inode *inode = new_inode(s);
5727 return ERR_PTR(-ENOMEM);
5729 BTRFS_I(inode)->root = root;
5730 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5731 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5733 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5734 inode->i_op = &btrfs_dir_ro_inode_operations;
5735 inode->i_opflags &= ~IOP_XATTR;
5736 inode->i_fop = &simple_dir_operations;
5737 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5738 inode->i_mtime = current_time(inode);
5739 inode->i_atime = inode->i_mtime;
5740 inode->i_ctime = inode->i_mtime;
5741 BTRFS_I(inode)->i_otime = inode->i_mtime;
5746 static inline u8 btrfs_inode_type(struct inode *inode)
5749 * Compile-time asserts that generic FT_* types still match
5752 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5753 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5754 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5755 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5756 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5757 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5758 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5759 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5761 return fs_umode_to_ftype(inode->i_mode);
5764 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5766 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5767 struct inode *inode;
5768 struct btrfs_root *root = BTRFS_I(dir)->root;
5769 struct btrfs_root *sub_root = root;
5770 struct btrfs_key location;
5775 if (dentry->d_name.len > BTRFS_NAME_LEN)
5776 return ERR_PTR(-ENAMETOOLONG);
5778 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5780 return ERR_PTR(ret);
5782 if (location.type == BTRFS_INODE_ITEM_KEY) {
5783 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5787 /* Do extra check against inode mode with di_type */
5788 if (btrfs_inode_type(inode) != di_type) {
5790 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5791 inode->i_mode, btrfs_inode_type(inode),
5794 return ERR_PTR(-EUCLEAN);
5799 index = srcu_read_lock(&fs_info->subvol_srcu);
5800 ret = fixup_tree_root_location(fs_info, dir, dentry,
5801 &location, &sub_root);
5804 inode = ERR_PTR(ret);
5806 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5808 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5810 srcu_read_unlock(&fs_info->subvol_srcu, index);
5812 if (!IS_ERR(inode) && root != sub_root) {
5813 down_read(&fs_info->cleanup_work_sem);
5814 if (!sb_rdonly(inode->i_sb))
5815 ret = btrfs_orphan_cleanup(sub_root);
5816 up_read(&fs_info->cleanup_work_sem);
5819 inode = ERR_PTR(ret);
5826 static int btrfs_dentry_delete(const struct dentry *dentry)
5828 struct btrfs_root *root;
5829 struct inode *inode = d_inode(dentry);
5831 if (!inode && !IS_ROOT(dentry))
5832 inode = d_inode(dentry->d_parent);
5835 root = BTRFS_I(inode)->root;
5836 if (btrfs_root_refs(&root->root_item) == 0)
5839 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5845 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5848 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5850 if (inode == ERR_PTR(-ENOENT))
5852 return d_splice_alias(inode, dentry);
5856 * All this infrastructure exists because dir_emit can fault, and we are holding
5857 * the tree lock when doing readdir. For now just allocate a buffer and copy
5858 * our information into that, and then dir_emit from the buffer. This is
5859 * similar to what NFS does, only we don't keep the buffer around in pagecache
5860 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5861 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5864 static int btrfs_opendir(struct inode *inode, struct file *file)
5866 struct btrfs_file_private *private;
5868 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5871 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5872 if (!private->filldir_buf) {
5876 file->private_data = private;
5887 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5890 struct dir_entry *entry = addr;
5891 char *name = (char *)(entry + 1);
5893 ctx->pos = get_unaligned(&entry->offset);
5894 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5895 get_unaligned(&entry->ino),
5896 get_unaligned(&entry->type)))
5898 addr += sizeof(struct dir_entry) +
5899 get_unaligned(&entry->name_len);
5905 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5907 struct inode *inode = file_inode(file);
5908 struct btrfs_root *root = BTRFS_I(inode)->root;
5909 struct btrfs_file_private *private = file->private_data;
5910 struct btrfs_dir_item *di;
5911 struct btrfs_key key;
5912 struct btrfs_key found_key;
5913 struct btrfs_path *path;
5915 struct list_head ins_list;
5916 struct list_head del_list;
5918 struct extent_buffer *leaf;
5925 struct btrfs_key location;
5927 if (!dir_emit_dots(file, ctx))
5930 path = btrfs_alloc_path();
5934 addr = private->filldir_buf;
5935 path->reada = READA_FORWARD;
5937 INIT_LIST_HEAD(&ins_list);
5938 INIT_LIST_HEAD(&del_list);
5939 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5942 key.type = BTRFS_DIR_INDEX_KEY;
5943 key.offset = ctx->pos;
5944 key.objectid = btrfs_ino(BTRFS_I(inode));
5946 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5951 struct dir_entry *entry;
5953 leaf = path->nodes[0];
5954 slot = path->slots[0];
5955 if (slot >= btrfs_header_nritems(leaf)) {
5956 ret = btrfs_next_leaf(root, path);
5964 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5966 if (found_key.objectid != key.objectid)
5968 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5970 if (found_key.offset < ctx->pos)
5972 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5974 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5975 name_len = btrfs_dir_name_len(leaf, di);
5976 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5978 btrfs_release_path(path);
5979 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5982 addr = private->filldir_buf;
5989 put_unaligned(name_len, &entry->name_len);
5990 name_ptr = (char *)(entry + 1);
5991 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5993 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5995 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5996 put_unaligned(location.objectid, &entry->ino);
5997 put_unaligned(found_key.offset, &entry->offset);
5999 addr += sizeof(struct dir_entry) + name_len;
6000 total_len += sizeof(struct dir_entry) + name_len;
6004 btrfs_release_path(path);
6006 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6010 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6015 * Stop new entries from being returned after we return the last
6018 * New directory entries are assigned a strictly increasing
6019 * offset. This means that new entries created during readdir
6020 * are *guaranteed* to be seen in the future by that readdir.
6021 * This has broken buggy programs which operate on names as
6022 * they're returned by readdir. Until we re-use freed offsets
6023 * we have this hack to stop new entries from being returned
6024 * under the assumption that they'll never reach this huge
6027 * This is being careful not to overflow 32bit loff_t unless the
6028 * last entry requires it because doing so has broken 32bit apps
6031 if (ctx->pos >= INT_MAX)
6032 ctx->pos = LLONG_MAX;
6039 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6040 btrfs_free_path(path);
6045 * This is somewhat expensive, updating the tree every time the
6046 * inode changes. But, it is most likely to find the inode in cache.
6047 * FIXME, needs more benchmarking...there are no reasons other than performance
6048 * to keep or drop this code.
6050 static int btrfs_dirty_inode(struct inode *inode)
6052 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6053 struct btrfs_root *root = BTRFS_I(inode)->root;
6054 struct btrfs_trans_handle *trans;
6057 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6060 trans = btrfs_join_transaction(root);
6062 return PTR_ERR(trans);
6064 ret = btrfs_update_inode(trans, root, inode);
6065 if (ret && ret == -ENOSPC) {
6066 /* whoops, lets try again with the full transaction */
6067 btrfs_end_transaction(trans);
6068 trans = btrfs_start_transaction(root, 1);
6070 return PTR_ERR(trans);
6072 ret = btrfs_update_inode(trans, root, inode);
6074 btrfs_end_transaction(trans);
6075 if (BTRFS_I(inode)->delayed_node)
6076 btrfs_balance_delayed_items(fs_info);
6082 * This is a copy of file_update_time. We need this so we can return error on
6083 * ENOSPC for updating the inode in the case of file write and mmap writes.
6085 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6088 struct btrfs_root *root = BTRFS_I(inode)->root;
6089 bool dirty = flags & ~S_VERSION;
6091 if (btrfs_root_readonly(root))
6094 if (flags & S_VERSION)
6095 dirty |= inode_maybe_inc_iversion(inode, dirty);
6096 if (flags & S_CTIME)
6097 inode->i_ctime = *now;
6098 if (flags & S_MTIME)
6099 inode->i_mtime = *now;
6100 if (flags & S_ATIME)
6101 inode->i_atime = *now;
6102 return dirty ? btrfs_dirty_inode(inode) : 0;
6106 * find the highest existing sequence number in a directory
6107 * and then set the in-memory index_cnt variable to reflect
6108 * free sequence numbers
6110 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6112 struct btrfs_root *root = inode->root;
6113 struct btrfs_key key, found_key;
6114 struct btrfs_path *path;
6115 struct extent_buffer *leaf;
6118 key.objectid = btrfs_ino(inode);
6119 key.type = BTRFS_DIR_INDEX_KEY;
6120 key.offset = (u64)-1;
6122 path = btrfs_alloc_path();
6126 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6129 /* FIXME: we should be able to handle this */
6135 * MAGIC NUMBER EXPLANATION:
6136 * since we search a directory based on f_pos we have to start at 2
6137 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6138 * else has to start at 2
6140 if (path->slots[0] == 0) {
6141 inode->index_cnt = 2;
6147 leaf = path->nodes[0];
6148 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6150 if (found_key.objectid != btrfs_ino(inode) ||
6151 found_key.type != BTRFS_DIR_INDEX_KEY) {
6152 inode->index_cnt = 2;
6156 inode->index_cnt = found_key.offset + 1;
6158 btrfs_free_path(path);
6163 * helper to find a free sequence number in a given directory. This current
6164 * code is very simple, later versions will do smarter things in the btree
6166 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6170 if (dir->index_cnt == (u64)-1) {
6171 ret = btrfs_inode_delayed_dir_index_count(dir);
6173 ret = btrfs_set_inode_index_count(dir);
6179 *index = dir->index_cnt;
6185 static int btrfs_insert_inode_locked(struct inode *inode)
6187 struct btrfs_iget_args args;
6188 args.location = &BTRFS_I(inode)->location;
6189 args.root = BTRFS_I(inode)->root;
6191 return insert_inode_locked4(inode,
6192 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6193 btrfs_find_actor, &args);
6197 * Inherit flags from the parent inode.
6199 * Currently only the compression flags and the cow flags are inherited.
6201 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6208 flags = BTRFS_I(dir)->flags;
6210 if (flags & BTRFS_INODE_NOCOMPRESS) {
6211 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6212 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6213 } else if (flags & BTRFS_INODE_COMPRESS) {
6214 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6215 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6218 if (flags & BTRFS_INODE_NODATACOW) {
6219 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6220 if (S_ISREG(inode->i_mode))
6221 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6224 btrfs_sync_inode_flags_to_i_flags(inode);
6227 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6228 struct btrfs_root *root,
6230 const char *name, int name_len,
6231 u64 ref_objectid, u64 objectid,
6232 umode_t mode, u64 *index)
6234 struct btrfs_fs_info *fs_info = root->fs_info;
6235 struct inode *inode;
6236 struct btrfs_inode_item *inode_item;
6237 struct btrfs_key *location;
6238 struct btrfs_path *path;
6239 struct btrfs_inode_ref *ref;
6240 struct btrfs_key key[2];
6242 int nitems = name ? 2 : 1;
6246 path = btrfs_alloc_path();
6248 return ERR_PTR(-ENOMEM);
6250 inode = new_inode(fs_info->sb);
6252 btrfs_free_path(path);
6253 return ERR_PTR(-ENOMEM);
6257 * O_TMPFILE, set link count to 0, so that after this point,
6258 * we fill in an inode item with the correct link count.
6261 set_nlink(inode, 0);
6264 * we have to initialize this early, so we can reclaim the inode
6265 * number if we fail afterwards in this function.
6267 inode->i_ino = objectid;
6270 trace_btrfs_inode_request(dir);
6272 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6274 btrfs_free_path(path);
6276 return ERR_PTR(ret);
6282 * index_cnt is ignored for everything but a dir,
6283 * btrfs_set_inode_index_count has an explanation for the magic
6286 BTRFS_I(inode)->index_cnt = 2;
6287 BTRFS_I(inode)->dir_index = *index;
6288 BTRFS_I(inode)->root = root;
6289 BTRFS_I(inode)->generation = trans->transid;
6290 inode->i_generation = BTRFS_I(inode)->generation;
6293 * We could have gotten an inode number from somebody who was fsynced
6294 * and then removed in this same transaction, so let's just set full
6295 * sync since it will be a full sync anyway and this will blow away the
6296 * old info in the log.
6298 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6300 key[0].objectid = objectid;
6301 key[0].type = BTRFS_INODE_ITEM_KEY;
6304 sizes[0] = sizeof(struct btrfs_inode_item);
6308 * Start new inodes with an inode_ref. This is slightly more
6309 * efficient for small numbers of hard links since they will
6310 * be packed into one item. Extended refs will kick in if we
6311 * add more hard links than can fit in the ref item.
6313 key[1].objectid = objectid;
6314 key[1].type = BTRFS_INODE_REF_KEY;
6315 key[1].offset = ref_objectid;
6317 sizes[1] = name_len + sizeof(*ref);
6320 location = &BTRFS_I(inode)->location;
6321 location->objectid = objectid;
6322 location->offset = 0;
6323 location->type = BTRFS_INODE_ITEM_KEY;
6325 ret = btrfs_insert_inode_locked(inode);
6331 path->leave_spinning = 1;
6332 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6336 inode_init_owner(inode, dir, mode);
6337 inode_set_bytes(inode, 0);
6339 inode->i_mtime = current_time(inode);
6340 inode->i_atime = inode->i_mtime;
6341 inode->i_ctime = inode->i_mtime;
6342 BTRFS_I(inode)->i_otime = inode->i_mtime;
6344 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6345 struct btrfs_inode_item);
6346 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6347 sizeof(*inode_item));
6348 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6351 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6352 struct btrfs_inode_ref);
6353 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6354 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6355 ptr = (unsigned long)(ref + 1);
6356 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6359 btrfs_mark_buffer_dirty(path->nodes[0]);
6360 btrfs_free_path(path);
6362 btrfs_inherit_iflags(inode, dir);
6364 if (S_ISREG(mode)) {
6365 if (btrfs_test_opt(fs_info, NODATASUM))
6366 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6367 if (btrfs_test_opt(fs_info, NODATACOW))
6368 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6369 BTRFS_INODE_NODATASUM;
6372 inode_tree_add(inode);
6374 trace_btrfs_inode_new(inode);
6375 btrfs_set_inode_last_trans(trans, inode);
6377 btrfs_update_root_times(trans, root);
6379 ret = btrfs_inode_inherit_props(trans, inode, dir);
6382 "error inheriting props for ino %llu (root %llu): %d",
6383 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6388 discard_new_inode(inode);
6391 BTRFS_I(dir)->index_cnt--;
6392 btrfs_free_path(path);
6393 return ERR_PTR(ret);
6397 * utility function to add 'inode' into 'parent_inode' with
6398 * a give name and a given sequence number.
6399 * if 'add_backref' is true, also insert a backref from the
6400 * inode to the parent directory.
6402 int btrfs_add_link(struct btrfs_trans_handle *trans,
6403 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6404 const char *name, int name_len, int add_backref, u64 index)
6407 struct btrfs_key key;
6408 struct btrfs_root *root = parent_inode->root;
6409 u64 ino = btrfs_ino(inode);
6410 u64 parent_ino = btrfs_ino(parent_inode);
6412 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6413 memcpy(&key, &inode->root->root_key, sizeof(key));
6416 key.type = BTRFS_INODE_ITEM_KEY;
6420 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6421 ret = btrfs_add_root_ref(trans, key.objectid,
6422 root->root_key.objectid, parent_ino,
6423 index, name, name_len);
6424 } else if (add_backref) {
6425 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6429 /* Nothing to clean up yet */
6433 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6434 btrfs_inode_type(&inode->vfs_inode), index);
6435 if (ret == -EEXIST || ret == -EOVERFLOW)
6438 btrfs_abort_transaction(trans, ret);
6442 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6444 inode_inc_iversion(&parent_inode->vfs_inode);
6445 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6446 current_time(&parent_inode->vfs_inode);
6447 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6449 btrfs_abort_transaction(trans, ret);
6453 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6456 err = btrfs_del_root_ref(trans, key.objectid,
6457 root->root_key.objectid, parent_ino,
6458 &local_index, name, name_len);
6460 btrfs_abort_transaction(trans, err);
6461 } else if (add_backref) {
6465 err = btrfs_del_inode_ref(trans, root, name, name_len,
6466 ino, parent_ino, &local_index);
6468 btrfs_abort_transaction(trans, err);
6471 /* Return the original error code */
6475 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6476 struct btrfs_inode *dir, struct dentry *dentry,
6477 struct btrfs_inode *inode, int backref, u64 index)
6479 int err = btrfs_add_link(trans, dir, inode,
6480 dentry->d_name.name, dentry->d_name.len,
6487 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6488 umode_t mode, dev_t rdev)
6490 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6491 struct btrfs_trans_handle *trans;
6492 struct btrfs_root *root = BTRFS_I(dir)->root;
6493 struct inode *inode = NULL;
6499 * 2 for inode item and ref
6501 * 1 for xattr if selinux is on
6503 trans = btrfs_start_transaction(root, 5);
6505 return PTR_ERR(trans);
6507 err = btrfs_find_free_ino(root, &objectid);
6511 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6512 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6514 if (IS_ERR(inode)) {
6515 err = PTR_ERR(inode);
6521 * If the active LSM wants to access the inode during
6522 * d_instantiate it needs these. Smack checks to see
6523 * if the filesystem supports xattrs by looking at the
6526 inode->i_op = &btrfs_special_inode_operations;
6527 init_special_inode(inode, inode->i_mode, rdev);
6529 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6533 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6538 btrfs_update_inode(trans, root, inode);
6539 d_instantiate_new(dentry, inode);
6542 btrfs_end_transaction(trans);
6543 btrfs_btree_balance_dirty(fs_info);
6545 inode_dec_link_count(inode);
6546 discard_new_inode(inode);
6551 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6552 umode_t mode, bool excl)
6554 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6555 struct btrfs_trans_handle *trans;
6556 struct btrfs_root *root = BTRFS_I(dir)->root;
6557 struct inode *inode = NULL;
6563 * 2 for inode item and ref
6565 * 1 for xattr if selinux is on
6567 trans = btrfs_start_transaction(root, 5);
6569 return PTR_ERR(trans);
6571 err = btrfs_find_free_ino(root, &objectid);
6575 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6576 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6578 if (IS_ERR(inode)) {
6579 err = PTR_ERR(inode);
6584 * If the active LSM wants to access the inode during
6585 * d_instantiate it needs these. Smack checks to see
6586 * if the filesystem supports xattrs by looking at the
6589 inode->i_fop = &btrfs_file_operations;
6590 inode->i_op = &btrfs_file_inode_operations;
6591 inode->i_mapping->a_ops = &btrfs_aops;
6593 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6597 err = btrfs_update_inode(trans, root, inode);
6601 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6606 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6607 d_instantiate_new(dentry, inode);
6610 btrfs_end_transaction(trans);
6612 inode_dec_link_count(inode);
6613 discard_new_inode(inode);
6615 btrfs_btree_balance_dirty(fs_info);
6619 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6620 struct dentry *dentry)
6622 struct btrfs_trans_handle *trans = NULL;
6623 struct btrfs_root *root = BTRFS_I(dir)->root;
6624 struct inode *inode = d_inode(old_dentry);
6625 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6630 /* do not allow sys_link's with other subvols of the same device */
6631 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6634 if (inode->i_nlink >= BTRFS_LINK_MAX)
6637 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6642 * 2 items for inode and inode ref
6643 * 2 items for dir items
6644 * 1 item for parent inode
6645 * 1 item for orphan item deletion if O_TMPFILE
6647 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6648 if (IS_ERR(trans)) {
6649 err = PTR_ERR(trans);
6654 /* There are several dir indexes for this inode, clear the cache. */
6655 BTRFS_I(inode)->dir_index = 0ULL;
6657 inode_inc_iversion(inode);
6658 inode->i_ctime = current_time(inode);
6660 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6662 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6668 struct dentry *parent = dentry->d_parent;
6671 err = btrfs_update_inode(trans, root, inode);
6674 if (inode->i_nlink == 1) {
6676 * If new hard link count is 1, it's a file created
6677 * with open(2) O_TMPFILE flag.
6679 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6683 d_instantiate(dentry, inode);
6684 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6686 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6687 err = btrfs_commit_transaction(trans);
6694 btrfs_end_transaction(trans);
6696 inode_dec_link_count(inode);
6699 btrfs_btree_balance_dirty(fs_info);
6703 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6705 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6706 struct inode *inode = NULL;
6707 struct btrfs_trans_handle *trans;
6708 struct btrfs_root *root = BTRFS_I(dir)->root;
6714 * 2 items for inode and ref
6715 * 2 items for dir items
6716 * 1 for xattr if selinux is on
6718 trans = btrfs_start_transaction(root, 5);
6720 return PTR_ERR(trans);
6722 err = btrfs_find_free_ino(root, &objectid);
6726 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6727 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6728 S_IFDIR | mode, &index);
6729 if (IS_ERR(inode)) {
6730 err = PTR_ERR(inode);
6735 /* these must be set before we unlock the inode */
6736 inode->i_op = &btrfs_dir_inode_operations;
6737 inode->i_fop = &btrfs_dir_file_operations;
6739 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6743 btrfs_i_size_write(BTRFS_I(inode), 0);
6744 err = btrfs_update_inode(trans, root, inode);
6748 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6749 dentry->d_name.name,
6750 dentry->d_name.len, 0, index);
6754 d_instantiate_new(dentry, inode);
6757 btrfs_end_transaction(trans);
6759 inode_dec_link_count(inode);
6760 discard_new_inode(inode);
6762 btrfs_btree_balance_dirty(fs_info);
6766 static noinline int uncompress_inline(struct btrfs_path *path,
6768 size_t pg_offset, u64 extent_offset,
6769 struct btrfs_file_extent_item *item)
6772 struct extent_buffer *leaf = path->nodes[0];
6775 unsigned long inline_size;
6779 WARN_ON(pg_offset != 0);
6780 compress_type = btrfs_file_extent_compression(leaf, item);
6781 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6782 inline_size = btrfs_file_extent_inline_item_len(leaf,
6783 btrfs_item_nr(path->slots[0]));
6784 tmp = kmalloc(inline_size, GFP_NOFS);
6787 ptr = btrfs_file_extent_inline_start(item);
6789 read_extent_buffer(leaf, tmp, ptr, inline_size);
6791 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6792 ret = btrfs_decompress(compress_type, tmp, page,
6793 extent_offset, inline_size, max_size);
6796 * decompression code contains a memset to fill in any space between the end
6797 * of the uncompressed data and the end of max_size in case the decompressed
6798 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6799 * the end of an inline extent and the beginning of the next block, so we
6800 * cover that region here.
6803 if (max_size + pg_offset < PAGE_SIZE) {
6804 char *map = kmap(page);
6805 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6813 * a bit scary, this does extent mapping from logical file offset to the disk.
6814 * the ugly parts come from merging extents from the disk with the in-ram
6815 * representation. This gets more complex because of the data=ordered code,
6816 * where the in-ram extents might be locked pending data=ordered completion.
6818 * This also copies inline extents directly into the page.
6820 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6822 size_t pg_offset, u64 start, u64 len,
6825 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6828 u64 extent_start = 0;
6830 u64 objectid = btrfs_ino(inode);
6832 struct btrfs_path *path = NULL;
6833 struct btrfs_root *root = inode->root;
6834 struct btrfs_file_extent_item *item;
6835 struct extent_buffer *leaf;
6836 struct btrfs_key found_key;
6837 struct extent_map *em = NULL;
6838 struct extent_map_tree *em_tree = &inode->extent_tree;
6839 struct extent_io_tree *io_tree = &inode->io_tree;
6840 const bool new_inline = !page || create;
6842 read_lock(&em_tree->lock);
6843 em = lookup_extent_mapping(em_tree, start, len);
6845 em->bdev = fs_info->fs_devices->latest_bdev;
6846 read_unlock(&em_tree->lock);
6849 if (em->start > start || em->start + em->len <= start)
6850 free_extent_map(em);
6851 else if (em->block_start == EXTENT_MAP_INLINE && page)
6852 free_extent_map(em);
6856 em = alloc_extent_map();
6861 em->bdev = fs_info->fs_devices->latest_bdev;
6862 em->start = EXTENT_MAP_HOLE;
6863 em->orig_start = EXTENT_MAP_HOLE;
6865 em->block_len = (u64)-1;
6867 path = btrfs_alloc_path();
6873 /* Chances are we'll be called again, so go ahead and do readahead */
6874 path->reada = READA_FORWARD;
6877 * Unless we're going to uncompress the inline extent, no sleep would
6880 path->leave_spinning = 1;
6882 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6886 } else if (ret > 0) {
6887 if (path->slots[0] == 0)
6892 leaf = path->nodes[0];
6893 item = btrfs_item_ptr(leaf, path->slots[0],
6894 struct btrfs_file_extent_item);
6895 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6896 if (found_key.objectid != objectid ||
6897 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6899 * If we backup past the first extent we want to move forward
6900 * and see if there is an extent in front of us, otherwise we'll
6901 * say there is a hole for our whole search range which can
6908 extent_type = btrfs_file_extent_type(leaf, item);
6909 extent_start = found_key.offset;
6910 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6911 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6912 /* Only regular file could have regular/prealloc extent */
6913 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6916 "regular/prealloc extent found for non-regular inode %llu",
6920 extent_end = extent_start +
6921 btrfs_file_extent_num_bytes(leaf, item);
6923 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6925 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6928 size = btrfs_file_extent_ram_bytes(leaf, item);
6929 extent_end = ALIGN(extent_start + size,
6930 fs_info->sectorsize);
6932 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6937 if (start >= extent_end) {
6939 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6940 ret = btrfs_next_leaf(root, path);
6944 } else if (ret > 0) {
6947 leaf = path->nodes[0];
6949 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6950 if (found_key.objectid != objectid ||
6951 found_key.type != BTRFS_EXTENT_DATA_KEY)
6953 if (start + len <= found_key.offset)
6955 if (start > found_key.offset)
6958 /* New extent overlaps with existing one */
6960 em->orig_start = start;
6961 em->len = found_key.offset - start;
6962 em->block_start = EXTENT_MAP_HOLE;
6966 btrfs_extent_item_to_extent_map(inode, path, item,
6969 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6970 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6972 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6976 size_t extent_offset;
6982 size = btrfs_file_extent_ram_bytes(leaf, item);
6983 extent_offset = page_offset(page) + pg_offset - extent_start;
6984 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6985 size - extent_offset);
6986 em->start = extent_start + extent_offset;
6987 em->len = ALIGN(copy_size, fs_info->sectorsize);
6988 em->orig_block_len = em->len;
6989 em->orig_start = em->start;
6990 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6992 btrfs_set_path_blocking(path);
6993 if (!PageUptodate(page)) {
6994 if (btrfs_file_extent_compression(leaf, item) !=
6995 BTRFS_COMPRESS_NONE) {
6996 ret = uncompress_inline(path, page, pg_offset,
6997 extent_offset, item);
7004 read_extent_buffer(leaf, map + pg_offset, ptr,
7006 if (pg_offset + copy_size < PAGE_SIZE) {
7007 memset(map + pg_offset + copy_size, 0,
7008 PAGE_SIZE - pg_offset -
7013 flush_dcache_page(page);
7015 set_extent_uptodate(io_tree, em->start,
7016 extent_map_end(em) - 1, NULL, GFP_NOFS);
7021 em->orig_start = start;
7023 em->block_start = EXTENT_MAP_HOLE;
7025 btrfs_release_path(path);
7026 if (em->start > start || extent_map_end(em) <= start) {
7028 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7029 em->start, em->len, start, len);
7035 write_lock(&em_tree->lock);
7036 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7037 write_unlock(&em_tree->lock);
7039 btrfs_free_path(path);
7041 trace_btrfs_get_extent(root, inode, em);
7044 free_extent_map(em);
7045 return ERR_PTR(err);
7047 BUG_ON(!em); /* Error is always set */
7051 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7054 struct extent_map *em;
7055 struct extent_map *hole_em = NULL;
7056 u64 delalloc_start = start;
7062 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7066 * If our em maps to:
7068 * - a pre-alloc extent,
7069 * there might actually be delalloc bytes behind it.
7071 if (em->block_start != EXTENT_MAP_HOLE &&
7072 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7077 /* check to see if we've wrapped (len == -1 or similar) */
7086 /* ok, we didn't find anything, lets look for delalloc */
7087 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7088 end, len, EXTENT_DELALLOC, 1);
7089 delalloc_end = delalloc_start + delalloc_len;
7090 if (delalloc_end < delalloc_start)
7091 delalloc_end = (u64)-1;
7094 * We didn't find anything useful, return the original results from
7097 if (delalloc_start > end || delalloc_end <= start) {
7104 * Adjust the delalloc_start to make sure it doesn't go backwards from
7105 * the start they passed in
7107 delalloc_start = max(start, delalloc_start);
7108 delalloc_len = delalloc_end - delalloc_start;
7110 if (delalloc_len > 0) {
7113 const u64 hole_end = extent_map_end(hole_em);
7115 em = alloc_extent_map();
7124 * When btrfs_get_extent can't find anything it returns one
7127 * Make sure what it found really fits our range, and adjust to
7128 * make sure it is based on the start from the caller
7130 if (hole_end <= start || hole_em->start > end) {
7131 free_extent_map(hole_em);
7134 hole_start = max(hole_em->start, start);
7135 hole_len = hole_end - hole_start;
7138 if (hole_em && delalloc_start > hole_start) {
7140 * Our hole starts before our delalloc, so we have to
7141 * return just the parts of the hole that go until the
7144 em->len = min(hole_len, delalloc_start - hole_start);
7145 em->start = hole_start;
7146 em->orig_start = hole_start;
7148 * Don't adjust block start at all, it is fixed at
7151 em->block_start = hole_em->block_start;
7152 em->block_len = hole_len;
7153 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7154 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7157 * Hole is out of passed range or it starts after
7160 em->start = delalloc_start;
7161 em->len = delalloc_len;
7162 em->orig_start = delalloc_start;
7163 em->block_start = EXTENT_MAP_DELALLOC;
7164 em->block_len = delalloc_len;
7171 free_extent_map(hole_em);
7173 free_extent_map(em);
7174 return ERR_PTR(err);
7179 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7182 const u64 orig_start,
7183 const u64 block_start,
7184 const u64 block_len,
7185 const u64 orig_block_len,
7186 const u64 ram_bytes,
7189 struct extent_map *em = NULL;
7192 if (type != BTRFS_ORDERED_NOCOW) {
7193 em = create_io_em(inode, start, len, orig_start,
7194 block_start, block_len, orig_block_len,
7196 BTRFS_COMPRESS_NONE, /* compress_type */
7201 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7202 len, block_len, type);
7205 free_extent_map(em);
7206 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7207 start + len - 1, 0);
7216 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7219 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7220 struct btrfs_root *root = BTRFS_I(inode)->root;
7221 struct extent_map *em;
7222 struct btrfs_key ins;
7226 alloc_hint = get_extent_allocation_hint(inode, start, len);
7227 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7228 0, alloc_hint, &ins, 1, 1);
7230 return ERR_PTR(ret);
7232 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7233 ins.objectid, ins.offset, ins.offset,
7234 ins.offset, BTRFS_ORDERED_REGULAR);
7235 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7237 btrfs_free_reserved_extent(fs_info, ins.objectid,
7244 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7245 * block must be cow'd
7247 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7248 u64 *orig_start, u64 *orig_block_len,
7251 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7252 struct btrfs_path *path;
7254 struct extent_buffer *leaf;
7255 struct btrfs_root *root = BTRFS_I(inode)->root;
7256 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7257 struct btrfs_file_extent_item *fi;
7258 struct btrfs_key key;
7265 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7267 path = btrfs_alloc_path();
7271 ret = btrfs_lookup_file_extent(NULL, root, path,
7272 btrfs_ino(BTRFS_I(inode)), offset, 0);
7276 slot = path->slots[0];
7279 /* can't find the item, must cow */
7286 leaf = path->nodes[0];
7287 btrfs_item_key_to_cpu(leaf, &key, slot);
7288 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7289 key.type != BTRFS_EXTENT_DATA_KEY) {
7290 /* not our file or wrong item type, must cow */
7294 if (key.offset > offset) {
7295 /* Wrong offset, must cow */
7299 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7300 found_type = btrfs_file_extent_type(leaf, fi);
7301 if (found_type != BTRFS_FILE_EXTENT_REG &&
7302 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7303 /* not a regular extent, must cow */
7307 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7310 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7311 if (extent_end <= offset)
7314 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7315 if (disk_bytenr == 0)
7318 if (btrfs_file_extent_compression(leaf, fi) ||
7319 btrfs_file_extent_encryption(leaf, fi) ||
7320 btrfs_file_extent_other_encoding(leaf, fi))
7324 * Do the same check as in btrfs_cross_ref_exist but without the
7325 * unnecessary search.
7327 if (btrfs_file_extent_generation(leaf, fi) <=
7328 btrfs_root_last_snapshot(&root->root_item))
7331 backref_offset = btrfs_file_extent_offset(leaf, fi);
7334 *orig_start = key.offset - backref_offset;
7335 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7336 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7339 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7342 num_bytes = min(offset + *len, extent_end) - offset;
7343 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7346 range_end = round_up(offset + num_bytes,
7347 root->fs_info->sectorsize) - 1;
7348 ret = test_range_bit(io_tree, offset, range_end,
7349 EXTENT_DELALLOC, 0, NULL);
7356 btrfs_release_path(path);
7359 * look for other files referencing this extent, if we
7360 * find any we must cow
7363 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7364 key.offset - backref_offset, disk_bytenr);
7371 * adjust disk_bytenr and num_bytes to cover just the bytes
7372 * in this extent we are about to write. If there
7373 * are any csums in that range we have to cow in order
7374 * to keep the csums correct
7376 disk_bytenr += backref_offset;
7377 disk_bytenr += offset - key.offset;
7378 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7381 * all of the above have passed, it is safe to overwrite this extent
7387 btrfs_free_path(path);
7391 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7392 struct extent_state **cached_state, int writing)
7394 struct btrfs_ordered_extent *ordered;
7398 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7401 * We're concerned with the entire range that we're going to be
7402 * doing DIO to, so we need to make sure there's no ordered
7403 * extents in this range.
7405 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7406 lockend - lockstart + 1);
7409 * We need to make sure there are no buffered pages in this
7410 * range either, we could have raced between the invalidate in
7411 * generic_file_direct_write and locking the extent. The
7412 * invalidate needs to happen so that reads after a write do not
7416 (!writing || !filemap_range_has_page(inode->i_mapping,
7417 lockstart, lockend)))
7420 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7425 * If we are doing a DIO read and the ordered extent we
7426 * found is for a buffered write, we can not wait for it
7427 * to complete and retry, because if we do so we can
7428 * deadlock with concurrent buffered writes on page
7429 * locks. This happens only if our DIO read covers more
7430 * than one extent map, if at this point has already
7431 * created an ordered extent for a previous extent map
7432 * and locked its range in the inode's io tree, and a
7433 * concurrent write against that previous extent map's
7434 * range and this range started (we unlock the ranges
7435 * in the io tree only when the bios complete and
7436 * buffered writes always lock pages before attempting
7437 * to lock range in the io tree).
7440 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7441 btrfs_start_ordered_extent(inode, ordered, 1);
7444 btrfs_put_ordered_extent(ordered);
7447 * We could trigger writeback for this range (and wait
7448 * for it to complete) and then invalidate the pages for
7449 * this range (through invalidate_inode_pages2_range()),
7450 * but that can lead us to a deadlock with a concurrent
7451 * call to readpages() (a buffered read or a defrag call
7452 * triggered a readahead) on a page lock due to an
7453 * ordered dio extent we created before but did not have
7454 * yet a corresponding bio submitted (whence it can not
7455 * complete), which makes readpages() wait for that
7456 * ordered extent to complete while holding a lock on
7471 /* The callers of this must take lock_extent() */
7472 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7473 u64 orig_start, u64 block_start,
7474 u64 block_len, u64 orig_block_len,
7475 u64 ram_bytes, int compress_type,
7478 struct extent_map_tree *em_tree;
7479 struct extent_map *em;
7480 struct btrfs_root *root = BTRFS_I(inode)->root;
7483 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7484 type == BTRFS_ORDERED_COMPRESSED ||
7485 type == BTRFS_ORDERED_NOCOW ||
7486 type == BTRFS_ORDERED_REGULAR);
7488 em_tree = &BTRFS_I(inode)->extent_tree;
7489 em = alloc_extent_map();
7491 return ERR_PTR(-ENOMEM);
7494 em->orig_start = orig_start;
7496 em->block_len = block_len;
7497 em->block_start = block_start;
7498 em->bdev = root->fs_info->fs_devices->latest_bdev;
7499 em->orig_block_len = orig_block_len;
7500 em->ram_bytes = ram_bytes;
7501 em->generation = -1;
7502 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7503 if (type == BTRFS_ORDERED_PREALLOC) {
7504 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7505 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7506 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7507 em->compress_type = compress_type;
7511 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7512 em->start + em->len - 1, 0);
7513 write_lock(&em_tree->lock);
7514 ret = add_extent_mapping(em_tree, em, 1);
7515 write_unlock(&em_tree->lock);
7517 * The caller has taken lock_extent(), who could race with us
7520 } while (ret == -EEXIST);
7523 free_extent_map(em);
7524 return ERR_PTR(ret);
7527 /* em got 2 refs now, callers needs to do free_extent_map once. */
7532 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7533 struct buffer_head *bh_result,
7534 struct inode *inode,
7537 if (em->block_start == EXTENT_MAP_HOLE ||
7538 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7541 len = min(len, em->len - (start - em->start));
7543 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7545 bh_result->b_size = len;
7546 bh_result->b_bdev = em->bdev;
7547 set_buffer_mapped(bh_result);
7552 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7553 struct buffer_head *bh_result,
7554 struct inode *inode,
7555 struct btrfs_dio_data *dio_data,
7558 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7559 struct extent_map *em = *map;
7563 * We don't allocate a new extent in the following cases
7565 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7567 * 2) The extent is marked as PREALLOC. We're good to go here and can
7568 * just use the extent.
7571 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7572 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7573 em->block_start != EXTENT_MAP_HOLE)) {
7575 u64 block_start, orig_start, orig_block_len, ram_bytes;
7577 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7578 type = BTRFS_ORDERED_PREALLOC;
7580 type = BTRFS_ORDERED_NOCOW;
7581 len = min(len, em->len - (start - em->start));
7582 block_start = em->block_start + (start - em->start);
7584 if (can_nocow_extent(inode, start, &len, &orig_start,
7585 &orig_block_len, &ram_bytes) == 1 &&
7586 btrfs_inc_nocow_writers(fs_info, block_start)) {
7587 struct extent_map *em2;
7589 em2 = btrfs_create_dio_extent(inode, start, len,
7590 orig_start, block_start,
7591 len, orig_block_len,
7593 btrfs_dec_nocow_writers(fs_info, block_start);
7594 if (type == BTRFS_ORDERED_PREALLOC) {
7595 free_extent_map(em);
7599 if (em2 && IS_ERR(em2)) {
7604 * For inode marked NODATACOW or extent marked PREALLOC,
7605 * use the existing or preallocated extent, so does not
7606 * need to adjust btrfs_space_info's bytes_may_use.
7608 btrfs_free_reserved_data_space_noquota(inode, start,
7614 /* this will cow the extent */
7615 len = bh_result->b_size;
7616 free_extent_map(em);
7617 *map = em = btrfs_new_extent_direct(inode, start, len);
7623 len = min(len, em->len - (start - em->start));
7626 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7628 bh_result->b_size = len;
7629 bh_result->b_bdev = em->bdev;
7630 set_buffer_mapped(bh_result);
7632 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7633 set_buffer_new(bh_result);
7636 * Need to update the i_size under the extent lock so buffered
7637 * readers will get the updated i_size when we unlock.
7639 if (!dio_data->overwrite && start + len > i_size_read(inode))
7640 i_size_write(inode, start + len);
7642 WARN_ON(dio_data->reserve < len);
7643 dio_data->reserve -= len;
7644 dio_data->unsubmitted_oe_range_end = start + len;
7645 current->journal_info = dio_data;
7650 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7651 struct buffer_head *bh_result, int create)
7653 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7654 struct extent_map *em;
7655 struct extent_state *cached_state = NULL;
7656 struct btrfs_dio_data *dio_data = NULL;
7657 u64 start = iblock << inode->i_blkbits;
7658 u64 lockstart, lockend;
7659 u64 len = bh_result->b_size;
7660 int unlock_bits = EXTENT_LOCKED;
7664 unlock_bits |= EXTENT_DIRTY;
7666 len = min_t(u64, len, fs_info->sectorsize);
7669 lockend = start + len - 1;
7671 if (current->journal_info) {
7673 * Need to pull our outstanding extents and set journal_info to NULL so
7674 * that anything that needs to check if there's a transaction doesn't get
7677 dio_data = current->journal_info;
7678 current->journal_info = NULL;
7682 * If this errors out it's because we couldn't invalidate pagecache for
7683 * this range and we need to fallback to buffered.
7685 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7691 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7698 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7699 * io. INLINE is special, and we could probably kludge it in here, but
7700 * it's still buffered so for safety lets just fall back to the generic
7703 * For COMPRESSED we _have_ to read the entire extent in so we can
7704 * decompress it, so there will be buffering required no matter what we
7705 * do, so go ahead and fallback to buffered.
7707 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7708 * to buffered IO. Don't blame me, this is the price we pay for using
7711 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7712 em->block_start == EXTENT_MAP_INLINE) {
7713 free_extent_map(em);
7719 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7720 dio_data, start, len);
7724 /* clear and unlock the entire range */
7725 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7726 unlock_bits, 1, 0, &cached_state);
7728 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7730 /* Can be negative only if we read from a hole */
7733 free_extent_map(em);
7737 * We need to unlock only the end area that we aren't using.
7738 * The rest is going to be unlocked by the endio routine.
7740 lockstart = start + bh_result->b_size;
7741 if (lockstart < lockend) {
7742 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7743 lockend, unlock_bits, 1, 0,
7746 free_extent_state(cached_state);
7750 free_extent_map(em);
7755 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7756 unlock_bits, 1, 0, &cached_state);
7759 current->journal_info = dio_data;
7763 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7767 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7770 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7772 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7776 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7781 static int btrfs_check_dio_repairable(struct inode *inode,
7782 struct bio *failed_bio,
7783 struct io_failure_record *failrec,
7786 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7789 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7790 if (num_copies == 1) {
7792 * we only have a single copy of the data, so don't bother with
7793 * all the retry and error correction code that follows. no
7794 * matter what the error is, it is very likely to persist.
7796 btrfs_debug(fs_info,
7797 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7798 num_copies, failrec->this_mirror, failed_mirror);
7802 failrec->failed_mirror = failed_mirror;
7803 failrec->this_mirror++;
7804 if (failrec->this_mirror == failed_mirror)
7805 failrec->this_mirror++;
7807 if (failrec->this_mirror > num_copies) {
7808 btrfs_debug(fs_info,
7809 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7810 num_copies, failrec->this_mirror, failed_mirror);
7817 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7818 struct page *page, unsigned int pgoff,
7819 u64 start, u64 end, int failed_mirror,
7820 bio_end_io_t *repair_endio, void *repair_arg)
7822 struct io_failure_record *failrec;
7823 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7824 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7827 unsigned int read_mode = 0;
7830 blk_status_t status;
7831 struct bio_vec bvec;
7833 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7835 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7837 return errno_to_blk_status(ret);
7839 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7842 free_io_failure(failure_tree, io_tree, failrec);
7843 return BLK_STS_IOERR;
7846 segs = bio_segments(failed_bio);
7847 bio_get_first_bvec(failed_bio, &bvec);
7849 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7850 read_mode |= REQ_FAILFAST_DEV;
7852 isector = start - btrfs_io_bio(failed_bio)->logical;
7853 isector >>= inode->i_sb->s_blocksize_bits;
7854 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7855 pgoff, isector, repair_endio, repair_arg);
7856 bio->bi_opf = REQ_OP_READ | read_mode;
7858 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7859 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7860 read_mode, failrec->this_mirror, failrec->in_validation);
7862 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7864 free_io_failure(failure_tree, io_tree, failrec);
7871 struct btrfs_retry_complete {
7872 struct completion done;
7873 struct inode *inode;
7878 static void btrfs_retry_endio_nocsum(struct bio *bio)
7880 struct btrfs_retry_complete *done = bio->bi_private;
7881 struct inode *inode = done->inode;
7882 struct bio_vec *bvec;
7883 struct extent_io_tree *io_tree, *failure_tree;
7885 struct bvec_iter_all iter_all;
7890 ASSERT(bio->bi_vcnt == 1);
7891 io_tree = &BTRFS_I(inode)->io_tree;
7892 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7893 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7896 ASSERT(!bio_flagged(bio, BIO_CLONED));
7897 bio_for_each_segment_all(bvec, bio, i, iter_all)
7898 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7899 io_tree, done->start, bvec->bv_page,
7900 btrfs_ino(BTRFS_I(inode)), 0);
7902 complete(&done->done);
7906 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7907 struct btrfs_io_bio *io_bio)
7909 struct btrfs_fs_info *fs_info;
7910 struct bio_vec bvec;
7911 struct bvec_iter iter;
7912 struct btrfs_retry_complete done;
7918 blk_status_t err = BLK_STS_OK;
7920 fs_info = BTRFS_I(inode)->root->fs_info;
7921 sectorsize = fs_info->sectorsize;
7923 start = io_bio->logical;
7925 io_bio->bio.bi_iter = io_bio->iter;
7927 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7928 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7929 pgoff = bvec.bv_offset;
7931 next_block_or_try_again:
7934 init_completion(&done.done);
7936 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7937 pgoff, start, start + sectorsize - 1,
7939 btrfs_retry_endio_nocsum, &done);
7945 wait_for_completion_io(&done.done);
7947 if (!done.uptodate) {
7948 /* We might have another mirror, so try again */
7949 goto next_block_or_try_again;
7953 start += sectorsize;
7957 pgoff += sectorsize;
7958 ASSERT(pgoff < PAGE_SIZE);
7959 goto next_block_or_try_again;
7966 static void btrfs_retry_endio(struct bio *bio)
7968 struct btrfs_retry_complete *done = bio->bi_private;
7969 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7970 struct extent_io_tree *io_tree, *failure_tree;
7971 struct inode *inode = done->inode;
7972 struct bio_vec *bvec;
7976 struct bvec_iter_all iter_all;
7983 ASSERT(bio->bi_vcnt == 1);
7984 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7986 io_tree = &BTRFS_I(inode)->io_tree;
7987 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7989 ASSERT(!bio_flagged(bio, BIO_CLONED));
7990 bio_for_each_segment_all(bvec, bio, i, iter_all) {
7991 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7992 bvec->bv_offset, done->start,
7995 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7996 failure_tree, io_tree, done->start,
7998 btrfs_ino(BTRFS_I(inode)),
8004 done->uptodate = uptodate;
8006 complete(&done->done);
8010 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8011 struct btrfs_io_bio *io_bio, blk_status_t err)
8013 struct btrfs_fs_info *fs_info;
8014 struct bio_vec bvec;
8015 struct bvec_iter iter;
8016 struct btrfs_retry_complete done;
8023 bool uptodate = (err == 0);
8025 blk_status_t status;
8027 fs_info = BTRFS_I(inode)->root->fs_info;
8028 sectorsize = fs_info->sectorsize;
8031 start = io_bio->logical;
8033 io_bio->bio.bi_iter = io_bio->iter;
8035 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8036 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8038 pgoff = bvec.bv_offset;
8041 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8042 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8043 bvec.bv_page, pgoff, start, sectorsize);
8050 init_completion(&done.done);
8052 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8053 pgoff, start, start + sectorsize - 1,
8054 io_bio->mirror_num, btrfs_retry_endio,
8061 wait_for_completion_io(&done.done);
8063 if (!done.uptodate) {
8064 /* We might have another mirror, so try again */
8068 offset += sectorsize;
8069 start += sectorsize;
8075 pgoff += sectorsize;
8076 ASSERT(pgoff < PAGE_SIZE);
8084 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8085 struct btrfs_io_bio *io_bio, blk_status_t err)
8087 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8091 return __btrfs_correct_data_nocsum(inode, io_bio);
8095 return __btrfs_subio_endio_read(inode, io_bio, err);
8099 static void btrfs_endio_direct_read(struct bio *bio)
8101 struct btrfs_dio_private *dip = bio->bi_private;
8102 struct inode *inode = dip->inode;
8103 struct bio *dio_bio;
8104 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8105 blk_status_t err = bio->bi_status;
8107 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8108 err = btrfs_subio_endio_read(inode, io_bio, err);
8110 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8111 dip->logical_offset + dip->bytes - 1);
8112 dio_bio = dip->dio_bio;
8116 dio_bio->bi_status = err;
8117 dio_end_io(dio_bio);
8118 btrfs_io_bio_free_csum(io_bio);
8122 static void __endio_write_update_ordered(struct inode *inode,
8123 const u64 offset, const u64 bytes,
8124 const bool uptodate)
8126 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8127 struct btrfs_ordered_extent *ordered = NULL;
8128 struct btrfs_workqueue *wq;
8129 btrfs_work_func_t func;
8130 u64 ordered_offset = offset;
8131 u64 ordered_bytes = bytes;
8134 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8135 wq = fs_info->endio_freespace_worker;
8136 func = btrfs_freespace_write_helper;
8138 wq = fs_info->endio_write_workers;
8139 func = btrfs_endio_write_helper;
8142 while (ordered_offset < offset + bytes) {
8143 last_offset = ordered_offset;
8144 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8148 btrfs_init_work(&ordered->work, func,
8151 btrfs_queue_work(wq, &ordered->work);
8154 * If btrfs_dec_test_ordered_pending does not find any ordered
8155 * extent in the range, we can exit.
8157 if (ordered_offset == last_offset)
8160 * Our bio might span multiple ordered extents. In this case
8161 * we keep going until we have accounted the whole dio.
8163 if (ordered_offset < offset + bytes) {
8164 ordered_bytes = offset + bytes - ordered_offset;
8170 static void btrfs_endio_direct_write(struct bio *bio)
8172 struct btrfs_dio_private *dip = bio->bi_private;
8173 struct bio *dio_bio = dip->dio_bio;
8175 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8176 dip->bytes, !bio->bi_status);
8180 dio_bio->bi_status = bio->bi_status;
8181 dio_end_io(dio_bio);
8185 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8186 struct bio *bio, u64 offset)
8188 struct inode *inode = private_data;
8190 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8191 BUG_ON(ret); /* -ENOMEM */
8195 static void btrfs_end_dio_bio(struct bio *bio)
8197 struct btrfs_dio_private *dip = bio->bi_private;
8198 blk_status_t err = bio->bi_status;
8201 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8202 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8203 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8205 (unsigned long long)bio->bi_iter.bi_sector,
8206 bio->bi_iter.bi_size, err);
8208 if (dip->subio_endio)
8209 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8213 * We want to perceive the errors flag being set before
8214 * decrementing the reference count. We don't need a barrier
8215 * since atomic operations with a return value are fully
8216 * ordered as per atomic_t.txt
8221 /* if there are more bios still pending for this dio, just exit */
8222 if (!atomic_dec_and_test(&dip->pending_bios))
8226 bio_io_error(dip->orig_bio);
8228 dip->dio_bio->bi_status = BLK_STS_OK;
8229 bio_endio(dip->orig_bio);
8235 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8236 struct btrfs_dio_private *dip,
8240 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8241 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8245 * We load all the csum data we need when we submit
8246 * the first bio to reduce the csum tree search and
8249 if (dip->logical_offset == file_offset) {
8250 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8256 if (bio == dip->orig_bio)
8259 file_offset -= dip->logical_offset;
8260 file_offset >>= inode->i_sb->s_blocksize_bits;
8261 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8266 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8267 struct inode *inode, u64 file_offset, int async_submit)
8269 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8270 struct btrfs_dio_private *dip = bio->bi_private;
8271 bool write = bio_op(bio) == REQ_OP_WRITE;
8274 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8276 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8279 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8284 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8287 if (write && async_submit) {
8288 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8290 btrfs_submit_bio_start_direct_io);
8294 * If we aren't doing async submit, calculate the csum of the
8297 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8301 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8307 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8312 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8314 struct inode *inode = dip->inode;
8315 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8317 struct bio *orig_bio = dip->orig_bio;
8318 u64 start_sector = orig_bio->bi_iter.bi_sector;
8319 u64 file_offset = dip->logical_offset;
8321 int async_submit = 0;
8323 int clone_offset = 0;
8326 blk_status_t status;
8328 map_length = orig_bio->bi_iter.bi_size;
8329 submit_len = map_length;
8330 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8331 &map_length, NULL, 0);
8335 if (map_length >= submit_len) {
8337 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8341 /* async crcs make it difficult to collect full stripe writes. */
8342 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8348 ASSERT(map_length <= INT_MAX);
8349 atomic_inc(&dip->pending_bios);
8351 clone_len = min_t(int, submit_len, map_length);
8354 * This will never fail as it's passing GPF_NOFS and
8355 * the allocation is backed by btrfs_bioset.
8357 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8359 bio->bi_private = dip;
8360 bio->bi_end_io = btrfs_end_dio_bio;
8361 btrfs_io_bio(bio)->logical = file_offset;
8363 ASSERT(submit_len >= clone_len);
8364 submit_len -= clone_len;
8365 if (submit_len == 0)
8369 * Increase the count before we submit the bio so we know
8370 * the end IO handler won't happen before we increase the
8371 * count. Otherwise, the dip might get freed before we're
8372 * done setting it up.
8374 atomic_inc(&dip->pending_bios);
8376 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8380 atomic_dec(&dip->pending_bios);
8384 clone_offset += clone_len;
8385 start_sector += clone_len >> 9;
8386 file_offset += clone_len;
8388 map_length = submit_len;
8389 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8390 start_sector << 9, &map_length, NULL, 0);
8393 } while (submit_len > 0);
8396 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8404 * Before atomic variable goto zero, we must make sure dip->errors is
8405 * perceived to be set. This ordering is ensured by the fact that an
8406 * atomic operations with a return value are fully ordered as per
8409 if (atomic_dec_and_test(&dip->pending_bios))
8410 bio_io_error(dip->orig_bio);
8412 /* bio_end_io() will handle error, so we needn't return it */
8416 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8419 struct btrfs_dio_private *dip = NULL;
8420 struct bio *bio = NULL;
8421 struct btrfs_io_bio *io_bio;
8422 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8425 bio = btrfs_bio_clone(dio_bio);
8427 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8433 dip->private = dio_bio->bi_private;
8435 dip->logical_offset = file_offset;
8436 dip->bytes = dio_bio->bi_iter.bi_size;
8437 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8438 bio->bi_private = dip;
8439 dip->orig_bio = bio;
8440 dip->dio_bio = dio_bio;
8441 atomic_set(&dip->pending_bios, 0);
8442 io_bio = btrfs_io_bio(bio);
8443 io_bio->logical = file_offset;
8446 bio->bi_end_io = btrfs_endio_direct_write;
8448 bio->bi_end_io = btrfs_endio_direct_read;
8449 dip->subio_endio = btrfs_subio_endio_read;
8453 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8454 * even if we fail to submit a bio, because in such case we do the
8455 * corresponding error handling below and it must not be done a second
8456 * time by btrfs_direct_IO().
8459 struct btrfs_dio_data *dio_data = current->journal_info;
8461 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8463 dio_data->unsubmitted_oe_range_start =
8464 dio_data->unsubmitted_oe_range_end;
8467 ret = btrfs_submit_direct_hook(dip);
8471 btrfs_io_bio_free_csum(io_bio);
8475 * If we arrived here it means either we failed to submit the dip
8476 * or we either failed to clone the dio_bio or failed to allocate the
8477 * dip. If we cloned the dio_bio and allocated the dip, we can just
8478 * call bio_endio against our io_bio so that we get proper resource
8479 * cleanup if we fail to submit the dip, otherwise, we must do the
8480 * same as btrfs_endio_direct_[write|read] because we can't call these
8481 * callbacks - they require an allocated dip and a clone of dio_bio.
8486 * The end io callbacks free our dip, do the final put on bio
8487 * and all the cleanup and final put for dio_bio (through
8494 __endio_write_update_ordered(inode,
8496 dio_bio->bi_iter.bi_size,
8499 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8500 file_offset + dio_bio->bi_iter.bi_size - 1);
8502 dio_bio->bi_status = BLK_STS_IOERR;
8504 * Releases and cleans up our dio_bio, no need to bio_put()
8505 * nor bio_endio()/bio_io_error() against dio_bio.
8507 dio_end_io(dio_bio);
8514 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8515 const struct iov_iter *iter, loff_t offset)
8519 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8520 ssize_t retval = -EINVAL;
8522 if (offset & blocksize_mask)
8525 if (iov_iter_alignment(iter) & blocksize_mask)
8528 /* If this is a write we don't need to check anymore */
8529 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8532 * Check to make sure we don't have duplicate iov_base's in this
8533 * iovec, if so return EINVAL, otherwise we'll get csum errors
8534 * when reading back.
8536 for (seg = 0; seg < iter->nr_segs; seg++) {
8537 for (i = seg + 1; i < iter->nr_segs; i++) {
8538 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8547 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8549 struct file *file = iocb->ki_filp;
8550 struct inode *inode = file->f_mapping->host;
8551 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8552 struct btrfs_dio_data dio_data = { 0 };
8553 struct extent_changeset *data_reserved = NULL;
8554 loff_t offset = iocb->ki_pos;
8558 bool relock = false;
8561 if (check_direct_IO(fs_info, iter, offset))
8564 inode_dio_begin(inode);
8567 * The generic stuff only does filemap_write_and_wait_range, which
8568 * isn't enough if we've written compressed pages to this area, so
8569 * we need to flush the dirty pages again to make absolutely sure
8570 * that any outstanding dirty pages are on disk.
8572 count = iov_iter_count(iter);
8573 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8574 &BTRFS_I(inode)->runtime_flags))
8575 filemap_fdatawrite_range(inode->i_mapping, offset,
8576 offset + count - 1);
8578 if (iov_iter_rw(iter) == WRITE) {
8580 * If the write DIO is beyond the EOF, we need update
8581 * the isize, but it is protected by i_mutex. So we can
8582 * not unlock the i_mutex at this case.
8584 if (offset + count <= inode->i_size) {
8585 dio_data.overwrite = 1;
8586 inode_unlock(inode);
8588 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8592 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8598 * We need to know how many extents we reserved so that we can
8599 * do the accounting properly if we go over the number we
8600 * originally calculated. Abuse current->journal_info for this.
8602 dio_data.reserve = round_up(count,
8603 fs_info->sectorsize);
8604 dio_data.unsubmitted_oe_range_start = (u64)offset;
8605 dio_data.unsubmitted_oe_range_end = (u64)offset;
8606 current->journal_info = &dio_data;
8607 down_read(&BTRFS_I(inode)->dio_sem);
8608 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8609 &BTRFS_I(inode)->runtime_flags)) {
8610 inode_dio_end(inode);
8611 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8615 ret = __blockdev_direct_IO(iocb, inode,
8616 fs_info->fs_devices->latest_bdev,
8617 iter, btrfs_get_blocks_direct, NULL,
8618 btrfs_submit_direct, flags);
8619 if (iov_iter_rw(iter) == WRITE) {
8620 up_read(&BTRFS_I(inode)->dio_sem);
8621 current->journal_info = NULL;
8622 if (ret < 0 && ret != -EIOCBQUEUED) {
8623 if (dio_data.reserve)
8624 btrfs_delalloc_release_space(inode, data_reserved,
8625 offset, dio_data.reserve, true);
8627 * On error we might have left some ordered extents
8628 * without submitting corresponding bios for them, so
8629 * cleanup them up to avoid other tasks getting them
8630 * and waiting for them to complete forever.
8632 if (dio_data.unsubmitted_oe_range_start <
8633 dio_data.unsubmitted_oe_range_end)
8634 __endio_write_update_ordered(inode,
8635 dio_data.unsubmitted_oe_range_start,
8636 dio_data.unsubmitted_oe_range_end -
8637 dio_data.unsubmitted_oe_range_start,
8639 } else if (ret >= 0 && (size_t)ret < count)
8640 btrfs_delalloc_release_space(inode, data_reserved,
8641 offset, count - (size_t)ret, true);
8642 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8646 inode_dio_end(inode);
8650 extent_changeset_free(data_reserved);
8654 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8656 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8657 __u64 start, __u64 len)
8661 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8665 return extent_fiemap(inode, fieinfo, start, len);
8668 int btrfs_readpage(struct file *file, struct page *page)
8670 struct extent_io_tree *tree;
8671 tree = &BTRFS_I(page->mapping->host)->io_tree;
8672 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8675 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8677 struct inode *inode = page->mapping->host;
8680 if (current->flags & PF_MEMALLOC) {
8681 redirty_page_for_writepage(wbc, page);
8687 * If we are under memory pressure we will call this directly from the
8688 * VM, we need to make sure we have the inode referenced for the ordered
8689 * extent. If not just return like we didn't do anything.
8691 if (!igrab(inode)) {
8692 redirty_page_for_writepage(wbc, page);
8693 return AOP_WRITEPAGE_ACTIVATE;
8695 ret = extent_write_full_page(page, wbc);
8696 btrfs_add_delayed_iput(inode);
8700 static int btrfs_writepages(struct address_space *mapping,
8701 struct writeback_control *wbc)
8703 return extent_writepages(mapping, wbc);
8707 btrfs_readpages(struct file *file, struct address_space *mapping,
8708 struct list_head *pages, unsigned nr_pages)
8710 return extent_readpages(mapping, pages, nr_pages);
8713 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8715 int ret = try_release_extent_mapping(page, gfp_flags);
8717 ClearPagePrivate(page);
8718 set_page_private(page, 0);
8724 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8726 if (PageWriteback(page) || PageDirty(page))
8728 return __btrfs_releasepage(page, gfp_flags);
8731 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8732 unsigned int length)
8734 struct inode *inode = page->mapping->host;
8735 struct extent_io_tree *tree;
8736 struct btrfs_ordered_extent *ordered;
8737 struct extent_state *cached_state = NULL;
8738 u64 page_start = page_offset(page);
8739 u64 page_end = page_start + PAGE_SIZE - 1;
8742 int inode_evicting = inode->i_state & I_FREEING;
8745 * we have the page locked, so new writeback can't start,
8746 * and the dirty bit won't be cleared while we are here.
8748 * Wait for IO on this page so that we can safely clear
8749 * the PagePrivate2 bit and do ordered accounting
8751 wait_on_page_writeback(page);
8753 tree = &BTRFS_I(inode)->io_tree;
8755 btrfs_releasepage(page, GFP_NOFS);
8759 if (!inode_evicting)
8760 lock_extent_bits(tree, page_start, page_end, &cached_state);
8763 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8764 page_end - start + 1);
8766 end = min(page_end, ordered->file_offset + ordered->len - 1);
8768 * IO on this page will never be started, so we need
8769 * to account for any ordered extents now
8771 if (!inode_evicting)
8772 clear_extent_bit(tree, start, end,
8773 EXTENT_DIRTY | EXTENT_DELALLOC |
8774 EXTENT_DELALLOC_NEW |
8775 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8776 EXTENT_DEFRAG, 1, 0, &cached_state);
8778 * whoever cleared the private bit is responsible
8779 * for the finish_ordered_io
8781 if (TestClearPagePrivate2(page)) {
8782 struct btrfs_ordered_inode_tree *tree;
8785 tree = &BTRFS_I(inode)->ordered_tree;
8787 spin_lock_irq(&tree->lock);
8788 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8789 new_len = start - ordered->file_offset;
8790 if (new_len < ordered->truncated_len)
8791 ordered->truncated_len = new_len;
8792 spin_unlock_irq(&tree->lock);
8794 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8796 end - start + 1, 1))
8797 btrfs_finish_ordered_io(ordered);
8799 btrfs_put_ordered_extent(ordered);
8800 if (!inode_evicting) {
8801 cached_state = NULL;
8802 lock_extent_bits(tree, start, end,
8807 if (start < page_end)
8812 * Qgroup reserved space handler
8813 * Page here will be either
8814 * 1) Already written to disk
8815 * In this case, its reserved space is released from data rsv map
8816 * and will be freed by delayed_ref handler finally.
8817 * So even we call qgroup_free_data(), it won't decrease reserved
8819 * 2) Not written to disk
8820 * This means the reserved space should be freed here. However,
8821 * if a truncate invalidates the page (by clearing PageDirty)
8822 * and the page is accounted for while allocating extent
8823 * in btrfs_check_data_free_space() we let delayed_ref to
8824 * free the entire extent.
8826 if (PageDirty(page))
8827 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8828 if (!inode_evicting) {
8829 clear_extent_bit(tree, page_start, page_end,
8830 EXTENT_LOCKED | EXTENT_DIRTY |
8831 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8832 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8835 __btrfs_releasepage(page, GFP_NOFS);
8838 ClearPageChecked(page);
8839 if (PagePrivate(page)) {
8840 ClearPagePrivate(page);
8841 set_page_private(page, 0);
8847 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8848 * called from a page fault handler when a page is first dirtied. Hence we must
8849 * be careful to check for EOF conditions here. We set the page up correctly
8850 * for a written page which means we get ENOSPC checking when writing into
8851 * holes and correct delalloc and unwritten extent mapping on filesystems that
8852 * support these features.
8854 * We are not allowed to take the i_mutex here so we have to play games to
8855 * protect against truncate races as the page could now be beyond EOF. Because
8856 * truncate_setsize() writes the inode size before removing pages, once we have
8857 * the page lock we can determine safely if the page is beyond EOF. If it is not
8858 * beyond EOF, then the page is guaranteed safe against truncation until we
8861 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8863 struct page *page = vmf->page;
8864 struct inode *inode = file_inode(vmf->vma->vm_file);
8865 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8866 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8867 struct btrfs_ordered_extent *ordered;
8868 struct extent_state *cached_state = NULL;
8869 struct extent_changeset *data_reserved = NULL;
8871 unsigned long zero_start;
8881 reserved_space = PAGE_SIZE;
8883 sb_start_pagefault(inode->i_sb);
8884 page_start = page_offset(page);
8885 page_end = page_start + PAGE_SIZE - 1;
8889 * Reserving delalloc space after obtaining the page lock can lead to
8890 * deadlock. For example, if a dirty page is locked by this function
8891 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8892 * dirty page write out, then the btrfs_writepage() function could
8893 * end up waiting indefinitely to get a lock on the page currently
8894 * being processed by btrfs_page_mkwrite() function.
8896 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8899 ret2 = file_update_time(vmf->vma->vm_file);
8903 ret = vmf_error(ret2);
8909 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8912 size = i_size_read(inode);
8914 if ((page->mapping != inode->i_mapping) ||
8915 (page_start >= size)) {
8916 /* page got truncated out from underneath us */
8919 wait_on_page_writeback(page);
8921 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8922 set_page_extent_mapped(page);
8925 * we can't set the delalloc bits if there are pending ordered
8926 * extents. Drop our locks and wait for them to finish
8928 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8931 unlock_extent_cached(io_tree, page_start, page_end,
8934 btrfs_start_ordered_extent(inode, ordered, 1);
8935 btrfs_put_ordered_extent(ordered);
8939 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8940 reserved_space = round_up(size - page_start,
8941 fs_info->sectorsize);
8942 if (reserved_space < PAGE_SIZE) {
8943 end = page_start + reserved_space - 1;
8944 btrfs_delalloc_release_space(inode, data_reserved,
8945 page_start, PAGE_SIZE - reserved_space,
8951 * page_mkwrite gets called when the page is firstly dirtied after it's
8952 * faulted in, but write(2) could also dirty a page and set delalloc
8953 * bits, thus in this case for space account reason, we still need to
8954 * clear any delalloc bits within this page range since we have to
8955 * reserve data&meta space before lock_page() (see above comments).
8957 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8958 EXTENT_DIRTY | EXTENT_DELALLOC |
8959 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8960 0, 0, &cached_state);
8962 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8965 unlock_extent_cached(io_tree, page_start, page_end,
8967 ret = VM_FAULT_SIGBUS;
8972 /* page is wholly or partially inside EOF */
8973 if (page_start + PAGE_SIZE > size)
8974 zero_start = offset_in_page(size);
8976 zero_start = PAGE_SIZE;
8978 if (zero_start != PAGE_SIZE) {
8980 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8981 flush_dcache_page(page);
8984 ClearPageChecked(page);
8985 set_page_dirty(page);
8986 SetPageUptodate(page);
8988 BTRFS_I(inode)->last_trans = fs_info->generation;
8989 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8990 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8992 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8995 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8996 sb_end_pagefault(inode->i_sb);
8997 extent_changeset_free(data_reserved);
8998 return VM_FAULT_LOCKED;
9004 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
9005 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9006 reserved_space, (ret != 0));
9008 sb_end_pagefault(inode->i_sb);
9009 extent_changeset_free(data_reserved);
9013 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9015 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9016 struct btrfs_root *root = BTRFS_I(inode)->root;
9017 struct btrfs_block_rsv *rsv;
9019 struct btrfs_trans_handle *trans;
9020 u64 mask = fs_info->sectorsize - 1;
9021 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9023 if (!skip_writeback) {
9024 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9031 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9032 * things going on here:
9034 * 1) We need to reserve space to update our inode.
9036 * 2) We need to have something to cache all the space that is going to
9037 * be free'd up by the truncate operation, but also have some slack
9038 * space reserved in case it uses space during the truncate (thank you
9039 * very much snapshotting).
9041 * And we need these to be separate. The fact is we can use a lot of
9042 * space doing the truncate, and we have no earthly idea how much space
9043 * we will use, so we need the truncate reservation to be separate so it
9044 * doesn't end up using space reserved for updating the inode. We also
9045 * need to be able to stop the transaction and start a new one, which
9046 * means we need to be able to update the inode several times, and we
9047 * have no idea of knowing how many times that will be, so we can't just
9048 * reserve 1 item for the entirety of the operation, so that has to be
9049 * done separately as well.
9051 * So that leaves us with
9053 * 1) rsv - for the truncate reservation, which we will steal from the
9054 * transaction reservation.
9055 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9056 * updating the inode.
9058 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9061 rsv->size = min_size;
9065 * 1 for the truncate slack space
9066 * 1 for updating the inode.
9068 trans = btrfs_start_transaction(root, 2);
9069 if (IS_ERR(trans)) {
9070 ret = PTR_ERR(trans);
9074 /* Migrate the slack space for the truncate to our reserve */
9075 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9080 * So if we truncate and then write and fsync we normally would just
9081 * write the extents that changed, which is a problem if we need to
9082 * first truncate that entire inode. So set this flag so we write out
9083 * all of the extents in the inode to the sync log so we're completely
9086 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9087 trans->block_rsv = rsv;
9090 ret = btrfs_truncate_inode_items(trans, root, inode,
9092 BTRFS_EXTENT_DATA_KEY);
9093 trans->block_rsv = &fs_info->trans_block_rsv;
9094 if (ret != -ENOSPC && ret != -EAGAIN)
9097 ret = btrfs_update_inode(trans, root, inode);
9101 btrfs_end_transaction(trans);
9102 btrfs_btree_balance_dirty(fs_info);
9104 trans = btrfs_start_transaction(root, 2);
9105 if (IS_ERR(trans)) {
9106 ret = PTR_ERR(trans);
9111 btrfs_block_rsv_release(fs_info, rsv, -1);
9112 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9113 rsv, min_size, false);
9114 BUG_ON(ret); /* shouldn't happen */
9115 trans->block_rsv = rsv;
9119 * We can't call btrfs_truncate_block inside a trans handle as we could
9120 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9121 * we've truncated everything except the last little bit, and can do
9122 * btrfs_truncate_block and then update the disk_i_size.
9124 if (ret == NEED_TRUNCATE_BLOCK) {
9125 btrfs_end_transaction(trans);
9126 btrfs_btree_balance_dirty(fs_info);
9128 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9131 trans = btrfs_start_transaction(root, 1);
9132 if (IS_ERR(trans)) {
9133 ret = PTR_ERR(trans);
9136 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9142 trans->block_rsv = &fs_info->trans_block_rsv;
9143 ret2 = btrfs_update_inode(trans, root, inode);
9147 ret2 = btrfs_end_transaction(trans);
9150 btrfs_btree_balance_dirty(fs_info);
9153 btrfs_free_block_rsv(fs_info, rsv);
9159 * create a new subvolume directory/inode (helper for the ioctl).
9161 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9162 struct btrfs_root *new_root,
9163 struct btrfs_root *parent_root,
9166 struct inode *inode;
9170 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9171 new_dirid, new_dirid,
9172 S_IFDIR | (~current_umask() & S_IRWXUGO),
9175 return PTR_ERR(inode);
9176 inode->i_op = &btrfs_dir_inode_operations;
9177 inode->i_fop = &btrfs_dir_file_operations;
9179 set_nlink(inode, 1);
9180 btrfs_i_size_write(BTRFS_I(inode), 0);
9181 unlock_new_inode(inode);
9183 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9185 btrfs_err(new_root->fs_info,
9186 "error inheriting subvolume %llu properties: %d",
9187 new_root->root_key.objectid, err);
9189 err = btrfs_update_inode(trans, new_root, inode);
9195 struct inode *btrfs_alloc_inode(struct super_block *sb)
9197 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9198 struct btrfs_inode *ei;
9199 struct inode *inode;
9201 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9208 ei->last_sub_trans = 0;
9209 ei->logged_trans = 0;
9210 ei->delalloc_bytes = 0;
9211 ei->new_delalloc_bytes = 0;
9212 ei->defrag_bytes = 0;
9213 ei->disk_i_size = 0;
9216 ei->index_cnt = (u64)-1;
9218 ei->last_unlink_trans = 0;
9219 ei->last_log_commit = 0;
9221 spin_lock_init(&ei->lock);
9222 ei->outstanding_extents = 0;
9223 if (sb->s_magic != BTRFS_TEST_MAGIC)
9224 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9225 BTRFS_BLOCK_RSV_DELALLOC);
9226 ei->runtime_flags = 0;
9227 ei->prop_compress = BTRFS_COMPRESS_NONE;
9228 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9230 ei->delayed_node = NULL;
9232 ei->i_otime.tv_sec = 0;
9233 ei->i_otime.tv_nsec = 0;
9235 inode = &ei->vfs_inode;
9236 extent_map_tree_init(&ei->extent_tree);
9237 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9238 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9239 IO_TREE_INODE_IO_FAILURE, inode);
9240 ei->io_tree.track_uptodate = true;
9241 ei->io_failure_tree.track_uptodate = true;
9242 atomic_set(&ei->sync_writers, 0);
9243 mutex_init(&ei->log_mutex);
9244 mutex_init(&ei->delalloc_mutex);
9245 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9246 INIT_LIST_HEAD(&ei->delalloc_inodes);
9247 INIT_LIST_HEAD(&ei->delayed_iput);
9248 RB_CLEAR_NODE(&ei->rb_node);
9249 init_rwsem(&ei->dio_sem);
9254 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9255 void btrfs_test_destroy_inode(struct inode *inode)
9257 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9258 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9262 static void btrfs_i_callback(struct rcu_head *head)
9264 struct inode *inode = container_of(head, struct inode, i_rcu);
9265 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9268 void btrfs_destroy_inode(struct inode *inode)
9270 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9271 struct btrfs_ordered_extent *ordered;
9272 struct btrfs_root *root = BTRFS_I(inode)->root;
9274 WARN_ON(!hlist_empty(&inode->i_dentry));
9275 WARN_ON(inode->i_data.nrpages);
9276 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9277 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9278 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9279 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9280 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9281 WARN_ON(BTRFS_I(inode)->csum_bytes);
9282 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9285 * This can happen where we create an inode, but somebody else also
9286 * created the same inode and we need to destroy the one we already
9293 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9298 "found ordered extent %llu %llu on inode cleanup",
9299 ordered->file_offset, ordered->len);
9300 btrfs_remove_ordered_extent(inode, ordered);
9301 btrfs_put_ordered_extent(ordered);
9302 btrfs_put_ordered_extent(ordered);
9305 btrfs_qgroup_check_reserved_leak(inode);
9306 inode_tree_del(inode);
9307 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9309 call_rcu(&inode->i_rcu, btrfs_i_callback);
9312 int btrfs_drop_inode(struct inode *inode)
9314 struct btrfs_root *root = BTRFS_I(inode)->root;
9319 /* the snap/subvol tree is on deleting */
9320 if (btrfs_root_refs(&root->root_item) == 0)
9323 return generic_drop_inode(inode);
9326 static void init_once(void *foo)
9328 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9330 inode_init_once(&ei->vfs_inode);
9333 void __cold btrfs_destroy_cachep(void)
9336 * Make sure all delayed rcu free inodes are flushed before we
9340 kmem_cache_destroy(btrfs_inode_cachep);
9341 kmem_cache_destroy(btrfs_trans_handle_cachep);
9342 kmem_cache_destroy(btrfs_path_cachep);
9343 kmem_cache_destroy(btrfs_free_space_cachep);
9346 int __init btrfs_init_cachep(void)
9348 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9349 sizeof(struct btrfs_inode), 0,
9350 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9352 if (!btrfs_inode_cachep)
9355 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9356 sizeof(struct btrfs_trans_handle), 0,
9357 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9358 if (!btrfs_trans_handle_cachep)
9361 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9362 sizeof(struct btrfs_path), 0,
9363 SLAB_MEM_SPREAD, NULL);
9364 if (!btrfs_path_cachep)
9367 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9368 sizeof(struct btrfs_free_space), 0,
9369 SLAB_MEM_SPREAD, NULL);
9370 if (!btrfs_free_space_cachep)
9375 btrfs_destroy_cachep();
9379 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9380 u32 request_mask, unsigned int flags)
9383 struct inode *inode = d_inode(path->dentry);
9384 u32 blocksize = inode->i_sb->s_blocksize;
9385 u32 bi_flags = BTRFS_I(inode)->flags;
9387 stat->result_mask |= STATX_BTIME;
9388 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9389 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9390 if (bi_flags & BTRFS_INODE_APPEND)
9391 stat->attributes |= STATX_ATTR_APPEND;
9392 if (bi_flags & BTRFS_INODE_COMPRESS)
9393 stat->attributes |= STATX_ATTR_COMPRESSED;
9394 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9395 stat->attributes |= STATX_ATTR_IMMUTABLE;
9396 if (bi_flags & BTRFS_INODE_NODUMP)
9397 stat->attributes |= STATX_ATTR_NODUMP;
9399 stat->attributes_mask |= (STATX_ATTR_APPEND |
9400 STATX_ATTR_COMPRESSED |
9401 STATX_ATTR_IMMUTABLE |
9404 generic_fillattr(inode, stat);
9405 stat->dev = BTRFS_I(inode)->root->anon_dev;
9407 spin_lock(&BTRFS_I(inode)->lock);
9408 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9409 spin_unlock(&BTRFS_I(inode)->lock);
9410 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9411 ALIGN(delalloc_bytes, blocksize)) >> 9;
9415 static int btrfs_rename_exchange(struct inode *old_dir,
9416 struct dentry *old_dentry,
9417 struct inode *new_dir,
9418 struct dentry *new_dentry)
9420 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9421 struct btrfs_trans_handle *trans;
9422 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9423 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9424 struct inode *new_inode = new_dentry->d_inode;
9425 struct inode *old_inode = old_dentry->d_inode;
9426 struct timespec64 ctime = current_time(old_inode);
9427 struct dentry *parent;
9428 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9429 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9434 bool root_log_pinned = false;
9435 bool dest_log_pinned = false;
9436 struct btrfs_log_ctx ctx_root;
9437 struct btrfs_log_ctx ctx_dest;
9438 bool sync_log_root = false;
9439 bool sync_log_dest = false;
9440 bool commit_transaction = false;
9442 /* we only allow rename subvolume link between subvolumes */
9443 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9446 btrfs_init_log_ctx(&ctx_root, old_inode);
9447 btrfs_init_log_ctx(&ctx_dest, new_inode);
9449 /* close the race window with snapshot create/destroy ioctl */
9450 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9451 down_read(&fs_info->subvol_sem);
9452 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9453 down_read(&fs_info->subvol_sem);
9456 * We want to reserve the absolute worst case amount of items. So if
9457 * both inodes are subvols and we need to unlink them then that would
9458 * require 4 item modifications, but if they are both normal inodes it
9459 * would require 5 item modifications, so we'll assume their normal
9460 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9461 * should cover the worst case number of items we'll modify.
9463 trans = btrfs_start_transaction(root, 12);
9464 if (IS_ERR(trans)) {
9465 ret = PTR_ERR(trans);
9470 * We need to find a free sequence number both in the source and
9471 * in the destination directory for the exchange.
9473 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9476 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9480 BTRFS_I(old_inode)->dir_index = 0ULL;
9481 BTRFS_I(new_inode)->dir_index = 0ULL;
9483 /* Reference for the source. */
9484 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9485 /* force full log commit if subvolume involved. */
9486 btrfs_set_log_full_commit(trans);
9488 btrfs_pin_log_trans(root);
9489 root_log_pinned = true;
9490 ret = btrfs_insert_inode_ref(trans, dest,
9491 new_dentry->d_name.name,
9492 new_dentry->d_name.len,
9494 btrfs_ino(BTRFS_I(new_dir)),
9500 /* And now for the dest. */
9501 if (new_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(dest);
9506 dest_log_pinned = true;
9507 ret = btrfs_insert_inode_ref(trans, root,
9508 old_dentry->d_name.name,
9509 old_dentry->d_name.len,
9511 btrfs_ino(BTRFS_I(old_dir)),
9517 /* Update inode version and ctime/mtime. */
9518 inode_inc_iversion(old_dir);
9519 inode_inc_iversion(new_dir);
9520 inode_inc_iversion(old_inode);
9521 inode_inc_iversion(new_inode);
9522 old_dir->i_ctime = old_dir->i_mtime = ctime;
9523 new_dir->i_ctime = new_dir->i_mtime = ctime;
9524 old_inode->i_ctime = ctime;
9525 new_inode->i_ctime = ctime;
9527 if (old_dentry->d_parent != new_dentry->d_parent) {
9528 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9529 BTRFS_I(old_inode), 1);
9530 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9531 BTRFS_I(new_inode), 1);
9534 /* src is a subvolume */
9535 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9536 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9537 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9538 old_dentry->d_name.name,
9539 old_dentry->d_name.len);
9540 } else { /* src is an inode */
9541 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9542 BTRFS_I(old_dentry->d_inode),
9543 old_dentry->d_name.name,
9544 old_dentry->d_name.len);
9546 ret = btrfs_update_inode(trans, root, old_inode);
9549 btrfs_abort_transaction(trans, ret);
9553 /* dest is a subvolume */
9554 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9555 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9556 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9557 new_dentry->d_name.name,
9558 new_dentry->d_name.len);
9559 } else { /* dest is an inode */
9560 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9561 BTRFS_I(new_dentry->d_inode),
9562 new_dentry->d_name.name,
9563 new_dentry->d_name.len);
9565 ret = btrfs_update_inode(trans, dest, new_inode);
9568 btrfs_abort_transaction(trans, ret);
9572 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9573 new_dentry->d_name.name,
9574 new_dentry->d_name.len, 0, old_idx);
9576 btrfs_abort_transaction(trans, ret);
9580 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9581 old_dentry->d_name.name,
9582 old_dentry->d_name.len, 0, new_idx);
9584 btrfs_abort_transaction(trans, ret);
9588 if (old_inode->i_nlink == 1)
9589 BTRFS_I(old_inode)->dir_index = old_idx;
9590 if (new_inode->i_nlink == 1)
9591 BTRFS_I(new_inode)->dir_index = new_idx;
9593 if (root_log_pinned) {
9594 parent = new_dentry->d_parent;
9595 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9596 BTRFS_I(old_dir), parent,
9598 if (ret == BTRFS_NEED_LOG_SYNC)
9599 sync_log_root = true;
9600 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9601 commit_transaction = true;
9603 btrfs_end_log_trans(root);
9604 root_log_pinned = false;
9606 if (dest_log_pinned) {
9607 if (!commit_transaction) {
9608 parent = old_dentry->d_parent;
9609 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9610 BTRFS_I(new_dir), parent,
9612 if (ret == BTRFS_NEED_LOG_SYNC)
9613 sync_log_dest = true;
9614 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9615 commit_transaction = true;
9618 btrfs_end_log_trans(dest);
9619 dest_log_pinned = false;
9623 * If we have pinned a log and an error happened, we unpin tasks
9624 * trying to sync the log and force them to fallback to a transaction
9625 * commit if the log currently contains any of the inodes involved in
9626 * this rename operation (to ensure we do not persist a log with an
9627 * inconsistent state for any of these inodes or leading to any
9628 * inconsistencies when replayed). If the transaction was aborted, the
9629 * abortion reason is propagated to userspace when attempting to commit
9630 * the transaction. If the log does not contain any of these inodes, we
9631 * allow the tasks to sync it.
9633 if (ret && (root_log_pinned || dest_log_pinned)) {
9634 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9635 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9636 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9638 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9639 btrfs_set_log_full_commit(trans);
9641 if (root_log_pinned) {
9642 btrfs_end_log_trans(root);
9643 root_log_pinned = false;
9645 if (dest_log_pinned) {
9646 btrfs_end_log_trans(dest);
9647 dest_log_pinned = false;
9650 if (!ret && sync_log_root && !commit_transaction) {
9651 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9654 commit_transaction = true;
9656 if (!ret && sync_log_dest && !commit_transaction) {
9657 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9660 commit_transaction = true;
9662 if (commit_transaction) {
9663 ret = btrfs_commit_transaction(trans);
9667 ret2 = btrfs_end_transaction(trans);
9668 ret = ret ? ret : ret2;
9671 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9672 up_read(&fs_info->subvol_sem);
9673 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9674 up_read(&fs_info->subvol_sem);
9679 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9680 struct btrfs_root *root,
9682 struct dentry *dentry)
9685 struct inode *inode;
9689 ret = btrfs_find_free_ino(root, &objectid);
9693 inode = btrfs_new_inode(trans, root, dir,
9694 dentry->d_name.name,
9696 btrfs_ino(BTRFS_I(dir)),
9698 S_IFCHR | WHITEOUT_MODE,
9701 if (IS_ERR(inode)) {
9702 ret = PTR_ERR(inode);
9706 inode->i_op = &btrfs_special_inode_operations;
9707 init_special_inode(inode, inode->i_mode,
9710 ret = btrfs_init_inode_security(trans, inode, dir,
9715 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9716 BTRFS_I(inode), 0, index);
9720 ret = btrfs_update_inode(trans, root, inode);
9722 unlock_new_inode(inode);
9724 inode_dec_link_count(inode);
9730 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9731 struct inode *new_dir, struct dentry *new_dentry,
9734 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9735 struct btrfs_trans_handle *trans;
9736 unsigned int trans_num_items;
9737 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9738 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9739 struct inode *new_inode = d_inode(new_dentry);
9740 struct inode *old_inode = d_inode(old_dentry);
9744 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9745 bool log_pinned = false;
9746 struct btrfs_log_ctx ctx;
9747 bool sync_log = false;
9748 bool commit_transaction = false;
9750 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9753 /* we only allow rename subvolume link between subvolumes */
9754 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9757 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9758 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9761 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9762 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9766 /* check for collisions, even if the name isn't there */
9767 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9768 new_dentry->d_name.name,
9769 new_dentry->d_name.len);
9772 if (ret == -EEXIST) {
9774 * eexist without a new_inode */
9775 if (WARN_ON(!new_inode)) {
9779 /* maybe -EOVERFLOW */
9786 * we're using rename to replace one file with another. Start IO on it
9787 * now so we don't add too much work to the end of the transaction
9789 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9790 filemap_flush(old_inode->i_mapping);
9792 /* close the racy window with snapshot create/destroy ioctl */
9793 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9794 down_read(&fs_info->subvol_sem);
9796 * We want to reserve the absolute worst case amount of items. So if
9797 * both inodes are subvols and we need to unlink them then that would
9798 * require 4 item modifications, but if they are both normal inodes it
9799 * would require 5 item modifications, so we'll assume they are normal
9800 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9801 * should cover the worst case number of items we'll modify.
9802 * If our rename has the whiteout flag, we need more 5 units for the
9803 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9804 * when selinux is enabled).
9806 trans_num_items = 11;
9807 if (flags & RENAME_WHITEOUT)
9808 trans_num_items += 5;
9809 trans = btrfs_start_transaction(root, trans_num_items);
9810 if (IS_ERR(trans)) {
9811 ret = PTR_ERR(trans);
9816 btrfs_record_root_in_trans(trans, dest);
9818 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9822 BTRFS_I(old_inode)->dir_index = 0ULL;
9823 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9824 /* force full log commit if subvolume involved. */
9825 btrfs_set_log_full_commit(trans);
9827 btrfs_pin_log_trans(root);
9829 ret = btrfs_insert_inode_ref(trans, dest,
9830 new_dentry->d_name.name,
9831 new_dentry->d_name.len,
9833 btrfs_ino(BTRFS_I(new_dir)), index);
9838 inode_inc_iversion(old_dir);
9839 inode_inc_iversion(new_dir);
9840 inode_inc_iversion(old_inode);
9841 old_dir->i_ctime = old_dir->i_mtime =
9842 new_dir->i_ctime = new_dir->i_mtime =
9843 old_inode->i_ctime = current_time(old_dir);
9845 if (old_dentry->d_parent != new_dentry->d_parent)
9846 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9847 BTRFS_I(old_inode), 1);
9849 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9850 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9851 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9852 old_dentry->d_name.name,
9853 old_dentry->d_name.len);
9855 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9856 BTRFS_I(d_inode(old_dentry)),
9857 old_dentry->d_name.name,
9858 old_dentry->d_name.len);
9860 ret = btrfs_update_inode(trans, root, old_inode);
9863 btrfs_abort_transaction(trans, ret);
9868 inode_inc_iversion(new_inode);
9869 new_inode->i_ctime = current_time(new_inode);
9870 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9871 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9872 root_objectid = BTRFS_I(new_inode)->location.objectid;
9873 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9874 new_dentry->d_name.name,
9875 new_dentry->d_name.len);
9876 BUG_ON(new_inode->i_nlink == 0);
9878 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9879 BTRFS_I(d_inode(new_dentry)),
9880 new_dentry->d_name.name,
9881 new_dentry->d_name.len);
9883 if (!ret && new_inode->i_nlink == 0)
9884 ret = btrfs_orphan_add(trans,
9885 BTRFS_I(d_inode(new_dentry)));
9887 btrfs_abort_transaction(trans, ret);
9892 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9893 new_dentry->d_name.name,
9894 new_dentry->d_name.len, 0, index);
9896 btrfs_abort_transaction(trans, ret);
9900 if (old_inode->i_nlink == 1)
9901 BTRFS_I(old_inode)->dir_index = index;
9904 struct dentry *parent = new_dentry->d_parent;
9906 btrfs_init_log_ctx(&ctx, old_inode);
9907 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9908 BTRFS_I(old_dir), parent,
9910 if (ret == BTRFS_NEED_LOG_SYNC)
9912 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9913 commit_transaction = true;
9915 btrfs_end_log_trans(root);
9919 if (flags & RENAME_WHITEOUT) {
9920 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9924 btrfs_abort_transaction(trans, ret);
9930 * If we have pinned the log and an error happened, we unpin tasks
9931 * trying to sync the log and force them to fallback to a transaction
9932 * commit if the log currently contains any of the inodes involved in
9933 * this rename operation (to ensure we do not persist a log with an
9934 * inconsistent state for any of these inodes or leading to any
9935 * inconsistencies when replayed). If the transaction was aborted, the
9936 * abortion reason is propagated to userspace when attempting to commit
9937 * the transaction. If the log does not contain any of these inodes, we
9938 * allow the tasks to sync it.
9940 if (ret && log_pinned) {
9941 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9942 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9943 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9945 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9946 btrfs_set_log_full_commit(trans);
9948 btrfs_end_log_trans(root);
9951 if (!ret && sync_log) {
9952 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9954 commit_transaction = true;
9956 if (commit_transaction) {
9957 ret = btrfs_commit_transaction(trans);
9961 ret2 = btrfs_end_transaction(trans);
9962 ret = ret ? ret : ret2;
9965 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9966 up_read(&fs_info->subvol_sem);
9971 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9972 struct inode *new_dir, struct dentry *new_dentry,
9975 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9978 if (flags & RENAME_EXCHANGE)
9979 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9982 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9985 struct btrfs_delalloc_work {
9986 struct inode *inode;
9987 struct completion completion;
9988 struct list_head list;
9989 struct btrfs_work work;
9992 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9994 struct btrfs_delalloc_work *delalloc_work;
9995 struct inode *inode;
9997 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9999 inode = delalloc_work->inode;
10000 filemap_flush(inode->i_mapping);
10001 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10002 &BTRFS_I(inode)->runtime_flags))
10003 filemap_flush(inode->i_mapping);
10006 complete(&delalloc_work->completion);
10009 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
10011 struct btrfs_delalloc_work *work;
10013 work = kmalloc(sizeof(*work), GFP_NOFS);
10017 init_completion(&work->completion);
10018 INIT_LIST_HEAD(&work->list);
10019 work->inode = inode;
10020 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10021 btrfs_run_delalloc_work, NULL, NULL);
10027 * some fairly slow code that needs optimization. This walks the list
10028 * of all the inodes with pending delalloc and forces them to disk.
10030 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
10032 struct btrfs_inode *binode;
10033 struct inode *inode;
10034 struct btrfs_delalloc_work *work, *next;
10035 struct list_head works;
10036 struct list_head splice;
10039 INIT_LIST_HEAD(&works);
10040 INIT_LIST_HEAD(&splice);
10042 mutex_lock(&root->delalloc_mutex);
10043 spin_lock(&root->delalloc_lock);
10044 list_splice_init(&root->delalloc_inodes, &splice);
10045 while (!list_empty(&splice)) {
10046 binode = list_entry(splice.next, struct btrfs_inode,
10049 list_move_tail(&binode->delalloc_inodes,
10050 &root->delalloc_inodes);
10051 inode = igrab(&binode->vfs_inode);
10053 cond_resched_lock(&root->delalloc_lock);
10056 spin_unlock(&root->delalloc_lock);
10059 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10060 &binode->runtime_flags);
10061 work = btrfs_alloc_delalloc_work(inode);
10067 list_add_tail(&work->list, &works);
10068 btrfs_queue_work(root->fs_info->flush_workers,
10071 if (nr != -1 && ret >= nr)
10074 spin_lock(&root->delalloc_lock);
10076 spin_unlock(&root->delalloc_lock);
10079 list_for_each_entry_safe(work, next, &works, list) {
10080 list_del_init(&work->list);
10081 wait_for_completion(&work->completion);
10085 if (!list_empty(&splice)) {
10086 spin_lock(&root->delalloc_lock);
10087 list_splice_tail(&splice, &root->delalloc_inodes);
10088 spin_unlock(&root->delalloc_lock);
10090 mutex_unlock(&root->delalloc_mutex);
10094 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10096 struct btrfs_fs_info *fs_info = root->fs_info;
10099 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10102 ret = start_delalloc_inodes(root, -1, true);
10108 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10110 struct btrfs_root *root;
10111 struct list_head splice;
10114 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10117 INIT_LIST_HEAD(&splice);
10119 mutex_lock(&fs_info->delalloc_root_mutex);
10120 spin_lock(&fs_info->delalloc_root_lock);
10121 list_splice_init(&fs_info->delalloc_roots, &splice);
10122 while (!list_empty(&splice) && nr) {
10123 root = list_first_entry(&splice, struct btrfs_root,
10125 root = btrfs_grab_fs_root(root);
10127 list_move_tail(&root->delalloc_root,
10128 &fs_info->delalloc_roots);
10129 spin_unlock(&fs_info->delalloc_root_lock);
10131 ret = start_delalloc_inodes(root, nr, false);
10132 btrfs_put_fs_root(root);
10140 spin_lock(&fs_info->delalloc_root_lock);
10142 spin_unlock(&fs_info->delalloc_root_lock);
10146 if (!list_empty(&splice)) {
10147 spin_lock(&fs_info->delalloc_root_lock);
10148 list_splice_tail(&splice, &fs_info->delalloc_roots);
10149 spin_unlock(&fs_info->delalloc_root_lock);
10151 mutex_unlock(&fs_info->delalloc_root_mutex);
10155 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10156 const char *symname)
10158 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10159 struct btrfs_trans_handle *trans;
10160 struct btrfs_root *root = BTRFS_I(dir)->root;
10161 struct btrfs_path *path;
10162 struct btrfs_key key;
10163 struct inode *inode = NULL;
10170 struct btrfs_file_extent_item *ei;
10171 struct extent_buffer *leaf;
10173 name_len = strlen(symname);
10174 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10175 return -ENAMETOOLONG;
10178 * 2 items for inode item and ref
10179 * 2 items for dir items
10180 * 1 item for updating parent inode item
10181 * 1 item for the inline extent item
10182 * 1 item for xattr if selinux is on
10184 trans = btrfs_start_transaction(root, 7);
10186 return PTR_ERR(trans);
10188 err = btrfs_find_free_ino(root, &objectid);
10192 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10193 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10194 objectid, S_IFLNK|S_IRWXUGO, &index);
10195 if (IS_ERR(inode)) {
10196 err = PTR_ERR(inode);
10202 * If the active LSM wants to access the inode during
10203 * d_instantiate it needs these. Smack checks to see
10204 * if the filesystem supports xattrs by looking at the
10207 inode->i_fop = &btrfs_file_operations;
10208 inode->i_op = &btrfs_file_inode_operations;
10209 inode->i_mapping->a_ops = &btrfs_aops;
10210 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10212 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10216 path = btrfs_alloc_path();
10221 key.objectid = btrfs_ino(BTRFS_I(inode));
10223 key.type = BTRFS_EXTENT_DATA_KEY;
10224 datasize = btrfs_file_extent_calc_inline_size(name_len);
10225 err = btrfs_insert_empty_item(trans, root, path, &key,
10228 btrfs_free_path(path);
10231 leaf = path->nodes[0];
10232 ei = btrfs_item_ptr(leaf, path->slots[0],
10233 struct btrfs_file_extent_item);
10234 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10235 btrfs_set_file_extent_type(leaf, ei,
10236 BTRFS_FILE_EXTENT_INLINE);
10237 btrfs_set_file_extent_encryption(leaf, ei, 0);
10238 btrfs_set_file_extent_compression(leaf, ei, 0);
10239 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10240 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10242 ptr = btrfs_file_extent_inline_start(ei);
10243 write_extent_buffer(leaf, symname, ptr, name_len);
10244 btrfs_mark_buffer_dirty(leaf);
10245 btrfs_free_path(path);
10247 inode->i_op = &btrfs_symlink_inode_operations;
10248 inode_nohighmem(inode);
10249 inode_set_bytes(inode, name_len);
10250 btrfs_i_size_write(BTRFS_I(inode), name_len);
10251 err = btrfs_update_inode(trans, root, inode);
10253 * Last step, add directory indexes for our symlink inode. This is the
10254 * last step to avoid extra cleanup of these indexes if an error happens
10258 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10259 BTRFS_I(inode), 0, index);
10263 d_instantiate_new(dentry, inode);
10266 btrfs_end_transaction(trans);
10267 if (err && inode) {
10268 inode_dec_link_count(inode);
10269 discard_new_inode(inode);
10271 btrfs_btree_balance_dirty(fs_info);
10275 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10276 u64 start, u64 num_bytes, u64 min_size,
10277 loff_t actual_len, u64 *alloc_hint,
10278 struct btrfs_trans_handle *trans)
10280 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10281 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10282 struct extent_map *em;
10283 struct btrfs_root *root = BTRFS_I(inode)->root;
10284 struct btrfs_key ins;
10285 u64 cur_offset = start;
10288 u64 last_alloc = (u64)-1;
10290 bool own_trans = true;
10291 u64 end = start + num_bytes - 1;
10295 while (num_bytes > 0) {
10297 trans = btrfs_start_transaction(root, 3);
10298 if (IS_ERR(trans)) {
10299 ret = PTR_ERR(trans);
10304 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10305 cur_bytes = max(cur_bytes, min_size);
10307 * If we are severely fragmented we could end up with really
10308 * small allocations, so if the allocator is returning small
10309 * chunks lets make its job easier by only searching for those
10312 cur_bytes = min(cur_bytes, last_alloc);
10313 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10314 min_size, 0, *alloc_hint, &ins, 1, 0);
10317 btrfs_end_transaction(trans);
10320 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10322 last_alloc = ins.offset;
10323 ret = insert_reserved_file_extent(trans, inode,
10324 cur_offset, ins.objectid,
10325 ins.offset, ins.offset,
10326 ins.offset, 0, 0, 0,
10327 BTRFS_FILE_EXTENT_PREALLOC);
10329 btrfs_free_reserved_extent(fs_info, ins.objectid,
10331 btrfs_abort_transaction(trans, ret);
10333 btrfs_end_transaction(trans);
10337 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10338 cur_offset + ins.offset -1, 0);
10340 em = alloc_extent_map();
10342 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10343 &BTRFS_I(inode)->runtime_flags);
10347 em->start = cur_offset;
10348 em->orig_start = cur_offset;
10349 em->len = ins.offset;
10350 em->block_start = ins.objectid;
10351 em->block_len = ins.offset;
10352 em->orig_block_len = ins.offset;
10353 em->ram_bytes = ins.offset;
10354 em->bdev = fs_info->fs_devices->latest_bdev;
10355 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10356 em->generation = trans->transid;
10359 write_lock(&em_tree->lock);
10360 ret = add_extent_mapping(em_tree, em, 1);
10361 write_unlock(&em_tree->lock);
10362 if (ret != -EEXIST)
10364 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10365 cur_offset + ins.offset - 1,
10368 free_extent_map(em);
10370 num_bytes -= ins.offset;
10371 cur_offset += ins.offset;
10372 *alloc_hint = ins.objectid + ins.offset;
10374 inode_inc_iversion(inode);
10375 inode->i_ctime = current_time(inode);
10376 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10377 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10378 (actual_len > inode->i_size) &&
10379 (cur_offset > inode->i_size)) {
10380 if (cur_offset > actual_len)
10381 i_size = actual_len;
10383 i_size = cur_offset;
10384 i_size_write(inode, i_size);
10385 btrfs_ordered_update_i_size(inode, i_size, NULL);
10388 ret = btrfs_update_inode(trans, root, inode);
10391 btrfs_abort_transaction(trans, ret);
10393 btrfs_end_transaction(trans);
10398 btrfs_end_transaction(trans);
10400 if (cur_offset < end)
10401 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10402 end - cur_offset + 1);
10406 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10407 u64 start, u64 num_bytes, u64 min_size,
10408 loff_t actual_len, u64 *alloc_hint)
10410 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10411 min_size, actual_len, alloc_hint,
10415 int btrfs_prealloc_file_range_trans(struct inode *inode,
10416 struct btrfs_trans_handle *trans, int mode,
10417 u64 start, u64 num_bytes, u64 min_size,
10418 loff_t actual_len, u64 *alloc_hint)
10420 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10421 min_size, actual_len, alloc_hint, trans);
10424 static int btrfs_set_page_dirty(struct page *page)
10426 return __set_page_dirty_nobuffers(page);
10429 static int btrfs_permission(struct inode *inode, int mask)
10431 struct btrfs_root *root = BTRFS_I(inode)->root;
10432 umode_t mode = inode->i_mode;
10434 if (mask & MAY_WRITE &&
10435 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10436 if (btrfs_root_readonly(root))
10438 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10441 return generic_permission(inode, mask);
10444 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10446 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10447 struct btrfs_trans_handle *trans;
10448 struct btrfs_root *root = BTRFS_I(dir)->root;
10449 struct inode *inode = NULL;
10455 * 5 units required for adding orphan entry
10457 trans = btrfs_start_transaction(root, 5);
10459 return PTR_ERR(trans);
10461 ret = btrfs_find_free_ino(root, &objectid);
10465 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10466 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10467 if (IS_ERR(inode)) {
10468 ret = PTR_ERR(inode);
10473 inode->i_fop = &btrfs_file_operations;
10474 inode->i_op = &btrfs_file_inode_operations;
10476 inode->i_mapping->a_ops = &btrfs_aops;
10477 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10479 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10483 ret = btrfs_update_inode(trans, root, inode);
10486 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10491 * We set number of links to 0 in btrfs_new_inode(), and here we set
10492 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10495 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10497 set_nlink(inode, 1);
10498 d_tmpfile(dentry, inode);
10499 unlock_new_inode(inode);
10500 mark_inode_dirty(inode);
10502 btrfs_end_transaction(trans);
10504 discard_new_inode(inode);
10505 btrfs_btree_balance_dirty(fs_info);
10509 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10511 struct inode *inode = tree->private_data;
10512 unsigned long index = start >> PAGE_SHIFT;
10513 unsigned long end_index = end >> PAGE_SHIFT;
10516 while (index <= end_index) {
10517 page = find_get_page(inode->i_mapping, index);
10518 ASSERT(page); /* Pages should be in the extent_io_tree */
10519 set_page_writeback(page);
10527 * Add an entry indicating a block group or device which is pinned by a
10528 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10529 * negative errno on failure.
10531 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10532 bool is_block_group)
10534 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10535 struct btrfs_swapfile_pin *sp, *entry;
10536 struct rb_node **p;
10537 struct rb_node *parent = NULL;
10539 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10544 sp->is_block_group = is_block_group;
10546 spin_lock(&fs_info->swapfile_pins_lock);
10547 p = &fs_info->swapfile_pins.rb_node;
10550 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10551 if (sp->ptr < entry->ptr ||
10552 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10553 p = &(*p)->rb_left;
10554 } else if (sp->ptr > entry->ptr ||
10555 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10556 p = &(*p)->rb_right;
10558 spin_unlock(&fs_info->swapfile_pins_lock);
10563 rb_link_node(&sp->node, parent, p);
10564 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10565 spin_unlock(&fs_info->swapfile_pins_lock);
10569 /* Free all of the entries pinned by this swapfile. */
10570 static void btrfs_free_swapfile_pins(struct inode *inode)
10572 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10573 struct btrfs_swapfile_pin *sp;
10574 struct rb_node *node, *next;
10576 spin_lock(&fs_info->swapfile_pins_lock);
10577 node = rb_first(&fs_info->swapfile_pins);
10579 next = rb_next(node);
10580 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10581 if (sp->inode == inode) {
10582 rb_erase(&sp->node, &fs_info->swapfile_pins);
10583 if (sp->is_block_group)
10584 btrfs_put_block_group(sp->ptr);
10589 spin_unlock(&fs_info->swapfile_pins_lock);
10592 struct btrfs_swap_info {
10598 unsigned long nr_pages;
10602 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10603 struct btrfs_swap_info *bsi)
10605 unsigned long nr_pages;
10606 u64 first_ppage, first_ppage_reported, next_ppage;
10609 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10610 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10611 PAGE_SIZE) >> PAGE_SHIFT;
10613 if (first_ppage >= next_ppage)
10615 nr_pages = next_ppage - first_ppage;
10617 first_ppage_reported = first_ppage;
10618 if (bsi->start == 0)
10619 first_ppage_reported++;
10620 if (bsi->lowest_ppage > first_ppage_reported)
10621 bsi->lowest_ppage = first_ppage_reported;
10622 if (bsi->highest_ppage < (next_ppage - 1))
10623 bsi->highest_ppage = next_ppage - 1;
10625 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10628 bsi->nr_extents += ret;
10629 bsi->nr_pages += nr_pages;
10633 static void btrfs_swap_deactivate(struct file *file)
10635 struct inode *inode = file_inode(file);
10637 btrfs_free_swapfile_pins(inode);
10638 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10641 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10644 struct inode *inode = file_inode(file);
10645 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10646 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10647 struct extent_state *cached_state = NULL;
10648 struct extent_map *em = NULL;
10649 struct btrfs_device *device = NULL;
10650 struct btrfs_swap_info bsi = {
10651 .lowest_ppage = (sector_t)-1ULL,
10658 * If the swap file was just created, make sure delalloc is done. If the
10659 * file changes again after this, the user is doing something stupid and
10660 * we don't really care.
10662 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10667 * The inode is locked, so these flags won't change after we check them.
10669 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10670 btrfs_warn(fs_info, "swapfile must not be compressed");
10673 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10674 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10677 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10678 btrfs_warn(fs_info, "swapfile must not be checksummed");
10683 * Balance or device remove/replace/resize can move stuff around from
10684 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10685 * concurrently while we are mapping the swap extents, and
10686 * fs_info->swapfile_pins prevents them from running while the swap file
10687 * is active and moving the extents. Note that this also prevents a
10688 * concurrent device add which isn't actually necessary, but it's not
10689 * really worth the trouble to allow it.
10691 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10692 btrfs_warn(fs_info,
10693 "cannot activate swapfile while exclusive operation is running");
10697 * Snapshots can create extents which require COW even if NODATACOW is
10698 * set. We use this counter to prevent snapshots. We must increment it
10699 * before walking the extents because we don't want a concurrent
10700 * snapshot to run after we've already checked the extents.
10702 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10704 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10706 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10708 while (start < isize) {
10709 u64 logical_block_start, physical_block_start;
10710 struct btrfs_block_group_cache *bg;
10711 u64 len = isize - start;
10713 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10719 if (em->block_start == EXTENT_MAP_HOLE) {
10720 btrfs_warn(fs_info, "swapfile must not have holes");
10724 if (em->block_start == EXTENT_MAP_INLINE) {
10726 * It's unlikely we'll ever actually find ourselves
10727 * here, as a file small enough to fit inline won't be
10728 * big enough to store more than the swap header, but in
10729 * case something changes in the future, let's catch it
10730 * here rather than later.
10732 btrfs_warn(fs_info, "swapfile must not be inline");
10736 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10737 btrfs_warn(fs_info, "swapfile must not be compressed");
10742 logical_block_start = em->block_start + (start - em->start);
10743 len = min(len, em->len - (start - em->start));
10744 free_extent_map(em);
10747 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10753 btrfs_warn(fs_info,
10754 "swapfile must not be copy-on-write");
10759 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10765 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10766 btrfs_warn(fs_info,
10767 "swapfile must have single data profile");
10772 if (device == NULL) {
10773 device = em->map_lookup->stripes[0].dev;
10774 ret = btrfs_add_swapfile_pin(inode, device, false);
10779 } else if (device != em->map_lookup->stripes[0].dev) {
10780 btrfs_warn(fs_info, "swapfile must be on one device");
10785 physical_block_start = (em->map_lookup->stripes[0].physical +
10786 (logical_block_start - em->start));
10787 len = min(len, em->len - (logical_block_start - em->start));
10788 free_extent_map(em);
10791 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10793 btrfs_warn(fs_info,
10794 "could not find block group containing swapfile");
10799 ret = btrfs_add_swapfile_pin(inode, bg, true);
10801 btrfs_put_block_group(bg);
10808 if (bsi.block_len &&
10809 bsi.block_start + bsi.block_len == physical_block_start) {
10810 bsi.block_len += len;
10812 if (bsi.block_len) {
10813 ret = btrfs_add_swap_extent(sis, &bsi);
10818 bsi.block_start = physical_block_start;
10819 bsi.block_len = len;
10826 ret = btrfs_add_swap_extent(sis, &bsi);
10829 if (!IS_ERR_OR_NULL(em))
10830 free_extent_map(em);
10832 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10835 btrfs_swap_deactivate(file);
10837 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10843 sis->bdev = device->bdev;
10844 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10845 sis->max = bsi.nr_pages;
10846 sis->pages = bsi.nr_pages - 1;
10847 sis->highest_bit = bsi.nr_pages - 1;
10848 return bsi.nr_extents;
10851 static void btrfs_swap_deactivate(struct file *file)
10855 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10858 return -EOPNOTSUPP;
10862 static const struct inode_operations btrfs_dir_inode_operations = {
10863 .getattr = btrfs_getattr,
10864 .lookup = btrfs_lookup,
10865 .create = btrfs_create,
10866 .unlink = btrfs_unlink,
10867 .link = btrfs_link,
10868 .mkdir = btrfs_mkdir,
10869 .rmdir = btrfs_rmdir,
10870 .rename = btrfs_rename2,
10871 .symlink = btrfs_symlink,
10872 .setattr = btrfs_setattr,
10873 .mknod = btrfs_mknod,
10874 .listxattr = btrfs_listxattr,
10875 .permission = btrfs_permission,
10876 .get_acl = btrfs_get_acl,
10877 .set_acl = btrfs_set_acl,
10878 .update_time = btrfs_update_time,
10879 .tmpfile = btrfs_tmpfile,
10881 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10882 .lookup = btrfs_lookup,
10883 .permission = btrfs_permission,
10884 .update_time = btrfs_update_time,
10887 static const struct file_operations btrfs_dir_file_operations = {
10888 .llseek = generic_file_llseek,
10889 .read = generic_read_dir,
10890 .iterate_shared = btrfs_real_readdir,
10891 .open = btrfs_opendir,
10892 .unlocked_ioctl = btrfs_ioctl,
10893 #ifdef CONFIG_COMPAT
10894 .compat_ioctl = btrfs_compat_ioctl,
10896 .release = btrfs_release_file,
10897 .fsync = btrfs_sync_file,
10900 static const struct extent_io_ops btrfs_extent_io_ops = {
10901 /* mandatory callbacks */
10902 .submit_bio_hook = btrfs_submit_bio_hook,
10903 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10907 * btrfs doesn't support the bmap operation because swapfiles
10908 * use bmap to make a mapping of extents in the file. They assume
10909 * these extents won't change over the life of the file and they
10910 * use the bmap result to do IO directly to the drive.
10912 * the btrfs bmap call would return logical addresses that aren't
10913 * suitable for IO and they also will change frequently as COW
10914 * operations happen. So, swapfile + btrfs == corruption.
10916 * For now we're avoiding this by dropping bmap.
10918 static const struct address_space_operations btrfs_aops = {
10919 .readpage = btrfs_readpage,
10920 .writepage = btrfs_writepage,
10921 .writepages = btrfs_writepages,
10922 .readpages = btrfs_readpages,
10923 .direct_IO = btrfs_direct_IO,
10924 .invalidatepage = btrfs_invalidatepage,
10925 .releasepage = btrfs_releasepage,
10926 .set_page_dirty = btrfs_set_page_dirty,
10927 .error_remove_page = generic_error_remove_page,
10928 .swap_activate = btrfs_swap_activate,
10929 .swap_deactivate = btrfs_swap_deactivate,
10932 static const struct inode_operations btrfs_file_inode_operations = {
10933 .getattr = btrfs_getattr,
10934 .setattr = btrfs_setattr,
10935 .listxattr = btrfs_listxattr,
10936 .permission = btrfs_permission,
10937 .fiemap = btrfs_fiemap,
10938 .get_acl = btrfs_get_acl,
10939 .set_acl = btrfs_set_acl,
10940 .update_time = btrfs_update_time,
10942 static const struct inode_operations btrfs_special_inode_operations = {
10943 .getattr = btrfs_getattr,
10944 .setattr = btrfs_setattr,
10945 .permission = btrfs_permission,
10946 .listxattr = btrfs_listxattr,
10947 .get_acl = btrfs_get_acl,
10948 .set_acl = btrfs_set_acl,
10949 .update_time = btrfs_update_time,
10951 static const struct inode_operations btrfs_symlink_inode_operations = {
10952 .get_link = page_get_link,
10953 .getattr = btrfs_getattr,
10954 .setattr = btrfs_setattr,
10955 .permission = btrfs_permission,
10956 .listxattr = btrfs_listxattr,
10957 .update_time = btrfs_update_time,
10960 const struct dentry_operations btrfs_dentry_operations = {
10961 .d_delete = btrfs_dentry_delete,