1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <crypto/hash.h>
7 #include <linux/kernel.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <linux/migrate.h>
32 #include <linux/sched/mm.h>
33 #include <linux/iomap.h>
34 #include <asm/unaligned.h>
38 #include "transaction.h"
39 #include "btrfs_inode.h"
40 #include "print-tree.h"
41 #include "ordered-data.h"
45 #include "compression.h"
47 #include "free-space-cache.h"
48 #include "inode-map.h"
51 #include "delalloc-space.h"
52 #include "block-group.h"
53 #include "space-info.h"
55 struct btrfs_iget_args {
57 struct btrfs_root *root;
60 struct btrfs_dio_data {
64 struct extent_changeset *data_reserved;
68 static const struct inode_operations btrfs_dir_inode_operations;
69 static const struct inode_operations btrfs_symlink_inode_operations;
70 static const struct inode_operations btrfs_special_inode_operations;
71 static const struct inode_operations btrfs_file_inode_operations;
72 static const struct address_space_operations btrfs_aops;
73 static const struct file_operations btrfs_dir_file_operations;
75 static struct kmem_cache *btrfs_inode_cachep;
76 struct kmem_cache *btrfs_trans_handle_cachep;
77 struct kmem_cache *btrfs_path_cachep;
78 struct kmem_cache *btrfs_free_space_cachep;
79 struct kmem_cache *btrfs_free_space_bitmap_cachep;
81 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
82 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
83 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
84 static noinline int cow_file_range(struct btrfs_inode *inode,
85 struct page *locked_page,
86 u64 start, u64 end, int *page_started,
87 unsigned long *nr_written, int unlock);
88 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
89 u64 len, u64 orig_start, u64 block_start,
90 u64 block_len, u64 orig_block_len,
91 u64 ram_bytes, int compress_type,
94 static void __endio_write_update_ordered(struct btrfs_inode *inode,
95 const u64 offset, const u64 bytes,
99 * Cleanup all submitted ordered extents in specified range to handle errors
100 * from the btrfs_run_delalloc_range() callback.
102 * NOTE: caller must ensure that when an error happens, it can not call
103 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
104 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
105 * to be released, which we want to happen only when finishing the ordered
106 * extent (btrfs_finish_ordered_io()).
108 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
109 struct page *locked_page,
110 u64 offset, u64 bytes)
112 unsigned long index = offset >> PAGE_SHIFT;
113 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
114 u64 page_start = page_offset(locked_page);
115 u64 page_end = page_start + PAGE_SIZE - 1;
119 while (index <= end_index) {
120 page = find_get_page(inode->vfs_inode.i_mapping, index);
124 ClearPagePrivate2(page);
129 * In case this page belongs to the delalloc range being instantiated
130 * then skip it, since the first page of a range is going to be
131 * properly cleaned up by the caller of run_delalloc_range
133 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
138 return __endio_write_update_ordered(inode, offset, bytes, false);
141 static int btrfs_dirty_inode(struct inode *inode);
143 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
144 struct inode *inode, struct inode *dir,
145 const struct qstr *qstr)
149 err = btrfs_init_acl(trans, inode, dir);
151 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
156 * this does all the hard work for inserting an inline extent into
157 * the btree. The caller should have done a btrfs_drop_extents so that
158 * no overlapping inline items exist in the btree
160 static int insert_inline_extent(struct btrfs_trans_handle *trans,
161 struct btrfs_path *path, int extent_inserted,
162 struct btrfs_root *root, struct inode *inode,
163 u64 start, size_t size, size_t compressed_size,
165 struct page **compressed_pages)
167 struct extent_buffer *leaf;
168 struct page *page = NULL;
171 struct btrfs_file_extent_item *ei;
173 size_t cur_size = size;
174 unsigned long offset;
176 ASSERT((compressed_size > 0 && compressed_pages) ||
177 (compressed_size == 0 && !compressed_pages));
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 align size to sectorsize for inline extents just for simplicity
244 size = ALIGN(size, root->fs_info->sectorsize);
245 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
250 * we're an inline extent, so nobody can
251 * extend the file past i_size without locking
252 * a page we already have locked.
254 * We must do any isize and inode updates
255 * before we unlock the pages. Otherwise we
256 * could end up racing with unlink.
258 BTRFS_I(inode)->disk_i_size = inode->i_size;
259 ret = btrfs_update_inode(trans, root, inode);
267 * conditionally insert an inline extent into the file. This
268 * does the checks required to make sure the data is small enough
269 * to fit as an inline extent.
271 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start,
272 u64 end, size_t compressed_size,
274 struct page **compressed_pages)
276 struct btrfs_root *root = inode->root;
277 struct btrfs_fs_info *fs_info = root->fs_info;
278 struct btrfs_trans_handle *trans;
279 u64 isize = i_size_read(&inode->vfs_inode);
280 u64 actual_end = min(end + 1, isize);
281 u64 inline_len = actual_end - start;
282 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
283 u64 data_len = inline_len;
285 struct btrfs_path *path;
286 int extent_inserted = 0;
287 u32 extent_item_size;
290 data_len = compressed_size;
293 actual_end > fs_info->sectorsize ||
294 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
296 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
298 data_len > fs_info->max_inline) {
302 path = btrfs_alloc_path();
306 trans = btrfs_join_transaction(root);
308 btrfs_free_path(path);
309 return PTR_ERR(trans);
311 trans->block_rsv = &inode->block_rsv;
313 if (compressed_size && compressed_pages)
314 extent_item_size = btrfs_file_extent_calc_inline_size(
317 extent_item_size = btrfs_file_extent_calc_inline_size(
320 ret = __btrfs_drop_extents(trans, root, inode, path, start, aligned_end,
321 NULL, 1, 1, extent_item_size,
324 btrfs_abort_transaction(trans, ret);
328 if (isize > actual_end)
329 inline_len = min_t(u64, isize, actual_end);
330 ret = insert_inline_extent(trans, path, extent_inserted,
331 root, &inode->vfs_inode, start,
332 inline_len, compressed_size,
333 compress_type, compressed_pages);
334 if (ret && ret != -ENOSPC) {
335 btrfs_abort_transaction(trans, ret);
337 } else if (ret == -ENOSPC) {
342 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
343 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
346 * Don't forget to free the reserved space, as for inlined extent
347 * it won't count as data extent, free them directly here.
348 * And at reserve time, it's always aligned to page size, so
349 * just free one page here.
351 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
352 btrfs_free_path(path);
353 btrfs_end_transaction(trans);
357 struct async_extent {
362 unsigned long nr_pages;
364 struct list_head list;
369 struct page *locked_page;
372 unsigned int write_flags;
373 struct list_head extents;
374 struct cgroup_subsys_state *blkcg_css;
375 struct btrfs_work work;
380 /* Number of chunks in flight; must be first in the structure */
382 struct async_chunk chunks[];
385 static noinline int add_async_extent(struct async_chunk *cow,
386 u64 start, u64 ram_size,
389 unsigned long nr_pages,
392 struct async_extent *async_extent;
394 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
395 BUG_ON(!async_extent); /* -ENOMEM */
396 async_extent->start = start;
397 async_extent->ram_size = ram_size;
398 async_extent->compressed_size = compressed_size;
399 async_extent->pages = pages;
400 async_extent->nr_pages = nr_pages;
401 async_extent->compress_type = compress_type;
402 list_add_tail(&async_extent->list, &cow->extents);
407 * Check if the inode has flags compatible with compression
409 static inline bool inode_can_compress(struct btrfs_inode *inode)
411 if (inode->flags & BTRFS_INODE_NODATACOW ||
412 inode->flags & BTRFS_INODE_NODATASUM)
418 * Check if the inode needs to be submitted to compression, based on mount
419 * options, defragmentation, properties or heuristics.
421 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
424 struct btrfs_fs_info *fs_info = inode->root->fs_info;
426 if (!inode_can_compress(inode)) {
427 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
428 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
433 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
436 if (inode->defrag_compress)
438 /* bad compression ratios */
439 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
441 if (btrfs_test_opt(fs_info, COMPRESS) ||
442 inode->flags & BTRFS_INODE_COMPRESS ||
443 inode->prop_compress)
444 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
448 static inline void inode_should_defrag(struct btrfs_inode *inode,
449 u64 start, u64 end, u64 num_bytes, u64 small_write)
451 /* If this is a small write inside eof, kick off a defrag */
452 if (num_bytes < small_write &&
453 (start > 0 || end + 1 < inode->disk_i_size))
454 btrfs_add_inode_defrag(NULL, inode);
458 * we create compressed extents in two phases. The first
459 * phase compresses a range of pages that have already been
460 * locked (both pages and state bits are locked).
462 * This is done inside an ordered work queue, and the compression
463 * is spread across many cpus. The actual IO submission is step
464 * two, and the ordered work queue takes care of making sure that
465 * happens in the same order things were put onto the queue by
466 * writepages and friends.
468 * If this code finds it can't get good compression, it puts an
469 * entry onto the work queue to write the uncompressed bytes. This
470 * makes sure that both compressed inodes and uncompressed inodes
471 * are written in the same order that the flusher thread sent them
474 static noinline int compress_file_range(struct async_chunk *async_chunk)
476 struct inode *inode = async_chunk->inode;
477 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
478 u64 blocksize = fs_info->sectorsize;
479 u64 start = async_chunk->start;
480 u64 end = async_chunk->end;
484 struct page **pages = NULL;
485 unsigned long nr_pages;
486 unsigned long total_compressed = 0;
487 unsigned long total_in = 0;
490 int compress_type = fs_info->compress_type;
491 int compressed_extents = 0;
494 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
498 * We need to save i_size before now because it could change in between
499 * us evaluating the size and assigning it. This is because we lock and
500 * unlock the page in truncate and fallocate, and then modify the i_size
503 * The barriers are to emulate READ_ONCE, remove that once i_size_read
507 i_size = i_size_read(inode);
509 actual_end = min_t(u64, i_size, end + 1);
512 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
513 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
514 nr_pages = min_t(unsigned long, nr_pages,
515 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
518 * we don't want to send crud past the end of i_size through
519 * compression, that's just a waste of CPU time. So, if the
520 * end of the file is before the start of our current
521 * requested range of bytes, we bail out to the uncompressed
522 * cleanup code that can deal with all of this.
524 * It isn't really the fastest way to fix things, but this is a
525 * very uncommon corner.
527 if (actual_end <= start)
528 goto cleanup_and_bail_uncompressed;
530 total_compressed = actual_end - start;
533 * skip compression for a small file range(<=blocksize) that
534 * isn't an inline extent, since it doesn't save disk space at all.
536 if (total_compressed <= blocksize &&
537 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
538 goto cleanup_and_bail_uncompressed;
540 total_compressed = min_t(unsigned long, total_compressed,
541 BTRFS_MAX_UNCOMPRESSED);
546 * we do compression for mount -o compress and when the
547 * inode has not been flagged as nocompress. This flag can
548 * change at any time if we discover bad compression ratios.
550 if (inode_need_compress(BTRFS_I(inode), start, end)) {
552 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
554 /* just bail out to the uncompressed code */
559 if (BTRFS_I(inode)->defrag_compress)
560 compress_type = BTRFS_I(inode)->defrag_compress;
561 else if (BTRFS_I(inode)->prop_compress)
562 compress_type = BTRFS_I(inode)->prop_compress;
565 * we need to call clear_page_dirty_for_io on each
566 * page in the range. Otherwise applications with the file
567 * mmap'd can wander in and change the page contents while
568 * we are compressing them.
570 * If the compression fails for any reason, we set the pages
571 * dirty again later on.
573 * Note that the remaining part is redirtied, the start pointer
574 * has moved, the end is the original one.
577 extent_range_clear_dirty_for_io(inode, start, end);
581 /* Compression level is applied here and only here */
582 ret = btrfs_compress_pages(
583 compress_type | (fs_info->compress_level << 4),
584 inode->i_mapping, start,
591 unsigned long offset = offset_in_page(total_compressed);
592 struct page *page = pages[nr_pages - 1];
595 /* zero the tail end of the last page, we might be
596 * sending it down to disk
599 kaddr = kmap_atomic(page);
600 memset(kaddr + offset, 0,
602 kunmap_atomic(kaddr);
609 /* lets try to make an inline extent */
610 if (ret || total_in < actual_end) {
611 /* we didn't compress the entire range, try
612 * to make an uncompressed inline extent.
614 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
615 0, BTRFS_COMPRESS_NONE,
618 /* try making a compressed inline extent */
619 ret = cow_file_range_inline(BTRFS_I(inode), start, end,
621 compress_type, pages);
624 unsigned long clear_flags = EXTENT_DELALLOC |
625 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
626 EXTENT_DO_ACCOUNTING;
627 unsigned long page_error_op;
629 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
632 * inline extent creation worked or returned error,
633 * we don't need to create any more async work items.
634 * Unlock and free up our temp pages.
636 * We use DO_ACCOUNTING here because we need the
637 * delalloc_release_metadata to be done _after_ we drop
638 * our outstanding extent for clearing delalloc for this
641 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
651 * Ensure we only free the compressed pages if we have
652 * them allocated, as we can still reach here with
653 * inode_need_compress() == false.
656 for (i = 0; i < nr_pages; i++) {
657 WARN_ON(pages[i]->mapping);
668 * we aren't doing an inline extent round the compressed size
669 * up to a block size boundary so the allocator does sane
672 total_compressed = ALIGN(total_compressed, blocksize);
675 * one last check to make sure the compression is really a
676 * win, compare the page count read with the blocks on disk,
677 * compression must free at least one sector size
679 total_in = ALIGN(total_in, PAGE_SIZE);
680 if (total_compressed + blocksize <= total_in) {
681 compressed_extents++;
684 * The async work queues will take care of doing actual
685 * allocation on disk for these compressed pages, and
686 * will submit them to the elevator.
688 add_async_extent(async_chunk, start, total_in,
689 total_compressed, pages, nr_pages,
692 if (start + total_in < end) {
698 return compressed_extents;
703 * the compression code ran but failed to make things smaller,
704 * free any pages it allocated and our page pointer array
706 for (i = 0; i < nr_pages; i++) {
707 WARN_ON(pages[i]->mapping);
712 total_compressed = 0;
715 /* flag the file so we don't compress in the future */
716 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
717 !(BTRFS_I(inode)->prop_compress)) {
718 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
721 cleanup_and_bail_uncompressed:
723 * No compression, but we still need to write the pages in the file
724 * we've been given so far. redirty the locked page if it corresponds
725 * to our extent and set things up for the async work queue to run
726 * cow_file_range to do the normal delalloc dance.
728 if (async_chunk->locked_page &&
729 (page_offset(async_chunk->locked_page) >= start &&
730 page_offset(async_chunk->locked_page)) <= end) {
731 __set_page_dirty_nobuffers(async_chunk->locked_page);
732 /* unlocked later on in the async handlers */
736 extent_range_redirty_for_io(inode, start, end);
737 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
738 BTRFS_COMPRESS_NONE);
739 compressed_extents++;
741 return compressed_extents;
744 static void free_async_extent_pages(struct async_extent *async_extent)
748 if (!async_extent->pages)
751 for (i = 0; i < async_extent->nr_pages; i++) {
752 WARN_ON(async_extent->pages[i]->mapping);
753 put_page(async_extent->pages[i]);
755 kfree(async_extent->pages);
756 async_extent->nr_pages = 0;
757 async_extent->pages = NULL;
761 * phase two of compressed writeback. This is the ordered portion
762 * of the code, which only gets called in the order the work was
763 * queued. We walk all the async extents created by compress_file_range
764 * and send them down to the disk.
766 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
768 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
769 struct btrfs_fs_info *fs_info = inode->root->fs_info;
770 struct async_extent *async_extent;
772 struct btrfs_key ins;
773 struct extent_map *em;
774 struct btrfs_root *root = inode->root;
775 struct extent_io_tree *io_tree = &inode->io_tree;
779 while (!list_empty(&async_chunk->extents)) {
780 async_extent = list_entry(async_chunk->extents.next,
781 struct async_extent, list);
782 list_del(&async_extent->list);
785 lock_extent(io_tree, async_extent->start,
786 async_extent->start + async_extent->ram_size - 1);
787 /* did the compression code fall back to uncompressed IO? */
788 if (!async_extent->pages) {
789 int page_started = 0;
790 unsigned long nr_written = 0;
792 /* allocate blocks */
793 ret = cow_file_range(inode, async_chunk->locked_page,
795 async_extent->start +
796 async_extent->ram_size - 1,
797 &page_started, &nr_written, 0);
802 * if page_started, cow_file_range inserted an
803 * inline extent and took care of all the unlocking
804 * and IO for us. Otherwise, we need to submit
805 * all those pages down to the drive.
807 if (!page_started && !ret)
808 extent_write_locked_range(&inode->vfs_inode,
810 async_extent->start +
811 async_extent->ram_size - 1,
813 else if (ret && async_chunk->locked_page)
814 unlock_page(async_chunk->locked_page);
820 ret = btrfs_reserve_extent(root, async_extent->ram_size,
821 async_extent->compressed_size,
822 async_extent->compressed_size,
823 0, alloc_hint, &ins, 1, 1);
825 free_async_extent_pages(async_extent);
827 if (ret == -ENOSPC) {
828 unlock_extent(io_tree, async_extent->start,
829 async_extent->start +
830 async_extent->ram_size - 1);
833 * we need to redirty the pages if we decide to
834 * fallback to uncompressed IO, otherwise we
835 * will not submit these pages down to lower
838 extent_range_redirty_for_io(&inode->vfs_inode,
840 async_extent->start +
841 async_extent->ram_size - 1);
848 * here we're doing allocation and writeback of the
851 em = create_io_em(inode, async_extent->start,
852 async_extent->ram_size, /* len */
853 async_extent->start, /* orig_start */
854 ins.objectid, /* block_start */
855 ins.offset, /* block_len */
856 ins.offset, /* orig_block_len */
857 async_extent->ram_size, /* ram_bytes */
858 async_extent->compress_type,
859 BTRFS_ORDERED_COMPRESSED);
861 /* ret value is not necessary due to void function */
862 goto out_free_reserve;
865 ret = btrfs_add_ordered_extent_compress(inode,
868 async_extent->ram_size,
870 BTRFS_ORDERED_COMPRESSED,
871 async_extent->compress_type);
873 btrfs_drop_extent_cache(inode, async_extent->start,
874 async_extent->start +
875 async_extent->ram_size - 1, 0);
876 goto out_free_reserve;
878 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
881 * clear dirty, set writeback and unlock the pages.
883 extent_clear_unlock_delalloc(inode, async_extent->start,
884 async_extent->start +
885 async_extent->ram_size - 1,
886 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
887 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
889 if (btrfs_submit_compressed_write(inode, async_extent->start,
890 async_extent->ram_size,
892 ins.offset, async_extent->pages,
893 async_extent->nr_pages,
894 async_chunk->write_flags,
895 async_chunk->blkcg_css)) {
896 struct page *p = async_extent->pages[0];
897 const u64 start = async_extent->start;
898 const u64 end = start + async_extent->ram_size - 1;
900 p->mapping = inode->vfs_inode.i_mapping;
901 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
904 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
907 free_async_extent_pages(async_extent);
909 alloc_hint = ins.objectid + ins.offset;
915 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
916 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
918 extent_clear_unlock_delalloc(inode, async_extent->start,
919 async_extent->start +
920 async_extent->ram_size - 1,
921 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
922 EXTENT_DELALLOC_NEW |
923 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
924 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
925 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
927 free_async_extent_pages(async_extent);
932 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
935 struct extent_map_tree *em_tree = &inode->extent_tree;
936 struct extent_map *em;
939 read_lock(&em_tree->lock);
940 em = search_extent_mapping(em_tree, start, num_bytes);
943 * if block start isn't an actual block number then find the
944 * first block in this inode and use that as a hint. If that
945 * block is also bogus then just don't worry about it.
947 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
949 em = search_extent_mapping(em_tree, 0, 0);
950 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
951 alloc_hint = em->block_start;
955 alloc_hint = em->block_start;
959 read_unlock(&em_tree->lock);
965 * when extent_io.c finds a delayed allocation range in the file,
966 * the call backs end up in this code. The basic idea is to
967 * allocate extents on disk for the range, and create ordered data structs
968 * in ram to track those extents.
970 * locked_page is the page that writepage had locked already. We use
971 * it to make sure we don't do extra locks or unlocks.
973 * *page_started is set to one if we unlock locked_page and do everything
974 * required to start IO on it. It may be clean and already done with
977 static noinline int cow_file_range(struct btrfs_inode *inode,
978 struct page *locked_page,
979 u64 start, u64 end, int *page_started,
980 unsigned long *nr_written, int unlock)
982 struct btrfs_root *root = inode->root;
983 struct btrfs_fs_info *fs_info = root->fs_info;
986 unsigned long ram_size;
987 u64 cur_alloc_size = 0;
989 u64 blocksize = fs_info->sectorsize;
990 struct btrfs_key ins;
991 struct extent_map *em;
993 unsigned long page_ops;
994 bool extent_reserved = false;
997 if (btrfs_is_free_space_inode(inode)) {
1002 num_bytes = ALIGN(end - start + 1, blocksize);
1003 num_bytes = max(blocksize, num_bytes);
1004 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1006 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1009 /* lets try to make an inline extent */
1010 ret = cow_file_range_inline(inode, start, end, 0,
1011 BTRFS_COMPRESS_NONE, NULL);
1014 * We use DO_ACCOUNTING here because we need the
1015 * delalloc_release_metadata to be run _after_ we drop
1016 * our outstanding extent for clearing delalloc for this
1019 extent_clear_unlock_delalloc(inode, start, end, NULL,
1020 EXTENT_LOCKED | EXTENT_DELALLOC |
1021 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1022 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1023 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1024 PAGE_END_WRITEBACK);
1025 *nr_written = *nr_written +
1026 (end - start + PAGE_SIZE) / PAGE_SIZE;
1029 } else if (ret < 0) {
1034 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1035 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1038 * Relocation relies on the relocated extents to have exactly the same
1039 * size as the original extents. Normally writeback for relocation data
1040 * extents follows a NOCOW path because relocation preallocates the
1041 * extents. However, due to an operation such as scrub turning a block
1042 * group to RO mode, it may fallback to COW mode, so we must make sure
1043 * an extent allocated during COW has exactly the requested size and can
1044 * not be split into smaller extents, otherwise relocation breaks and
1045 * fails during the stage where it updates the bytenr of file extent
1048 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1049 min_alloc_size = num_bytes;
1051 min_alloc_size = fs_info->sectorsize;
1053 while (num_bytes > 0) {
1054 cur_alloc_size = num_bytes;
1055 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1056 min_alloc_size, 0, alloc_hint,
1060 cur_alloc_size = ins.offset;
1061 extent_reserved = true;
1063 ram_size = ins.offset;
1064 em = create_io_em(inode, start, ins.offset, /* len */
1065 start, /* orig_start */
1066 ins.objectid, /* block_start */
1067 ins.offset, /* block_len */
1068 ins.offset, /* orig_block_len */
1069 ram_size, /* ram_bytes */
1070 BTRFS_COMPRESS_NONE, /* compress_type */
1071 BTRFS_ORDERED_REGULAR /* type */);
1076 free_extent_map(em);
1078 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1079 ram_size, cur_alloc_size, 0);
1081 goto out_drop_extent_cache;
1083 if (root->root_key.objectid ==
1084 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1085 ret = btrfs_reloc_clone_csums(inode, start,
1088 * Only drop cache here, and process as normal.
1090 * We must not allow extent_clear_unlock_delalloc()
1091 * at out_unlock label to free meta of this ordered
1092 * extent, as its meta should be freed by
1093 * btrfs_finish_ordered_io().
1095 * So we must continue until @start is increased to
1096 * skip current ordered extent.
1099 btrfs_drop_extent_cache(inode, start,
1100 start + ram_size - 1, 0);
1103 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1105 /* we're not doing compressed IO, don't unlock the first
1106 * page (which the caller expects to stay locked), don't
1107 * clear any dirty bits and don't set any writeback bits
1109 * Do set the Private2 bit so we know this page was properly
1110 * setup for writepage
1112 page_ops = unlock ? PAGE_UNLOCK : 0;
1113 page_ops |= PAGE_SET_PRIVATE2;
1115 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1117 EXTENT_LOCKED | EXTENT_DELALLOC,
1119 if (num_bytes < cur_alloc_size)
1122 num_bytes -= cur_alloc_size;
1123 alloc_hint = ins.objectid + ins.offset;
1124 start += cur_alloc_size;
1125 extent_reserved = false;
1128 * btrfs_reloc_clone_csums() error, since start is increased
1129 * extent_clear_unlock_delalloc() at out_unlock label won't
1130 * free metadata of current ordered extent, we're OK to exit.
1138 out_drop_extent_cache:
1139 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1141 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1142 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1144 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1145 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1146 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1149 * If we reserved an extent for our delalloc range (or a subrange) and
1150 * failed to create the respective ordered extent, then it means that
1151 * when we reserved the extent we decremented the extent's size from
1152 * the data space_info's bytes_may_use counter and incremented the
1153 * space_info's bytes_reserved counter by the same amount. We must make
1154 * sure extent_clear_unlock_delalloc() does not try to decrement again
1155 * the data space_info's bytes_may_use counter, therefore we do not pass
1156 * it the flag EXTENT_CLEAR_DATA_RESV.
1158 if (extent_reserved) {
1159 extent_clear_unlock_delalloc(inode, start,
1160 start + cur_alloc_size - 1,
1164 start += cur_alloc_size;
1168 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1169 clear_bits | EXTENT_CLEAR_DATA_RESV,
1175 * work queue call back to started compression on a file and pages
1177 static noinline void async_cow_start(struct btrfs_work *work)
1179 struct async_chunk *async_chunk;
1180 int compressed_extents;
1182 async_chunk = container_of(work, struct async_chunk, work);
1184 compressed_extents = compress_file_range(async_chunk);
1185 if (compressed_extents == 0) {
1186 btrfs_add_delayed_iput(async_chunk->inode);
1187 async_chunk->inode = NULL;
1192 * work queue call back to submit previously compressed pages
1194 static noinline void async_cow_submit(struct btrfs_work *work)
1196 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1198 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1199 unsigned long nr_pages;
1201 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1205 * ->inode could be NULL if async_chunk_start has failed to compress,
1206 * in which case we don't have anything to submit, yet we need to
1207 * always adjust ->async_delalloc_pages as its paired with the init
1208 * happening in cow_file_range_async
1210 if (async_chunk->inode)
1211 submit_compressed_extents(async_chunk);
1213 /* atomic_sub_return implies a barrier */
1214 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1216 cond_wake_up_nomb(&fs_info->async_submit_wait);
1219 static noinline void async_cow_free(struct btrfs_work *work)
1221 struct async_chunk *async_chunk;
1223 async_chunk = container_of(work, struct async_chunk, work);
1224 if (async_chunk->inode)
1225 btrfs_add_delayed_iput(async_chunk->inode);
1226 if (async_chunk->blkcg_css)
1227 css_put(async_chunk->blkcg_css);
1229 * Since the pointer to 'pending' is at the beginning of the array of
1230 * async_chunk's, freeing it ensures the whole array has been freed.
1232 if (atomic_dec_and_test(async_chunk->pending))
1233 kvfree(async_chunk->pending);
1236 static int cow_file_range_async(struct btrfs_inode *inode,
1237 struct writeback_control *wbc,
1238 struct page *locked_page,
1239 u64 start, u64 end, int *page_started,
1240 unsigned long *nr_written)
1242 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1243 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1244 struct async_cow *ctx;
1245 struct async_chunk *async_chunk;
1246 unsigned long nr_pages;
1248 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1250 bool should_compress;
1252 const unsigned int write_flags = wbc_to_write_flags(wbc);
1254 unlock_extent(&inode->io_tree, start, end);
1256 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1257 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1259 should_compress = false;
1261 should_compress = true;
1264 nofs_flag = memalloc_nofs_save();
1265 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1266 memalloc_nofs_restore(nofs_flag);
1269 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1270 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1271 EXTENT_DO_ACCOUNTING;
1272 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1273 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1276 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1277 clear_bits, page_ops);
1281 async_chunk = ctx->chunks;
1282 atomic_set(&ctx->num_chunks, num_chunks);
1284 for (i = 0; i < num_chunks; i++) {
1285 if (should_compress)
1286 cur_end = min(end, start + SZ_512K - 1);
1291 * igrab is called higher up in the call chain, take only the
1292 * lightweight reference for the callback lifetime
1294 ihold(&inode->vfs_inode);
1295 async_chunk[i].pending = &ctx->num_chunks;
1296 async_chunk[i].inode = &inode->vfs_inode;
1297 async_chunk[i].start = start;
1298 async_chunk[i].end = cur_end;
1299 async_chunk[i].write_flags = write_flags;
1300 INIT_LIST_HEAD(&async_chunk[i].extents);
1303 * The locked_page comes all the way from writepage and its
1304 * the original page we were actually given. As we spread
1305 * this large delalloc region across multiple async_chunk
1306 * structs, only the first struct needs a pointer to locked_page
1308 * This way we don't need racey decisions about who is supposed
1313 * Depending on the compressibility, the pages might or
1314 * might not go through async. We want all of them to
1315 * be accounted against wbc once. Let's do it here
1316 * before the paths diverge. wbc accounting is used
1317 * only for foreign writeback detection and doesn't
1318 * need full accuracy. Just account the whole thing
1319 * against the first page.
1321 wbc_account_cgroup_owner(wbc, locked_page,
1323 async_chunk[i].locked_page = locked_page;
1326 async_chunk[i].locked_page = NULL;
1329 if (blkcg_css != blkcg_root_css) {
1331 async_chunk[i].blkcg_css = blkcg_css;
1333 async_chunk[i].blkcg_css = NULL;
1336 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1337 async_cow_submit, async_cow_free);
1339 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1340 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1342 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1344 *nr_written += nr_pages;
1345 start = cur_end + 1;
1351 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1352 u64 bytenr, u64 num_bytes)
1355 struct btrfs_ordered_sum *sums;
1358 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1359 bytenr + num_bytes - 1, &list, 0);
1360 if (ret == 0 && list_empty(&list))
1363 while (!list_empty(&list)) {
1364 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1365 list_del(&sums->list);
1373 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1374 const u64 start, const u64 end,
1375 int *page_started, unsigned long *nr_written)
1377 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1378 const bool is_reloc_ino = (inode->root->root_key.objectid ==
1379 BTRFS_DATA_RELOC_TREE_OBJECTID);
1380 const u64 range_bytes = end + 1 - start;
1381 struct extent_io_tree *io_tree = &inode->io_tree;
1382 u64 range_start = start;
1386 * If EXTENT_NORESERVE is set it means that when the buffered write was
1387 * made we had not enough available data space and therefore we did not
1388 * reserve data space for it, since we though we could do NOCOW for the
1389 * respective file range (either there is prealloc extent or the inode
1390 * has the NOCOW bit set).
1392 * However when we need to fallback to COW mode (because for example the
1393 * block group for the corresponding extent was turned to RO mode by a
1394 * scrub or relocation) we need to do the following:
1396 * 1) We increment the bytes_may_use counter of the data space info.
1397 * If COW succeeds, it allocates a new data extent and after doing
1398 * that it decrements the space info's bytes_may_use counter and
1399 * increments its bytes_reserved counter by the same amount (we do
1400 * this at btrfs_add_reserved_bytes()). So we need to increment the
1401 * bytes_may_use counter to compensate (when space is reserved at
1402 * buffered write time, the bytes_may_use counter is incremented);
1404 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1405 * that if the COW path fails for any reason, it decrements (through
1406 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1407 * data space info, which we incremented in the step above.
1409 * If we need to fallback to cow and the inode corresponds to a free
1410 * space cache inode or an inode of the data relocation tree, we must
1411 * also increment bytes_may_use of the data space_info for the same
1412 * reason. Space caches and relocated data extents always get a prealloc
1413 * extent for them, however scrub or balance may have set the block
1414 * group that contains that extent to RO mode and therefore force COW
1415 * when starting writeback.
1417 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1418 EXTENT_NORESERVE, 0);
1419 if (count > 0 || is_space_ino || is_reloc_ino) {
1421 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1422 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1424 if (is_space_ino || is_reloc_ino)
1425 bytes = range_bytes;
1427 spin_lock(&sinfo->lock);
1428 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1429 spin_unlock(&sinfo->lock);
1432 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1436 return cow_file_range(inode, locked_page, start, end, page_started,
1441 * when nowcow writeback call back. This checks for snapshots or COW copies
1442 * of the extents that exist in the file, and COWs the file as required.
1444 * If no cow copies or snapshots exist, we write directly to the existing
1447 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1448 struct page *locked_page,
1449 const u64 start, const u64 end,
1450 int *page_started, int force,
1451 unsigned long *nr_written)
1453 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1454 struct btrfs_root *root = inode->root;
1455 struct btrfs_path *path;
1456 u64 cow_start = (u64)-1;
1457 u64 cur_offset = start;
1459 bool check_prev = true;
1460 const bool freespace_inode = btrfs_is_free_space_inode(inode);
1461 u64 ino = btrfs_ino(inode);
1463 u64 disk_bytenr = 0;
1465 path = btrfs_alloc_path();
1467 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1468 EXTENT_LOCKED | EXTENT_DELALLOC |
1469 EXTENT_DO_ACCOUNTING |
1470 EXTENT_DEFRAG, PAGE_UNLOCK |
1472 PAGE_SET_WRITEBACK |
1473 PAGE_END_WRITEBACK);
1478 struct btrfs_key found_key;
1479 struct btrfs_file_extent_item *fi;
1480 struct extent_buffer *leaf;
1490 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1496 * If there is no extent for our range when doing the initial
1497 * search, then go back to the previous slot as it will be the
1498 * one containing the search offset
1500 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1501 leaf = path->nodes[0];
1502 btrfs_item_key_to_cpu(leaf, &found_key,
1503 path->slots[0] - 1);
1504 if (found_key.objectid == ino &&
1505 found_key.type == BTRFS_EXTENT_DATA_KEY)
1510 /* Go to next leaf if we have exhausted the current one */
1511 leaf = path->nodes[0];
1512 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1513 ret = btrfs_next_leaf(root, path);
1515 if (cow_start != (u64)-1)
1516 cur_offset = cow_start;
1521 leaf = path->nodes[0];
1524 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1526 /* Didn't find anything for our INO */
1527 if (found_key.objectid > ino)
1530 * Keep searching until we find an EXTENT_ITEM or there are no
1531 * more extents for this inode
1533 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1534 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1539 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1540 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1541 found_key.offset > end)
1545 * If the found extent starts after requested offset, then
1546 * adjust extent_end to be right before this extent begins
1548 if (found_key.offset > cur_offset) {
1549 extent_end = found_key.offset;
1555 * Found extent which begins before our range and potentially
1558 fi = btrfs_item_ptr(leaf, path->slots[0],
1559 struct btrfs_file_extent_item);
1560 extent_type = btrfs_file_extent_type(leaf, fi);
1562 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1563 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1564 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1565 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1566 extent_offset = btrfs_file_extent_offset(leaf, fi);
1567 extent_end = found_key.offset +
1568 btrfs_file_extent_num_bytes(leaf, fi);
1570 btrfs_file_extent_disk_num_bytes(leaf, fi);
1572 * If the extent we got ends before our current offset,
1573 * skip to the next extent.
1575 if (extent_end <= cur_offset) {
1580 if (disk_bytenr == 0)
1582 /* Skip compressed/encrypted/encoded extents */
1583 if (btrfs_file_extent_compression(leaf, fi) ||
1584 btrfs_file_extent_encryption(leaf, fi) ||
1585 btrfs_file_extent_other_encoding(leaf, fi))
1588 * If extent is created before the last volume's snapshot
1589 * this implies the extent is shared, hence we can't do
1590 * nocow. This is the same check as in
1591 * btrfs_cross_ref_exist but without calling
1592 * btrfs_search_slot.
1594 if (!freespace_inode &&
1595 btrfs_file_extent_generation(leaf, fi) <=
1596 btrfs_root_last_snapshot(&root->root_item))
1598 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1600 /* If extent is RO, we must COW it */
1601 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1603 ret = btrfs_cross_ref_exist(root, ino,
1605 extent_offset, disk_bytenr, false);
1608 * ret could be -EIO if the above fails to read
1612 if (cow_start != (u64)-1)
1613 cur_offset = cow_start;
1617 WARN_ON_ONCE(freespace_inode);
1620 disk_bytenr += extent_offset;
1621 disk_bytenr += cur_offset - found_key.offset;
1622 num_bytes = min(end + 1, extent_end) - cur_offset;
1624 * If there are pending snapshots for this root, we
1625 * fall into common COW way
1627 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1630 * force cow if csum exists in the range.
1631 * this ensure that csum for a given extent are
1632 * either valid or do not exist.
1634 ret = csum_exist_in_range(fs_info, disk_bytenr,
1638 * ret could be -EIO if the above fails to read
1642 if (cow_start != (u64)-1)
1643 cur_offset = cow_start;
1646 WARN_ON_ONCE(freespace_inode);
1649 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1652 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1653 extent_end = found_key.offset + ram_bytes;
1654 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1655 /* Skip extents outside of our requested range */
1656 if (extent_end <= start) {
1661 /* If this triggers then we have a memory corruption */
1666 * If nocow is false then record the beginning of the range
1667 * that needs to be COWed
1670 if (cow_start == (u64)-1)
1671 cow_start = cur_offset;
1672 cur_offset = extent_end;
1673 if (cur_offset > end)
1679 btrfs_release_path(path);
1682 * COW range from cow_start to found_key.offset - 1. As the key
1683 * will contain the beginning of the first extent that can be
1684 * NOCOW, following one which needs to be COW'ed
1686 if (cow_start != (u64)-1) {
1687 ret = fallback_to_cow(inode, locked_page,
1688 cow_start, found_key.offset - 1,
1689 page_started, nr_written);
1692 cow_start = (u64)-1;
1695 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1696 u64 orig_start = found_key.offset - extent_offset;
1697 struct extent_map *em;
1699 em = create_io_em(inode, cur_offset, num_bytes,
1701 disk_bytenr, /* block_start */
1702 num_bytes, /* block_len */
1703 disk_num_bytes, /* orig_block_len */
1704 ram_bytes, BTRFS_COMPRESS_NONE,
1705 BTRFS_ORDERED_PREALLOC);
1710 free_extent_map(em);
1711 ret = btrfs_add_ordered_extent(inode, cur_offset,
1712 disk_bytenr, num_bytes,
1714 BTRFS_ORDERED_PREALLOC);
1716 btrfs_drop_extent_cache(inode, cur_offset,
1717 cur_offset + num_bytes - 1,
1722 ret = btrfs_add_ordered_extent(inode, cur_offset,
1723 disk_bytenr, num_bytes,
1725 BTRFS_ORDERED_NOCOW);
1731 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1734 if (root->root_key.objectid ==
1735 BTRFS_DATA_RELOC_TREE_OBJECTID)
1737 * Error handled later, as we must prevent
1738 * extent_clear_unlock_delalloc() in error handler
1739 * from freeing metadata of created ordered extent.
1741 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1744 extent_clear_unlock_delalloc(inode, cur_offset,
1745 cur_offset + num_bytes - 1,
1746 locked_page, EXTENT_LOCKED |
1748 EXTENT_CLEAR_DATA_RESV,
1749 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1751 cur_offset = extent_end;
1754 * btrfs_reloc_clone_csums() error, now we're OK to call error
1755 * handler, as metadata for created ordered extent will only
1756 * be freed by btrfs_finish_ordered_io().
1760 if (cur_offset > end)
1763 btrfs_release_path(path);
1765 if (cur_offset <= end && cow_start == (u64)-1)
1766 cow_start = cur_offset;
1768 if (cow_start != (u64)-1) {
1770 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1771 page_started, nr_written);
1778 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1780 if (ret && cur_offset < end)
1781 extent_clear_unlock_delalloc(inode, cur_offset, end,
1782 locked_page, EXTENT_LOCKED |
1783 EXTENT_DELALLOC | EXTENT_DEFRAG |
1784 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1786 PAGE_SET_WRITEBACK |
1787 PAGE_END_WRITEBACK);
1788 btrfs_free_path(path);
1792 static inline int need_force_cow(struct btrfs_inode *inode, u64 start, u64 end)
1795 if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1796 !(inode->flags & BTRFS_INODE_PREALLOC))
1800 * @defrag_bytes is a hint value, no spinlock held here,
1801 * if is not zero, it means the file is defragging.
1802 * Force cow if given extent needs to be defragged.
1804 if (inode->defrag_bytes &&
1805 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG, 0, NULL))
1812 * Function to process delayed allocation (create CoW) for ranges which are
1813 * being touched for the first time.
1815 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1816 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1817 struct writeback_control *wbc)
1820 int force_cow = need_force_cow(inode, start, end);
1822 if (inode->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1823 ret = run_delalloc_nocow(inode, locked_page, start, end,
1824 page_started, 1, nr_written);
1825 } else if (inode->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1826 ret = run_delalloc_nocow(inode, locked_page, start, end,
1827 page_started, 0, nr_written);
1828 } else if (!inode_can_compress(inode) ||
1829 !inode_need_compress(inode, start, end)) {
1830 ret = cow_file_range(inode, locked_page, start, end,
1831 page_started, nr_written, 1);
1833 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1834 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1835 page_started, nr_written);
1838 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1843 void btrfs_split_delalloc_extent(struct inode *inode,
1844 struct extent_state *orig, u64 split)
1848 /* not delalloc, ignore it */
1849 if (!(orig->state & EXTENT_DELALLOC))
1852 size = orig->end - orig->start + 1;
1853 if (size > BTRFS_MAX_EXTENT_SIZE) {
1858 * See the explanation in btrfs_merge_delalloc_extent, the same
1859 * applies here, just in reverse.
1861 new_size = orig->end - split + 1;
1862 num_extents = count_max_extents(new_size);
1863 new_size = split - orig->start;
1864 num_extents += count_max_extents(new_size);
1865 if (count_max_extents(size) >= num_extents)
1869 spin_lock(&BTRFS_I(inode)->lock);
1870 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1871 spin_unlock(&BTRFS_I(inode)->lock);
1875 * Handle merged delayed allocation extents so we can keep track of new extents
1876 * that are just merged onto old extents, such as when we are doing sequential
1877 * writes, so we can properly account for the metadata space we'll need.
1879 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1880 struct extent_state *other)
1882 u64 new_size, old_size;
1885 /* not delalloc, ignore it */
1886 if (!(other->state & EXTENT_DELALLOC))
1889 if (new->start > other->start)
1890 new_size = new->end - other->start + 1;
1892 new_size = other->end - new->start + 1;
1894 /* we're not bigger than the max, unreserve the space and go */
1895 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1896 spin_lock(&BTRFS_I(inode)->lock);
1897 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1898 spin_unlock(&BTRFS_I(inode)->lock);
1903 * We have to add up either side to figure out how many extents were
1904 * accounted for before we merged into one big extent. If the number of
1905 * extents we accounted for is <= the amount we need for the new range
1906 * then we can return, otherwise drop. Think of it like this
1910 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1911 * need 2 outstanding extents, on one side we have 1 and the other side
1912 * we have 1 so they are == and we can return. But in this case
1914 * [MAX_SIZE+4k][MAX_SIZE+4k]
1916 * Each range on their own accounts for 2 extents, but merged together
1917 * they are only 3 extents worth of accounting, so we need to drop in
1920 old_size = other->end - other->start + 1;
1921 num_extents = count_max_extents(old_size);
1922 old_size = new->end - new->start + 1;
1923 num_extents += count_max_extents(old_size);
1924 if (count_max_extents(new_size) >= num_extents)
1927 spin_lock(&BTRFS_I(inode)->lock);
1928 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1929 spin_unlock(&BTRFS_I(inode)->lock);
1932 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1933 struct inode *inode)
1935 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1937 spin_lock(&root->delalloc_lock);
1938 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1939 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1940 &root->delalloc_inodes);
1941 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1942 &BTRFS_I(inode)->runtime_flags);
1943 root->nr_delalloc_inodes++;
1944 if (root->nr_delalloc_inodes == 1) {
1945 spin_lock(&fs_info->delalloc_root_lock);
1946 BUG_ON(!list_empty(&root->delalloc_root));
1947 list_add_tail(&root->delalloc_root,
1948 &fs_info->delalloc_roots);
1949 spin_unlock(&fs_info->delalloc_root_lock);
1952 spin_unlock(&root->delalloc_lock);
1956 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1957 struct btrfs_inode *inode)
1959 struct btrfs_fs_info *fs_info = root->fs_info;
1961 if (!list_empty(&inode->delalloc_inodes)) {
1962 list_del_init(&inode->delalloc_inodes);
1963 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1964 &inode->runtime_flags);
1965 root->nr_delalloc_inodes--;
1966 if (!root->nr_delalloc_inodes) {
1967 ASSERT(list_empty(&root->delalloc_inodes));
1968 spin_lock(&fs_info->delalloc_root_lock);
1969 BUG_ON(list_empty(&root->delalloc_root));
1970 list_del_init(&root->delalloc_root);
1971 spin_unlock(&fs_info->delalloc_root_lock);
1976 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1977 struct btrfs_inode *inode)
1979 spin_lock(&root->delalloc_lock);
1980 __btrfs_del_delalloc_inode(root, inode);
1981 spin_unlock(&root->delalloc_lock);
1985 * Properly track delayed allocation bytes in the inode and to maintain the
1986 * list of inodes that have pending delalloc work to be done.
1988 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1991 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1993 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1996 * set_bit and clear bit hooks normally require _irqsave/restore
1997 * but in this case, we are only testing for the DELALLOC
1998 * bit, which is only set or cleared with irqs on
2000 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2001 struct btrfs_root *root = BTRFS_I(inode)->root;
2002 u64 len = state->end + 1 - state->start;
2003 u32 num_extents = count_max_extents(len);
2004 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2006 spin_lock(&BTRFS_I(inode)->lock);
2007 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2008 spin_unlock(&BTRFS_I(inode)->lock);
2010 /* For sanity tests */
2011 if (btrfs_is_testing(fs_info))
2014 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2015 fs_info->delalloc_batch);
2016 spin_lock(&BTRFS_I(inode)->lock);
2017 BTRFS_I(inode)->delalloc_bytes += len;
2018 if (*bits & EXTENT_DEFRAG)
2019 BTRFS_I(inode)->defrag_bytes += len;
2020 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2021 &BTRFS_I(inode)->runtime_flags))
2022 btrfs_add_delalloc_inodes(root, inode);
2023 spin_unlock(&BTRFS_I(inode)->lock);
2026 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2027 (*bits & EXTENT_DELALLOC_NEW)) {
2028 spin_lock(&BTRFS_I(inode)->lock);
2029 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2031 spin_unlock(&BTRFS_I(inode)->lock);
2036 * Once a range is no longer delalloc this function ensures that proper
2037 * accounting happens.
2039 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2040 struct extent_state *state, unsigned *bits)
2042 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2043 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2044 u64 len = state->end + 1 - state->start;
2045 u32 num_extents = count_max_extents(len);
2047 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2048 spin_lock(&inode->lock);
2049 inode->defrag_bytes -= len;
2050 spin_unlock(&inode->lock);
2054 * set_bit and clear bit hooks normally require _irqsave/restore
2055 * but in this case, we are only testing for the DELALLOC
2056 * bit, which is only set or cleared with irqs on
2058 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2059 struct btrfs_root *root = inode->root;
2060 bool do_list = !btrfs_is_free_space_inode(inode);
2062 spin_lock(&inode->lock);
2063 btrfs_mod_outstanding_extents(inode, -num_extents);
2064 spin_unlock(&inode->lock);
2067 * We don't reserve metadata space for space cache inodes so we
2068 * don't need to call delalloc_release_metadata if there is an
2071 if (*bits & EXTENT_CLEAR_META_RESV &&
2072 root != fs_info->tree_root)
2073 btrfs_delalloc_release_metadata(inode, len, true);
2075 /* For sanity tests. */
2076 if (btrfs_is_testing(fs_info))
2079 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2080 do_list && !(state->state & EXTENT_NORESERVE) &&
2081 (*bits & EXTENT_CLEAR_DATA_RESV))
2082 btrfs_free_reserved_data_space_noquota(fs_info, len);
2084 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2085 fs_info->delalloc_batch);
2086 spin_lock(&inode->lock);
2087 inode->delalloc_bytes -= len;
2088 if (do_list && inode->delalloc_bytes == 0 &&
2089 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2090 &inode->runtime_flags))
2091 btrfs_del_delalloc_inode(root, inode);
2092 spin_unlock(&inode->lock);
2095 if ((state->state & EXTENT_DELALLOC_NEW) &&
2096 (*bits & EXTENT_DELALLOC_NEW)) {
2097 spin_lock(&inode->lock);
2098 ASSERT(inode->new_delalloc_bytes >= len);
2099 inode->new_delalloc_bytes -= len;
2100 spin_unlock(&inode->lock);
2105 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2106 * in a chunk's stripe. This function ensures that bios do not span a
2109 * @page - The page we are about to add to the bio
2110 * @size - size we want to add to the bio
2111 * @bio - bio we want to ensure is smaller than a stripe
2112 * @bio_flags - flags of the bio
2114 * return 1 if page cannot be added to the bio
2115 * return 0 if page can be added to the bio
2116 * return error otherwise
2118 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2119 unsigned long bio_flags)
2121 struct inode *inode = page->mapping->host;
2122 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2123 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2127 struct btrfs_io_geometry geom;
2129 if (bio_flags & EXTENT_BIO_COMPRESSED)
2132 length = bio->bi_iter.bi_size;
2133 map_length = length;
2134 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2139 if (geom.len < length + size)
2145 * in order to insert checksums into the metadata in large chunks,
2146 * we wait until bio submission time. All the pages in the bio are
2147 * checksummed and sums are attached onto the ordered extent record.
2149 * At IO completion time the cums attached on the ordered extent record
2150 * are inserted into the btree
2152 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
2155 struct inode *inode = private_data;
2157 return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2161 * extent_io.c submission hook. This does the right thing for csum calculation
2162 * on write, or reading the csums from the tree before a read.
2164 * Rules about async/sync submit,
2165 * a) read: sync submit
2167 * b) write without checksum: sync submit
2169 * c) write with checksum:
2170 * c-1) if bio is issued by fsync: sync submit
2171 * (sync_writers != 0)
2173 * c-2) if root is reloc root: sync submit
2174 * (only in case of buffered IO)
2176 * c-3) otherwise: async submit
2178 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2179 int mirror_num, unsigned long bio_flags)
2182 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2183 struct btrfs_root *root = BTRFS_I(inode)->root;
2184 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2185 blk_status_t ret = 0;
2187 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2189 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2191 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2192 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2194 if (bio_op(bio) != REQ_OP_WRITE) {
2195 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2199 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2200 ret = btrfs_submit_compressed_read(inode, bio,
2204 } else if (!skip_sum) {
2205 ret = btrfs_lookup_bio_sums(inode, bio, (u64)-1, NULL);
2210 } else if (async && !skip_sum) {
2211 /* csum items have already been cloned */
2212 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2214 /* we're doing a write, do the async checksumming */
2215 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2216 0, inode, btrfs_submit_bio_start);
2218 } else if (!skip_sum) {
2219 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2225 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2229 bio->bi_status = ret;
2236 * given a list of ordered sums record them in the inode. This happens
2237 * at IO completion time based on sums calculated at bio submission time.
2239 static int add_pending_csums(struct btrfs_trans_handle *trans,
2240 struct list_head *list)
2242 struct btrfs_ordered_sum *sum;
2245 list_for_each_entry(sum, list, list) {
2246 trans->adding_csums = true;
2247 ret = btrfs_csum_file_blocks(trans, trans->fs_info->csum_root, sum);
2248 trans->adding_csums = false;
2255 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2258 struct extent_state **cached_state)
2260 u64 search_start = start;
2261 const u64 end = start + len - 1;
2263 while (search_start < end) {
2264 const u64 search_len = end - search_start + 1;
2265 struct extent_map *em;
2269 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2273 if (em->block_start != EXTENT_MAP_HOLE)
2277 if (em->start < search_start)
2278 em_len -= search_start - em->start;
2279 if (em_len > search_len)
2280 em_len = search_len;
2282 ret = set_extent_bit(&inode->io_tree, search_start,
2283 search_start + em_len - 1,
2284 EXTENT_DELALLOC_NEW,
2285 NULL, cached_state, GFP_NOFS);
2287 search_start = extent_map_end(em);
2288 free_extent_map(em);
2295 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2296 unsigned int extra_bits,
2297 struct extent_state **cached_state)
2299 WARN_ON(PAGE_ALIGNED(end));
2301 if (start >= i_size_read(&inode->vfs_inode) &&
2302 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2304 * There can't be any extents following eof in this case so just
2305 * set the delalloc new bit for the range directly.
2307 extra_bits |= EXTENT_DELALLOC_NEW;
2311 ret = btrfs_find_new_delalloc_bytes(inode, start,
2318 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2322 /* see btrfs_writepage_start_hook for details on why this is required */
2323 struct btrfs_writepage_fixup {
2325 struct inode *inode;
2326 struct btrfs_work work;
2329 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2331 struct btrfs_writepage_fixup *fixup;
2332 struct btrfs_ordered_extent *ordered;
2333 struct extent_state *cached_state = NULL;
2334 struct extent_changeset *data_reserved = NULL;
2336 struct btrfs_inode *inode;
2340 bool free_delalloc_space = true;
2342 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2344 inode = BTRFS_I(fixup->inode);
2345 page_start = page_offset(page);
2346 page_end = page_offset(page) + PAGE_SIZE - 1;
2349 * This is similar to page_mkwrite, we need to reserve the space before
2350 * we take the page lock.
2352 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2358 * Before we queued this fixup, we took a reference on the page.
2359 * page->mapping may go NULL, but it shouldn't be moved to a different
2362 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2364 * Unfortunately this is a little tricky, either
2366 * 1) We got here and our page had already been dealt with and
2367 * we reserved our space, thus ret == 0, so we need to just
2368 * drop our space reservation and bail. This can happen the
2369 * first time we come into the fixup worker, or could happen
2370 * while waiting for the ordered extent.
2371 * 2) Our page was already dealt with, but we happened to get an
2372 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2373 * this case we obviously don't have anything to release, but
2374 * because the page was already dealt with we don't want to
2375 * mark the page with an error, so make sure we're resetting
2376 * ret to 0. This is why we have this check _before_ the ret
2377 * check, because we do not want to have a surprise ENOSPC
2378 * when the page was already properly dealt with.
2381 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2382 btrfs_delalloc_release_space(inode, data_reserved,
2383 page_start, PAGE_SIZE,
2391 * We can't mess with the page state unless it is locked, so now that
2392 * it is locked bail if we failed to make our space reservation.
2397 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2399 /* already ordered? We're done */
2400 if (PagePrivate2(page))
2403 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2405 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2408 btrfs_start_ordered_extent(ordered, 1);
2409 btrfs_put_ordered_extent(ordered);
2413 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2419 * Everything went as planned, we're now the owner of a dirty page with
2420 * delayed allocation bits set and space reserved for our COW
2423 * The page was dirty when we started, nothing should have cleaned it.
2425 BUG_ON(!PageDirty(page));
2426 free_delalloc_space = false;
2428 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2429 if (free_delalloc_space)
2430 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2432 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2437 * We hit ENOSPC or other errors. Update the mapping and page
2438 * to reflect the errors and clean the page.
2440 mapping_set_error(page->mapping, ret);
2441 end_extent_writepage(page, ret, page_start, page_end);
2442 clear_page_dirty_for_io(page);
2445 ClearPageChecked(page);
2449 extent_changeset_free(data_reserved);
2451 * As a precaution, do a delayed iput in case it would be the last iput
2452 * that could need flushing space. Recursing back to fixup worker would
2455 btrfs_add_delayed_iput(&inode->vfs_inode);
2459 * There are a few paths in the higher layers of the kernel that directly
2460 * set the page dirty bit without asking the filesystem if it is a
2461 * good idea. This causes problems because we want to make sure COW
2462 * properly happens and the data=ordered rules are followed.
2464 * In our case any range that doesn't have the ORDERED bit set
2465 * hasn't been properly setup for IO. We kick off an async process
2466 * to fix it up. The async helper will wait for ordered extents, set
2467 * the delalloc bit and make it safe to write the page.
2469 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2471 struct inode *inode = page->mapping->host;
2472 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2473 struct btrfs_writepage_fixup *fixup;
2475 /* this page is properly in the ordered list */
2476 if (TestClearPagePrivate2(page))
2480 * PageChecked is set below when we create a fixup worker for this page,
2481 * don't try to create another one if we're already PageChecked()
2483 * The extent_io writepage code will redirty the page if we send back
2486 if (PageChecked(page))
2489 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2494 * We are already holding a reference to this inode from
2495 * write_cache_pages. We need to hold it because the space reservation
2496 * takes place outside of the page lock, and we can't trust
2497 * page->mapping outside of the page lock.
2500 SetPageChecked(page);
2502 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2504 fixup->inode = inode;
2505 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2510 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2511 struct btrfs_inode *inode, u64 file_pos,
2512 struct btrfs_file_extent_item *stack_fi,
2513 u64 qgroup_reserved)
2515 struct btrfs_root *root = inode->root;
2516 struct btrfs_path *path;
2517 struct extent_buffer *leaf;
2518 struct btrfs_key ins;
2519 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2520 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2521 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2522 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2523 int extent_inserted = 0;
2526 path = btrfs_alloc_path();
2531 * we may be replacing one extent in the tree with another.
2532 * The new extent is pinned in the extent map, and we don't want
2533 * to drop it from the cache until it is completely in the btree.
2535 * So, tell btrfs_drop_extents to leave this extent in the cache.
2536 * the caller is expected to unpin it and allow it to be merged
2539 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2540 file_pos + num_bytes, NULL, 0,
2541 1, sizeof(*stack_fi), &extent_inserted);
2545 if (!extent_inserted) {
2546 ins.objectid = btrfs_ino(inode);
2547 ins.offset = file_pos;
2548 ins.type = BTRFS_EXTENT_DATA_KEY;
2550 path->leave_spinning = 1;
2551 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2556 leaf = path->nodes[0];
2557 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2558 write_extent_buffer(leaf, stack_fi,
2559 btrfs_item_ptr_offset(leaf, path->slots[0]),
2560 sizeof(struct btrfs_file_extent_item));
2562 btrfs_mark_buffer_dirty(leaf);
2563 btrfs_release_path(path);
2565 inode_add_bytes(&inode->vfs_inode, num_bytes);
2567 ins.objectid = disk_bytenr;
2568 ins.offset = disk_num_bytes;
2569 ins.type = BTRFS_EXTENT_ITEM_KEY;
2571 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2575 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2576 file_pos, qgroup_reserved, &ins);
2578 btrfs_free_path(path);
2583 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2586 struct btrfs_block_group *cache;
2588 cache = btrfs_lookup_block_group(fs_info, start);
2591 spin_lock(&cache->lock);
2592 cache->delalloc_bytes -= len;
2593 spin_unlock(&cache->lock);
2595 btrfs_put_block_group(cache);
2598 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2599 struct btrfs_ordered_extent *oe)
2601 struct btrfs_file_extent_item stack_fi;
2604 memset(&stack_fi, 0, sizeof(stack_fi));
2605 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2606 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2607 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2608 oe->disk_num_bytes);
2609 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2610 logical_len = oe->truncated_len;
2612 logical_len = oe->num_bytes;
2613 btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
2614 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
2615 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2616 /* Encryption and other encoding is reserved and all 0 */
2618 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
2619 oe->file_offset, &stack_fi,
2624 * As ordered data IO finishes, this gets called so we can finish
2625 * an ordered extent if the range of bytes in the file it covers are
2628 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2630 struct inode *inode = ordered_extent->inode;
2631 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2632 struct btrfs_root *root = BTRFS_I(inode)->root;
2633 struct btrfs_trans_handle *trans = NULL;
2634 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2635 struct extent_state *cached_state = NULL;
2637 int compress_type = 0;
2639 u64 logical_len = ordered_extent->num_bytes;
2640 bool freespace_inode;
2641 bool truncated = false;
2642 bool range_locked = false;
2643 bool clear_new_delalloc_bytes = false;
2644 bool clear_reserved_extent = true;
2645 unsigned int clear_bits;
2647 start = ordered_extent->file_offset;
2648 end = start + ordered_extent->num_bytes - 1;
2650 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2651 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2652 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2653 clear_new_delalloc_bytes = true;
2655 freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
2657 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2662 btrfs_free_io_failure_record(BTRFS_I(inode), start, end);
2664 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2666 logical_len = ordered_extent->truncated_len;
2667 /* Truncated the entire extent, don't bother adding */
2672 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2673 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2675 btrfs_inode_safe_disk_i_size_write(inode, 0);
2676 if (freespace_inode)
2677 trans = btrfs_join_transaction_spacecache(root);
2679 trans = btrfs_join_transaction(root);
2680 if (IS_ERR(trans)) {
2681 ret = PTR_ERR(trans);
2685 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2686 ret = btrfs_update_inode_fallback(trans, root, inode);
2687 if (ret) /* -ENOMEM or corruption */
2688 btrfs_abort_transaction(trans, ret);
2692 range_locked = true;
2693 lock_extent_bits(io_tree, start, end, &cached_state);
2695 if (freespace_inode)
2696 trans = btrfs_join_transaction_spacecache(root);
2698 trans = btrfs_join_transaction(root);
2699 if (IS_ERR(trans)) {
2700 ret = PTR_ERR(trans);
2705 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2707 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2708 compress_type = ordered_extent->compress_type;
2709 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2710 BUG_ON(compress_type);
2711 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
2712 ordered_extent->file_offset,
2713 ordered_extent->file_offset +
2716 BUG_ON(root == fs_info->tree_root);
2717 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
2719 clear_reserved_extent = false;
2720 btrfs_release_delalloc_bytes(fs_info,
2721 ordered_extent->disk_bytenr,
2722 ordered_extent->disk_num_bytes);
2725 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2726 ordered_extent->file_offset,
2727 ordered_extent->num_bytes, trans->transid);
2729 btrfs_abort_transaction(trans, ret);
2733 ret = add_pending_csums(trans, &ordered_extent->list);
2735 btrfs_abort_transaction(trans, ret);
2739 btrfs_inode_safe_disk_i_size_write(inode, 0);
2740 ret = btrfs_update_inode_fallback(trans, root, inode);
2741 if (ret) { /* -ENOMEM or corruption */
2742 btrfs_abort_transaction(trans, ret);
2747 clear_bits = EXTENT_DEFRAG;
2749 clear_bits |= EXTENT_LOCKED;
2750 if (clear_new_delalloc_bytes)
2751 clear_bits |= EXTENT_DELALLOC_NEW;
2752 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits,
2753 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
2757 btrfs_end_transaction(trans);
2759 if (ret || truncated) {
2760 u64 unwritten_start = start;
2763 * If we failed to finish this ordered extent for any reason we
2764 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
2765 * extent, and mark the inode with the error if it wasn't
2766 * already set. Any error during writeback would have already
2767 * set the mapping error, so we need to set it if we're the ones
2768 * marking this ordered extent as failed.
2770 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
2771 &ordered_extent->flags))
2772 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
2775 unwritten_start += logical_len;
2776 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
2778 /* Drop the cache for the part of the extent we didn't write. */
2779 btrfs_drop_extent_cache(BTRFS_I(inode), unwritten_start, end, 0);
2782 * If the ordered extent had an IOERR or something else went
2783 * wrong we need to return the space for this ordered extent
2784 * back to the allocator. We only free the extent in the
2785 * truncated case if we didn't write out the extent at all.
2787 * If we made it past insert_reserved_file_extent before we
2788 * errored out then we don't need to do this as the accounting
2789 * has already been done.
2791 if ((ret || !logical_len) &&
2792 clear_reserved_extent &&
2793 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2794 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2796 * Discard the range before returning it back to the
2799 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
2800 btrfs_discard_extent(fs_info,
2801 ordered_extent->disk_bytenr,
2802 ordered_extent->disk_num_bytes,
2804 btrfs_free_reserved_extent(fs_info,
2805 ordered_extent->disk_bytenr,
2806 ordered_extent->disk_num_bytes, 1);
2811 * This needs to be done to make sure anybody waiting knows we are done
2812 * updating everything for this ordered extent.
2814 btrfs_remove_ordered_extent(BTRFS_I(inode), ordered_extent);
2817 btrfs_put_ordered_extent(ordered_extent);
2818 /* once for the tree */
2819 btrfs_put_ordered_extent(ordered_extent);
2824 static void finish_ordered_fn(struct btrfs_work *work)
2826 struct btrfs_ordered_extent *ordered_extent;
2827 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2828 btrfs_finish_ordered_io(ordered_extent);
2831 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
2832 u64 end, int uptodate)
2834 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
2835 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2836 struct btrfs_ordered_extent *ordered_extent = NULL;
2837 struct btrfs_workqueue *wq;
2839 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2841 ClearPagePrivate2(page);
2842 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2843 end - start + 1, uptodate))
2846 if (btrfs_is_free_space_inode(inode))
2847 wq = fs_info->endio_freespace_worker;
2849 wq = fs_info->endio_write_workers;
2851 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
2852 btrfs_queue_work(wq, &ordered_extent->work);
2855 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
2856 int icsum, struct page *page, int pgoff, u64 start,
2859 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2860 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
2862 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2864 u8 csum[BTRFS_CSUM_SIZE];
2866 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
2868 kaddr = kmap_atomic(page);
2869 shash->tfm = fs_info->csum_shash;
2871 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
2873 if (memcmp(csum, csum_expected, csum_size))
2876 kunmap_atomic(kaddr);
2879 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2880 io_bio->mirror_num);
2882 btrfs_dev_stat_inc_and_print(io_bio->device,
2883 BTRFS_DEV_STAT_CORRUPTION_ERRS);
2884 memset(kaddr + pgoff, 1, len);
2885 flush_dcache_page(page);
2886 kunmap_atomic(kaddr);
2891 * when reads are done, we need to check csums to verify the data is correct
2892 * if there's a match, we allow the bio to finish. If not, the code in
2893 * extent_io.c will try to find good copies for us.
2895 int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u64 phy_offset,
2896 struct page *page, u64 start, u64 end, int mirror)
2898 size_t offset = start - page_offset(page);
2899 struct inode *inode = page->mapping->host;
2900 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2901 struct btrfs_root *root = BTRFS_I(inode)->root;
2903 if (PageChecked(page)) {
2904 ClearPageChecked(page);
2908 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2911 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2912 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2913 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2917 phy_offset >>= inode->i_sb->s_blocksize_bits;
2918 return check_data_csum(inode, io_bio, phy_offset, page, offset, start,
2919 (size_t)(end - start + 1));
2923 * btrfs_add_delayed_iput - perform a delayed iput on @inode
2925 * @inode: The inode we want to perform iput on
2927 * This function uses the generic vfs_inode::i_count to track whether we should
2928 * just decrement it (in case it's > 1) or if this is the last iput then link
2929 * the inode to the delayed iput machinery. Delayed iputs are processed at
2930 * transaction commit time/superblock commit/cleaner kthread.
2932 void btrfs_add_delayed_iput(struct inode *inode)
2934 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2935 struct btrfs_inode *binode = BTRFS_I(inode);
2937 if (atomic_add_unless(&inode->i_count, -1, 1))
2940 atomic_inc(&fs_info->nr_delayed_iputs);
2941 spin_lock(&fs_info->delayed_iput_lock);
2942 ASSERT(list_empty(&binode->delayed_iput));
2943 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2944 spin_unlock(&fs_info->delayed_iput_lock);
2945 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2946 wake_up_process(fs_info->cleaner_kthread);
2949 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2950 struct btrfs_inode *inode)
2952 list_del_init(&inode->delayed_iput);
2953 spin_unlock(&fs_info->delayed_iput_lock);
2954 iput(&inode->vfs_inode);
2955 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2956 wake_up(&fs_info->delayed_iputs_wait);
2957 spin_lock(&fs_info->delayed_iput_lock);
2960 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2961 struct btrfs_inode *inode)
2963 if (!list_empty(&inode->delayed_iput)) {
2964 spin_lock(&fs_info->delayed_iput_lock);
2965 if (!list_empty(&inode->delayed_iput))
2966 run_delayed_iput_locked(fs_info, inode);
2967 spin_unlock(&fs_info->delayed_iput_lock);
2971 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
2974 spin_lock(&fs_info->delayed_iput_lock);
2975 while (!list_empty(&fs_info->delayed_iputs)) {
2976 struct btrfs_inode *inode;
2978 inode = list_first_entry(&fs_info->delayed_iputs,
2979 struct btrfs_inode, delayed_iput);
2980 run_delayed_iput_locked(fs_info, inode);
2981 cond_resched_lock(&fs_info->delayed_iput_lock);
2983 spin_unlock(&fs_info->delayed_iput_lock);
2987 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2988 * @fs_info - the fs_info for this fs
2989 * @return - EINTR if we were killed, 0 if nothing's pending
2991 * This will wait on any delayed iputs that are currently running with KILLABLE
2992 * set. Once they are all done running we will return, unless we are killed in
2993 * which case we return EINTR. This helps in user operations like fallocate etc
2994 * that might get blocked on the iputs.
2996 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2998 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2999 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3006 * This creates an orphan entry for the given inode in case something goes wrong
3007 * in the middle of an unlink.
3009 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3010 struct btrfs_inode *inode)
3014 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3015 if (ret && ret != -EEXIST) {
3016 btrfs_abort_transaction(trans, ret);
3024 * We have done the delete so we can go ahead and remove the orphan item for
3025 * this particular inode.
3027 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3028 struct btrfs_inode *inode)
3030 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3034 * this cleans up any orphans that may be left on the list from the last use
3037 int btrfs_orphan_cleanup(struct btrfs_root *root)
3039 struct btrfs_fs_info *fs_info = root->fs_info;
3040 struct btrfs_path *path;
3041 struct extent_buffer *leaf;
3042 struct btrfs_key key, found_key;
3043 struct btrfs_trans_handle *trans;
3044 struct inode *inode;
3045 u64 last_objectid = 0;
3046 int ret = 0, nr_unlink = 0;
3048 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3051 path = btrfs_alloc_path();
3056 path->reada = READA_BACK;
3058 key.objectid = BTRFS_ORPHAN_OBJECTID;
3059 key.type = BTRFS_ORPHAN_ITEM_KEY;
3060 key.offset = (u64)-1;
3063 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3068 * if ret == 0 means we found what we were searching for, which
3069 * is weird, but possible, so only screw with path if we didn't
3070 * find the key and see if we have stuff that matches
3074 if (path->slots[0] == 0)
3079 /* pull out the item */
3080 leaf = path->nodes[0];
3081 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3083 /* make sure the item matches what we want */
3084 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3086 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3089 /* release the path since we're done with it */
3090 btrfs_release_path(path);
3093 * this is where we are basically btrfs_lookup, without the
3094 * crossing root thing. we store the inode number in the
3095 * offset of the orphan item.
3098 if (found_key.offset == last_objectid) {
3100 "Error removing orphan entry, stopping orphan cleanup");
3105 last_objectid = found_key.offset;
3107 found_key.objectid = found_key.offset;
3108 found_key.type = BTRFS_INODE_ITEM_KEY;
3109 found_key.offset = 0;
3110 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3111 ret = PTR_ERR_OR_ZERO(inode);
3112 if (ret && ret != -ENOENT)
3115 if (ret == -ENOENT && root == fs_info->tree_root) {
3116 struct btrfs_root *dead_root;
3117 int is_dead_root = 0;
3120 * this is an orphan in the tree root. Currently these
3121 * could come from 2 sources:
3122 * a) a snapshot deletion in progress
3123 * b) a free space cache inode
3124 * We need to distinguish those two, as the snapshot
3125 * orphan must not get deleted.
3126 * find_dead_roots already ran before us, so if this
3127 * is a snapshot deletion, we should find the root
3128 * in the fs_roots radix tree.
3131 spin_lock(&fs_info->fs_roots_radix_lock);
3132 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3133 (unsigned long)found_key.objectid);
3134 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3136 spin_unlock(&fs_info->fs_roots_radix_lock);
3139 /* prevent this orphan from being found again */
3140 key.offset = found_key.objectid - 1;
3147 * If we have an inode with links, there are a couple of
3148 * possibilities. Old kernels (before v3.12) used to create an
3149 * orphan item for truncate indicating that there were possibly
3150 * extent items past i_size that needed to be deleted. In v3.12,
3151 * truncate was changed to update i_size in sync with the extent
3152 * items, but the (useless) orphan item was still created. Since
3153 * v4.18, we don't create the orphan item for truncate at all.
3155 * So, this item could mean that we need to do a truncate, but
3156 * only if this filesystem was last used on a pre-v3.12 kernel
3157 * and was not cleanly unmounted. The odds of that are quite
3158 * slim, and it's a pain to do the truncate now, so just delete
3161 * It's also possible that this orphan item was supposed to be
3162 * deleted but wasn't. The inode number may have been reused,
3163 * but either way, we can delete the orphan item.
3165 if (ret == -ENOENT || inode->i_nlink) {
3168 trans = btrfs_start_transaction(root, 1);
3169 if (IS_ERR(trans)) {
3170 ret = PTR_ERR(trans);
3173 btrfs_debug(fs_info, "auto deleting %Lu",
3174 found_key.objectid);
3175 ret = btrfs_del_orphan_item(trans, root,
3176 found_key.objectid);
3177 btrfs_end_transaction(trans);
3185 /* this will do delete_inode and everything for us */
3188 /* release the path since we're done with it */
3189 btrfs_release_path(path);
3191 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3193 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3194 trans = btrfs_join_transaction(root);
3196 btrfs_end_transaction(trans);
3200 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3204 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3205 btrfs_free_path(path);
3210 * very simple check to peek ahead in the leaf looking for xattrs. If we
3211 * don't find any xattrs, we know there can't be any acls.
3213 * slot is the slot the inode is in, objectid is the objectid of the inode
3215 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3216 int slot, u64 objectid,
3217 int *first_xattr_slot)
3219 u32 nritems = btrfs_header_nritems(leaf);
3220 struct btrfs_key found_key;
3221 static u64 xattr_access = 0;
3222 static u64 xattr_default = 0;
3225 if (!xattr_access) {
3226 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3227 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3228 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3229 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3233 *first_xattr_slot = -1;
3234 while (slot < nritems) {
3235 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3237 /* we found a different objectid, there must not be acls */
3238 if (found_key.objectid != objectid)
3241 /* we found an xattr, assume we've got an acl */
3242 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3243 if (*first_xattr_slot == -1)
3244 *first_xattr_slot = slot;
3245 if (found_key.offset == xattr_access ||
3246 found_key.offset == xattr_default)
3251 * we found a key greater than an xattr key, there can't
3252 * be any acls later on
3254 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3261 * it goes inode, inode backrefs, xattrs, extents,
3262 * so if there are a ton of hard links to an inode there can
3263 * be a lot of backrefs. Don't waste time searching too hard,
3264 * this is just an optimization
3269 /* we hit the end of the leaf before we found an xattr or
3270 * something larger than an xattr. We have to assume the inode
3273 if (*first_xattr_slot == -1)
3274 *first_xattr_slot = slot;
3279 * read an inode from the btree into the in-memory inode
3281 static int btrfs_read_locked_inode(struct inode *inode,
3282 struct btrfs_path *in_path)
3284 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3285 struct btrfs_path *path = in_path;
3286 struct extent_buffer *leaf;
3287 struct btrfs_inode_item *inode_item;
3288 struct btrfs_root *root = BTRFS_I(inode)->root;
3289 struct btrfs_key location;
3294 bool filled = false;
3295 int first_xattr_slot;
3297 ret = btrfs_fill_inode(inode, &rdev);
3302 path = btrfs_alloc_path();
3307 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3309 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3311 if (path != in_path)
3312 btrfs_free_path(path);
3316 leaf = path->nodes[0];
3321 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3322 struct btrfs_inode_item);
3323 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3324 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3325 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3326 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3327 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3328 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3329 round_up(i_size_read(inode), fs_info->sectorsize));
3331 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3332 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3334 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3335 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3337 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3338 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3340 BTRFS_I(inode)->i_otime.tv_sec =
3341 btrfs_timespec_sec(leaf, &inode_item->otime);
3342 BTRFS_I(inode)->i_otime.tv_nsec =
3343 btrfs_timespec_nsec(leaf, &inode_item->otime);
3345 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3346 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3347 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3349 inode_set_iversion_queried(inode,
3350 btrfs_inode_sequence(leaf, inode_item));
3351 inode->i_generation = BTRFS_I(inode)->generation;
3353 rdev = btrfs_inode_rdev(leaf, inode_item);
3355 BTRFS_I(inode)->index_cnt = (u64)-1;
3356 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3360 * If we were modified in the current generation and evicted from memory
3361 * and then re-read we need to do a full sync since we don't have any
3362 * idea about which extents were modified before we were evicted from
3365 * This is required for both inode re-read from disk and delayed inode
3366 * in delayed_nodes_tree.
3368 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3369 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3370 &BTRFS_I(inode)->runtime_flags);
3373 * We don't persist the id of the transaction where an unlink operation
3374 * against the inode was last made. So here we assume the inode might
3375 * have been evicted, and therefore the exact value of last_unlink_trans
3376 * lost, and set it to last_trans to avoid metadata inconsistencies
3377 * between the inode and its parent if the inode is fsync'ed and the log
3378 * replayed. For example, in the scenario:
3381 * ln mydir/foo mydir/bar
3384 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3385 * xfs_io -c fsync mydir/foo
3387 * mount fs, triggers fsync log replay
3389 * We must make sure that when we fsync our inode foo we also log its
3390 * parent inode, otherwise after log replay the parent still has the
3391 * dentry with the "bar" name but our inode foo has a link count of 1
3392 * and doesn't have an inode ref with the name "bar" anymore.
3394 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3395 * but it guarantees correctness at the expense of occasional full
3396 * transaction commits on fsync if our inode is a directory, or if our
3397 * inode is not a directory, logging its parent unnecessarily.
3399 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3402 * Same logic as for last_unlink_trans. We don't persist the generation
3403 * of the last transaction where this inode was used for a reflink
3404 * operation, so after eviction and reloading the inode we must be
3405 * pessimistic and assume the last transaction that modified the inode.
3407 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3410 if (inode->i_nlink != 1 ||
3411 path->slots[0] >= btrfs_header_nritems(leaf))
3414 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3415 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3418 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3419 if (location.type == BTRFS_INODE_REF_KEY) {
3420 struct btrfs_inode_ref *ref;
3422 ref = (struct btrfs_inode_ref *)ptr;
3423 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3424 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3425 struct btrfs_inode_extref *extref;
3427 extref = (struct btrfs_inode_extref *)ptr;
3428 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3433 * try to precache a NULL acl entry for files that don't have
3434 * any xattrs or acls
3436 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3437 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3438 if (first_xattr_slot != -1) {
3439 path->slots[0] = first_xattr_slot;
3440 ret = btrfs_load_inode_props(inode, path);
3443 "error loading props for ino %llu (root %llu): %d",
3444 btrfs_ino(BTRFS_I(inode)),
3445 root->root_key.objectid, ret);
3447 if (path != in_path)
3448 btrfs_free_path(path);
3451 cache_no_acl(inode);
3453 switch (inode->i_mode & S_IFMT) {
3455 inode->i_mapping->a_ops = &btrfs_aops;
3456 inode->i_fop = &btrfs_file_operations;
3457 inode->i_op = &btrfs_file_inode_operations;
3460 inode->i_fop = &btrfs_dir_file_operations;
3461 inode->i_op = &btrfs_dir_inode_operations;
3464 inode->i_op = &btrfs_symlink_inode_operations;
3465 inode_nohighmem(inode);
3466 inode->i_mapping->a_ops = &btrfs_aops;
3469 inode->i_op = &btrfs_special_inode_operations;
3470 init_special_inode(inode, inode->i_mode, rdev);
3474 btrfs_sync_inode_flags_to_i_flags(inode);
3479 * given a leaf and an inode, copy the inode fields into the leaf
3481 static void fill_inode_item(struct btrfs_trans_handle *trans,
3482 struct extent_buffer *leaf,
3483 struct btrfs_inode_item *item,
3484 struct inode *inode)
3486 struct btrfs_map_token token;
3488 btrfs_init_map_token(&token, leaf);
3490 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3491 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3492 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3493 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3494 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3496 btrfs_set_token_timespec_sec(&token, &item->atime,
3497 inode->i_atime.tv_sec);
3498 btrfs_set_token_timespec_nsec(&token, &item->atime,
3499 inode->i_atime.tv_nsec);
3501 btrfs_set_token_timespec_sec(&token, &item->mtime,
3502 inode->i_mtime.tv_sec);
3503 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3504 inode->i_mtime.tv_nsec);
3506 btrfs_set_token_timespec_sec(&token, &item->ctime,
3507 inode->i_ctime.tv_sec);
3508 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3509 inode->i_ctime.tv_nsec);
3511 btrfs_set_token_timespec_sec(&token, &item->otime,
3512 BTRFS_I(inode)->i_otime.tv_sec);
3513 btrfs_set_token_timespec_nsec(&token, &item->otime,
3514 BTRFS_I(inode)->i_otime.tv_nsec);
3516 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3517 btrfs_set_token_inode_generation(&token, item,
3518 BTRFS_I(inode)->generation);
3519 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3520 btrfs_set_token_inode_transid(&token, item, trans->transid);
3521 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3522 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3523 btrfs_set_token_inode_block_group(&token, item, 0);
3527 * copy everything in the in-memory inode into the btree.
3529 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3530 struct btrfs_root *root, struct inode *inode)
3532 struct btrfs_inode_item *inode_item;
3533 struct btrfs_path *path;
3534 struct extent_buffer *leaf;
3537 path = btrfs_alloc_path();
3541 path->leave_spinning = 1;
3542 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3550 leaf = path->nodes[0];
3551 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3552 struct btrfs_inode_item);
3554 fill_inode_item(trans, leaf, inode_item, inode);
3555 btrfs_mark_buffer_dirty(leaf);
3556 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
3559 btrfs_free_path(path);
3564 * copy everything in the in-memory inode into the btree.
3566 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3567 struct btrfs_root *root, struct inode *inode)
3569 struct btrfs_fs_info *fs_info = root->fs_info;
3573 * If the inode is a free space inode, we can deadlock during commit
3574 * if we put it into the delayed code.
3576 * The data relocation inode should also be directly updated
3579 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3580 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3581 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3582 btrfs_update_root_times(trans, root);
3584 ret = btrfs_delayed_update_inode(trans, root, inode);
3586 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
3590 return btrfs_update_inode_item(trans, root, inode);
3593 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3594 struct btrfs_root *root,
3595 struct inode *inode)
3599 ret = btrfs_update_inode(trans, root, inode);
3601 return btrfs_update_inode_item(trans, root, inode);
3606 * unlink helper that gets used here in inode.c and in the tree logging
3607 * recovery code. It remove a link in a directory with a given name, and
3608 * also drops the back refs in the inode to the directory
3610 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3611 struct btrfs_root *root,
3612 struct btrfs_inode *dir,
3613 struct btrfs_inode *inode,
3614 const char *name, int name_len)
3616 struct btrfs_fs_info *fs_info = root->fs_info;
3617 struct btrfs_path *path;
3619 struct btrfs_dir_item *di;
3621 u64 ino = btrfs_ino(inode);
3622 u64 dir_ino = btrfs_ino(dir);
3624 path = btrfs_alloc_path();
3630 path->leave_spinning = 1;
3631 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3632 name, name_len, -1);
3633 if (IS_ERR_OR_NULL(di)) {
3634 ret = di ? PTR_ERR(di) : -ENOENT;
3637 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3640 btrfs_release_path(path);
3643 * If we don't have dir index, we have to get it by looking up
3644 * the inode ref, since we get the inode ref, remove it directly,
3645 * it is unnecessary to do delayed deletion.
3647 * But if we have dir index, needn't search inode ref to get it.
3648 * Since the inode ref is close to the inode item, it is better
3649 * that we delay to delete it, and just do this deletion when
3650 * we update the inode item.
3652 if (inode->dir_index) {
3653 ret = btrfs_delayed_delete_inode_ref(inode);
3655 index = inode->dir_index;
3660 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3664 "failed to delete reference to %.*s, inode %llu parent %llu",
3665 name_len, name, ino, dir_ino);
3666 btrfs_abort_transaction(trans, ret);
3670 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3672 btrfs_abort_transaction(trans, ret);
3676 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3678 if (ret != 0 && ret != -ENOENT) {
3679 btrfs_abort_transaction(trans, ret);
3683 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3688 btrfs_abort_transaction(trans, ret);
3691 * If we have a pending delayed iput we could end up with the final iput
3692 * being run in btrfs-cleaner context. If we have enough of these built
3693 * up we can end up burning a lot of time in btrfs-cleaner without any
3694 * way to throttle the unlinks. Since we're currently holding a ref on
3695 * the inode we can run the delayed iput here without any issues as the
3696 * final iput won't be done until after we drop the ref we're currently
3699 btrfs_run_delayed_iput(fs_info, inode);
3701 btrfs_free_path(path);
3705 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3706 inode_inc_iversion(&inode->vfs_inode);
3707 inode_inc_iversion(&dir->vfs_inode);
3708 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3709 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3710 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3715 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3716 struct btrfs_root *root,
3717 struct btrfs_inode *dir, struct btrfs_inode *inode,
3718 const char *name, int name_len)
3721 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3723 drop_nlink(&inode->vfs_inode);
3724 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3730 * helper to start transaction for unlink and rmdir.
3732 * unlink and rmdir are special in btrfs, they do not always free space, so
3733 * if we cannot make our reservations the normal way try and see if there is
3734 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3735 * allow the unlink to occur.
3737 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3739 struct btrfs_root *root = BTRFS_I(dir)->root;
3742 * 1 for the possible orphan item
3743 * 1 for the dir item
3744 * 1 for the dir index
3745 * 1 for the inode ref
3748 return btrfs_start_transaction_fallback_global_rsv(root, 5);
3751 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3753 struct btrfs_root *root = BTRFS_I(dir)->root;
3754 struct btrfs_trans_handle *trans;
3755 struct inode *inode = d_inode(dentry);
3758 trans = __unlink_start_trans(dir);
3760 return PTR_ERR(trans);
3762 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3765 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3766 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3767 dentry->d_name.len);
3771 if (inode->i_nlink == 0) {
3772 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3778 btrfs_end_transaction(trans);
3779 btrfs_btree_balance_dirty(root->fs_info);
3783 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3784 struct inode *dir, struct dentry *dentry)
3786 struct btrfs_root *root = BTRFS_I(dir)->root;
3787 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3788 struct btrfs_path *path;
3789 struct extent_buffer *leaf;
3790 struct btrfs_dir_item *di;
3791 struct btrfs_key key;
3792 const char *name = dentry->d_name.name;
3793 int name_len = dentry->d_name.len;
3797 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3799 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3800 objectid = inode->root->root_key.objectid;
3801 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3802 objectid = inode->location.objectid;
3808 path = btrfs_alloc_path();
3812 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3813 name, name_len, -1);
3814 if (IS_ERR_OR_NULL(di)) {
3815 ret = di ? PTR_ERR(di) : -ENOENT;
3819 leaf = path->nodes[0];
3820 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3821 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3822 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3824 btrfs_abort_transaction(trans, ret);
3827 btrfs_release_path(path);
3830 * This is a placeholder inode for a subvolume we didn't have a
3831 * reference to at the time of the snapshot creation. In the meantime
3832 * we could have renamed the real subvol link into our snapshot, so
3833 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3834 * Instead simply lookup the dir_index_item for this entry so we can
3835 * remove it. Otherwise we know we have a ref to the root and we can
3836 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3838 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3839 di = btrfs_search_dir_index_item(root, path, dir_ino,
3841 if (IS_ERR_OR_NULL(di)) {
3846 btrfs_abort_transaction(trans, ret);
3850 leaf = path->nodes[0];
3851 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3853 btrfs_release_path(path);
3855 ret = btrfs_del_root_ref(trans, objectid,
3856 root->root_key.objectid, dir_ino,
3857 &index, name, name_len);
3859 btrfs_abort_transaction(trans, ret);
3864 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3866 btrfs_abort_transaction(trans, ret);
3870 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3871 inode_inc_iversion(dir);
3872 dir->i_mtime = dir->i_ctime = current_time(dir);
3873 ret = btrfs_update_inode_fallback(trans, root, dir);
3875 btrfs_abort_transaction(trans, ret);
3877 btrfs_free_path(path);
3882 * Helper to check if the subvolume references other subvolumes or if it's
3885 static noinline int may_destroy_subvol(struct btrfs_root *root)
3887 struct btrfs_fs_info *fs_info = root->fs_info;
3888 struct btrfs_path *path;
3889 struct btrfs_dir_item *di;
3890 struct btrfs_key key;
3894 path = btrfs_alloc_path();
3898 /* Make sure this root isn't set as the default subvol */
3899 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3900 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3901 dir_id, "default", 7, 0);
3902 if (di && !IS_ERR(di)) {
3903 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3904 if (key.objectid == root->root_key.objectid) {
3907 "deleting default subvolume %llu is not allowed",
3911 btrfs_release_path(path);
3914 key.objectid = root->root_key.objectid;
3915 key.type = BTRFS_ROOT_REF_KEY;
3916 key.offset = (u64)-1;
3918 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3924 if (path->slots[0] > 0) {
3926 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3927 if (key.objectid == root->root_key.objectid &&
3928 key.type == BTRFS_ROOT_REF_KEY)
3932 btrfs_free_path(path);
3936 /* Delete all dentries for inodes belonging to the root */
3937 static void btrfs_prune_dentries(struct btrfs_root *root)
3939 struct btrfs_fs_info *fs_info = root->fs_info;
3940 struct rb_node *node;
3941 struct rb_node *prev;
3942 struct btrfs_inode *entry;
3943 struct inode *inode;
3946 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3947 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3949 spin_lock(&root->inode_lock);
3951 node = root->inode_tree.rb_node;
3955 entry = rb_entry(node, struct btrfs_inode, rb_node);
3957 if (objectid < btrfs_ino(entry))
3958 node = node->rb_left;
3959 else if (objectid > btrfs_ino(entry))
3960 node = node->rb_right;
3966 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3967 if (objectid <= btrfs_ino(entry)) {
3971 prev = rb_next(prev);
3975 entry = rb_entry(node, struct btrfs_inode, rb_node);
3976 objectid = btrfs_ino(entry) + 1;
3977 inode = igrab(&entry->vfs_inode);
3979 spin_unlock(&root->inode_lock);
3980 if (atomic_read(&inode->i_count) > 1)
3981 d_prune_aliases(inode);
3983 * btrfs_drop_inode will have it removed from the inode
3984 * cache when its usage count hits zero.
3988 spin_lock(&root->inode_lock);
3992 if (cond_resched_lock(&root->inode_lock))
3995 node = rb_next(node);
3997 spin_unlock(&root->inode_lock);
4000 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4002 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4003 struct btrfs_root *root = BTRFS_I(dir)->root;
4004 struct inode *inode = d_inode(dentry);
4005 struct btrfs_root *dest = BTRFS_I(inode)->root;
4006 struct btrfs_trans_handle *trans;
4007 struct btrfs_block_rsv block_rsv;
4011 down_write(&fs_info->subvol_sem);
4014 * Don't allow to delete a subvolume with send in progress. This is
4015 * inside the inode lock so the error handling that has to drop the bit
4016 * again is not run concurrently.
4018 spin_lock(&dest->root_item_lock);
4019 if (dest->send_in_progress) {
4020 spin_unlock(&dest->root_item_lock);
4022 "attempt to delete subvolume %llu during send",
4023 dest->root_key.objectid);
4027 if (atomic_read(&dest->nr_swapfiles)) {
4028 spin_unlock(&dest->root_item_lock);
4030 "attempt to delete subvolume %llu with active swapfile",
4031 root->root_key.objectid);
4035 root_flags = btrfs_root_flags(&dest->root_item);
4036 btrfs_set_root_flags(&dest->root_item,
4037 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4038 spin_unlock(&dest->root_item_lock);
4040 ret = may_destroy_subvol(dest);
4044 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4046 * One for dir inode,
4047 * two for dir entries,
4048 * two for root ref/backref.
4050 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4054 trans = btrfs_start_transaction(root, 0);
4055 if (IS_ERR(trans)) {
4056 ret = PTR_ERR(trans);
4059 trans->block_rsv = &block_rsv;
4060 trans->bytes_reserved = block_rsv.size;
4062 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4064 ret = btrfs_unlink_subvol(trans, dir, dentry);
4066 btrfs_abort_transaction(trans, ret);
4070 btrfs_record_root_in_trans(trans, dest);
4072 memset(&dest->root_item.drop_progress, 0,
4073 sizeof(dest->root_item.drop_progress));
4074 dest->root_item.drop_level = 0;
4075 btrfs_set_root_refs(&dest->root_item, 0);
4077 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4078 ret = btrfs_insert_orphan_item(trans,
4080 dest->root_key.objectid);
4082 btrfs_abort_transaction(trans, ret);
4087 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4088 BTRFS_UUID_KEY_SUBVOL,
4089 dest->root_key.objectid);
4090 if (ret && ret != -ENOENT) {
4091 btrfs_abort_transaction(trans, ret);
4094 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4095 ret = btrfs_uuid_tree_remove(trans,
4096 dest->root_item.received_uuid,
4097 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4098 dest->root_key.objectid);
4099 if (ret && ret != -ENOENT) {
4100 btrfs_abort_transaction(trans, ret);
4105 free_anon_bdev(dest->anon_dev);
4108 trans->block_rsv = NULL;
4109 trans->bytes_reserved = 0;
4110 ret = btrfs_end_transaction(trans);
4111 inode->i_flags |= S_DEAD;
4113 btrfs_subvolume_release_metadata(root, &block_rsv);
4116 spin_lock(&dest->root_item_lock);
4117 root_flags = btrfs_root_flags(&dest->root_item);
4118 btrfs_set_root_flags(&dest->root_item,
4119 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4120 spin_unlock(&dest->root_item_lock);
4123 up_write(&fs_info->subvol_sem);
4125 d_invalidate(dentry);
4126 btrfs_prune_dentries(dest);
4127 ASSERT(dest->send_in_progress == 0);
4130 if (dest->ino_cache_inode) {
4131 iput(dest->ino_cache_inode);
4132 dest->ino_cache_inode = NULL;
4139 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4141 struct inode *inode = d_inode(dentry);
4143 struct btrfs_root *root = BTRFS_I(dir)->root;
4144 struct btrfs_trans_handle *trans;
4145 u64 last_unlink_trans;
4147 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4149 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4150 return btrfs_delete_subvolume(dir, dentry);
4152 trans = __unlink_start_trans(dir);
4154 return PTR_ERR(trans);
4156 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4157 err = btrfs_unlink_subvol(trans, dir, dentry);
4161 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4165 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4167 /* now the directory is empty */
4168 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4169 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4170 dentry->d_name.len);
4172 btrfs_i_size_write(BTRFS_I(inode), 0);
4174 * Propagate the last_unlink_trans value of the deleted dir to
4175 * its parent directory. This is to prevent an unrecoverable
4176 * log tree in the case we do something like this:
4178 * 2) create snapshot under dir foo
4179 * 3) delete the snapshot
4182 * 6) fsync foo or some file inside foo
4184 if (last_unlink_trans >= trans->transid)
4185 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4188 btrfs_end_transaction(trans);
4189 btrfs_btree_balance_dirty(root->fs_info);
4195 * Return this if we need to call truncate_block for the last bit of the
4198 #define NEED_TRUNCATE_BLOCK 1
4201 * this can truncate away extent items, csum items and directory items.
4202 * It starts at a high offset and removes keys until it can't find
4203 * any higher than new_size
4205 * csum items that cross the new i_size are truncated to the new size
4208 * min_type is the minimum key type to truncate down to. If set to 0, this
4209 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4211 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4212 struct btrfs_root *root,
4213 struct inode *inode,
4214 u64 new_size, u32 min_type)
4216 struct btrfs_fs_info *fs_info = root->fs_info;
4217 struct btrfs_path *path;
4218 struct extent_buffer *leaf;
4219 struct btrfs_file_extent_item *fi;
4220 struct btrfs_key key;
4221 struct btrfs_key found_key;
4222 u64 extent_start = 0;
4223 u64 extent_num_bytes = 0;
4224 u64 extent_offset = 0;
4226 u64 last_size = new_size;
4227 u32 found_type = (u8)-1;
4230 int pending_del_nr = 0;
4231 int pending_del_slot = 0;
4232 int extent_type = -1;
4234 u64 ino = btrfs_ino(BTRFS_I(inode));
4235 u64 bytes_deleted = 0;
4236 bool be_nice = false;
4237 bool should_throttle = false;
4238 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4239 struct extent_state *cached_state = NULL;
4241 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4244 * For non-free space inodes and non-shareable roots, we want to back
4245 * off from time to time. This means all inodes in subvolume roots,
4246 * reloc roots, and data reloc roots.
4248 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4249 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4252 path = btrfs_alloc_path();
4255 path->reada = READA_BACK;
4257 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4258 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4262 * We want to drop from the next block forward in case this
4263 * new size is not block aligned since we will be keeping the
4264 * last block of the extent just the way it is.
4266 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4267 fs_info->sectorsize),
4272 * This function is also used to drop the items in the log tree before
4273 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4274 * it is used to drop the logged items. So we shouldn't kill the delayed
4277 if (min_type == 0 && root == BTRFS_I(inode)->root)
4278 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4281 key.offset = (u64)-1;
4286 * with a 16K leaf size and 128MB extents, you can actually queue
4287 * up a huge file in a single leaf. Most of the time that
4288 * bytes_deleted is > 0, it will be huge by the time we get here
4290 if (be_nice && bytes_deleted > SZ_32M &&
4291 btrfs_should_end_transaction(trans)) {
4296 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4302 /* there are no items in the tree for us to truncate, we're
4305 if (path->slots[0] == 0)
4311 u64 clear_start = 0, clear_len = 0;
4314 leaf = path->nodes[0];
4315 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4316 found_type = found_key.type;
4318 if (found_key.objectid != ino)
4321 if (found_type < min_type)
4324 item_end = found_key.offset;
4325 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4326 fi = btrfs_item_ptr(leaf, path->slots[0],
4327 struct btrfs_file_extent_item);
4328 extent_type = btrfs_file_extent_type(leaf, fi);
4329 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4331 btrfs_file_extent_num_bytes(leaf, fi);
4333 trace_btrfs_truncate_show_fi_regular(
4334 BTRFS_I(inode), leaf, fi,
4336 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4337 item_end += btrfs_file_extent_ram_bytes(leaf,
4340 trace_btrfs_truncate_show_fi_inline(
4341 BTRFS_I(inode), leaf, fi, path->slots[0],
4346 if (found_type > min_type) {
4349 if (item_end < new_size)
4351 if (found_key.offset >= new_size)
4357 /* FIXME, shrink the extent if the ref count is only 1 */
4358 if (found_type != BTRFS_EXTENT_DATA_KEY)
4361 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4364 clear_start = found_key.offset;
4365 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4367 u64 orig_num_bytes =
4368 btrfs_file_extent_num_bytes(leaf, fi);
4369 extent_num_bytes = ALIGN(new_size -
4371 fs_info->sectorsize);
4372 clear_start = ALIGN(new_size, fs_info->sectorsize);
4373 btrfs_set_file_extent_num_bytes(leaf, fi,
4375 num_dec = (orig_num_bytes -
4377 if (test_bit(BTRFS_ROOT_SHAREABLE,
4380 inode_sub_bytes(inode, num_dec);
4381 btrfs_mark_buffer_dirty(leaf);
4384 btrfs_file_extent_disk_num_bytes(leaf,
4386 extent_offset = found_key.offset -
4387 btrfs_file_extent_offset(leaf, fi);
4389 /* FIXME blocksize != 4096 */
4390 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4391 if (extent_start != 0) {
4393 if (test_bit(BTRFS_ROOT_SHAREABLE,
4395 inode_sub_bytes(inode, num_dec);
4398 clear_len = num_dec;
4399 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4401 * we can't truncate inline items that have had
4405 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4406 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4407 btrfs_file_extent_compression(leaf, fi) == 0) {
4408 u32 size = (u32)(new_size - found_key.offset);
4410 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4411 size = btrfs_file_extent_calc_inline_size(size);
4412 btrfs_truncate_item(path, size, 1);
4413 } else if (!del_item) {
4415 * We have to bail so the last_size is set to
4416 * just before this extent.
4418 ret = NEED_TRUNCATE_BLOCK;
4422 * Inline extents are special, we just treat
4423 * them as a full sector worth in the file
4424 * extent tree just for simplicity sake.
4426 clear_len = fs_info->sectorsize;
4429 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4430 inode_sub_bytes(inode, item_end + 1 - new_size);
4434 * We use btrfs_truncate_inode_items() to clean up log trees for
4435 * multiple fsyncs, and in this case we don't want to clear the
4436 * file extent range because it's just the log.
4438 if (root == BTRFS_I(inode)->root) {
4439 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4440 clear_start, clear_len);
4442 btrfs_abort_transaction(trans, ret);
4448 last_size = found_key.offset;
4450 last_size = new_size;
4452 if (!pending_del_nr) {
4453 /* no pending yet, add ourselves */
4454 pending_del_slot = path->slots[0];
4456 } else if (pending_del_nr &&
4457 path->slots[0] + 1 == pending_del_slot) {
4458 /* hop on the pending chunk */
4460 pending_del_slot = path->slots[0];
4467 should_throttle = false;
4470 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4471 struct btrfs_ref ref = { 0 };
4473 bytes_deleted += extent_num_bytes;
4475 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4476 extent_start, extent_num_bytes, 0);
4477 ref.real_root = root->root_key.objectid;
4478 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4479 ino, extent_offset);
4480 ret = btrfs_free_extent(trans, &ref);
4482 btrfs_abort_transaction(trans, ret);
4486 if (btrfs_should_throttle_delayed_refs(trans))
4487 should_throttle = true;
4491 if (found_type == BTRFS_INODE_ITEM_KEY)
4494 if (path->slots[0] == 0 ||
4495 path->slots[0] != pending_del_slot ||
4497 if (pending_del_nr) {
4498 ret = btrfs_del_items(trans, root, path,
4502 btrfs_abort_transaction(trans, ret);
4507 btrfs_release_path(path);
4510 * We can generate a lot of delayed refs, so we need to
4511 * throttle every once and a while and make sure we're
4512 * adding enough space to keep up with the work we are
4513 * generating. Since we hold a transaction here we
4514 * can't flush, and we don't want to FLUSH_LIMIT because
4515 * we could have generated too many delayed refs to
4516 * actually allocate, so just bail if we're short and
4517 * let the normal reservation dance happen higher up.
4519 if (should_throttle) {
4520 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4521 BTRFS_RESERVE_NO_FLUSH);
4533 if (ret >= 0 && pending_del_nr) {
4536 err = btrfs_del_items(trans, root, path, pending_del_slot,
4539 btrfs_abort_transaction(trans, err);
4543 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4544 ASSERT(last_size >= new_size);
4545 if (!ret && last_size > new_size)
4546 last_size = new_size;
4547 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4548 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4549 (u64)-1, &cached_state);
4552 btrfs_free_path(path);
4557 * btrfs_truncate_block - read, zero a chunk and write a block
4558 * @inode - inode that we're zeroing
4559 * @from - the offset to start zeroing
4560 * @len - the length to zero, 0 to zero the entire range respective to the
4562 * @front - zero up to the offset instead of from the offset on
4564 * This will find the block for the "from" offset and cow the block and zero the
4565 * part we want to zero. This is used with truncate and hole punching.
4567 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4570 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4571 struct address_space *mapping = inode->i_mapping;
4572 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4573 struct btrfs_ordered_extent *ordered;
4574 struct extent_state *cached_state = NULL;
4575 struct extent_changeset *data_reserved = NULL;
4577 bool only_release_metadata = false;
4578 u32 blocksize = fs_info->sectorsize;
4579 pgoff_t index = from >> PAGE_SHIFT;
4580 unsigned offset = from & (blocksize - 1);
4582 gfp_t mask = btrfs_alloc_write_mask(mapping);
4583 size_t write_bytes = blocksize;
4588 if (IS_ALIGNED(offset, blocksize) &&
4589 (!len || IS_ALIGNED(len, blocksize)))
4592 block_start = round_down(from, blocksize);
4593 block_end = block_start + blocksize - 1;
4595 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved,
4596 block_start, blocksize);
4598 if (btrfs_check_nocow_lock(BTRFS_I(inode), block_start,
4599 &write_bytes) > 0) {
4600 /* For nocow case, no need to reserve data space */
4601 only_release_metadata = true;
4606 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), blocksize);
4608 if (!only_release_metadata)
4609 btrfs_free_reserved_data_space(BTRFS_I(inode),
4610 data_reserved, block_start, blocksize);
4614 page = find_or_create_page(mapping, index, mask);
4616 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved,
4617 block_start, blocksize, true);
4618 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4623 if (!PageUptodate(page)) {
4624 ret = btrfs_readpage(NULL, page);
4626 if (page->mapping != mapping) {
4631 if (!PageUptodate(page)) {
4636 wait_on_page_writeback(page);
4638 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4639 set_page_extent_mapped(page);
4641 ordered = btrfs_lookup_ordered_extent(BTRFS_I(inode), block_start);
4643 unlock_extent_cached(io_tree, block_start, block_end,
4647 btrfs_start_ordered_extent(ordered, 1);
4648 btrfs_put_ordered_extent(ordered);
4652 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4653 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4654 0, 0, &cached_state);
4656 ret = btrfs_set_extent_delalloc(BTRFS_I(inode), block_start, block_end, 0,
4659 unlock_extent_cached(io_tree, block_start, block_end,
4664 if (offset != blocksize) {
4666 len = blocksize - offset;
4669 memset(kaddr + (block_start - page_offset(page)),
4672 memset(kaddr + (block_start - page_offset(page)) + offset,
4674 flush_dcache_page(page);
4677 ClearPageChecked(page);
4678 set_page_dirty(page);
4679 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4681 if (only_release_metadata)
4682 set_extent_bit(&BTRFS_I(inode)->io_tree, block_start,
4683 block_end, EXTENT_NORESERVE, NULL, NULL,
4688 if (only_release_metadata)
4689 btrfs_delalloc_release_metadata(BTRFS_I(inode),
4692 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved,
4693 block_start, blocksize, true);
4695 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4699 if (only_release_metadata)
4700 btrfs_check_nocow_unlock(BTRFS_I(inode));
4701 extent_changeset_free(data_reserved);
4705 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4706 u64 offset, u64 len)
4708 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4709 struct btrfs_trans_handle *trans;
4713 * Still need to make sure the inode looks like it's been updated so
4714 * that any holes get logged if we fsync.
4716 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4717 BTRFS_I(inode)->last_trans = fs_info->generation;
4718 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4719 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4724 * 1 - for the one we're dropping
4725 * 1 - for the one we're adding
4726 * 1 - for updating the inode.
4728 trans = btrfs_start_transaction(root, 3);
4730 return PTR_ERR(trans);
4732 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4734 btrfs_abort_transaction(trans, ret);
4735 btrfs_end_transaction(trans);
4739 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4740 offset, 0, 0, len, 0, len, 0, 0, 0);
4742 btrfs_abort_transaction(trans, ret);
4744 btrfs_update_inode(trans, root, inode);
4745 btrfs_end_transaction(trans);
4750 * This function puts in dummy file extents for the area we're creating a hole
4751 * for. So if we are truncating this file to a larger size we need to insert
4752 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4753 * the range between oldsize and size
4755 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4757 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4758 struct btrfs_root *root = BTRFS_I(inode)->root;
4759 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4760 struct extent_map *em = NULL;
4761 struct extent_state *cached_state = NULL;
4762 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4763 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4764 u64 block_end = ALIGN(size, fs_info->sectorsize);
4771 * If our size started in the middle of a block we need to zero out the
4772 * rest of the block before we expand the i_size, otherwise we could
4773 * expose stale data.
4775 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4779 if (size <= hole_start)
4782 btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
4783 block_end - 1, &cached_state);
4784 cur_offset = hole_start;
4786 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4787 block_end - cur_offset);
4793 last_byte = min(extent_map_end(em), block_end);
4794 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4795 hole_size = last_byte - cur_offset;
4797 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4798 struct extent_map *hole_em;
4800 err = maybe_insert_hole(root, inode, cur_offset,
4805 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4806 cur_offset, hole_size);
4810 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4811 cur_offset + hole_size - 1, 0);
4812 hole_em = alloc_extent_map();
4814 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4815 &BTRFS_I(inode)->runtime_flags);
4818 hole_em->start = cur_offset;
4819 hole_em->len = hole_size;
4820 hole_em->orig_start = cur_offset;
4822 hole_em->block_start = EXTENT_MAP_HOLE;
4823 hole_em->block_len = 0;
4824 hole_em->orig_block_len = 0;
4825 hole_em->ram_bytes = hole_size;
4826 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4827 hole_em->generation = fs_info->generation;
4830 write_lock(&em_tree->lock);
4831 err = add_extent_mapping(em_tree, hole_em, 1);
4832 write_unlock(&em_tree->lock);
4835 btrfs_drop_extent_cache(BTRFS_I(inode),
4840 free_extent_map(hole_em);
4842 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4843 cur_offset, hole_size);
4848 free_extent_map(em);
4850 cur_offset = last_byte;
4851 if (cur_offset >= block_end)
4854 free_extent_map(em);
4855 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4859 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4861 struct btrfs_root *root = BTRFS_I(inode)->root;
4862 struct btrfs_trans_handle *trans;
4863 loff_t oldsize = i_size_read(inode);
4864 loff_t newsize = attr->ia_size;
4865 int mask = attr->ia_valid;
4869 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4870 * special case where we need to update the times despite not having
4871 * these flags set. For all other operations the VFS set these flags
4872 * explicitly if it wants a timestamp update.
4874 if (newsize != oldsize) {
4875 inode_inc_iversion(inode);
4876 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4877 inode->i_ctime = inode->i_mtime =
4878 current_time(inode);
4881 if (newsize > oldsize) {
4883 * Don't do an expanding truncate while snapshotting is ongoing.
4884 * This is to ensure the snapshot captures a fully consistent
4885 * state of this file - if the snapshot captures this expanding
4886 * truncation, it must capture all writes that happened before
4889 btrfs_drew_write_lock(&root->snapshot_lock);
4890 ret = btrfs_cont_expand(inode, oldsize, newsize);
4892 btrfs_drew_write_unlock(&root->snapshot_lock);
4896 trans = btrfs_start_transaction(root, 1);
4897 if (IS_ERR(trans)) {
4898 btrfs_drew_write_unlock(&root->snapshot_lock);
4899 return PTR_ERR(trans);
4902 i_size_write(inode, newsize);
4903 btrfs_inode_safe_disk_i_size_write(inode, 0);
4904 pagecache_isize_extended(inode, oldsize, newsize);
4905 ret = btrfs_update_inode(trans, root, inode);
4906 btrfs_drew_write_unlock(&root->snapshot_lock);
4907 btrfs_end_transaction(trans);
4911 * We're truncating a file that used to have good data down to
4912 * zero. Make sure any new writes to the file get on disk
4916 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
4917 &BTRFS_I(inode)->runtime_flags);
4919 truncate_setsize(inode, newsize);
4921 inode_dio_wait(inode);
4923 ret = btrfs_truncate(inode, newsize == oldsize);
4924 if (ret && inode->i_nlink) {
4928 * Truncate failed, so fix up the in-memory size. We
4929 * adjusted disk_i_size down as we removed extents, so
4930 * wait for disk_i_size to be stable and then update the
4931 * in-memory size to match.
4933 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4936 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4943 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4945 struct inode *inode = d_inode(dentry);
4946 struct btrfs_root *root = BTRFS_I(inode)->root;
4949 if (btrfs_root_readonly(root))
4952 err = setattr_prepare(dentry, attr);
4956 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4957 err = btrfs_setsize(inode, attr);
4962 if (attr->ia_valid) {
4963 setattr_copy(inode, attr);
4964 inode_inc_iversion(inode);
4965 err = btrfs_dirty_inode(inode);
4967 if (!err && attr->ia_valid & ATTR_MODE)
4968 err = posix_acl_chmod(inode, inode->i_mode);
4975 * While truncating the inode pages during eviction, we get the VFS calling
4976 * btrfs_invalidatepage() against each page of the inode. This is slow because
4977 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4978 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4979 * extent_state structures over and over, wasting lots of time.
4981 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4982 * those expensive operations on a per page basis and do only the ordered io
4983 * finishing, while we release here the extent_map and extent_state structures,
4984 * without the excessive merging and splitting.
4986 static void evict_inode_truncate_pages(struct inode *inode)
4988 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4989 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4990 struct rb_node *node;
4992 ASSERT(inode->i_state & I_FREEING);
4993 truncate_inode_pages_final(&inode->i_data);
4995 write_lock(&map_tree->lock);
4996 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
4997 struct extent_map *em;
4999 node = rb_first_cached(&map_tree->map);
5000 em = rb_entry(node, struct extent_map, rb_node);
5001 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5002 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5003 remove_extent_mapping(map_tree, em);
5004 free_extent_map(em);
5005 if (need_resched()) {
5006 write_unlock(&map_tree->lock);
5008 write_lock(&map_tree->lock);
5011 write_unlock(&map_tree->lock);
5014 * Keep looping until we have no more ranges in the io tree.
5015 * We can have ongoing bios started by readahead that have
5016 * their endio callback (extent_io.c:end_bio_extent_readpage)
5017 * still in progress (unlocked the pages in the bio but did not yet
5018 * unlocked the ranges in the io tree). Therefore this means some
5019 * ranges can still be locked and eviction started because before
5020 * submitting those bios, which are executed by a separate task (work
5021 * queue kthread), inode references (inode->i_count) were not taken
5022 * (which would be dropped in the end io callback of each bio).
5023 * Therefore here we effectively end up waiting for those bios and
5024 * anyone else holding locked ranges without having bumped the inode's
5025 * reference count - if we don't do it, when they access the inode's
5026 * io_tree to unlock a range it may be too late, leading to an
5027 * use-after-free issue.
5029 spin_lock(&io_tree->lock);
5030 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5031 struct extent_state *state;
5032 struct extent_state *cached_state = NULL;
5035 unsigned state_flags;
5037 node = rb_first(&io_tree->state);
5038 state = rb_entry(node, struct extent_state, rb_node);
5039 start = state->start;
5041 state_flags = state->state;
5042 spin_unlock(&io_tree->lock);
5044 lock_extent_bits(io_tree, start, end, &cached_state);
5047 * If still has DELALLOC flag, the extent didn't reach disk,
5048 * and its reserved space won't be freed by delayed_ref.
5049 * So we need to free its reserved space here.
5050 * (Refer to comment in btrfs_invalidatepage, case 2)
5052 * Note, end is the bytenr of last byte, so we need + 1 here.
5054 if (state_flags & EXTENT_DELALLOC)
5055 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5058 clear_extent_bit(io_tree, start, end,
5059 EXTENT_LOCKED | EXTENT_DELALLOC |
5060 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5064 spin_lock(&io_tree->lock);
5066 spin_unlock(&io_tree->lock);
5069 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5070 struct btrfs_block_rsv *rsv)
5072 struct btrfs_fs_info *fs_info = root->fs_info;
5073 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5074 struct btrfs_trans_handle *trans;
5075 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5079 * Eviction should be taking place at some place safe because of our
5080 * delayed iputs. However the normal flushing code will run delayed
5081 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5083 * We reserve the delayed_refs_extra here again because we can't use
5084 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5085 * above. We reserve our extra bit here because we generate a ton of
5086 * delayed refs activity by truncating.
5088 * If we cannot make our reservation we'll attempt to steal from the
5089 * global reserve, because we really want to be able to free up space.
5091 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5092 BTRFS_RESERVE_FLUSH_EVICT);
5095 * Try to steal from the global reserve if there is space for
5098 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5099 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5101 "could not allocate space for delete; will truncate on mount");
5102 return ERR_PTR(-ENOSPC);
5104 delayed_refs_extra = 0;
5107 trans = btrfs_join_transaction(root);
5111 if (delayed_refs_extra) {
5112 trans->block_rsv = &fs_info->trans_block_rsv;
5113 trans->bytes_reserved = delayed_refs_extra;
5114 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5115 delayed_refs_extra, 1);
5120 void btrfs_evict_inode(struct inode *inode)
5122 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5123 struct btrfs_trans_handle *trans;
5124 struct btrfs_root *root = BTRFS_I(inode)->root;
5125 struct btrfs_block_rsv *rsv;
5128 trace_btrfs_inode_evict(inode);
5135 evict_inode_truncate_pages(inode);
5137 if (inode->i_nlink &&
5138 ((btrfs_root_refs(&root->root_item) != 0 &&
5139 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5140 btrfs_is_free_space_inode(BTRFS_I(inode))))
5143 if (is_bad_inode(inode))
5146 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5148 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5151 if (inode->i_nlink > 0) {
5152 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5153 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5157 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5161 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5164 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5167 btrfs_i_size_write(BTRFS_I(inode), 0);
5170 trans = evict_refill_and_join(root, rsv);
5174 trans->block_rsv = rsv;
5176 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5177 trans->block_rsv = &fs_info->trans_block_rsv;
5178 btrfs_end_transaction(trans);
5179 btrfs_btree_balance_dirty(fs_info);
5180 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5187 * Errors here aren't a big deal, it just means we leave orphan items in
5188 * the tree. They will be cleaned up on the next mount. If the inode
5189 * number gets reused, cleanup deletes the orphan item without doing
5190 * anything, and unlink reuses the existing orphan item.
5192 * If it turns out that we are dropping too many of these, we might want
5193 * to add a mechanism for retrying these after a commit.
5195 trans = evict_refill_and_join(root, rsv);
5196 if (!IS_ERR(trans)) {
5197 trans->block_rsv = rsv;
5198 btrfs_orphan_del(trans, BTRFS_I(inode));
5199 trans->block_rsv = &fs_info->trans_block_rsv;
5200 btrfs_end_transaction(trans);
5203 if (!(root == fs_info->tree_root ||
5204 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5205 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5208 btrfs_free_block_rsv(fs_info, rsv);
5211 * If we didn't successfully delete, the orphan item will still be in
5212 * the tree and we'll retry on the next mount. Again, we might also want
5213 * to retry these periodically in the future.
5215 btrfs_remove_delayed_node(BTRFS_I(inode));
5220 * Return the key found in the dir entry in the location pointer, fill @type
5221 * with BTRFS_FT_*, and return 0.
5223 * If no dir entries were found, returns -ENOENT.
5224 * If found a corrupted location in dir entry, returns -EUCLEAN.
5226 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5227 struct btrfs_key *location, u8 *type)
5229 const char *name = dentry->d_name.name;
5230 int namelen = dentry->d_name.len;
5231 struct btrfs_dir_item *di;
5232 struct btrfs_path *path;
5233 struct btrfs_root *root = BTRFS_I(dir)->root;
5236 path = btrfs_alloc_path();
5240 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5242 if (IS_ERR_OR_NULL(di)) {
5243 ret = di ? PTR_ERR(di) : -ENOENT;
5247 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5248 if (location->type != BTRFS_INODE_ITEM_KEY &&
5249 location->type != BTRFS_ROOT_ITEM_KEY) {
5251 btrfs_warn(root->fs_info,
5252 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5253 __func__, name, btrfs_ino(BTRFS_I(dir)),
5254 location->objectid, location->type, location->offset);
5257 *type = btrfs_dir_type(path->nodes[0], di);
5259 btrfs_free_path(path);
5264 * when we hit a tree root in a directory, the btrfs part of the inode
5265 * needs to be changed to reflect the root directory of the tree root. This
5266 * is kind of like crossing a mount point.
5268 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5270 struct dentry *dentry,
5271 struct btrfs_key *location,
5272 struct btrfs_root **sub_root)
5274 struct btrfs_path *path;
5275 struct btrfs_root *new_root;
5276 struct btrfs_root_ref *ref;
5277 struct extent_buffer *leaf;
5278 struct btrfs_key key;
5282 path = btrfs_alloc_path();
5289 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5290 key.type = BTRFS_ROOT_REF_KEY;
5291 key.offset = location->objectid;
5293 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5300 leaf = path->nodes[0];
5301 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5302 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5303 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5306 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5307 (unsigned long)(ref + 1),
5308 dentry->d_name.len);
5312 btrfs_release_path(path);
5314 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5315 if (IS_ERR(new_root)) {
5316 err = PTR_ERR(new_root);
5320 *sub_root = new_root;
5321 location->objectid = btrfs_root_dirid(&new_root->root_item);
5322 location->type = BTRFS_INODE_ITEM_KEY;
5323 location->offset = 0;
5326 btrfs_free_path(path);
5330 static void inode_tree_add(struct inode *inode)
5332 struct btrfs_root *root = BTRFS_I(inode)->root;
5333 struct btrfs_inode *entry;
5335 struct rb_node *parent;
5336 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5337 u64 ino = btrfs_ino(BTRFS_I(inode));
5339 if (inode_unhashed(inode))
5342 spin_lock(&root->inode_lock);
5343 p = &root->inode_tree.rb_node;
5346 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5348 if (ino < btrfs_ino(entry))
5349 p = &parent->rb_left;
5350 else if (ino > btrfs_ino(entry))
5351 p = &parent->rb_right;
5353 WARN_ON(!(entry->vfs_inode.i_state &
5354 (I_WILL_FREE | I_FREEING)));
5355 rb_replace_node(parent, new, &root->inode_tree);
5356 RB_CLEAR_NODE(parent);
5357 spin_unlock(&root->inode_lock);
5361 rb_link_node(new, parent, p);
5362 rb_insert_color(new, &root->inode_tree);
5363 spin_unlock(&root->inode_lock);
5366 static void inode_tree_del(struct btrfs_inode *inode)
5368 struct btrfs_root *root = inode->root;
5371 spin_lock(&root->inode_lock);
5372 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5373 rb_erase(&inode->rb_node, &root->inode_tree);
5374 RB_CLEAR_NODE(&inode->rb_node);
5375 empty = RB_EMPTY_ROOT(&root->inode_tree);
5377 spin_unlock(&root->inode_lock);
5379 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5380 spin_lock(&root->inode_lock);
5381 empty = RB_EMPTY_ROOT(&root->inode_tree);
5382 spin_unlock(&root->inode_lock);
5384 btrfs_add_dead_root(root);
5389 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5391 struct btrfs_iget_args *args = p;
5393 inode->i_ino = args->ino;
5394 BTRFS_I(inode)->location.objectid = args->ino;
5395 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5396 BTRFS_I(inode)->location.offset = 0;
5397 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5398 BUG_ON(args->root && !BTRFS_I(inode)->root);
5402 static int btrfs_find_actor(struct inode *inode, void *opaque)
5404 struct btrfs_iget_args *args = opaque;
5406 return args->ino == BTRFS_I(inode)->location.objectid &&
5407 args->root == BTRFS_I(inode)->root;
5410 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5411 struct btrfs_root *root)
5413 struct inode *inode;
5414 struct btrfs_iget_args args;
5415 unsigned long hashval = btrfs_inode_hash(ino, root);
5420 inode = iget5_locked(s, hashval, btrfs_find_actor,
5421 btrfs_init_locked_inode,
5427 * Get an inode object given its inode number and corresponding root.
5428 * Path can be preallocated to prevent recursing back to iget through
5429 * allocator. NULL is also valid but may require an additional allocation
5432 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5433 struct btrfs_root *root, struct btrfs_path *path)
5435 struct inode *inode;
5437 inode = btrfs_iget_locked(s, ino, root);
5439 return ERR_PTR(-ENOMEM);
5441 if (inode->i_state & I_NEW) {
5444 ret = btrfs_read_locked_inode(inode, path);
5446 inode_tree_add(inode);
5447 unlock_new_inode(inode);
5451 * ret > 0 can come from btrfs_search_slot called by
5452 * btrfs_read_locked_inode, this means the inode item
5457 inode = ERR_PTR(ret);
5464 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5466 return btrfs_iget_path(s, ino, root, NULL);
5469 static struct inode *new_simple_dir(struct super_block *s,
5470 struct btrfs_key *key,
5471 struct btrfs_root *root)
5473 struct inode *inode = new_inode(s);
5476 return ERR_PTR(-ENOMEM);
5478 BTRFS_I(inode)->root = btrfs_grab_root(root);
5479 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5480 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5482 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5484 * We only need lookup, the rest is read-only and there's no inode
5485 * associated with the dentry
5487 inode->i_op = &simple_dir_inode_operations;
5488 inode->i_opflags &= ~IOP_XATTR;
5489 inode->i_fop = &simple_dir_operations;
5490 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5491 inode->i_mtime = current_time(inode);
5492 inode->i_atime = inode->i_mtime;
5493 inode->i_ctime = inode->i_mtime;
5494 BTRFS_I(inode)->i_otime = inode->i_mtime;
5499 static inline u8 btrfs_inode_type(struct inode *inode)
5502 * Compile-time asserts that generic FT_* types still match
5505 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5506 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5507 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5508 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5509 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5510 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5511 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5512 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5514 return fs_umode_to_ftype(inode->i_mode);
5517 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5519 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5520 struct inode *inode;
5521 struct btrfs_root *root = BTRFS_I(dir)->root;
5522 struct btrfs_root *sub_root = root;
5523 struct btrfs_key location;
5527 if (dentry->d_name.len > BTRFS_NAME_LEN)
5528 return ERR_PTR(-ENAMETOOLONG);
5530 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5532 return ERR_PTR(ret);
5534 if (location.type == BTRFS_INODE_ITEM_KEY) {
5535 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5539 /* Do extra check against inode mode with di_type */
5540 if (btrfs_inode_type(inode) != di_type) {
5542 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5543 inode->i_mode, btrfs_inode_type(inode),
5546 return ERR_PTR(-EUCLEAN);
5551 ret = fixup_tree_root_location(fs_info, dir, dentry,
5552 &location, &sub_root);
5555 inode = ERR_PTR(ret);
5557 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5559 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5561 if (root != sub_root)
5562 btrfs_put_root(sub_root);
5564 if (!IS_ERR(inode) && root != sub_root) {
5565 down_read(&fs_info->cleanup_work_sem);
5566 if (!sb_rdonly(inode->i_sb))
5567 ret = btrfs_orphan_cleanup(sub_root);
5568 up_read(&fs_info->cleanup_work_sem);
5571 inode = ERR_PTR(ret);
5578 static int btrfs_dentry_delete(const struct dentry *dentry)
5580 struct btrfs_root *root;
5581 struct inode *inode = d_inode(dentry);
5583 if (!inode && !IS_ROOT(dentry))
5584 inode = d_inode(dentry->d_parent);
5587 root = BTRFS_I(inode)->root;
5588 if (btrfs_root_refs(&root->root_item) == 0)
5591 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5597 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5600 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5602 if (inode == ERR_PTR(-ENOENT))
5604 return d_splice_alias(inode, dentry);
5608 * All this infrastructure exists because dir_emit can fault, and we are holding
5609 * the tree lock when doing readdir. For now just allocate a buffer and copy
5610 * our information into that, and then dir_emit from the buffer. This is
5611 * similar to what NFS does, only we don't keep the buffer around in pagecache
5612 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5613 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5616 static int btrfs_opendir(struct inode *inode, struct file *file)
5618 struct btrfs_file_private *private;
5620 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5623 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5624 if (!private->filldir_buf) {
5628 file->private_data = private;
5639 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5642 struct dir_entry *entry = addr;
5643 char *name = (char *)(entry + 1);
5645 ctx->pos = get_unaligned(&entry->offset);
5646 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5647 get_unaligned(&entry->ino),
5648 get_unaligned(&entry->type)))
5650 addr += sizeof(struct dir_entry) +
5651 get_unaligned(&entry->name_len);
5657 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5659 struct inode *inode = file_inode(file);
5660 struct btrfs_root *root = BTRFS_I(inode)->root;
5661 struct btrfs_file_private *private = file->private_data;
5662 struct btrfs_dir_item *di;
5663 struct btrfs_key key;
5664 struct btrfs_key found_key;
5665 struct btrfs_path *path;
5667 struct list_head ins_list;
5668 struct list_head del_list;
5670 struct extent_buffer *leaf;
5677 struct btrfs_key location;
5679 if (!dir_emit_dots(file, ctx))
5682 path = btrfs_alloc_path();
5686 addr = private->filldir_buf;
5687 path->reada = READA_FORWARD;
5689 INIT_LIST_HEAD(&ins_list);
5690 INIT_LIST_HEAD(&del_list);
5691 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5694 key.type = BTRFS_DIR_INDEX_KEY;
5695 key.offset = ctx->pos;
5696 key.objectid = btrfs_ino(BTRFS_I(inode));
5698 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5703 struct dir_entry *entry;
5705 leaf = path->nodes[0];
5706 slot = path->slots[0];
5707 if (slot >= btrfs_header_nritems(leaf)) {
5708 ret = btrfs_next_leaf(root, path);
5716 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5718 if (found_key.objectid != key.objectid)
5720 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5722 if (found_key.offset < ctx->pos)
5724 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5726 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5727 name_len = btrfs_dir_name_len(leaf, di);
5728 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5730 btrfs_release_path(path);
5731 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5734 addr = private->filldir_buf;
5741 put_unaligned(name_len, &entry->name_len);
5742 name_ptr = (char *)(entry + 1);
5743 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5745 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5747 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5748 put_unaligned(location.objectid, &entry->ino);
5749 put_unaligned(found_key.offset, &entry->offset);
5751 addr += sizeof(struct dir_entry) + name_len;
5752 total_len += sizeof(struct dir_entry) + name_len;
5756 btrfs_release_path(path);
5758 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5762 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5767 * Stop new entries from being returned after we return the last
5770 * New directory entries are assigned a strictly increasing
5771 * offset. This means that new entries created during readdir
5772 * are *guaranteed* to be seen in the future by that readdir.
5773 * This has broken buggy programs which operate on names as
5774 * they're returned by readdir. Until we re-use freed offsets
5775 * we have this hack to stop new entries from being returned
5776 * under the assumption that they'll never reach this huge
5779 * This is being careful not to overflow 32bit loff_t unless the
5780 * last entry requires it because doing so has broken 32bit apps
5783 if (ctx->pos >= INT_MAX)
5784 ctx->pos = LLONG_MAX;
5791 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5792 btrfs_free_path(path);
5797 * This is somewhat expensive, updating the tree every time the
5798 * inode changes. But, it is most likely to find the inode in cache.
5799 * FIXME, needs more benchmarking...there are no reasons other than performance
5800 * to keep or drop this code.
5802 static int btrfs_dirty_inode(struct inode *inode)
5804 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5805 struct btrfs_root *root = BTRFS_I(inode)->root;
5806 struct btrfs_trans_handle *trans;
5809 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5812 trans = btrfs_join_transaction(root);
5814 return PTR_ERR(trans);
5816 ret = btrfs_update_inode(trans, root, inode);
5817 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
5818 /* whoops, lets try again with the full transaction */
5819 btrfs_end_transaction(trans);
5820 trans = btrfs_start_transaction(root, 1);
5822 return PTR_ERR(trans);
5824 ret = btrfs_update_inode(trans, root, inode);
5826 btrfs_end_transaction(trans);
5827 if (BTRFS_I(inode)->delayed_node)
5828 btrfs_balance_delayed_items(fs_info);
5834 * This is a copy of file_update_time. We need this so we can return error on
5835 * ENOSPC for updating the inode in the case of file write and mmap writes.
5837 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5840 struct btrfs_root *root = BTRFS_I(inode)->root;
5841 bool dirty = flags & ~S_VERSION;
5843 if (btrfs_root_readonly(root))
5846 if (flags & S_VERSION)
5847 dirty |= inode_maybe_inc_iversion(inode, dirty);
5848 if (flags & S_CTIME)
5849 inode->i_ctime = *now;
5850 if (flags & S_MTIME)
5851 inode->i_mtime = *now;
5852 if (flags & S_ATIME)
5853 inode->i_atime = *now;
5854 return dirty ? btrfs_dirty_inode(inode) : 0;
5858 * find the highest existing sequence number in a directory
5859 * and then set the in-memory index_cnt variable to reflect
5860 * free sequence numbers
5862 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5864 struct btrfs_root *root = inode->root;
5865 struct btrfs_key key, found_key;
5866 struct btrfs_path *path;
5867 struct extent_buffer *leaf;
5870 key.objectid = btrfs_ino(inode);
5871 key.type = BTRFS_DIR_INDEX_KEY;
5872 key.offset = (u64)-1;
5874 path = btrfs_alloc_path();
5878 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5881 /* FIXME: we should be able to handle this */
5887 * MAGIC NUMBER EXPLANATION:
5888 * since we search a directory based on f_pos we have to start at 2
5889 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5890 * else has to start at 2
5892 if (path->slots[0] == 0) {
5893 inode->index_cnt = 2;
5899 leaf = path->nodes[0];
5900 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5902 if (found_key.objectid != btrfs_ino(inode) ||
5903 found_key.type != BTRFS_DIR_INDEX_KEY) {
5904 inode->index_cnt = 2;
5908 inode->index_cnt = found_key.offset + 1;
5910 btrfs_free_path(path);
5915 * helper to find a free sequence number in a given directory. This current
5916 * code is very simple, later versions will do smarter things in the btree
5918 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5922 if (dir->index_cnt == (u64)-1) {
5923 ret = btrfs_inode_delayed_dir_index_count(dir);
5925 ret = btrfs_set_inode_index_count(dir);
5931 *index = dir->index_cnt;
5937 static int btrfs_insert_inode_locked(struct inode *inode)
5939 struct btrfs_iget_args args;
5941 args.ino = BTRFS_I(inode)->location.objectid;
5942 args.root = BTRFS_I(inode)->root;
5944 return insert_inode_locked4(inode,
5945 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5946 btrfs_find_actor, &args);
5950 * Inherit flags from the parent inode.
5952 * Currently only the compression flags and the cow flags are inherited.
5954 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5961 flags = BTRFS_I(dir)->flags;
5963 if (flags & BTRFS_INODE_NOCOMPRESS) {
5964 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5965 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5966 } else if (flags & BTRFS_INODE_COMPRESS) {
5967 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5968 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5971 if (flags & BTRFS_INODE_NODATACOW) {
5972 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5973 if (S_ISREG(inode->i_mode))
5974 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5977 btrfs_sync_inode_flags_to_i_flags(inode);
5980 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5981 struct btrfs_root *root,
5983 const char *name, int name_len,
5984 u64 ref_objectid, u64 objectid,
5985 umode_t mode, u64 *index)
5987 struct btrfs_fs_info *fs_info = root->fs_info;
5988 struct inode *inode;
5989 struct btrfs_inode_item *inode_item;
5990 struct btrfs_key *location;
5991 struct btrfs_path *path;
5992 struct btrfs_inode_ref *ref;
5993 struct btrfs_key key[2];
5995 int nitems = name ? 2 : 1;
5997 unsigned int nofs_flag;
6000 path = btrfs_alloc_path();
6002 return ERR_PTR(-ENOMEM);
6004 nofs_flag = memalloc_nofs_save();
6005 inode = new_inode(fs_info->sb);
6006 memalloc_nofs_restore(nofs_flag);
6008 btrfs_free_path(path);
6009 return ERR_PTR(-ENOMEM);
6013 * O_TMPFILE, set link count to 0, so that after this point,
6014 * we fill in an inode item with the correct link count.
6017 set_nlink(inode, 0);
6020 * we have to initialize this early, so we can reclaim the inode
6021 * number if we fail afterwards in this function.
6023 inode->i_ino = objectid;
6026 trace_btrfs_inode_request(dir);
6028 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6030 btrfs_free_path(path);
6032 return ERR_PTR(ret);
6038 * index_cnt is ignored for everything but a dir,
6039 * btrfs_set_inode_index_count has an explanation for the magic
6042 BTRFS_I(inode)->index_cnt = 2;
6043 BTRFS_I(inode)->dir_index = *index;
6044 BTRFS_I(inode)->root = btrfs_grab_root(root);
6045 BTRFS_I(inode)->generation = trans->transid;
6046 inode->i_generation = BTRFS_I(inode)->generation;
6049 * We could have gotten an inode number from somebody who was fsynced
6050 * and then removed in this same transaction, so let's just set full
6051 * sync since it will be a full sync anyway and this will blow away the
6052 * old info in the log.
6054 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6056 key[0].objectid = objectid;
6057 key[0].type = BTRFS_INODE_ITEM_KEY;
6060 sizes[0] = sizeof(struct btrfs_inode_item);
6064 * Start new inodes with an inode_ref. This is slightly more
6065 * efficient for small numbers of hard links since they will
6066 * be packed into one item. Extended refs will kick in if we
6067 * add more hard links than can fit in the ref item.
6069 key[1].objectid = objectid;
6070 key[1].type = BTRFS_INODE_REF_KEY;
6071 key[1].offset = ref_objectid;
6073 sizes[1] = name_len + sizeof(*ref);
6076 location = &BTRFS_I(inode)->location;
6077 location->objectid = objectid;
6078 location->offset = 0;
6079 location->type = BTRFS_INODE_ITEM_KEY;
6081 ret = btrfs_insert_inode_locked(inode);
6087 path->leave_spinning = 1;
6088 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6092 inode_init_owner(inode, dir, mode);
6093 inode_set_bytes(inode, 0);
6095 inode->i_mtime = current_time(inode);
6096 inode->i_atime = inode->i_mtime;
6097 inode->i_ctime = inode->i_mtime;
6098 BTRFS_I(inode)->i_otime = inode->i_mtime;
6100 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6101 struct btrfs_inode_item);
6102 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6103 sizeof(*inode_item));
6104 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6107 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6108 struct btrfs_inode_ref);
6109 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6110 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6111 ptr = (unsigned long)(ref + 1);
6112 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6115 btrfs_mark_buffer_dirty(path->nodes[0]);
6116 btrfs_free_path(path);
6118 btrfs_inherit_iflags(inode, dir);
6120 if (S_ISREG(mode)) {
6121 if (btrfs_test_opt(fs_info, NODATASUM))
6122 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6123 if (btrfs_test_opt(fs_info, NODATACOW))
6124 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6125 BTRFS_INODE_NODATASUM;
6128 inode_tree_add(inode);
6130 trace_btrfs_inode_new(inode);
6131 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6133 btrfs_update_root_times(trans, root);
6135 ret = btrfs_inode_inherit_props(trans, inode, dir);
6138 "error inheriting props for ino %llu (root %llu): %d",
6139 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6144 discard_new_inode(inode);
6147 BTRFS_I(dir)->index_cnt--;
6148 btrfs_free_path(path);
6149 return ERR_PTR(ret);
6153 * utility function to add 'inode' into 'parent_inode' with
6154 * a give name and a given sequence number.
6155 * if 'add_backref' is true, also insert a backref from the
6156 * inode to the parent directory.
6158 int btrfs_add_link(struct btrfs_trans_handle *trans,
6159 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6160 const char *name, int name_len, int add_backref, u64 index)
6163 struct btrfs_key key;
6164 struct btrfs_root *root = parent_inode->root;
6165 u64 ino = btrfs_ino(inode);
6166 u64 parent_ino = btrfs_ino(parent_inode);
6168 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6169 memcpy(&key, &inode->root->root_key, sizeof(key));
6172 key.type = BTRFS_INODE_ITEM_KEY;
6176 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6177 ret = btrfs_add_root_ref(trans, key.objectid,
6178 root->root_key.objectid, parent_ino,
6179 index, name, name_len);
6180 } else if (add_backref) {
6181 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6185 /* Nothing to clean up yet */
6189 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6190 btrfs_inode_type(&inode->vfs_inode), index);
6191 if (ret == -EEXIST || ret == -EOVERFLOW)
6194 btrfs_abort_transaction(trans, ret);
6198 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6200 inode_inc_iversion(&parent_inode->vfs_inode);
6202 * If we are replaying a log tree, we do not want to update the mtime
6203 * and ctime of the parent directory with the current time, since the
6204 * log replay procedure is responsible for setting them to their correct
6205 * values (the ones it had when the fsync was done).
6207 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6208 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6210 parent_inode->vfs_inode.i_mtime = now;
6211 parent_inode->vfs_inode.i_ctime = now;
6213 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6215 btrfs_abort_transaction(trans, ret);
6219 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6222 err = btrfs_del_root_ref(trans, key.objectid,
6223 root->root_key.objectid, parent_ino,
6224 &local_index, name, name_len);
6226 btrfs_abort_transaction(trans, err);
6227 } else if (add_backref) {
6231 err = btrfs_del_inode_ref(trans, root, name, name_len,
6232 ino, parent_ino, &local_index);
6234 btrfs_abort_transaction(trans, err);
6237 /* Return the original error code */
6241 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6242 struct btrfs_inode *dir, struct dentry *dentry,
6243 struct btrfs_inode *inode, int backref, u64 index)
6245 int err = btrfs_add_link(trans, dir, inode,
6246 dentry->d_name.name, dentry->d_name.len,
6253 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6254 umode_t mode, dev_t rdev)
6256 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6257 struct btrfs_trans_handle *trans;
6258 struct btrfs_root *root = BTRFS_I(dir)->root;
6259 struct inode *inode = NULL;
6265 * 2 for inode item and ref
6267 * 1 for xattr if selinux is on
6269 trans = btrfs_start_transaction(root, 5);
6271 return PTR_ERR(trans);
6273 err = btrfs_find_free_objectid(root, &objectid);
6277 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6278 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6280 if (IS_ERR(inode)) {
6281 err = PTR_ERR(inode);
6287 * If the active LSM wants to access the inode during
6288 * d_instantiate it needs these. Smack checks to see
6289 * if the filesystem supports xattrs by looking at the
6292 inode->i_op = &btrfs_special_inode_operations;
6293 init_special_inode(inode, inode->i_mode, rdev);
6295 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6299 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6304 btrfs_update_inode(trans, root, inode);
6305 d_instantiate_new(dentry, inode);
6308 btrfs_end_transaction(trans);
6309 btrfs_btree_balance_dirty(fs_info);
6311 inode_dec_link_count(inode);
6312 discard_new_inode(inode);
6317 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6318 umode_t mode, bool excl)
6320 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6321 struct btrfs_trans_handle *trans;
6322 struct btrfs_root *root = BTRFS_I(dir)->root;
6323 struct inode *inode = NULL;
6329 * 2 for inode item and ref
6331 * 1 for xattr if selinux is on
6333 trans = btrfs_start_transaction(root, 5);
6335 return PTR_ERR(trans);
6337 err = btrfs_find_free_objectid(root, &objectid);
6341 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6342 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6344 if (IS_ERR(inode)) {
6345 err = PTR_ERR(inode);
6350 * If the active LSM wants to access the inode during
6351 * d_instantiate it needs these. Smack checks to see
6352 * if the filesystem supports xattrs by looking at the
6355 inode->i_fop = &btrfs_file_operations;
6356 inode->i_op = &btrfs_file_inode_operations;
6357 inode->i_mapping->a_ops = &btrfs_aops;
6359 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6363 err = btrfs_update_inode(trans, root, inode);
6367 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6372 d_instantiate_new(dentry, inode);
6375 btrfs_end_transaction(trans);
6377 inode_dec_link_count(inode);
6378 discard_new_inode(inode);
6380 btrfs_btree_balance_dirty(fs_info);
6384 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6385 struct dentry *dentry)
6387 struct btrfs_trans_handle *trans = NULL;
6388 struct btrfs_root *root = BTRFS_I(dir)->root;
6389 struct inode *inode = d_inode(old_dentry);
6390 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6395 /* do not allow sys_link's with other subvols of the same device */
6396 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6399 if (inode->i_nlink >= BTRFS_LINK_MAX)
6402 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6407 * 2 items for inode and inode ref
6408 * 2 items for dir items
6409 * 1 item for parent inode
6410 * 1 item for orphan item deletion if O_TMPFILE
6412 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6413 if (IS_ERR(trans)) {
6414 err = PTR_ERR(trans);
6419 /* There are several dir indexes for this inode, clear the cache. */
6420 BTRFS_I(inode)->dir_index = 0ULL;
6422 inode_inc_iversion(inode);
6423 inode->i_ctime = current_time(inode);
6425 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6427 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6433 struct dentry *parent = dentry->d_parent;
6435 err = btrfs_update_inode(trans, root, inode);
6438 if (inode->i_nlink == 1) {
6440 * If new hard link count is 1, it's a file created
6441 * with open(2) O_TMPFILE flag.
6443 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6447 d_instantiate(dentry, inode);
6448 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6453 btrfs_end_transaction(trans);
6455 inode_dec_link_count(inode);
6458 btrfs_btree_balance_dirty(fs_info);
6462 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6464 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6465 struct inode *inode = NULL;
6466 struct btrfs_trans_handle *trans;
6467 struct btrfs_root *root = BTRFS_I(dir)->root;
6473 * 2 items for inode and ref
6474 * 2 items for dir items
6475 * 1 for xattr if selinux is on
6477 trans = btrfs_start_transaction(root, 5);
6479 return PTR_ERR(trans);
6481 err = btrfs_find_free_objectid(root, &objectid);
6485 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6486 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6487 S_IFDIR | mode, &index);
6488 if (IS_ERR(inode)) {
6489 err = PTR_ERR(inode);
6494 /* these must be set before we unlock the inode */
6495 inode->i_op = &btrfs_dir_inode_operations;
6496 inode->i_fop = &btrfs_dir_file_operations;
6498 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6502 btrfs_i_size_write(BTRFS_I(inode), 0);
6503 err = btrfs_update_inode(trans, root, inode);
6507 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6508 dentry->d_name.name,
6509 dentry->d_name.len, 0, index);
6513 d_instantiate_new(dentry, inode);
6516 btrfs_end_transaction(trans);
6518 inode_dec_link_count(inode);
6519 discard_new_inode(inode);
6521 btrfs_btree_balance_dirty(fs_info);
6525 static noinline int uncompress_inline(struct btrfs_path *path,
6527 size_t pg_offset, u64 extent_offset,
6528 struct btrfs_file_extent_item *item)
6531 struct extent_buffer *leaf = path->nodes[0];
6534 unsigned long inline_size;
6538 WARN_ON(pg_offset != 0);
6539 compress_type = btrfs_file_extent_compression(leaf, item);
6540 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6541 inline_size = btrfs_file_extent_inline_item_len(leaf,
6542 btrfs_item_nr(path->slots[0]));
6543 tmp = kmalloc(inline_size, GFP_NOFS);
6546 ptr = btrfs_file_extent_inline_start(item);
6548 read_extent_buffer(leaf, tmp, ptr, inline_size);
6550 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6551 ret = btrfs_decompress(compress_type, tmp, page,
6552 extent_offset, inline_size, max_size);
6555 * decompression code contains a memset to fill in any space between the end
6556 * of the uncompressed data and the end of max_size in case the decompressed
6557 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6558 * the end of an inline extent and the beginning of the next block, so we
6559 * cover that region here.
6562 if (max_size + pg_offset < PAGE_SIZE) {
6563 char *map = kmap(page);
6564 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6572 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6573 * @inode: file to search in
6574 * @page: page to read extent data into if the extent is inline
6575 * @pg_offset: offset into @page to copy to
6576 * @start: file offset
6577 * @len: length of range starting at @start
6579 * This returns the first &struct extent_map which overlaps with the given
6580 * range, reading it from the B-tree and caching it if necessary. Note that
6581 * there may be more extents which overlap the given range after the returned
6584 * If @page is not NULL and the extent is inline, this also reads the extent
6585 * data directly into the page and marks the extent up to date in the io_tree.
6587 * Return: ERR_PTR on error, non-NULL extent_map on success.
6589 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6590 struct page *page, size_t pg_offset,
6593 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6595 u64 extent_start = 0;
6597 u64 objectid = btrfs_ino(inode);
6598 int extent_type = -1;
6599 struct btrfs_path *path = NULL;
6600 struct btrfs_root *root = inode->root;
6601 struct btrfs_file_extent_item *item;
6602 struct extent_buffer *leaf;
6603 struct btrfs_key found_key;
6604 struct extent_map *em = NULL;
6605 struct extent_map_tree *em_tree = &inode->extent_tree;
6606 struct extent_io_tree *io_tree = &inode->io_tree;
6608 read_lock(&em_tree->lock);
6609 em = lookup_extent_mapping(em_tree, start, len);
6610 read_unlock(&em_tree->lock);
6613 if (em->start > start || em->start + em->len <= start)
6614 free_extent_map(em);
6615 else if (em->block_start == EXTENT_MAP_INLINE && page)
6616 free_extent_map(em);
6620 em = alloc_extent_map();
6625 em->start = EXTENT_MAP_HOLE;
6626 em->orig_start = EXTENT_MAP_HOLE;
6628 em->block_len = (u64)-1;
6630 path = btrfs_alloc_path();
6636 /* Chances are we'll be called again, so go ahead and do readahead */
6637 path->reada = READA_FORWARD;
6640 * Unless we're going to uncompress the inline extent, no sleep would
6643 path->leave_spinning = 1;
6645 path->recurse = btrfs_is_free_space_inode(inode);
6647 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6650 } else if (ret > 0) {
6651 if (path->slots[0] == 0)
6657 leaf = path->nodes[0];
6658 item = btrfs_item_ptr(leaf, path->slots[0],
6659 struct btrfs_file_extent_item);
6660 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6661 if (found_key.objectid != objectid ||
6662 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6664 * If we backup past the first extent we want to move forward
6665 * and see if there is an extent in front of us, otherwise we'll
6666 * say there is a hole for our whole search range which can
6673 extent_type = btrfs_file_extent_type(leaf, item);
6674 extent_start = found_key.offset;
6675 extent_end = btrfs_file_extent_end(path);
6676 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6677 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6678 /* Only regular file could have regular/prealloc extent */
6679 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6682 "regular/prealloc extent found for non-regular inode %llu",
6686 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6688 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6689 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6694 if (start >= extent_end) {
6696 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6697 ret = btrfs_next_leaf(root, path);
6703 leaf = path->nodes[0];
6705 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6706 if (found_key.objectid != objectid ||
6707 found_key.type != BTRFS_EXTENT_DATA_KEY)
6709 if (start + len <= found_key.offset)
6711 if (start > found_key.offset)
6714 /* New extent overlaps with existing one */
6716 em->orig_start = start;
6717 em->len = found_key.offset - start;
6718 em->block_start = EXTENT_MAP_HOLE;
6722 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6724 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6725 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6727 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6731 size_t extent_offset;
6737 size = btrfs_file_extent_ram_bytes(leaf, item);
6738 extent_offset = page_offset(page) + pg_offset - extent_start;
6739 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6740 size - extent_offset);
6741 em->start = extent_start + extent_offset;
6742 em->len = ALIGN(copy_size, fs_info->sectorsize);
6743 em->orig_block_len = em->len;
6744 em->orig_start = em->start;
6745 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6747 btrfs_set_path_blocking(path);
6748 if (!PageUptodate(page)) {
6749 if (btrfs_file_extent_compression(leaf, item) !=
6750 BTRFS_COMPRESS_NONE) {
6751 ret = uncompress_inline(path, page, pg_offset,
6752 extent_offset, item);
6757 read_extent_buffer(leaf, map + pg_offset, ptr,
6759 if (pg_offset + copy_size < PAGE_SIZE) {
6760 memset(map + pg_offset + copy_size, 0,
6761 PAGE_SIZE - pg_offset -
6766 flush_dcache_page(page);
6768 set_extent_uptodate(io_tree, em->start,
6769 extent_map_end(em) - 1, NULL, GFP_NOFS);
6774 em->orig_start = start;
6776 em->block_start = EXTENT_MAP_HOLE;
6779 btrfs_release_path(path);
6780 if (em->start > start || extent_map_end(em) <= start) {
6782 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6783 em->start, em->len, start, len);
6788 write_lock(&em_tree->lock);
6789 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6790 write_unlock(&em_tree->lock);
6792 btrfs_free_path(path);
6794 trace_btrfs_get_extent(root, inode, em);
6797 free_extent_map(em);
6798 return ERR_PTR(ret);
6803 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6806 struct extent_map *em;
6807 struct extent_map *hole_em = NULL;
6808 u64 delalloc_start = start;
6814 em = btrfs_get_extent(inode, NULL, 0, start, len);
6818 * If our em maps to:
6820 * - a pre-alloc extent,
6821 * there might actually be delalloc bytes behind it.
6823 if (em->block_start != EXTENT_MAP_HOLE &&
6824 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6829 /* check to see if we've wrapped (len == -1 or similar) */
6838 /* ok, we didn't find anything, lets look for delalloc */
6839 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6840 end, len, EXTENT_DELALLOC, 1);
6841 delalloc_end = delalloc_start + delalloc_len;
6842 if (delalloc_end < delalloc_start)
6843 delalloc_end = (u64)-1;
6846 * We didn't find anything useful, return the original results from
6849 if (delalloc_start > end || delalloc_end <= start) {
6856 * Adjust the delalloc_start to make sure it doesn't go backwards from
6857 * the start they passed in
6859 delalloc_start = max(start, delalloc_start);
6860 delalloc_len = delalloc_end - delalloc_start;
6862 if (delalloc_len > 0) {
6865 const u64 hole_end = extent_map_end(hole_em);
6867 em = alloc_extent_map();
6875 * When btrfs_get_extent can't find anything it returns one
6878 * Make sure what it found really fits our range, and adjust to
6879 * make sure it is based on the start from the caller
6881 if (hole_end <= start || hole_em->start > end) {
6882 free_extent_map(hole_em);
6885 hole_start = max(hole_em->start, start);
6886 hole_len = hole_end - hole_start;
6889 if (hole_em && delalloc_start > hole_start) {
6891 * Our hole starts before our delalloc, so we have to
6892 * return just the parts of the hole that go until the
6895 em->len = min(hole_len, delalloc_start - hole_start);
6896 em->start = hole_start;
6897 em->orig_start = hole_start;
6899 * Don't adjust block start at all, it is fixed at
6902 em->block_start = hole_em->block_start;
6903 em->block_len = hole_len;
6904 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6905 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6908 * Hole is out of passed range or it starts after
6911 em->start = delalloc_start;
6912 em->len = delalloc_len;
6913 em->orig_start = delalloc_start;
6914 em->block_start = EXTENT_MAP_DELALLOC;
6915 em->block_len = delalloc_len;
6922 free_extent_map(hole_em);
6924 free_extent_map(em);
6925 return ERR_PTR(err);
6930 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
6933 const u64 orig_start,
6934 const u64 block_start,
6935 const u64 block_len,
6936 const u64 orig_block_len,
6937 const u64 ram_bytes,
6940 struct extent_map *em = NULL;
6943 if (type != BTRFS_ORDERED_NOCOW) {
6944 em = create_io_em(inode, start, len, orig_start, block_start,
6945 block_len, orig_block_len, ram_bytes,
6946 BTRFS_COMPRESS_NONE, /* compress_type */
6951 ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
6955 free_extent_map(em);
6956 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
6965 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
6968 struct btrfs_root *root = inode->root;
6969 struct btrfs_fs_info *fs_info = root->fs_info;
6970 struct extent_map *em;
6971 struct btrfs_key ins;
6975 alloc_hint = get_extent_allocation_hint(inode, start, len);
6976 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
6977 0, alloc_hint, &ins, 1, 1);
6979 return ERR_PTR(ret);
6981 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6982 ins.objectid, ins.offset, ins.offset,
6983 ins.offset, BTRFS_ORDERED_REGULAR);
6984 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
6986 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
6993 * Check if we can do nocow write into the range [@offset, @offset + @len)
6995 * @offset: File offset
6996 * @len: The length to write, will be updated to the nocow writeable
6998 * @orig_start: (optional) Return the original file offset of the file extent
6999 * @orig_len: (optional) Return the original on-disk length of the file extent
7000 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7001 * @strict: if true, omit optimizations that might force us into unnecessary
7002 * cow. e.g., don't trust generation number.
7004 * This function will flush ordered extents in the range to ensure proper
7005 * nocow checks for (nowait == false) case.
7008 * >0 and update @len if we can do nocow write
7009 * 0 if we can't do nocow write
7010 * <0 if error happened
7012 * NOTE: This only checks the file extents, caller is responsible to wait for
7013 * any ordered extents.
7015 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7016 u64 *orig_start, u64 *orig_block_len,
7017 u64 *ram_bytes, bool strict)
7019 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7020 struct btrfs_path *path;
7022 struct extent_buffer *leaf;
7023 struct btrfs_root *root = BTRFS_I(inode)->root;
7024 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7025 struct btrfs_file_extent_item *fi;
7026 struct btrfs_key key;
7033 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7035 path = btrfs_alloc_path();
7039 ret = btrfs_lookup_file_extent(NULL, root, path,
7040 btrfs_ino(BTRFS_I(inode)), offset, 0);
7044 slot = path->slots[0];
7047 /* can't find the item, must cow */
7054 leaf = path->nodes[0];
7055 btrfs_item_key_to_cpu(leaf, &key, slot);
7056 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7057 key.type != BTRFS_EXTENT_DATA_KEY) {
7058 /* not our file or wrong item type, must cow */
7062 if (key.offset > offset) {
7063 /* Wrong offset, must cow */
7067 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7068 found_type = btrfs_file_extent_type(leaf, fi);
7069 if (found_type != BTRFS_FILE_EXTENT_REG &&
7070 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7071 /* not a regular extent, must cow */
7075 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7078 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7079 if (extent_end <= offset)
7082 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7083 if (disk_bytenr == 0)
7086 if (btrfs_file_extent_compression(leaf, fi) ||
7087 btrfs_file_extent_encryption(leaf, fi) ||
7088 btrfs_file_extent_other_encoding(leaf, fi))
7092 * Do the same check as in btrfs_cross_ref_exist but without the
7093 * unnecessary search.
7096 (btrfs_file_extent_generation(leaf, fi) <=
7097 btrfs_root_last_snapshot(&root->root_item)))
7100 backref_offset = btrfs_file_extent_offset(leaf, fi);
7103 *orig_start = key.offset - backref_offset;
7104 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7105 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7108 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7111 num_bytes = min(offset + *len, extent_end) - offset;
7112 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7115 range_end = round_up(offset + num_bytes,
7116 root->fs_info->sectorsize) - 1;
7117 ret = test_range_bit(io_tree, offset, range_end,
7118 EXTENT_DELALLOC, 0, NULL);
7125 btrfs_release_path(path);
7128 * look for other files referencing this extent, if we
7129 * find any we must cow
7132 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7133 key.offset - backref_offset, disk_bytenr,
7141 * adjust disk_bytenr and num_bytes to cover just the bytes
7142 * in this extent we are about to write. If there
7143 * are any csums in that range we have to cow in order
7144 * to keep the csums correct
7146 disk_bytenr += backref_offset;
7147 disk_bytenr += offset - key.offset;
7148 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7151 * all of the above have passed, it is safe to overwrite this extent
7157 btrfs_free_path(path);
7161 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7162 struct extent_state **cached_state, bool writing)
7164 struct btrfs_ordered_extent *ordered;
7168 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7171 * We're concerned with the entire range that we're going to be
7172 * doing DIO to, so we need to make sure there's no ordered
7173 * extents in this range.
7175 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7176 lockend - lockstart + 1);
7179 * We need to make sure there are no buffered pages in this
7180 * range either, we could have raced between the invalidate in
7181 * generic_file_direct_write and locking the extent. The
7182 * invalidate needs to happen so that reads after a write do not
7186 (!writing || !filemap_range_has_page(inode->i_mapping,
7187 lockstart, lockend)))
7190 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7195 * If we are doing a DIO read and the ordered extent we
7196 * found is for a buffered write, we can not wait for it
7197 * to complete and retry, because if we do so we can
7198 * deadlock with concurrent buffered writes on page
7199 * locks. This happens only if our DIO read covers more
7200 * than one extent map, if at this point has already
7201 * created an ordered extent for a previous extent map
7202 * and locked its range in the inode's io tree, and a
7203 * concurrent write against that previous extent map's
7204 * range and this range started (we unlock the ranges
7205 * in the io tree only when the bios complete and
7206 * buffered writes always lock pages before attempting
7207 * to lock range in the io tree).
7210 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7211 btrfs_start_ordered_extent(ordered, 1);
7214 btrfs_put_ordered_extent(ordered);
7217 * We could trigger writeback for this range (and wait
7218 * for it to complete) and then invalidate the pages for
7219 * this range (through invalidate_inode_pages2_range()),
7220 * but that can lead us to a deadlock with a concurrent
7221 * call to readahead (a buffered read or a defrag call
7222 * triggered a readahead) on a page lock due to an
7223 * ordered dio extent we created before but did not have
7224 * yet a corresponding bio submitted (whence it can not
7225 * complete), which makes readahead wait for that
7226 * ordered extent to complete while holding a lock on
7241 /* The callers of this must take lock_extent() */
7242 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7243 u64 len, u64 orig_start, u64 block_start,
7244 u64 block_len, u64 orig_block_len,
7245 u64 ram_bytes, int compress_type,
7248 struct extent_map_tree *em_tree;
7249 struct extent_map *em;
7252 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7253 type == BTRFS_ORDERED_COMPRESSED ||
7254 type == BTRFS_ORDERED_NOCOW ||
7255 type == BTRFS_ORDERED_REGULAR);
7257 em_tree = &inode->extent_tree;
7258 em = alloc_extent_map();
7260 return ERR_PTR(-ENOMEM);
7263 em->orig_start = orig_start;
7265 em->block_len = block_len;
7266 em->block_start = block_start;
7267 em->orig_block_len = orig_block_len;
7268 em->ram_bytes = ram_bytes;
7269 em->generation = -1;
7270 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7271 if (type == BTRFS_ORDERED_PREALLOC) {
7272 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7273 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7274 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7275 em->compress_type = compress_type;
7279 btrfs_drop_extent_cache(inode, em->start,
7280 em->start + em->len - 1, 0);
7281 write_lock(&em_tree->lock);
7282 ret = add_extent_mapping(em_tree, em, 1);
7283 write_unlock(&em_tree->lock);
7285 * The caller has taken lock_extent(), who could race with us
7288 } while (ret == -EEXIST);
7291 free_extent_map(em);
7292 return ERR_PTR(ret);
7295 /* em got 2 refs now, callers needs to do free_extent_map once. */
7300 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7301 struct inode *inode,
7302 struct btrfs_dio_data *dio_data,
7305 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7306 struct extent_map *em = *map;
7310 * We don't allocate a new extent in the following cases
7312 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7314 * 2) The extent is marked as PREALLOC. We're good to go here and can
7315 * just use the extent.
7318 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7319 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7320 em->block_start != EXTENT_MAP_HOLE)) {
7322 u64 block_start, orig_start, orig_block_len, ram_bytes;
7324 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7325 type = BTRFS_ORDERED_PREALLOC;
7327 type = BTRFS_ORDERED_NOCOW;
7328 len = min(len, em->len - (start - em->start));
7329 block_start = em->block_start + (start - em->start);
7331 if (can_nocow_extent(inode, start, &len, &orig_start,
7332 &orig_block_len, &ram_bytes, false) == 1 &&
7333 btrfs_inc_nocow_writers(fs_info, block_start)) {
7334 struct extent_map *em2;
7336 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7337 orig_start, block_start,
7338 len, orig_block_len,
7340 btrfs_dec_nocow_writers(fs_info, block_start);
7341 if (type == BTRFS_ORDERED_PREALLOC) {
7342 free_extent_map(em);
7346 if (em2 && IS_ERR(em2)) {
7351 * For inode marked NODATACOW or extent marked PREALLOC,
7352 * use the existing or preallocated extent, so does not
7353 * need to adjust btrfs_space_info's bytes_may_use.
7355 btrfs_free_reserved_data_space_noquota(fs_info, len);
7360 /* this will cow the extent */
7361 free_extent_map(em);
7362 *map = em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7368 len = min(len, em->len - (start - em->start));
7372 * Need to update the i_size under the extent lock so buffered
7373 * readers will get the updated i_size when we unlock.
7375 if (start + len > i_size_read(inode))
7376 i_size_write(inode, start + len);
7378 dio_data->reserve -= len;
7383 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7384 loff_t length, unsigned int flags, struct iomap *iomap,
7385 struct iomap *srcmap)
7387 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7388 struct extent_map *em;
7389 struct extent_state *cached_state = NULL;
7390 struct btrfs_dio_data *dio_data = NULL;
7391 u64 lockstart, lockend;
7392 const bool write = !!(flags & IOMAP_WRITE);
7395 bool unlock_extents = false;
7396 bool sync = (current->journal_info == BTRFS_DIO_SYNC_STUB);
7399 * We used current->journal_info here to see if we were sync, but
7400 * there's a lot of tests in the enospc machinery to not do flushing if
7401 * we have a journal_info set, so we need to clear this out and re-set
7404 ASSERT(current->journal_info == NULL ||
7405 current->journal_info == BTRFS_DIO_SYNC_STUB);
7406 current->journal_info = NULL;
7409 len = min_t(u64, len, fs_info->sectorsize);
7412 lockend = start + len - 1;
7415 * The generic stuff only does filemap_write_and_wait_range, which
7416 * isn't enough if we've written compressed pages to this area, so we
7417 * need to flush the dirty pages again to make absolutely sure that any
7418 * outstanding dirty pages are on disk.
7420 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7421 &BTRFS_I(inode)->runtime_flags)) {
7422 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7423 start + length - 1);
7428 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7432 dio_data->sync = sync;
7433 dio_data->length = length;
7435 dio_data->reserve = round_up(length, fs_info->sectorsize);
7436 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7437 &dio_data->data_reserved,
7438 start, dio_data->reserve);
7440 extent_changeset_free(dio_data->data_reserved);
7445 iomap->private = dio_data;
7449 * If this errors out it's because we couldn't invalidate pagecache for
7450 * this range and we need to fallback to buffered.
7452 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7457 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7464 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7465 * io. INLINE is special, and we could probably kludge it in here, but
7466 * it's still buffered so for safety lets just fall back to the generic
7469 * For COMPRESSED we _have_ to read the entire extent in so we can
7470 * decompress it, so there will be buffering required no matter what we
7471 * do, so go ahead and fallback to buffered.
7473 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7474 * to buffered IO. Don't blame me, this is the price we pay for using
7477 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7478 em->block_start == EXTENT_MAP_INLINE) {
7479 free_extent_map(em);
7481 * If we are in a NOWAIT context, return -EAGAIN in order to
7482 * fallback to buffered IO. This is not only because we can
7483 * block with buffered IO (no support for NOWAIT semantics at
7484 * the moment) but also to avoid returning short reads to user
7485 * space - this happens if we were able to read some data from
7486 * previous non-compressed extents and then when we fallback to
7487 * buffered IO, at btrfs_file_read_iter() by calling
7488 * filemap_read(), we fail to fault in pages for the read buffer,
7489 * in which case filemap_read() returns a short read (the number
7490 * of bytes previously read is > 0, so it does not return -EFAULT).
7492 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
7496 len = min(len, em->len - (start - em->start));
7498 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7502 unlock_extents = true;
7503 /* Recalc len in case the new em is smaller than requested */
7504 len = min(len, em->len - (start - em->start));
7507 * We need to unlock only the end area that we aren't using.
7508 * The rest is going to be unlocked by the endio routine.
7510 lockstart = start + len;
7511 if (lockstart < lockend)
7512 unlock_extents = true;
7516 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7517 lockstart, lockend, &cached_state);
7519 free_extent_state(cached_state);
7522 * Translate extent map information to iomap.
7523 * We trim the extents (and move the addr) even though iomap code does
7524 * that, since we have locked only the parts we are performing I/O in.
7526 if ((em->block_start == EXTENT_MAP_HOLE) ||
7527 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7528 iomap->addr = IOMAP_NULL_ADDR;
7529 iomap->type = IOMAP_HOLE;
7531 iomap->addr = em->block_start + (start - em->start);
7532 iomap->type = IOMAP_MAPPED;
7534 iomap->offset = start;
7535 iomap->bdev = fs_info->fs_devices->latest_bdev;
7536 iomap->length = len;
7538 free_extent_map(em);
7543 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7547 btrfs_delalloc_release_space(BTRFS_I(inode),
7548 dio_data->data_reserved, start,
7549 dio_data->reserve, true);
7550 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7551 extent_changeset_free(dio_data->data_reserved);
7557 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7558 ssize_t written, unsigned int flags, struct iomap *iomap)
7561 struct btrfs_dio_data *dio_data = iomap->private;
7562 size_t submitted = dio_data->submitted;
7563 const bool write = !!(flags & IOMAP_WRITE);
7565 if (!write && (iomap->type == IOMAP_HOLE)) {
7566 /* If reading from a hole, unlock and return */
7567 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7571 if (submitted < length) {
7573 length -= submitted;
7575 __endio_write_update_ordered(BTRFS_I(inode), pos,
7578 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7584 if (dio_data->reserve)
7585 btrfs_delalloc_release_space(BTRFS_I(inode),
7586 dio_data->data_reserved, pos,
7587 dio_data->reserve, true);
7588 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
7589 extent_changeset_free(dio_data->data_reserved);
7593 * We're all done, we can re-set the current->journal_info now safely
7596 if (dio_data->sync) {
7597 ASSERT(current->journal_info == NULL);
7598 current->journal_info = BTRFS_DIO_SYNC_STUB;
7601 iomap->private = NULL;
7606 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7609 * This implies a barrier so that stores to dio_bio->bi_status before
7610 * this and loads of dio_bio->bi_status after this are fully ordered.
7612 if (!refcount_dec_and_test(&dip->refs))
7615 if (bio_op(dip->dio_bio) == REQ_OP_WRITE) {
7616 __endio_write_update_ordered(BTRFS_I(dip->inode),
7617 dip->logical_offset,
7619 !dip->dio_bio->bi_status);
7621 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7622 dip->logical_offset,
7623 dip->logical_offset + dip->bytes - 1);
7626 bio_endio(dip->dio_bio);
7630 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7632 unsigned long bio_flags)
7634 struct btrfs_dio_private *dip = bio->bi_private;
7635 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7638 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7640 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7644 refcount_inc(&dip->refs);
7645 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7647 refcount_dec(&dip->refs);
7651 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7652 struct btrfs_io_bio *io_bio,
7653 const bool uptodate)
7655 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7656 const u32 sectorsize = fs_info->sectorsize;
7657 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7658 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7659 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7660 struct bio_vec bvec;
7661 struct bvec_iter iter;
7662 u64 start = io_bio->logical;
7664 blk_status_t err = BLK_STS_OK;
7666 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7667 unsigned int i, nr_sectors, pgoff;
7669 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7670 pgoff = bvec.bv_offset;
7671 for (i = 0; i < nr_sectors; i++) {
7672 ASSERT(pgoff < PAGE_SIZE);
7674 (!csum || !check_data_csum(inode, io_bio, icsum,
7675 bvec.bv_page, pgoff,
7676 start, sectorsize))) {
7677 clean_io_failure(fs_info, failure_tree, io_tree,
7678 start, bvec.bv_page,
7679 btrfs_ino(BTRFS_I(inode)),
7682 blk_status_t status;
7684 status = btrfs_submit_read_repair(inode,
7686 start - io_bio->logical,
7687 bvec.bv_page, pgoff,
7689 start + sectorsize - 1,
7691 submit_dio_repair_bio);
7695 start += sectorsize;
7697 pgoff += sectorsize;
7703 static void __endio_write_update_ordered(struct btrfs_inode *inode,
7704 const u64 offset, const u64 bytes,
7705 const bool uptodate)
7707 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7708 struct btrfs_ordered_extent *ordered = NULL;
7709 struct btrfs_workqueue *wq;
7710 u64 ordered_offset = offset;
7711 u64 ordered_bytes = bytes;
7714 if (btrfs_is_free_space_inode(inode))
7715 wq = fs_info->endio_freespace_worker;
7717 wq = fs_info->endio_write_workers;
7719 while (ordered_offset < offset + bytes) {
7720 last_offset = ordered_offset;
7721 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7725 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7727 btrfs_queue_work(wq, &ordered->work);
7730 * If btrfs_dec_test_ordered_pending does not find any ordered
7731 * extent in the range, we can exit.
7733 if (ordered_offset == last_offset)
7736 * Our bio might span multiple ordered extents. In this case
7737 * we keep going until we have accounted the whole dio.
7739 if (ordered_offset < offset + bytes) {
7740 ordered_bytes = offset + bytes - ordered_offset;
7746 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
7747 struct bio *bio, u64 offset)
7749 struct inode *inode = private_data;
7751 return btrfs_csum_one_bio(BTRFS_I(inode), bio, offset, 1);
7754 static void btrfs_end_dio_bio(struct bio *bio)
7756 struct btrfs_dio_private *dip = bio->bi_private;
7757 blk_status_t err = bio->bi_status;
7760 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7761 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7762 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7764 (unsigned long long)bio->bi_iter.bi_sector,
7765 bio->bi_iter.bi_size, err);
7767 if (bio_op(bio) == REQ_OP_READ) {
7768 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
7773 dip->dio_bio->bi_status = err;
7776 btrfs_dio_private_put(dip);
7779 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7780 struct inode *inode, u64 file_offset, int async_submit)
7782 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7783 struct btrfs_dio_private *dip = bio->bi_private;
7784 bool write = bio_op(bio) == REQ_OP_WRITE;
7787 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7789 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7792 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7797 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7800 if (write && async_submit) {
7801 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7803 btrfs_submit_bio_start_direct_io);
7807 * If we aren't doing async submit, calculate the csum of the
7810 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
7816 csum_offset = file_offset - dip->logical_offset;
7817 csum_offset >>= inode->i_sb->s_blocksize_bits;
7818 csum_offset *= btrfs_super_csum_size(fs_info->super_copy);
7819 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
7822 ret = btrfs_map_bio(fs_info, bio, 0);
7828 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7829 * or ordered extents whether or not we submit any bios.
7831 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7832 struct inode *inode,
7835 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7836 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7838 struct btrfs_dio_private *dip;
7840 dip_size = sizeof(*dip);
7841 if (!write && csum) {
7842 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7843 const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
7846 nblocks = dio_bio->bi_iter.bi_size >> inode->i_sb->s_blocksize_bits;
7847 dip_size += csum_size * nblocks;
7850 dip = kzalloc(dip_size, GFP_NOFS);
7855 dip->logical_offset = file_offset;
7856 dip->bytes = dio_bio->bi_iter.bi_size;
7857 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7858 dip->dio_bio = dio_bio;
7859 refcount_set(&dip->refs, 1);
7863 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
7864 struct bio *dio_bio, loff_t file_offset)
7866 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7867 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7868 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7869 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7870 BTRFS_BLOCK_GROUP_RAID56_MASK);
7871 struct btrfs_dio_private *dip;
7874 int async_submit = 0;
7876 int clone_offset = 0;
7879 blk_status_t status;
7880 struct btrfs_io_geometry geom;
7881 struct btrfs_dio_data *dio_data = iomap->private;
7883 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7886 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7887 file_offset + dio_bio->bi_iter.bi_size - 1);
7889 dio_bio->bi_status = BLK_STS_RESOURCE;
7891 return BLK_QC_T_NONE;
7894 if (!write && csum) {
7896 * Load the csums up front to reduce csum tree searches and
7897 * contention when submitting bios.
7899 status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset,
7901 if (status != BLK_STS_OK)
7905 start_sector = dio_bio->bi_iter.bi_sector;
7906 submit_len = dio_bio->bi_iter.bi_size;
7909 ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio),
7910 start_sector << 9, submit_len,
7913 status = errno_to_blk_status(ret);
7916 ASSERT(geom.len <= INT_MAX);
7918 clone_len = min_t(int, submit_len, geom.len);
7921 * This will never fail as it's passing GPF_NOFS and
7922 * the allocation is backed by btrfs_bioset.
7924 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
7925 bio->bi_private = dip;
7926 bio->bi_end_io = btrfs_end_dio_bio;
7927 btrfs_io_bio(bio)->logical = file_offset;
7929 ASSERT(submit_len >= clone_len);
7930 submit_len -= clone_len;
7933 * Increase the count before we submit the bio so we know
7934 * the end IO handler won't happen before we increase the
7935 * count. Otherwise, the dip might get freed before we're
7936 * done setting it up.
7938 * We transfer the initial reference to the last bio, so we
7939 * don't need to increment the reference count for the last one.
7941 if (submit_len > 0) {
7942 refcount_inc(&dip->refs);
7944 * If we are submitting more than one bio, submit them
7945 * all asynchronously. The exception is RAID 5 or 6, as
7946 * asynchronous checksums make it difficult to collect
7947 * full stripe writes.
7953 status = btrfs_submit_dio_bio(bio, inode, file_offset,
7958 refcount_dec(&dip->refs);
7962 dio_data->submitted += clone_len;
7963 clone_offset += clone_len;
7964 start_sector += clone_len >> 9;
7965 file_offset += clone_len;
7966 } while (submit_len > 0);
7967 return BLK_QC_T_NONE;
7970 dip->dio_bio->bi_status = status;
7971 btrfs_dio_private_put(dip);
7972 return BLK_QC_T_NONE;
7975 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
7976 const struct iov_iter *iter, loff_t offset)
7980 unsigned int blocksize_mask = fs_info->sectorsize - 1;
7981 ssize_t retval = -EINVAL;
7983 if (offset & blocksize_mask)
7986 if (iov_iter_alignment(iter) & blocksize_mask)
7989 /* If this is a write we don't need to check anymore */
7990 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
7993 * Check to make sure we don't have duplicate iov_base's in this
7994 * iovec, if so return EINVAL, otherwise we'll get csum errors
7995 * when reading back.
7997 for (seg = 0; seg < iter->nr_segs; seg++) {
7998 for (i = seg + 1; i < iter->nr_segs; i++) {
7999 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8008 static inline int btrfs_maybe_fsync_end_io(struct kiocb *iocb, ssize_t size,
8009 int error, unsigned flags)
8012 * Now if we're still in the context of our submitter we know we can't
8013 * safely run generic_write_sync(), so clear our flag here so that the
8014 * caller knows to follow up with a sync.
8016 if (current->journal_info == BTRFS_DIO_SYNC_STUB) {
8017 current->journal_info = NULL;
8025 iocb->ki_flags |= IOCB_DSYNC;
8026 return generic_write_sync(iocb, size);
8032 static const struct iomap_ops btrfs_dio_iomap_ops = {
8033 .iomap_begin = btrfs_dio_iomap_begin,
8034 .iomap_end = btrfs_dio_iomap_end,
8037 static const struct iomap_dio_ops btrfs_dio_ops = {
8038 .submit_io = btrfs_submit_direct,
8041 static const struct iomap_dio_ops btrfs_sync_dops = {
8042 .submit_io = btrfs_submit_direct,
8043 .end_io = btrfs_maybe_fsync_end_io,
8046 ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8048 struct file *file = iocb->ki_filp;
8049 struct inode *inode = file->f_mapping->host;
8050 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8051 struct extent_changeset *data_reserved = NULL;
8052 loff_t offset = iocb->ki_pos;
8054 bool relock = false;
8057 if (check_direct_IO(fs_info, iter, offset)) {
8058 ASSERT(current->journal_info == NULL ||
8059 current->journal_info == BTRFS_DIO_SYNC_STUB);
8060 current->journal_info = NULL;
8064 count = iov_iter_count(iter);
8065 if (iov_iter_rw(iter) == WRITE) {
8067 * If the write DIO is beyond the EOF, we need update
8068 * the isize, but it is protected by i_mutex. So we can
8069 * not unlock the i_mutex at this case.
8071 if (offset + count <= inode->i_size) {
8072 inode_unlock(inode);
8075 down_read(&BTRFS_I(inode)->dio_sem);
8079 * We have are actually a sync iocb, so we need our fancy endio to know
8080 * if we need to sync.
8082 if (current->journal_info)
8083 ret = iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops,
8084 &btrfs_sync_dops, is_sync_kiocb(iocb));
8086 ret = iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops,
8087 &btrfs_dio_ops, is_sync_kiocb(iocb));
8089 if (ret == -ENOTBLK)
8092 if (iov_iter_rw(iter) == WRITE)
8093 up_read(&BTRFS_I(inode)->dio_sem);
8098 extent_changeset_free(data_reserved);
8102 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8107 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8111 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8114 int btrfs_readpage(struct file *file, struct page *page)
8116 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8117 u64 start = page_offset(page);
8118 u64 end = start + PAGE_SIZE - 1;
8119 unsigned long bio_flags = 0;
8120 struct bio *bio = NULL;
8123 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8125 ret = btrfs_do_readpage(page, NULL, &bio, &bio_flags, 0, NULL);
8127 ret = submit_one_bio(bio, 0, bio_flags);
8131 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8133 struct inode *inode = page->mapping->host;
8136 if (current->flags & PF_MEMALLOC) {
8137 redirty_page_for_writepage(wbc, page);
8143 * If we are under memory pressure we will call this directly from the
8144 * VM, we need to make sure we have the inode referenced for the ordered
8145 * extent. If not just return like we didn't do anything.
8147 if (!igrab(inode)) {
8148 redirty_page_for_writepage(wbc, page);
8149 return AOP_WRITEPAGE_ACTIVATE;
8151 ret = extent_write_full_page(page, wbc);
8152 btrfs_add_delayed_iput(inode);
8156 static int btrfs_writepages(struct address_space *mapping,
8157 struct writeback_control *wbc)
8159 return extent_writepages(mapping, wbc);
8162 static void btrfs_readahead(struct readahead_control *rac)
8164 extent_readahead(rac);
8167 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8169 int ret = try_release_extent_mapping(page, gfp_flags);
8171 detach_page_private(page);
8175 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8177 if (PageWriteback(page) || PageDirty(page))
8179 return __btrfs_releasepage(page, gfp_flags);
8182 #ifdef CONFIG_MIGRATION
8183 static int btrfs_migratepage(struct address_space *mapping,
8184 struct page *newpage, struct page *page,
8185 enum migrate_mode mode)
8189 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8190 if (ret != MIGRATEPAGE_SUCCESS)
8193 if (page_has_private(page))
8194 attach_page_private(newpage, detach_page_private(page));
8196 if (PagePrivate2(page)) {
8197 ClearPagePrivate2(page);
8198 SetPagePrivate2(newpage);
8201 if (mode != MIGRATE_SYNC_NO_COPY)
8202 migrate_page_copy(newpage, page);
8204 migrate_page_states(newpage, page);
8205 return MIGRATEPAGE_SUCCESS;
8209 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8210 unsigned int length)
8212 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8213 struct extent_io_tree *tree = &inode->io_tree;
8214 struct btrfs_ordered_extent *ordered;
8215 struct extent_state *cached_state = NULL;
8216 u64 page_start = page_offset(page);
8217 u64 page_end = page_start + PAGE_SIZE - 1;
8220 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8223 * we have the page locked, so new writeback can't start,
8224 * and the dirty bit won't be cleared while we are here.
8226 * Wait for IO on this page so that we can safely clear
8227 * the PagePrivate2 bit and do ordered accounting
8229 wait_on_page_writeback(page);
8232 * For subpage case, we have call sites like
8233 * btrfs_punch_hole_lock_range() which passes range not aligned to
8235 * If the range doesn't cover the full page, we don't need to and
8236 * shouldn't clear page extent mapped, as page->private can still
8237 * record subpage dirty bits for other part of the range.
8239 * For cases that can invalidate the full even the range doesn't
8240 * cover the full page, like invalidating the last page, we're
8241 * still safe to wait for ordered extent to finish.
8243 if (!(offset == 0 && length == PAGE_SIZE)) {
8244 btrfs_releasepage(page, GFP_NOFS);
8248 if (!inode_evicting)
8249 lock_extent_bits(tree, page_start, page_end, &cached_state);
8253 ordered = btrfs_lookup_ordered_range(inode, start, page_end - start + 1);
8256 ordered->file_offset + ordered->num_bytes - 1);
8258 * IO on this page will never be started, so we need
8259 * to account for any ordered extents now
8261 if (!inode_evicting)
8262 clear_extent_bit(tree, start, end,
8263 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8264 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8265 EXTENT_DEFRAG, 1, 0, &cached_state);
8267 * whoever cleared the private bit is responsible
8268 * for the finish_ordered_io
8270 if (TestClearPagePrivate2(page)) {
8271 struct btrfs_ordered_inode_tree *tree;
8274 tree = &inode->ordered_tree;
8276 spin_lock_irq(&tree->lock);
8277 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8278 new_len = start - ordered->file_offset;
8279 if (new_len < ordered->truncated_len)
8280 ordered->truncated_len = new_len;
8281 spin_unlock_irq(&tree->lock);
8283 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8285 end - start + 1, 1))
8286 btrfs_finish_ordered_io(ordered);
8288 btrfs_put_ordered_extent(ordered);
8289 if (!inode_evicting) {
8290 cached_state = NULL;
8291 lock_extent_bits(tree, start, end,
8296 if (start < page_end)
8301 * Qgroup reserved space handler
8302 * Page here will be either
8303 * 1) Already written to disk or ordered extent already submitted
8304 * Then its QGROUP_RESERVED bit in io_tree is already cleaned.
8305 * Qgroup will be handled by its qgroup_record then.
8306 * btrfs_qgroup_free_data() call will do nothing here.
8308 * 2) Not written to disk yet
8309 * Then btrfs_qgroup_free_data() call will clear the QGROUP_RESERVED
8310 * bit of its io_tree, and free the qgroup reserved data space.
8311 * Since the IO will never happen for this page.
8313 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8314 if (!inode_evicting) {
8315 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8316 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8317 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8320 __btrfs_releasepage(page, GFP_NOFS);
8323 ClearPageChecked(page);
8324 detach_page_private(page);
8328 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8329 * called from a page fault handler when a page is first dirtied. Hence we must
8330 * be careful to check for EOF conditions here. We set the page up correctly
8331 * for a written page which means we get ENOSPC checking when writing into
8332 * holes and correct delalloc and unwritten extent mapping on filesystems that
8333 * support these features.
8335 * We are not allowed to take the i_mutex here so we have to play games to
8336 * protect against truncate races as the page could now be beyond EOF. Because
8337 * truncate_setsize() writes the inode size before removing pages, once we have
8338 * the page lock we can determine safely if the page is beyond EOF. If it is not
8339 * beyond EOF, then the page is guaranteed safe against truncation until we
8342 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8344 struct page *page = vmf->page;
8345 struct inode *inode = file_inode(vmf->vma->vm_file);
8346 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8347 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8348 struct btrfs_ordered_extent *ordered;
8349 struct extent_state *cached_state = NULL;
8350 struct extent_changeset *data_reserved = NULL;
8352 unsigned long zero_start;
8362 reserved_space = PAGE_SIZE;
8364 sb_start_pagefault(inode->i_sb);
8365 page_start = page_offset(page);
8366 page_end = page_start + PAGE_SIZE - 1;
8370 * Reserving delalloc space after obtaining the page lock can lead to
8371 * deadlock. For example, if a dirty page is locked by this function
8372 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8373 * dirty page write out, then the btrfs_writepage() function could
8374 * end up waiting indefinitely to get a lock on the page currently
8375 * being processed by btrfs_page_mkwrite() function.
8377 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8378 page_start, reserved_space);
8380 ret2 = file_update_time(vmf->vma->vm_file);
8384 ret = vmf_error(ret2);
8390 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8393 size = i_size_read(inode);
8395 if ((page->mapping != inode->i_mapping) ||
8396 (page_start >= size)) {
8397 /* page got truncated out from underneath us */
8400 wait_on_page_writeback(page);
8402 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8403 set_page_extent_mapped(page);
8406 * we can't set the delalloc bits if there are pending ordered
8407 * extents. Drop our locks and wait for them to finish
8409 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8412 unlock_extent_cached(io_tree, page_start, page_end,
8415 btrfs_start_ordered_extent(ordered, 1);
8416 btrfs_put_ordered_extent(ordered);
8420 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8421 reserved_space = round_up(size - page_start,
8422 fs_info->sectorsize);
8423 if (reserved_space < PAGE_SIZE) {
8424 end = page_start + reserved_space - 1;
8425 btrfs_delalloc_release_space(BTRFS_I(inode),
8426 data_reserved, page_start,
8427 PAGE_SIZE - reserved_space, true);
8432 * page_mkwrite gets called when the page is firstly dirtied after it's
8433 * faulted in, but write(2) could also dirty a page and set delalloc
8434 * bits, thus in this case for space account reason, we still need to
8435 * clear any delalloc bits within this page range since we have to
8436 * reserve data&meta space before lock_page() (see above comments).
8438 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8439 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8440 EXTENT_DEFRAG, 0, 0, &cached_state);
8442 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8445 unlock_extent_cached(io_tree, page_start, page_end,
8447 ret = VM_FAULT_SIGBUS;
8451 /* page is wholly or partially inside EOF */
8452 if (page_start + PAGE_SIZE > size)
8453 zero_start = offset_in_page(size);
8455 zero_start = PAGE_SIZE;
8457 if (zero_start != PAGE_SIZE) {
8459 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8460 flush_dcache_page(page);
8463 ClearPageChecked(page);
8464 set_page_dirty(page);
8465 SetPageUptodate(page);
8467 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8469 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8471 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8472 sb_end_pagefault(inode->i_sb);
8473 extent_changeset_free(data_reserved);
8474 return VM_FAULT_LOCKED;
8479 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8480 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8481 reserved_space, (ret != 0));
8483 sb_end_pagefault(inode->i_sb);
8484 extent_changeset_free(data_reserved);
8488 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8490 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8491 struct btrfs_root *root = BTRFS_I(inode)->root;
8492 struct btrfs_block_rsv *rsv;
8494 struct btrfs_trans_handle *trans;
8495 u64 mask = fs_info->sectorsize - 1;
8496 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8498 if (!skip_writeback) {
8499 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8506 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8507 * things going on here:
8509 * 1) We need to reserve space to update our inode.
8511 * 2) We need to have something to cache all the space that is going to
8512 * be free'd up by the truncate operation, but also have some slack
8513 * space reserved in case it uses space during the truncate (thank you
8514 * very much snapshotting).
8516 * And we need these to be separate. The fact is we can use a lot of
8517 * space doing the truncate, and we have no earthly idea how much space
8518 * we will use, so we need the truncate reservation to be separate so it
8519 * doesn't end up using space reserved for updating the inode. We also
8520 * need to be able to stop the transaction and start a new one, which
8521 * means we need to be able to update the inode several times, and we
8522 * have no idea of knowing how many times that will be, so we can't just
8523 * reserve 1 item for the entirety of the operation, so that has to be
8524 * done separately as well.
8526 * So that leaves us with
8528 * 1) rsv - for the truncate reservation, which we will steal from the
8529 * transaction reservation.
8530 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8531 * updating the inode.
8533 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8536 rsv->size = min_size;
8540 * 1 for the truncate slack space
8541 * 1 for updating the inode.
8543 trans = btrfs_start_transaction(root, 2);
8544 if (IS_ERR(trans)) {
8545 ret = PTR_ERR(trans);
8549 /* Migrate the slack space for the truncate to our reserve */
8550 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8555 * So if we truncate and then write and fsync we normally would just
8556 * write the extents that changed, which is a problem if we need to
8557 * first truncate that entire inode. So set this flag so we write out
8558 * all of the extents in the inode to the sync log so we're completely
8561 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8562 trans->block_rsv = rsv;
8565 ret = btrfs_truncate_inode_items(trans, root, inode,
8567 BTRFS_EXTENT_DATA_KEY);
8568 trans->block_rsv = &fs_info->trans_block_rsv;
8569 if (ret != -ENOSPC && ret != -EAGAIN)
8572 ret = btrfs_update_inode(trans, root, inode);
8576 btrfs_end_transaction(trans);
8577 btrfs_btree_balance_dirty(fs_info);
8579 trans = btrfs_start_transaction(root, 2);
8580 if (IS_ERR(trans)) {
8581 ret = PTR_ERR(trans);
8586 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8587 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8588 rsv, min_size, false);
8589 BUG_ON(ret); /* shouldn't happen */
8590 trans->block_rsv = rsv;
8594 * We can't call btrfs_truncate_block inside a trans handle as we could
8595 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8596 * we've truncated everything except the last little bit, and can do
8597 * btrfs_truncate_block and then update the disk_i_size.
8599 if (ret == NEED_TRUNCATE_BLOCK) {
8600 btrfs_end_transaction(trans);
8601 btrfs_btree_balance_dirty(fs_info);
8603 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8606 trans = btrfs_start_transaction(root, 1);
8607 if (IS_ERR(trans)) {
8608 ret = PTR_ERR(trans);
8611 btrfs_inode_safe_disk_i_size_write(inode, 0);
8617 trans->block_rsv = &fs_info->trans_block_rsv;
8618 ret2 = btrfs_update_inode(trans, root, inode);
8622 ret2 = btrfs_end_transaction(trans);
8625 btrfs_btree_balance_dirty(fs_info);
8628 btrfs_free_block_rsv(fs_info, rsv);
8634 * create a new subvolume directory/inode (helper for the ioctl).
8636 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8637 struct btrfs_root *new_root,
8638 struct btrfs_root *parent_root,
8641 struct inode *inode;
8645 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8646 new_dirid, new_dirid,
8647 S_IFDIR | (~current_umask() & S_IRWXUGO),
8650 return PTR_ERR(inode);
8651 inode->i_op = &btrfs_dir_inode_operations;
8652 inode->i_fop = &btrfs_dir_file_operations;
8654 set_nlink(inode, 1);
8655 btrfs_i_size_write(BTRFS_I(inode), 0);
8656 unlock_new_inode(inode);
8658 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8660 btrfs_err(new_root->fs_info,
8661 "error inheriting subvolume %llu properties: %d",
8662 new_root->root_key.objectid, err);
8664 err = btrfs_update_inode(trans, new_root, inode);
8670 struct inode *btrfs_alloc_inode(struct super_block *sb)
8672 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8673 struct btrfs_inode *ei;
8674 struct inode *inode;
8676 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8683 ei->last_sub_trans = 0;
8684 ei->logged_trans = 0;
8685 ei->delalloc_bytes = 0;
8686 ei->new_delalloc_bytes = 0;
8687 ei->defrag_bytes = 0;
8688 ei->disk_i_size = 0;
8691 ei->index_cnt = (u64)-1;
8693 ei->last_unlink_trans = 0;
8694 ei->last_reflink_trans = 0;
8695 ei->last_log_commit = 0;
8697 spin_lock_init(&ei->lock);
8698 ei->outstanding_extents = 0;
8699 if (sb->s_magic != BTRFS_TEST_MAGIC)
8700 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8701 BTRFS_BLOCK_RSV_DELALLOC);
8702 ei->runtime_flags = 0;
8703 ei->prop_compress = BTRFS_COMPRESS_NONE;
8704 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8706 ei->delayed_node = NULL;
8708 ei->i_otime.tv_sec = 0;
8709 ei->i_otime.tv_nsec = 0;
8711 inode = &ei->vfs_inode;
8712 extent_map_tree_init(&ei->extent_tree);
8713 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8714 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8715 IO_TREE_INODE_IO_FAILURE, inode);
8716 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8717 IO_TREE_INODE_FILE_EXTENT, inode);
8718 ei->io_tree.track_uptodate = true;
8719 ei->io_failure_tree.track_uptodate = true;
8720 atomic_set(&ei->sync_writers, 0);
8721 mutex_init(&ei->log_mutex);
8722 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8723 INIT_LIST_HEAD(&ei->delalloc_inodes);
8724 INIT_LIST_HEAD(&ei->delayed_iput);
8725 RB_CLEAR_NODE(&ei->rb_node);
8726 init_rwsem(&ei->dio_sem);
8731 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8732 void btrfs_test_destroy_inode(struct inode *inode)
8734 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8735 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8739 void btrfs_free_inode(struct inode *inode)
8741 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8744 void btrfs_destroy_inode(struct inode *vfs_inode)
8746 struct btrfs_ordered_extent *ordered;
8747 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8748 struct btrfs_root *root = inode->root;
8750 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8751 WARN_ON(vfs_inode->i_data.nrpages);
8752 WARN_ON(inode->block_rsv.reserved);
8753 WARN_ON(inode->block_rsv.size);
8754 WARN_ON(inode->outstanding_extents);
8755 WARN_ON(inode->delalloc_bytes);
8756 WARN_ON(inode->new_delalloc_bytes);
8757 WARN_ON(inode->csum_bytes);
8758 WARN_ON(inode->defrag_bytes);
8761 * This can happen where we create an inode, but somebody else also
8762 * created the same inode and we need to destroy the one we already
8769 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8773 btrfs_err(root->fs_info,
8774 "found ordered extent %llu %llu on inode cleanup",
8775 ordered->file_offset, ordered->num_bytes);
8776 btrfs_remove_ordered_extent(inode, ordered);
8777 btrfs_put_ordered_extent(ordered);
8778 btrfs_put_ordered_extent(ordered);
8781 btrfs_qgroup_check_reserved_leak(inode);
8782 inode_tree_del(inode);
8783 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8784 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8785 btrfs_put_root(inode->root);
8788 int btrfs_drop_inode(struct inode *inode)
8790 struct btrfs_root *root = BTRFS_I(inode)->root;
8795 /* the snap/subvol tree is on deleting */
8796 if (btrfs_root_refs(&root->root_item) == 0)
8799 return generic_drop_inode(inode);
8802 static void init_once(void *foo)
8804 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8806 inode_init_once(&ei->vfs_inode);
8809 void __cold btrfs_destroy_cachep(void)
8812 * Make sure all delayed rcu free inodes are flushed before we
8816 kmem_cache_destroy(btrfs_inode_cachep);
8817 kmem_cache_destroy(btrfs_trans_handle_cachep);
8818 kmem_cache_destroy(btrfs_path_cachep);
8819 kmem_cache_destroy(btrfs_free_space_cachep);
8820 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8823 int __init btrfs_init_cachep(void)
8825 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8826 sizeof(struct btrfs_inode), 0,
8827 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8829 if (!btrfs_inode_cachep)
8832 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8833 sizeof(struct btrfs_trans_handle), 0,
8834 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8835 if (!btrfs_trans_handle_cachep)
8838 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8839 sizeof(struct btrfs_path), 0,
8840 SLAB_MEM_SPREAD, NULL);
8841 if (!btrfs_path_cachep)
8844 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8845 sizeof(struct btrfs_free_space), 0,
8846 SLAB_MEM_SPREAD, NULL);
8847 if (!btrfs_free_space_cachep)
8850 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8851 PAGE_SIZE, PAGE_SIZE,
8852 SLAB_MEM_SPREAD, NULL);
8853 if (!btrfs_free_space_bitmap_cachep)
8858 btrfs_destroy_cachep();
8862 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8863 u32 request_mask, unsigned int flags)
8866 struct inode *inode = d_inode(path->dentry);
8867 u32 blocksize = inode->i_sb->s_blocksize;
8868 u32 bi_flags = BTRFS_I(inode)->flags;
8870 stat->result_mask |= STATX_BTIME;
8871 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8872 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8873 if (bi_flags & BTRFS_INODE_APPEND)
8874 stat->attributes |= STATX_ATTR_APPEND;
8875 if (bi_flags & BTRFS_INODE_COMPRESS)
8876 stat->attributes |= STATX_ATTR_COMPRESSED;
8877 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8878 stat->attributes |= STATX_ATTR_IMMUTABLE;
8879 if (bi_flags & BTRFS_INODE_NODUMP)
8880 stat->attributes |= STATX_ATTR_NODUMP;
8882 stat->attributes_mask |= (STATX_ATTR_APPEND |
8883 STATX_ATTR_COMPRESSED |
8884 STATX_ATTR_IMMUTABLE |
8887 generic_fillattr(inode, stat);
8888 stat->dev = BTRFS_I(inode)->root->anon_dev;
8890 spin_lock(&BTRFS_I(inode)->lock);
8891 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8892 spin_unlock(&BTRFS_I(inode)->lock);
8893 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8894 ALIGN(delalloc_bytes, blocksize)) >> 9;
8898 static int btrfs_rename_exchange(struct inode *old_dir,
8899 struct dentry *old_dentry,
8900 struct inode *new_dir,
8901 struct dentry *new_dentry)
8903 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8904 struct btrfs_trans_handle *trans;
8905 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8906 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8907 struct inode *new_inode = new_dentry->d_inode;
8908 struct inode *old_inode = old_dentry->d_inode;
8909 struct timespec64 ctime = current_time(old_inode);
8910 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8911 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8916 bool root_log_pinned = false;
8917 bool dest_log_pinned = false;
8918 bool need_abort = false;
8921 * For non-subvolumes allow exchange only within one subvolume, in the
8922 * same inode namespace. Two subvolumes (represented as directory) can
8923 * be exchanged as they're a logical link and have a fixed inode number.
8926 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8927 new_ino != BTRFS_FIRST_FREE_OBJECTID))
8930 /* close the race window with snapshot create/destroy ioctl */
8931 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8932 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8933 down_read(&fs_info->subvol_sem);
8936 * We want to reserve the absolute worst case amount of items. So if
8937 * both inodes are subvols and we need to unlink them then that would
8938 * require 4 item modifications, but if they are both normal inodes it
8939 * would require 5 item modifications, so we'll assume their normal
8940 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
8941 * should cover the worst case number of items we'll modify.
8943 trans = btrfs_start_transaction(root, 12);
8944 if (IS_ERR(trans)) {
8945 ret = PTR_ERR(trans);
8950 btrfs_record_root_in_trans(trans, dest);
8953 * We need to find a free sequence number both in the source and
8954 * in the destination directory for the exchange.
8956 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8959 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8963 BTRFS_I(old_inode)->dir_index = 0ULL;
8964 BTRFS_I(new_inode)->dir_index = 0ULL;
8966 /* Reference for the source. */
8967 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8968 /* force full log commit if subvolume involved. */
8969 btrfs_set_log_full_commit(trans);
8971 ret = btrfs_insert_inode_ref(trans, dest,
8972 new_dentry->d_name.name,
8973 new_dentry->d_name.len,
8975 btrfs_ino(BTRFS_I(new_dir)),
8982 /* And now for the dest. */
8983 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8984 /* force full log commit if subvolume involved. */
8985 btrfs_set_log_full_commit(trans);
8987 ret = btrfs_insert_inode_ref(trans, root,
8988 old_dentry->d_name.name,
8989 old_dentry->d_name.len,
8991 btrfs_ino(BTRFS_I(old_dir)),
8995 btrfs_abort_transaction(trans, ret);
9000 /* Update inode version and ctime/mtime. */
9001 inode_inc_iversion(old_dir);
9002 inode_inc_iversion(new_dir);
9003 inode_inc_iversion(old_inode);
9004 inode_inc_iversion(new_inode);
9005 old_dir->i_ctime = old_dir->i_mtime = ctime;
9006 new_dir->i_ctime = new_dir->i_mtime = ctime;
9007 old_inode->i_ctime = ctime;
9008 new_inode->i_ctime = ctime;
9010 if (old_dentry->d_parent != new_dentry->d_parent) {
9011 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9012 BTRFS_I(old_inode), 1);
9013 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9014 BTRFS_I(new_inode), 1);
9018 * Now pin the logs of the roots. We do it to ensure that no other task
9019 * can sync the logs while we are in progress with the rename, because
9020 * that could result in an inconsistency in case any of the inodes that
9021 * are part of this rename operation were logged before.
9023 * We pin the logs even if at this precise moment none of the inodes was
9024 * logged before. This is because right after we checked for that, some
9025 * other task fsyncing some other inode not involved with this rename
9026 * operation could log that one of our inodes exists.
9028 * We don't need to pin the logs before the above calls to
9029 * btrfs_insert_inode_ref(), since those don't ever need to change a log.
9031 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
9032 btrfs_pin_log_trans(root);
9033 root_log_pinned = true;
9035 if (new_ino != BTRFS_FIRST_FREE_OBJECTID) {
9036 btrfs_pin_log_trans(dest);
9037 dest_log_pinned = true;
9040 /* src is a subvolume */
9041 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9042 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9043 } else { /* src is an inode */
9044 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9045 BTRFS_I(old_dentry->d_inode),
9046 old_dentry->d_name.name,
9047 old_dentry->d_name.len);
9049 ret = btrfs_update_inode(trans, root, old_inode);
9052 btrfs_abort_transaction(trans, ret);
9056 /* dest is a subvolume */
9057 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9058 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9059 } else { /* dest is an inode */
9060 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9061 BTRFS_I(new_dentry->d_inode),
9062 new_dentry->d_name.name,
9063 new_dentry->d_name.len);
9065 ret = btrfs_update_inode(trans, dest, new_inode);
9068 btrfs_abort_transaction(trans, ret);
9072 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9073 new_dentry->d_name.name,
9074 new_dentry->d_name.len, 0, old_idx);
9076 btrfs_abort_transaction(trans, ret);
9080 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9081 old_dentry->d_name.name,
9082 old_dentry->d_name.len, 0, new_idx);
9084 btrfs_abort_transaction(trans, ret);
9088 if (old_inode->i_nlink == 1)
9089 BTRFS_I(old_inode)->dir_index = old_idx;
9090 if (new_inode->i_nlink == 1)
9091 BTRFS_I(new_inode)->dir_index = new_idx;
9093 if (root_log_pinned) {
9094 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9095 new_dentry->d_parent);
9096 btrfs_end_log_trans(root);
9097 root_log_pinned = false;
9099 if (dest_log_pinned) {
9100 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9101 old_dentry->d_parent);
9102 btrfs_end_log_trans(dest);
9103 dest_log_pinned = false;
9107 * If we have pinned a log and an error happened, we unpin tasks
9108 * trying to sync the log and force them to fallback to a transaction
9109 * commit if the log currently contains any of the inodes involved in
9110 * this rename operation (to ensure we do not persist a log with an
9111 * inconsistent state for any of these inodes or leading to any
9112 * inconsistencies when replayed). If the transaction was aborted, the
9113 * abortion reason is propagated to userspace when attempting to commit
9114 * the transaction. If the log does not contain any of these inodes, we
9115 * allow the tasks to sync it.
9117 if (ret && (root_log_pinned || dest_log_pinned)) {
9118 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9119 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9120 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9122 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9123 btrfs_set_log_full_commit(trans);
9125 if (root_log_pinned) {
9126 btrfs_end_log_trans(root);
9127 root_log_pinned = false;
9129 if (dest_log_pinned) {
9130 btrfs_end_log_trans(dest);
9131 dest_log_pinned = false;
9134 ret2 = btrfs_end_transaction(trans);
9135 ret = ret ? ret : ret2;
9137 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9138 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9139 up_read(&fs_info->subvol_sem);
9144 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9145 struct btrfs_root *root,
9147 struct dentry *dentry)
9150 struct inode *inode;
9154 ret = btrfs_find_free_objectid(root, &objectid);
9158 inode = btrfs_new_inode(trans, root, dir,
9159 dentry->d_name.name,
9161 btrfs_ino(BTRFS_I(dir)),
9163 S_IFCHR | WHITEOUT_MODE,
9166 if (IS_ERR(inode)) {
9167 ret = PTR_ERR(inode);
9171 inode->i_op = &btrfs_special_inode_operations;
9172 init_special_inode(inode, inode->i_mode,
9175 ret = btrfs_init_inode_security(trans, inode, dir,
9180 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9181 BTRFS_I(inode), 0, index);
9185 ret = btrfs_update_inode(trans, root, inode);
9187 unlock_new_inode(inode);
9189 inode_dec_link_count(inode);
9195 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9196 struct inode *new_dir, struct dentry *new_dentry,
9199 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9200 struct btrfs_trans_handle *trans;
9201 unsigned int trans_num_items;
9202 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9203 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9204 struct inode *new_inode = d_inode(new_dentry);
9205 struct inode *old_inode = d_inode(old_dentry);
9209 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9210 bool log_pinned = false;
9212 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9215 /* we only allow rename subvolume link between subvolumes */
9216 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9219 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9220 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9223 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9224 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9228 /* check for collisions, even if the name isn't there */
9229 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9230 new_dentry->d_name.name,
9231 new_dentry->d_name.len);
9234 if (ret == -EEXIST) {
9236 * eexist without a new_inode */
9237 if (WARN_ON(!new_inode)) {
9241 /* maybe -EOVERFLOW */
9248 * we're using rename to replace one file with another. Start IO on it
9249 * now so we don't add too much work to the end of the transaction
9251 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9252 filemap_flush(old_inode->i_mapping);
9254 /* close the racy window with snapshot create/destroy ioctl */
9255 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9256 down_read(&fs_info->subvol_sem);
9258 * We want to reserve the absolute worst case amount of items. So if
9259 * both inodes are subvols and we need to unlink them then that would
9260 * require 4 item modifications, but if they are both normal inodes it
9261 * would require 5 item modifications, so we'll assume they are normal
9262 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9263 * should cover the worst case number of items we'll modify.
9264 * If our rename has the whiteout flag, we need more 5 units for the
9265 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9266 * when selinux is enabled).
9268 trans_num_items = 11;
9269 if (flags & RENAME_WHITEOUT)
9270 trans_num_items += 5;
9271 trans = btrfs_start_transaction(root, trans_num_items);
9272 if (IS_ERR(trans)) {
9273 ret = PTR_ERR(trans);
9278 btrfs_record_root_in_trans(trans, dest);
9280 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9284 BTRFS_I(old_inode)->dir_index = 0ULL;
9285 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9286 /* force full log commit if subvolume involved. */
9287 btrfs_set_log_full_commit(trans);
9289 ret = btrfs_insert_inode_ref(trans, dest,
9290 new_dentry->d_name.name,
9291 new_dentry->d_name.len,
9293 btrfs_ino(BTRFS_I(new_dir)), index);
9298 inode_inc_iversion(old_dir);
9299 inode_inc_iversion(new_dir);
9300 inode_inc_iversion(old_inode);
9301 old_dir->i_ctime = old_dir->i_mtime =
9302 new_dir->i_ctime = new_dir->i_mtime =
9303 old_inode->i_ctime = current_time(old_dir);
9305 if (old_dentry->d_parent != new_dentry->d_parent)
9306 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9307 BTRFS_I(old_inode), 1);
9309 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9310 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9313 * Now pin the log. We do it to ensure that no other task can
9314 * sync the log while we are in progress with the rename, as
9315 * that could result in an inconsistency in case any of the
9316 * inodes that are part of this rename operation were logged
9319 * We pin the log even if at this precise moment none of the
9320 * inodes was logged before. This is because right after we
9321 * checked for that, some other task fsyncing some other inode
9322 * not involved with this rename operation could log that one of
9323 * our inodes exists.
9325 * We don't need to pin the logs before the above call to
9326 * btrfs_insert_inode_ref(), since that does not need to change
9329 btrfs_pin_log_trans(root);
9331 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9332 BTRFS_I(d_inode(old_dentry)),
9333 old_dentry->d_name.name,
9334 old_dentry->d_name.len);
9336 ret = btrfs_update_inode(trans, root, old_inode);
9339 btrfs_abort_transaction(trans, ret);
9344 inode_inc_iversion(new_inode);
9345 new_inode->i_ctime = current_time(new_inode);
9346 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9347 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9348 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9349 BUG_ON(new_inode->i_nlink == 0);
9351 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9352 BTRFS_I(d_inode(new_dentry)),
9353 new_dentry->d_name.name,
9354 new_dentry->d_name.len);
9356 if (!ret && new_inode->i_nlink == 0)
9357 ret = btrfs_orphan_add(trans,
9358 BTRFS_I(d_inode(new_dentry)));
9360 btrfs_abort_transaction(trans, ret);
9365 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9366 new_dentry->d_name.name,
9367 new_dentry->d_name.len, 0, index);
9369 btrfs_abort_transaction(trans, ret);
9373 if (old_inode->i_nlink == 1)
9374 BTRFS_I(old_inode)->dir_index = index;
9377 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9378 new_dentry->d_parent);
9379 btrfs_end_log_trans(root);
9383 if (flags & RENAME_WHITEOUT) {
9384 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9388 btrfs_abort_transaction(trans, ret);
9394 * If we have pinned the log and an error happened, we unpin tasks
9395 * trying to sync the log and force them to fallback to a transaction
9396 * commit if the log currently contains any of the inodes involved in
9397 * this rename operation (to ensure we do not persist a log with an
9398 * inconsistent state for any of these inodes or leading to any
9399 * inconsistencies when replayed). If the transaction was aborted, the
9400 * abortion reason is propagated to userspace when attempting to commit
9401 * the transaction. If the log does not contain any of these inodes, we
9402 * allow the tasks to sync it.
9404 if (ret && log_pinned) {
9405 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9406 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9407 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9409 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9410 btrfs_set_log_full_commit(trans);
9412 btrfs_end_log_trans(root);
9415 ret2 = btrfs_end_transaction(trans);
9416 ret = ret ? ret : ret2;
9418 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9419 up_read(&fs_info->subvol_sem);
9424 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9425 struct inode *new_dir, struct dentry *new_dentry,
9428 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9431 if (flags & RENAME_EXCHANGE)
9432 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9435 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9438 struct btrfs_delalloc_work {
9439 struct inode *inode;
9440 struct completion completion;
9441 struct list_head list;
9442 struct btrfs_work work;
9445 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9447 struct btrfs_delalloc_work *delalloc_work;
9448 struct inode *inode;
9450 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9452 inode = delalloc_work->inode;
9453 filemap_flush(inode->i_mapping);
9454 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9455 &BTRFS_I(inode)->runtime_flags))
9456 filemap_flush(inode->i_mapping);
9459 complete(&delalloc_work->completion);
9462 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9464 struct btrfs_delalloc_work *work;
9466 work = kmalloc(sizeof(*work), GFP_NOFS);
9470 init_completion(&work->completion);
9471 INIT_LIST_HEAD(&work->list);
9472 work->inode = inode;
9473 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9479 * some fairly slow code that needs optimization. This walks the list
9480 * of all the inodes with pending delalloc and forces them to disk.
9482 static int start_delalloc_inodes(struct btrfs_root *root,
9483 struct writeback_control *wbc, bool snapshot,
9484 bool in_reclaim_context)
9486 struct btrfs_inode *binode;
9487 struct inode *inode;
9488 struct btrfs_delalloc_work *work, *next;
9489 struct list_head works;
9490 struct list_head splice;
9492 bool full_flush = wbc->nr_to_write == LONG_MAX;
9494 INIT_LIST_HEAD(&works);
9495 INIT_LIST_HEAD(&splice);
9497 mutex_lock(&root->delalloc_mutex);
9498 spin_lock(&root->delalloc_lock);
9499 list_splice_init(&root->delalloc_inodes, &splice);
9500 while (!list_empty(&splice)) {
9501 binode = list_entry(splice.next, struct btrfs_inode,
9504 list_move_tail(&binode->delalloc_inodes,
9505 &root->delalloc_inodes);
9507 if (in_reclaim_context &&
9508 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9511 inode = igrab(&binode->vfs_inode);
9513 cond_resched_lock(&root->delalloc_lock);
9516 spin_unlock(&root->delalloc_lock);
9519 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9520 &binode->runtime_flags);
9522 work = btrfs_alloc_delalloc_work(inode);
9528 list_add_tail(&work->list, &works);
9529 btrfs_queue_work(root->fs_info->flush_workers,
9532 ret = sync_inode(inode, wbc);
9534 test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9535 &BTRFS_I(inode)->runtime_flags))
9536 ret = sync_inode(inode, wbc);
9537 btrfs_add_delayed_iput(inode);
9538 if (ret || wbc->nr_to_write <= 0)
9542 spin_lock(&root->delalloc_lock);
9544 spin_unlock(&root->delalloc_lock);
9547 list_for_each_entry_safe(work, next, &works, list) {
9548 list_del_init(&work->list);
9549 wait_for_completion(&work->completion);
9553 if (!list_empty(&splice)) {
9554 spin_lock(&root->delalloc_lock);
9555 list_splice_tail(&splice, &root->delalloc_inodes);
9556 spin_unlock(&root->delalloc_lock);
9558 mutex_unlock(&root->delalloc_mutex);
9562 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9564 struct writeback_control wbc = {
9565 .nr_to_write = LONG_MAX,
9566 .sync_mode = WB_SYNC_NONE,
9568 .range_end = LLONG_MAX,
9570 struct btrfs_fs_info *fs_info = root->fs_info;
9572 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9575 return start_delalloc_inodes(root, &wbc, true, false);
9578 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, u64 nr,
9579 bool in_reclaim_context)
9581 struct writeback_control wbc = {
9582 .nr_to_write = (nr == U64_MAX) ? LONG_MAX : (unsigned long)nr,
9583 .sync_mode = WB_SYNC_NONE,
9585 .range_end = LLONG_MAX,
9587 struct btrfs_root *root;
9588 struct list_head splice;
9591 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9594 INIT_LIST_HEAD(&splice);
9596 mutex_lock(&fs_info->delalloc_root_mutex);
9597 spin_lock(&fs_info->delalloc_root_lock);
9598 list_splice_init(&fs_info->delalloc_roots, &splice);
9599 while (!list_empty(&splice) && nr) {
9601 * Reset nr_to_write here so we know that we're doing a full
9605 wbc.nr_to_write = LONG_MAX;
9607 root = list_first_entry(&splice, struct btrfs_root,
9609 root = btrfs_grab_root(root);
9611 list_move_tail(&root->delalloc_root,
9612 &fs_info->delalloc_roots);
9613 spin_unlock(&fs_info->delalloc_root_lock);
9615 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9616 btrfs_put_root(root);
9617 if (ret < 0 || wbc.nr_to_write <= 0)
9619 spin_lock(&fs_info->delalloc_root_lock);
9621 spin_unlock(&fs_info->delalloc_root_lock);
9625 if (!list_empty(&splice)) {
9626 spin_lock(&fs_info->delalloc_root_lock);
9627 list_splice_tail(&splice, &fs_info->delalloc_roots);
9628 spin_unlock(&fs_info->delalloc_root_lock);
9630 mutex_unlock(&fs_info->delalloc_root_mutex);
9634 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9635 const char *symname)
9637 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9638 struct btrfs_trans_handle *trans;
9639 struct btrfs_root *root = BTRFS_I(dir)->root;
9640 struct btrfs_path *path;
9641 struct btrfs_key key;
9642 struct inode *inode = NULL;
9649 struct btrfs_file_extent_item *ei;
9650 struct extent_buffer *leaf;
9652 name_len = strlen(symname);
9653 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9654 return -ENAMETOOLONG;
9657 * 2 items for inode item and ref
9658 * 2 items for dir items
9659 * 1 item for updating parent inode item
9660 * 1 item for the inline extent item
9661 * 1 item for xattr if selinux is on
9663 trans = btrfs_start_transaction(root, 7);
9665 return PTR_ERR(trans);
9667 err = btrfs_find_free_objectid(root, &objectid);
9671 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9672 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9673 objectid, S_IFLNK|S_IRWXUGO, &index);
9674 if (IS_ERR(inode)) {
9675 err = PTR_ERR(inode);
9681 * If the active LSM wants to access the inode during
9682 * d_instantiate it needs these. Smack checks to see
9683 * if the filesystem supports xattrs by looking at the
9686 inode->i_fop = &btrfs_file_operations;
9687 inode->i_op = &btrfs_file_inode_operations;
9688 inode->i_mapping->a_ops = &btrfs_aops;
9690 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9694 path = btrfs_alloc_path();
9699 key.objectid = btrfs_ino(BTRFS_I(inode));
9701 key.type = BTRFS_EXTENT_DATA_KEY;
9702 datasize = btrfs_file_extent_calc_inline_size(name_len);
9703 err = btrfs_insert_empty_item(trans, root, path, &key,
9706 btrfs_free_path(path);
9709 leaf = path->nodes[0];
9710 ei = btrfs_item_ptr(leaf, path->slots[0],
9711 struct btrfs_file_extent_item);
9712 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9713 btrfs_set_file_extent_type(leaf, ei,
9714 BTRFS_FILE_EXTENT_INLINE);
9715 btrfs_set_file_extent_encryption(leaf, ei, 0);
9716 btrfs_set_file_extent_compression(leaf, ei, 0);
9717 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9718 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9720 ptr = btrfs_file_extent_inline_start(ei);
9721 write_extent_buffer(leaf, symname, ptr, name_len);
9722 btrfs_mark_buffer_dirty(leaf);
9723 btrfs_free_path(path);
9725 inode->i_op = &btrfs_symlink_inode_operations;
9726 inode_nohighmem(inode);
9727 inode_set_bytes(inode, name_len);
9728 btrfs_i_size_write(BTRFS_I(inode), name_len);
9729 err = btrfs_update_inode(trans, root, inode);
9731 * Last step, add directory indexes for our symlink inode. This is the
9732 * last step to avoid extra cleanup of these indexes if an error happens
9736 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9737 BTRFS_I(inode), 0, index);
9741 d_instantiate_new(dentry, inode);
9744 btrfs_end_transaction(trans);
9746 inode_dec_link_count(inode);
9747 discard_new_inode(inode);
9749 btrfs_btree_balance_dirty(fs_info);
9753 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9754 struct btrfs_trans_handle *trans_in,
9755 struct inode *inode, struct btrfs_key *ins,
9758 struct btrfs_file_extent_item stack_fi;
9759 struct btrfs_replace_extent_info extent_info;
9760 struct btrfs_trans_handle *trans = trans_in;
9761 struct btrfs_path *path;
9762 u64 start = ins->objectid;
9763 u64 len = ins->offset;
9766 memset(&stack_fi, 0, sizeof(stack_fi));
9768 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9769 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9770 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9771 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9772 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9773 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9774 /* Encryption and other encoding is reserved and all 0 */
9776 ret = btrfs_qgroup_release_data(BTRFS_I(inode), file_offset, len);
9778 return ERR_PTR(ret);
9781 ret = insert_reserved_file_extent(trans, BTRFS_I(inode),
9782 file_offset, &stack_fi, ret);
9784 return ERR_PTR(ret);
9788 extent_info.disk_offset = start;
9789 extent_info.disk_len = len;
9790 extent_info.data_offset = 0;
9791 extent_info.data_len = len;
9792 extent_info.file_offset = file_offset;
9793 extent_info.extent_buf = (char *)&stack_fi;
9794 extent_info.is_new_extent = true;
9795 extent_info.qgroup_reserved = ret;
9796 extent_info.insertions = 0;
9798 path = btrfs_alloc_path();
9800 return ERR_PTR(-ENOMEM);
9802 ret = btrfs_replace_file_extents(inode, path, file_offset,
9803 file_offset + len - 1, &extent_info,
9805 btrfs_free_path(path);
9807 return ERR_PTR(ret);
9812 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9813 u64 start, u64 num_bytes, u64 min_size,
9814 loff_t actual_len, u64 *alloc_hint,
9815 struct btrfs_trans_handle *trans)
9817 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9818 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9819 struct extent_map *em;
9820 struct btrfs_root *root = BTRFS_I(inode)->root;
9821 struct btrfs_key ins;
9822 u64 cur_offset = start;
9823 u64 clear_offset = start;
9826 u64 last_alloc = (u64)-1;
9828 bool own_trans = true;
9829 u64 end = start + num_bytes - 1;
9833 while (num_bytes > 0) {
9834 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9835 cur_bytes = max(cur_bytes, min_size);
9837 * If we are severely fragmented we could end up with really
9838 * small allocations, so if the allocator is returning small
9839 * chunks lets make its job easier by only searching for those
9842 cur_bytes = min(cur_bytes, last_alloc);
9843 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9844 min_size, 0, *alloc_hint, &ins, 1, 0);
9849 * We've reserved this space, and thus converted it from
9850 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9851 * from here on out we will only need to clear our reservation
9852 * for the remaining unreserved area, so advance our
9853 * clear_offset by our extent size.
9855 clear_offset += ins.offset;
9857 last_alloc = ins.offset;
9858 trans = insert_prealloc_file_extent(trans, inode, &ins, cur_offset);
9860 * Now that we inserted the prealloc extent we can finally
9861 * decrement the number of reservations in the block group.
9862 * If we did it before, we could race with relocation and have
9863 * relocation miss the reserved extent, making it fail later.
9865 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9866 if (IS_ERR(trans)) {
9867 ret = PTR_ERR(trans);
9868 btrfs_free_reserved_extent(fs_info, ins.objectid,
9873 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9874 cur_offset + ins.offset -1, 0);
9876 em = alloc_extent_map();
9878 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9879 &BTRFS_I(inode)->runtime_flags);
9883 em->start = cur_offset;
9884 em->orig_start = cur_offset;
9885 em->len = ins.offset;
9886 em->block_start = ins.objectid;
9887 em->block_len = ins.offset;
9888 em->orig_block_len = ins.offset;
9889 em->ram_bytes = ins.offset;
9890 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9891 em->generation = trans->transid;
9894 write_lock(&em_tree->lock);
9895 ret = add_extent_mapping(em_tree, em, 1);
9896 write_unlock(&em_tree->lock);
9899 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9900 cur_offset + ins.offset - 1,
9903 free_extent_map(em);
9905 num_bytes -= ins.offset;
9906 cur_offset += ins.offset;
9907 *alloc_hint = ins.objectid + ins.offset;
9909 inode_inc_iversion(inode);
9910 inode->i_ctime = current_time(inode);
9911 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9912 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9913 (actual_len > inode->i_size) &&
9914 (cur_offset > inode->i_size)) {
9915 if (cur_offset > actual_len)
9916 i_size = actual_len;
9918 i_size = cur_offset;
9919 i_size_write(inode, i_size);
9920 btrfs_inode_safe_disk_i_size_write(inode, 0);
9923 ret = btrfs_update_inode(trans, root, inode);
9926 btrfs_abort_transaction(trans, ret);
9928 btrfs_end_transaction(trans);
9933 btrfs_end_transaction(trans);
9937 if (clear_offset < end)
9938 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9939 end - clear_offset + 1);
9943 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9944 u64 start, u64 num_bytes, u64 min_size,
9945 loff_t actual_len, u64 *alloc_hint)
9947 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9948 min_size, actual_len, alloc_hint,
9952 int btrfs_prealloc_file_range_trans(struct inode *inode,
9953 struct btrfs_trans_handle *trans, int mode,
9954 u64 start, u64 num_bytes, u64 min_size,
9955 loff_t actual_len, u64 *alloc_hint)
9957 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9958 min_size, actual_len, alloc_hint, trans);
9961 static int btrfs_set_page_dirty(struct page *page)
9963 return __set_page_dirty_nobuffers(page);
9966 static int btrfs_permission(struct inode *inode, int mask)
9968 struct btrfs_root *root = BTRFS_I(inode)->root;
9969 umode_t mode = inode->i_mode;
9971 if (mask & MAY_WRITE &&
9972 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9973 if (btrfs_root_readonly(root))
9975 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9978 return generic_permission(inode, mask);
9981 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9983 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9984 struct btrfs_trans_handle *trans;
9985 struct btrfs_root *root = BTRFS_I(dir)->root;
9986 struct inode *inode = NULL;
9992 * 5 units required for adding orphan entry
9994 trans = btrfs_start_transaction(root, 5);
9996 return PTR_ERR(trans);
9998 ret = btrfs_find_free_objectid(root, &objectid);
10002 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10003 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10004 if (IS_ERR(inode)) {
10005 ret = PTR_ERR(inode);
10010 inode->i_fop = &btrfs_file_operations;
10011 inode->i_op = &btrfs_file_inode_operations;
10013 inode->i_mapping->a_ops = &btrfs_aops;
10015 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10019 ret = btrfs_update_inode(trans, root, inode);
10022 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10027 * We set number of links to 0 in btrfs_new_inode(), and here we set
10028 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10031 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10033 set_nlink(inode, 1);
10034 d_tmpfile(dentry, inode);
10035 unlock_new_inode(inode);
10036 mark_inode_dirty(inode);
10038 btrfs_end_transaction(trans);
10040 discard_new_inode(inode);
10041 btrfs_btree_balance_dirty(fs_info);
10045 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10047 struct inode *inode = tree->private_data;
10048 unsigned long index = start >> PAGE_SHIFT;
10049 unsigned long end_index = end >> PAGE_SHIFT;
10052 while (index <= end_index) {
10053 page = find_get_page(inode->i_mapping, index);
10054 ASSERT(page); /* Pages should be in the extent_io_tree */
10055 set_page_writeback(page);
10063 * Add an entry indicating a block group or device which is pinned by a
10064 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10065 * negative errno on failure.
10067 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10068 bool is_block_group)
10070 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10071 struct btrfs_swapfile_pin *sp, *entry;
10072 struct rb_node **p;
10073 struct rb_node *parent = NULL;
10075 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10080 sp->is_block_group = is_block_group;
10081 sp->bg_extent_count = 1;
10083 spin_lock(&fs_info->swapfile_pins_lock);
10084 p = &fs_info->swapfile_pins.rb_node;
10087 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10088 if (sp->ptr < entry->ptr ||
10089 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10090 p = &(*p)->rb_left;
10091 } else if (sp->ptr > entry->ptr ||
10092 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10093 p = &(*p)->rb_right;
10095 if (is_block_group)
10096 entry->bg_extent_count++;
10097 spin_unlock(&fs_info->swapfile_pins_lock);
10102 rb_link_node(&sp->node, parent, p);
10103 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10104 spin_unlock(&fs_info->swapfile_pins_lock);
10108 /* Free all of the entries pinned by this swapfile. */
10109 static void btrfs_free_swapfile_pins(struct inode *inode)
10111 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10112 struct btrfs_swapfile_pin *sp;
10113 struct rb_node *node, *next;
10115 spin_lock(&fs_info->swapfile_pins_lock);
10116 node = rb_first(&fs_info->swapfile_pins);
10118 next = rb_next(node);
10119 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10120 if (sp->inode == inode) {
10121 rb_erase(&sp->node, &fs_info->swapfile_pins);
10122 if (sp->is_block_group) {
10123 btrfs_dec_block_group_swap_extents(sp->ptr,
10124 sp->bg_extent_count);
10125 btrfs_put_block_group(sp->ptr);
10131 spin_unlock(&fs_info->swapfile_pins_lock);
10134 struct btrfs_swap_info {
10140 unsigned long nr_pages;
10144 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10145 struct btrfs_swap_info *bsi)
10147 unsigned long nr_pages;
10148 unsigned long max_pages;
10149 u64 first_ppage, first_ppage_reported, next_ppage;
10153 * Our swapfile may have had its size extended after the swap header was
10154 * written. In that case activating the swapfile should not go beyond
10155 * the max size set in the swap header.
10157 if (bsi->nr_pages >= sis->max)
10160 max_pages = sis->max - bsi->nr_pages;
10161 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10162 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10163 PAGE_SIZE) >> PAGE_SHIFT;
10165 if (first_ppage >= next_ppage)
10167 nr_pages = next_ppage - first_ppage;
10168 nr_pages = min(nr_pages, max_pages);
10170 first_ppage_reported = first_ppage;
10171 if (bsi->start == 0)
10172 first_ppage_reported++;
10173 if (bsi->lowest_ppage > first_ppage_reported)
10174 bsi->lowest_ppage = first_ppage_reported;
10175 if (bsi->highest_ppage < (next_ppage - 1))
10176 bsi->highest_ppage = next_ppage - 1;
10178 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10181 bsi->nr_extents += ret;
10182 bsi->nr_pages += nr_pages;
10186 static void btrfs_swap_deactivate(struct file *file)
10188 struct inode *inode = file_inode(file);
10190 btrfs_free_swapfile_pins(inode);
10191 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10194 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10197 struct inode *inode = file_inode(file);
10198 struct btrfs_root *root = BTRFS_I(inode)->root;
10199 struct btrfs_fs_info *fs_info = root->fs_info;
10200 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10201 struct extent_state *cached_state = NULL;
10202 struct extent_map *em = NULL;
10203 struct btrfs_device *device = NULL;
10204 struct btrfs_swap_info bsi = {
10205 .lowest_ppage = (sector_t)-1ULL,
10212 * If the swap file was just created, make sure delalloc is done. If the
10213 * file changes again after this, the user is doing something stupid and
10214 * we don't really care.
10216 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10221 * The inode is locked, so these flags won't change after we check them.
10223 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10224 btrfs_warn(fs_info, "swapfile must not be compressed");
10227 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10228 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10231 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10232 btrfs_warn(fs_info, "swapfile must not be checksummed");
10237 * Balance or device remove/replace/resize can move stuff around from
10238 * under us. The exclop protection makes sure they aren't running/won't
10239 * run concurrently while we are mapping the swap extents, and
10240 * fs_info->swapfile_pins prevents them from running while the swap
10241 * file is active and moving the extents. Note that this also prevents
10242 * a concurrent device add which isn't actually necessary, but it's not
10243 * really worth the trouble to allow it.
10245 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10246 btrfs_warn(fs_info,
10247 "cannot activate swapfile while exclusive operation is running");
10252 * Prevent snapshot creation while we are activating the swap file.
10253 * We do not want to race with snapshot creation. If snapshot creation
10254 * already started before we bumped nr_swapfiles from 0 to 1 and
10255 * completes before the first write into the swap file after it is
10256 * activated, than that write would fallback to COW.
10258 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10259 btrfs_exclop_finish(fs_info);
10260 btrfs_warn(fs_info,
10261 "cannot activate swapfile because snapshot creation is in progress");
10265 * Snapshots can create extents which require COW even if NODATACOW is
10266 * set. We use this counter to prevent snapshots. We must increment it
10267 * before walking the extents because we don't want a concurrent
10268 * snapshot to run after we've already checked the extents.
10270 * It is possible that subvolume is marked for deletion but still not
10271 * removed yet. To prevent this race, we check the root status before
10272 * activating the swapfile.
10274 spin_lock(&root->root_item_lock);
10275 if (btrfs_root_dead(root)) {
10276 spin_unlock(&root->root_item_lock);
10278 btrfs_exclop_finish(fs_info);
10279 btrfs_warn(fs_info,
10280 "cannot activate swapfile because subvolume %llu is being deleted",
10281 root->root_key.objectid);
10284 atomic_inc(&root->nr_swapfiles);
10285 spin_unlock(&root->root_item_lock);
10287 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10289 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10291 while (start < isize) {
10292 u64 logical_block_start, physical_block_start;
10293 struct btrfs_block_group *bg;
10294 u64 len = isize - start;
10296 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10302 if (em->block_start == EXTENT_MAP_HOLE) {
10303 btrfs_warn(fs_info, "swapfile must not have holes");
10307 if (em->block_start == EXTENT_MAP_INLINE) {
10309 * It's unlikely we'll ever actually find ourselves
10310 * here, as a file small enough to fit inline won't be
10311 * big enough to store more than the swap header, but in
10312 * case something changes in the future, let's catch it
10313 * here rather than later.
10315 btrfs_warn(fs_info, "swapfile must not be inline");
10319 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10320 btrfs_warn(fs_info, "swapfile must not be compressed");
10325 logical_block_start = em->block_start + (start - em->start);
10326 len = min(len, em->len - (start - em->start));
10327 free_extent_map(em);
10330 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10336 btrfs_warn(fs_info,
10337 "swapfile must not be copy-on-write");
10342 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10348 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10349 btrfs_warn(fs_info,
10350 "swapfile must have single data profile");
10355 if (device == NULL) {
10356 device = em->map_lookup->stripes[0].dev;
10357 ret = btrfs_add_swapfile_pin(inode, device, false);
10362 } else if (device != em->map_lookup->stripes[0].dev) {
10363 btrfs_warn(fs_info, "swapfile must be on one device");
10368 physical_block_start = (em->map_lookup->stripes[0].physical +
10369 (logical_block_start - em->start));
10370 len = min(len, em->len - (logical_block_start - em->start));
10371 free_extent_map(em);
10374 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10376 btrfs_warn(fs_info,
10377 "could not find block group containing swapfile");
10382 if (!btrfs_inc_block_group_swap_extents(bg)) {
10383 btrfs_warn(fs_info,
10384 "block group for swapfile at %llu is read-only%s",
10386 atomic_read(&fs_info->scrubs_running) ?
10387 " (scrub running)" : "");
10388 btrfs_put_block_group(bg);
10393 ret = btrfs_add_swapfile_pin(inode, bg, true);
10395 btrfs_put_block_group(bg);
10402 if (bsi.block_len &&
10403 bsi.block_start + bsi.block_len == physical_block_start) {
10404 bsi.block_len += len;
10406 if (bsi.block_len) {
10407 ret = btrfs_add_swap_extent(sis, &bsi);
10412 bsi.block_start = physical_block_start;
10413 bsi.block_len = len;
10420 ret = btrfs_add_swap_extent(sis, &bsi);
10423 if (!IS_ERR_OR_NULL(em))
10424 free_extent_map(em);
10426 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10429 btrfs_swap_deactivate(file);
10431 btrfs_drew_write_unlock(&root->snapshot_lock);
10433 btrfs_exclop_finish(fs_info);
10439 sis->bdev = device->bdev;
10440 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10441 sis->max = bsi.nr_pages;
10442 sis->pages = bsi.nr_pages - 1;
10443 sis->highest_bit = bsi.nr_pages - 1;
10444 return bsi.nr_extents;
10447 static void btrfs_swap_deactivate(struct file *file)
10451 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10454 return -EOPNOTSUPP;
10458 static const struct inode_operations btrfs_dir_inode_operations = {
10459 .getattr = btrfs_getattr,
10460 .lookup = btrfs_lookup,
10461 .create = btrfs_create,
10462 .unlink = btrfs_unlink,
10463 .link = btrfs_link,
10464 .mkdir = btrfs_mkdir,
10465 .rmdir = btrfs_rmdir,
10466 .rename = btrfs_rename2,
10467 .symlink = btrfs_symlink,
10468 .setattr = btrfs_setattr,
10469 .mknod = btrfs_mknod,
10470 .listxattr = btrfs_listxattr,
10471 .permission = btrfs_permission,
10472 .get_acl = btrfs_get_acl,
10473 .set_acl = btrfs_set_acl,
10474 .update_time = btrfs_update_time,
10475 .tmpfile = btrfs_tmpfile,
10478 static const struct file_operations btrfs_dir_file_operations = {
10479 .llseek = generic_file_llseek,
10480 .read = generic_read_dir,
10481 .iterate_shared = btrfs_real_readdir,
10482 .open = btrfs_opendir,
10483 .unlocked_ioctl = btrfs_ioctl,
10484 #ifdef CONFIG_COMPAT
10485 .compat_ioctl = btrfs_compat_ioctl,
10487 .release = btrfs_release_file,
10488 .fsync = btrfs_sync_file,
10492 * btrfs doesn't support the bmap operation because swapfiles
10493 * use bmap to make a mapping of extents in the file. They assume
10494 * these extents won't change over the life of the file and they
10495 * use the bmap result to do IO directly to the drive.
10497 * the btrfs bmap call would return logical addresses that aren't
10498 * suitable for IO and they also will change frequently as COW
10499 * operations happen. So, swapfile + btrfs == corruption.
10501 * For now we're avoiding this by dropping bmap.
10503 static const struct address_space_operations btrfs_aops = {
10504 .readpage = btrfs_readpage,
10505 .writepage = btrfs_writepage,
10506 .writepages = btrfs_writepages,
10507 .readahead = btrfs_readahead,
10508 .direct_IO = noop_direct_IO,
10509 .invalidatepage = btrfs_invalidatepage,
10510 .releasepage = btrfs_releasepage,
10511 #ifdef CONFIG_MIGRATION
10512 .migratepage = btrfs_migratepage,
10514 .set_page_dirty = btrfs_set_page_dirty,
10515 .error_remove_page = generic_error_remove_page,
10516 .swap_activate = btrfs_swap_activate,
10517 .swap_deactivate = btrfs_swap_deactivate,
10520 static const struct inode_operations btrfs_file_inode_operations = {
10521 .getattr = btrfs_getattr,
10522 .setattr = btrfs_setattr,
10523 .listxattr = btrfs_listxattr,
10524 .permission = btrfs_permission,
10525 .fiemap = btrfs_fiemap,
10526 .get_acl = btrfs_get_acl,
10527 .set_acl = btrfs_set_acl,
10528 .update_time = btrfs_update_time,
10530 static const struct inode_operations btrfs_special_inode_operations = {
10531 .getattr = btrfs_getattr,
10532 .setattr = btrfs_setattr,
10533 .permission = btrfs_permission,
10534 .listxattr = btrfs_listxattr,
10535 .get_acl = btrfs_get_acl,
10536 .set_acl = btrfs_set_acl,
10537 .update_time = btrfs_update_time,
10539 static const struct inode_operations btrfs_symlink_inode_operations = {
10540 .get_link = page_get_link,
10541 .getattr = btrfs_getattr,
10542 .setattr = btrfs_setattr,
10543 .permission = btrfs_permission,
10544 .listxattr = btrfs_listxattr,
10545 .update_time = btrfs_update_time,
10548 const struct dentry_operations btrfs_dentry_operations = {
10549 .d_delete = btrfs_dentry_delete,