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/blk-cgroup.h>
10 #include <linux/file.h>
12 #include <linux/pagemap.h>
13 #include <linux/highmem.h>
14 #include <linux/time.h>
15 #include <linux/init.h>
16 #include <linux/string.h>
17 #include <linux/backing-dev.h>
18 #include <linux/writeback.h>
19 #include <linux/compat.h>
20 #include <linux/xattr.h>
21 #include <linux/posix_acl.h>
22 #include <linux/falloc.h>
23 #include <linux/slab.h>
24 #include <linux/ratelimit.h>
25 #include <linux/btrfs.h>
26 #include <linux/blkdev.h>
27 #include <linux/posix_acl_xattr.h>
28 #include <linux/uio.h>
29 #include <linux/magic.h>
30 #include <linux/iversion.h>
31 #include <linux/swap.h>
32 #include <linux/migrate.h>
33 #include <linux/sched/mm.h>
34 #include <linux/iomap.h>
35 #include <asm/unaligned.h>
36 #include <linux/fsverity.h>
40 #include "transaction.h"
41 #include "btrfs_inode.h"
42 #include "print-tree.h"
43 #include "ordered-data.h"
47 #include "compression.h"
49 #include "free-space-cache.h"
52 #include "delalloc-space.h"
53 #include "block-group.h"
54 #include "space-info.h"
57 #include "inode-item.h"
59 #include "accessors.h"
60 #include "extent-tree.h"
61 #include "root-tree.h"
64 #include "file-item.h"
65 #include "uuid-tree.h"
69 #include "relocation.h"
74 struct btrfs_iget_args {
76 struct btrfs_root *root;
79 struct btrfs_dio_data {
81 struct extent_changeset *data_reserved;
82 bool data_space_reserved;
86 struct btrfs_dio_private {
90 * Since DIO can use anonymous page, we cannot use page_offset() to
91 * grab the file offset, thus need a dedicated member for file offset.
94 /* Used for bio::bi_size */
98 * References to this structure. There is one reference per in-flight
99 * bio plus one while we're still setting up.
103 /* Array of checksums */
106 /* This must be last */
110 static struct bio_set btrfs_dio_bioset;
112 struct btrfs_rename_ctx {
113 /* Output field. Stores the index number of the old directory entry. */
117 static const struct inode_operations btrfs_dir_inode_operations;
118 static const struct inode_operations btrfs_symlink_inode_operations;
119 static const struct inode_operations btrfs_special_inode_operations;
120 static const struct inode_operations btrfs_file_inode_operations;
121 static const struct address_space_operations btrfs_aops;
122 static const struct file_operations btrfs_dir_file_operations;
124 static struct kmem_cache *btrfs_inode_cachep;
126 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
127 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
128 static noinline int cow_file_range(struct btrfs_inode *inode,
129 struct page *locked_page,
130 u64 start, u64 end, int *page_started,
131 unsigned long *nr_written, int unlock,
133 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
134 u64 len, u64 orig_start, u64 block_start,
135 u64 block_len, u64 orig_block_len,
136 u64 ram_bytes, int compress_type,
139 static void __cold btrfs_print_data_csum_error(struct btrfs_inode *inode,
140 u64 logical_start, u8 *csum, u8 *csum_expected, int mirror_num)
142 struct btrfs_root *root = inode->root;
143 const u32 csum_size = root->fs_info->csum_size;
145 /* Output without objectid, which is more meaningful */
146 if (root->root_key.objectid >= BTRFS_LAST_FREE_OBJECTID) {
147 btrfs_warn_rl(root->fs_info,
148 "csum failed root %lld ino %lld off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
149 root->root_key.objectid, btrfs_ino(inode),
151 CSUM_FMT_VALUE(csum_size, csum),
152 CSUM_FMT_VALUE(csum_size, csum_expected),
155 btrfs_warn_rl(root->fs_info,
156 "csum failed root %llu ino %llu off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
157 root->root_key.objectid, btrfs_ino(inode),
159 CSUM_FMT_VALUE(csum_size, csum),
160 CSUM_FMT_VALUE(csum_size, csum_expected),
166 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
168 * ilock_flags can have the following bit set:
170 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
171 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
173 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
175 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
177 if (ilock_flags & BTRFS_ILOCK_SHARED) {
178 if (ilock_flags & BTRFS_ILOCK_TRY) {
179 if (!inode_trylock_shared(inode))
184 inode_lock_shared(inode);
186 if (ilock_flags & BTRFS_ILOCK_TRY) {
187 if (!inode_trylock(inode))
194 if (ilock_flags & BTRFS_ILOCK_MMAP)
195 down_write(&BTRFS_I(inode)->i_mmap_lock);
200 * btrfs_inode_unlock - unock inode i_rwsem
202 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
203 * to decide whether the lock acquired is shared or exclusive.
205 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
207 if (ilock_flags & BTRFS_ILOCK_MMAP)
208 up_write(&BTRFS_I(inode)->i_mmap_lock);
209 if (ilock_flags & BTRFS_ILOCK_SHARED)
210 inode_unlock_shared(inode);
216 * Cleanup all submitted ordered extents in specified range to handle errors
217 * from the btrfs_run_delalloc_range() callback.
219 * NOTE: caller must ensure that when an error happens, it can not call
220 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
221 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
222 * to be released, which we want to happen only when finishing the ordered
223 * extent (btrfs_finish_ordered_io()).
225 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
226 struct page *locked_page,
227 u64 offset, u64 bytes)
229 unsigned long index = offset >> PAGE_SHIFT;
230 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
231 u64 page_start, page_end;
235 page_start = page_offset(locked_page);
236 page_end = page_start + PAGE_SIZE - 1;
239 while (index <= end_index) {
241 * For locked page, we will call end_extent_writepage() on it
242 * in run_delalloc_range() for the error handling. That
243 * end_extent_writepage() function will call
244 * btrfs_mark_ordered_io_finished() to clear page Ordered and
245 * run the ordered extent accounting.
247 * Here we can't just clear the Ordered bit, or
248 * btrfs_mark_ordered_io_finished() would skip the accounting
249 * for the page range, and the ordered extent will never finish.
251 if (locked_page && index == (page_start >> PAGE_SHIFT)) {
255 page = find_get_page(inode->vfs_inode.i_mapping, index);
261 * Here we just clear all Ordered bits for every page in the
262 * range, then btrfs_mark_ordered_io_finished() will handle
263 * the ordered extent accounting for the range.
265 btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
271 /* The locked page covers the full range, nothing needs to be done */
272 if (bytes + offset <= page_start + PAGE_SIZE)
275 * In case this page belongs to the delalloc range being
276 * instantiated then skip it, since the first page of a range is
277 * going to be properly cleaned up by the caller of
280 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
281 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
282 offset = page_offset(locked_page) + PAGE_SIZE;
286 return btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes, false);
289 static int btrfs_dirty_inode(struct inode *inode);
291 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
292 struct btrfs_new_inode_args *args)
296 if (args->default_acl) {
297 err = __btrfs_set_acl(trans, args->inode, args->default_acl,
303 err = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
307 if (!args->default_acl && !args->acl)
308 cache_no_acl(args->inode);
309 return btrfs_xattr_security_init(trans, args->inode, args->dir,
310 &args->dentry->d_name);
314 * this does all the hard work for inserting an inline extent into
315 * the btree. The caller should have done a btrfs_drop_extents so that
316 * no overlapping inline items exist in the btree
318 static int insert_inline_extent(struct btrfs_trans_handle *trans,
319 struct btrfs_path *path,
320 struct btrfs_inode *inode, bool extent_inserted,
321 size_t size, size_t compressed_size,
323 struct page **compressed_pages,
326 struct btrfs_root *root = inode->root;
327 struct extent_buffer *leaf;
328 struct page *page = NULL;
331 struct btrfs_file_extent_item *ei;
333 size_t cur_size = size;
336 ASSERT((compressed_size > 0 && compressed_pages) ||
337 (compressed_size == 0 && !compressed_pages));
339 if (compressed_size && compressed_pages)
340 cur_size = compressed_size;
342 if (!extent_inserted) {
343 struct btrfs_key key;
346 key.objectid = btrfs_ino(inode);
348 key.type = BTRFS_EXTENT_DATA_KEY;
350 datasize = btrfs_file_extent_calc_inline_size(cur_size);
351 ret = btrfs_insert_empty_item(trans, root, path, &key,
356 leaf = path->nodes[0];
357 ei = btrfs_item_ptr(leaf, path->slots[0],
358 struct btrfs_file_extent_item);
359 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
360 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
361 btrfs_set_file_extent_encryption(leaf, ei, 0);
362 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
363 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
364 ptr = btrfs_file_extent_inline_start(ei);
366 if (compress_type != BTRFS_COMPRESS_NONE) {
369 while (compressed_size > 0) {
370 cpage = compressed_pages[i];
371 cur_size = min_t(unsigned long, compressed_size,
374 kaddr = kmap_local_page(cpage);
375 write_extent_buffer(leaf, kaddr, ptr, cur_size);
380 compressed_size -= cur_size;
382 btrfs_set_file_extent_compression(leaf, ei,
385 page = find_get_page(inode->vfs_inode.i_mapping, 0);
386 btrfs_set_file_extent_compression(leaf, ei, 0);
387 kaddr = kmap_local_page(page);
388 write_extent_buffer(leaf, kaddr, ptr, size);
392 btrfs_mark_buffer_dirty(leaf);
393 btrfs_release_path(path);
396 * We align size to sectorsize for inline extents just for simplicity
399 ret = btrfs_inode_set_file_extent_range(inode, 0,
400 ALIGN(size, root->fs_info->sectorsize));
405 * We're an inline extent, so nobody can extend the file past i_size
406 * without locking a page we already have locked.
408 * We must do any i_size and inode updates before we unlock the pages.
409 * Otherwise we could end up racing with unlink.
411 i_size = i_size_read(&inode->vfs_inode);
412 if (update_i_size && size > i_size) {
413 i_size_write(&inode->vfs_inode, size);
416 inode->disk_i_size = i_size;
424 * conditionally insert an inline extent into the file. This
425 * does the checks required to make sure the data is small enough
426 * to fit as an inline extent.
428 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 size,
429 size_t compressed_size,
431 struct page **compressed_pages,
434 struct btrfs_drop_extents_args drop_args = { 0 };
435 struct btrfs_root *root = inode->root;
436 struct btrfs_fs_info *fs_info = root->fs_info;
437 struct btrfs_trans_handle *trans;
438 u64 data_len = (compressed_size ?: size);
440 struct btrfs_path *path;
443 * We can create an inline extent if it ends at or beyond the current
444 * i_size, is no larger than a sector (decompressed), and the (possibly
445 * compressed) data fits in a leaf and the configured maximum inline
448 if (size < i_size_read(&inode->vfs_inode) ||
449 size > fs_info->sectorsize ||
450 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
451 data_len > fs_info->max_inline)
454 path = btrfs_alloc_path();
458 trans = btrfs_join_transaction(root);
460 btrfs_free_path(path);
461 return PTR_ERR(trans);
463 trans->block_rsv = &inode->block_rsv;
465 drop_args.path = path;
467 drop_args.end = fs_info->sectorsize;
468 drop_args.drop_cache = true;
469 drop_args.replace_extent = true;
470 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
471 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
473 btrfs_abort_transaction(trans, ret);
477 ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
478 size, compressed_size, compress_type,
479 compressed_pages, update_i_size);
480 if (ret && ret != -ENOSPC) {
481 btrfs_abort_transaction(trans, ret);
483 } else if (ret == -ENOSPC) {
488 btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
489 ret = btrfs_update_inode(trans, root, inode);
490 if (ret && ret != -ENOSPC) {
491 btrfs_abort_transaction(trans, ret);
493 } else if (ret == -ENOSPC) {
498 btrfs_set_inode_full_sync(inode);
501 * Don't forget to free the reserved space, as for inlined extent
502 * it won't count as data extent, free them directly here.
503 * And at reserve time, it's always aligned to page size, so
504 * just free one page here.
506 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
507 btrfs_free_path(path);
508 btrfs_end_transaction(trans);
512 struct async_extent {
517 unsigned long nr_pages;
519 struct list_head list;
524 struct page *locked_page;
527 blk_opf_t write_flags;
528 struct list_head extents;
529 struct cgroup_subsys_state *blkcg_css;
530 struct btrfs_work work;
531 struct async_cow *async_cow;
536 struct async_chunk chunks[];
539 static noinline int add_async_extent(struct async_chunk *cow,
540 u64 start, u64 ram_size,
543 unsigned long nr_pages,
546 struct async_extent *async_extent;
548 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
549 BUG_ON(!async_extent); /* -ENOMEM */
550 async_extent->start = start;
551 async_extent->ram_size = ram_size;
552 async_extent->compressed_size = compressed_size;
553 async_extent->pages = pages;
554 async_extent->nr_pages = nr_pages;
555 async_extent->compress_type = compress_type;
556 list_add_tail(&async_extent->list, &cow->extents);
561 * Check if the inode needs to be submitted to compression, based on mount
562 * options, defragmentation, properties or heuristics.
564 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
567 struct btrfs_fs_info *fs_info = inode->root->fs_info;
569 if (!btrfs_inode_can_compress(inode)) {
570 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
571 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
576 * Special check for subpage.
578 * We lock the full page then run each delalloc range in the page, thus
579 * for the following case, we will hit some subpage specific corner case:
582 * | |///////| |///////|
585 * In above case, both range A and range B will try to unlock the full
586 * page [0, 64K), causing the one finished later will have page
587 * unlocked already, triggering various page lock requirement BUG_ON()s.
589 * So here we add an artificial limit that subpage compression can only
590 * if the range is fully page aligned.
592 * In theory we only need to ensure the first page is fully covered, but
593 * the tailing partial page will be locked until the full compression
594 * finishes, delaying the write of other range.
596 * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
597 * first to prevent any submitted async extent to unlock the full page.
598 * By this, we can ensure for subpage case that only the last async_cow
599 * will unlock the full page.
601 if (fs_info->sectorsize < PAGE_SIZE) {
602 if (!PAGE_ALIGNED(start) ||
603 !PAGE_ALIGNED(end + 1))
608 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
611 if (inode->defrag_compress)
613 /* bad compression ratios */
614 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
616 if (btrfs_test_opt(fs_info, COMPRESS) ||
617 inode->flags & BTRFS_INODE_COMPRESS ||
618 inode->prop_compress)
619 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
623 static inline void inode_should_defrag(struct btrfs_inode *inode,
624 u64 start, u64 end, u64 num_bytes, u32 small_write)
626 /* If this is a small write inside eof, kick off a defrag */
627 if (num_bytes < small_write &&
628 (start > 0 || end + 1 < inode->disk_i_size))
629 btrfs_add_inode_defrag(NULL, inode, small_write);
633 * we create compressed extents in two phases. The first
634 * phase compresses a range of pages that have already been
635 * locked (both pages and state bits are locked).
637 * This is done inside an ordered work queue, and the compression
638 * is spread across many cpus. The actual IO submission is step
639 * two, and the ordered work queue takes care of making sure that
640 * happens in the same order things were put onto the queue by
641 * writepages and friends.
643 * If this code finds it can't get good compression, it puts an
644 * entry onto the work queue to write the uncompressed bytes. This
645 * makes sure that both compressed inodes and uncompressed inodes
646 * are written in the same order that the flusher thread sent them
649 static noinline int compress_file_range(struct async_chunk *async_chunk)
651 struct inode *inode = async_chunk->inode;
652 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
653 u64 blocksize = fs_info->sectorsize;
654 u64 start = async_chunk->start;
655 u64 end = async_chunk->end;
659 struct page **pages = NULL;
660 unsigned long nr_pages;
661 unsigned long total_compressed = 0;
662 unsigned long total_in = 0;
665 int compress_type = fs_info->compress_type;
666 int compressed_extents = 0;
669 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
673 * We need to save i_size before now because it could change in between
674 * us evaluating the size and assigning it. This is because we lock and
675 * unlock the page in truncate and fallocate, and then modify the i_size
678 * The barriers are to emulate READ_ONCE, remove that once i_size_read
682 i_size = i_size_read(inode);
684 actual_end = min_t(u64, i_size, end + 1);
687 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
688 nr_pages = min_t(unsigned long, nr_pages,
689 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
692 * we don't want to send crud past the end of i_size through
693 * compression, that's just a waste of CPU time. So, if the
694 * end of the file is before the start of our current
695 * requested range of bytes, we bail out to the uncompressed
696 * cleanup code that can deal with all of this.
698 * It isn't really the fastest way to fix things, but this is a
699 * very uncommon corner.
701 if (actual_end <= start)
702 goto cleanup_and_bail_uncompressed;
704 total_compressed = actual_end - start;
707 * Skip compression for a small file range(<=blocksize) that
708 * isn't an inline extent, since it doesn't save disk space at all.
710 if (total_compressed <= blocksize &&
711 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
712 goto cleanup_and_bail_uncompressed;
715 * For subpage case, we require full page alignment for the sector
717 * Thus we must also check against @actual_end, not just @end.
719 if (blocksize < PAGE_SIZE) {
720 if (!PAGE_ALIGNED(start) ||
721 !PAGE_ALIGNED(round_up(actual_end, blocksize)))
722 goto cleanup_and_bail_uncompressed;
725 total_compressed = min_t(unsigned long, total_compressed,
726 BTRFS_MAX_UNCOMPRESSED);
731 * we do compression for mount -o compress and when the
732 * inode has not been flagged as nocompress. This flag can
733 * change at any time if we discover bad compression ratios.
735 if (inode_need_compress(BTRFS_I(inode), start, end)) {
737 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
739 /* just bail out to the uncompressed code */
744 if (BTRFS_I(inode)->defrag_compress)
745 compress_type = BTRFS_I(inode)->defrag_compress;
746 else if (BTRFS_I(inode)->prop_compress)
747 compress_type = BTRFS_I(inode)->prop_compress;
750 * we need to call clear_page_dirty_for_io on each
751 * page in the range. Otherwise applications with the file
752 * mmap'd can wander in and change the page contents while
753 * we are compressing them.
755 * If the compression fails for any reason, we set the pages
756 * dirty again later on.
758 * Note that the remaining part is redirtied, the start pointer
759 * has moved, the end is the original one.
762 extent_range_clear_dirty_for_io(inode, start, end);
766 /* Compression level is applied here and only here */
767 ret = btrfs_compress_pages(
768 compress_type | (fs_info->compress_level << 4),
769 inode->i_mapping, start,
776 unsigned long offset = offset_in_page(total_compressed);
777 struct page *page = pages[nr_pages - 1];
779 /* zero the tail end of the last page, we might be
780 * sending it down to disk
783 memzero_page(page, offset, PAGE_SIZE - offset);
789 * Check cow_file_range() for why we don't even try to create inline
790 * extent for subpage case.
792 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
793 /* lets try to make an inline extent */
794 if (ret || total_in < actual_end) {
795 /* we didn't compress the entire range, try
796 * to make an uncompressed inline extent.
798 ret = cow_file_range_inline(BTRFS_I(inode), actual_end,
799 0, BTRFS_COMPRESS_NONE,
802 /* try making a compressed inline extent */
803 ret = cow_file_range_inline(BTRFS_I(inode), actual_end,
805 compress_type, pages,
809 unsigned long clear_flags = EXTENT_DELALLOC |
810 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
811 EXTENT_DO_ACCOUNTING;
812 unsigned long page_error_op;
814 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
817 * inline extent creation worked or returned error,
818 * we don't need to create any more async work items.
819 * Unlock and free up our temp pages.
821 * We use DO_ACCOUNTING here because we need the
822 * delalloc_release_metadata to be done _after_ we drop
823 * our outstanding extent for clearing delalloc for this
826 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
830 PAGE_START_WRITEBACK |
835 * Ensure we only free the compressed pages if we have
836 * them allocated, as we can still reach here with
837 * inode_need_compress() == false.
840 for (i = 0; i < nr_pages; i++) {
841 WARN_ON(pages[i]->mapping);
852 * we aren't doing an inline extent round the compressed size
853 * up to a block size boundary so the allocator does sane
856 total_compressed = ALIGN(total_compressed, blocksize);
859 * one last check to make sure the compression is really a
860 * win, compare the page count read with the blocks on disk,
861 * compression must free at least one sector size
863 total_in = round_up(total_in, fs_info->sectorsize);
864 if (total_compressed + blocksize <= total_in) {
865 compressed_extents++;
868 * The async work queues will take care of doing actual
869 * allocation on disk for these compressed pages, and
870 * will submit them to the elevator.
872 add_async_extent(async_chunk, start, total_in,
873 total_compressed, pages, nr_pages,
876 if (start + total_in < end) {
882 return compressed_extents;
887 * the compression code ran but failed to make things smaller,
888 * free any pages it allocated and our page pointer array
890 for (i = 0; i < nr_pages; i++) {
891 WARN_ON(pages[i]->mapping);
896 total_compressed = 0;
899 /* flag the file so we don't compress in the future */
900 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
901 !(BTRFS_I(inode)->prop_compress)) {
902 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
905 cleanup_and_bail_uncompressed:
907 * No compression, but we still need to write the pages in the file
908 * we've been given so far. redirty the locked page if it corresponds
909 * to our extent and set things up for the async work queue to run
910 * cow_file_range to do the normal delalloc dance.
912 if (async_chunk->locked_page &&
913 (page_offset(async_chunk->locked_page) >= start &&
914 page_offset(async_chunk->locked_page)) <= end) {
915 __set_page_dirty_nobuffers(async_chunk->locked_page);
916 /* unlocked later on in the async handlers */
920 extent_range_redirty_for_io(inode, start, end);
921 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
922 BTRFS_COMPRESS_NONE);
923 compressed_extents++;
925 return compressed_extents;
928 static void free_async_extent_pages(struct async_extent *async_extent)
932 if (!async_extent->pages)
935 for (i = 0; i < async_extent->nr_pages; i++) {
936 WARN_ON(async_extent->pages[i]->mapping);
937 put_page(async_extent->pages[i]);
939 kfree(async_extent->pages);
940 async_extent->nr_pages = 0;
941 async_extent->pages = NULL;
944 static int submit_uncompressed_range(struct btrfs_inode *inode,
945 struct async_extent *async_extent,
946 struct page *locked_page)
948 u64 start = async_extent->start;
949 u64 end = async_extent->start + async_extent->ram_size - 1;
950 unsigned long nr_written = 0;
951 int page_started = 0;
955 * Call cow_file_range() to run the delalloc range directly, since we
956 * won't go to NOCOW or async path again.
958 * Also we call cow_file_range() with @unlock_page == 0, so that we
959 * can directly submit them without interruption.
961 ret = cow_file_range(inode, locked_page, start, end, &page_started,
962 &nr_written, 0, NULL);
963 /* Inline extent inserted, page gets unlocked and everything is done */
969 btrfs_cleanup_ordered_extents(inode, locked_page, start, end - start + 1);
971 const u64 page_start = page_offset(locked_page);
972 const u64 page_end = page_start + PAGE_SIZE - 1;
974 btrfs_page_set_error(inode->root->fs_info, locked_page,
975 page_start, PAGE_SIZE);
976 set_page_writeback(locked_page);
977 end_page_writeback(locked_page);
978 end_extent_writepage(locked_page, ret, page_start, page_end);
979 unlock_page(locked_page);
984 ret = extent_write_locked_range(&inode->vfs_inode, start, end);
985 /* All pages will be unlocked, including @locked_page */
991 static int submit_one_async_extent(struct btrfs_inode *inode,
992 struct async_chunk *async_chunk,
993 struct async_extent *async_extent,
996 struct extent_io_tree *io_tree = &inode->io_tree;
997 struct btrfs_root *root = inode->root;
998 struct btrfs_fs_info *fs_info = root->fs_info;
999 struct btrfs_key ins;
1000 struct page *locked_page = NULL;
1001 struct extent_map *em;
1003 u64 start = async_extent->start;
1004 u64 end = async_extent->start + async_extent->ram_size - 1;
1007 * If async_chunk->locked_page is in the async_extent range, we need to
1010 if (async_chunk->locked_page) {
1011 u64 locked_page_start = page_offset(async_chunk->locked_page);
1012 u64 locked_page_end = locked_page_start + PAGE_SIZE - 1;
1014 if (!(start >= locked_page_end || end <= locked_page_start))
1015 locked_page = async_chunk->locked_page;
1017 lock_extent(io_tree, start, end, NULL);
1019 /* We have fall back to uncompressed write */
1020 if (!async_extent->pages)
1021 return submit_uncompressed_range(inode, async_extent, locked_page);
1023 ret = btrfs_reserve_extent(root, async_extent->ram_size,
1024 async_extent->compressed_size,
1025 async_extent->compressed_size,
1026 0, *alloc_hint, &ins, 1, 1);
1028 free_async_extent_pages(async_extent);
1030 * Here we used to try again by going back to non-compressed
1031 * path for ENOSPC. But we can't reserve space even for
1032 * compressed size, how could it work for uncompressed size
1033 * which requires larger size? So here we directly go error
1039 /* Here we're doing allocation and writeback of the compressed pages */
1040 em = create_io_em(inode, start,
1041 async_extent->ram_size, /* len */
1042 start, /* orig_start */
1043 ins.objectid, /* block_start */
1044 ins.offset, /* block_len */
1045 ins.offset, /* orig_block_len */
1046 async_extent->ram_size, /* ram_bytes */
1047 async_extent->compress_type,
1048 BTRFS_ORDERED_COMPRESSED);
1051 goto out_free_reserve;
1053 free_extent_map(em);
1055 ret = btrfs_add_ordered_extent(inode, start, /* file_offset */
1056 async_extent->ram_size, /* num_bytes */
1057 async_extent->ram_size, /* ram_bytes */
1058 ins.objectid, /* disk_bytenr */
1059 ins.offset, /* disk_num_bytes */
1061 1 << BTRFS_ORDERED_COMPRESSED,
1062 async_extent->compress_type);
1064 btrfs_drop_extent_map_range(inode, start, end, false);
1065 goto out_free_reserve;
1067 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1069 /* Clear dirty, set writeback and unlock the pages. */
1070 extent_clear_unlock_delalloc(inode, start, end,
1071 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
1072 PAGE_UNLOCK | PAGE_START_WRITEBACK);
1073 if (btrfs_submit_compressed_write(inode, start, /* file_offset */
1074 async_extent->ram_size, /* num_bytes */
1075 ins.objectid, /* disk_bytenr */
1076 ins.offset, /* compressed_len */
1077 async_extent->pages, /* compressed_pages */
1078 async_extent->nr_pages,
1079 async_chunk->write_flags,
1080 async_chunk->blkcg_css, true)) {
1081 const u64 start = async_extent->start;
1082 const u64 end = start + async_extent->ram_size - 1;
1084 btrfs_writepage_endio_finish_ordered(inode, NULL, start, end, 0);
1086 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
1087 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1088 free_async_extent_pages(async_extent);
1090 *alloc_hint = ins.objectid + ins.offset;
1091 kfree(async_extent);
1095 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1096 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1098 extent_clear_unlock_delalloc(inode, start, end,
1099 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
1100 EXTENT_DELALLOC_NEW |
1101 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
1102 PAGE_UNLOCK | PAGE_START_WRITEBACK |
1103 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1104 free_async_extent_pages(async_extent);
1105 kfree(async_extent);
1110 * Phase two of compressed writeback. This is the ordered portion of the code,
1111 * which only gets called in the order the work was queued. We walk all the
1112 * async extents created by compress_file_range and send them down to the disk.
1114 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
1116 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
1117 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1118 struct async_extent *async_extent;
1122 while (!list_empty(&async_chunk->extents)) {
1126 async_extent = list_entry(async_chunk->extents.next,
1127 struct async_extent, list);
1128 list_del(&async_extent->list);
1129 extent_start = async_extent->start;
1130 ram_size = async_extent->ram_size;
1132 ret = submit_one_async_extent(inode, async_chunk, async_extent,
1134 btrfs_debug(fs_info,
1135 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1136 inode->root->root_key.objectid,
1137 btrfs_ino(inode), extent_start, ram_size, ret);
1141 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1144 struct extent_map_tree *em_tree = &inode->extent_tree;
1145 struct extent_map *em;
1148 read_lock(&em_tree->lock);
1149 em = search_extent_mapping(em_tree, start, num_bytes);
1152 * if block start isn't an actual block number then find the
1153 * first block in this inode and use that as a hint. If that
1154 * block is also bogus then just don't worry about it.
1156 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1157 free_extent_map(em);
1158 em = search_extent_mapping(em_tree, 0, 0);
1159 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1160 alloc_hint = em->block_start;
1162 free_extent_map(em);
1164 alloc_hint = em->block_start;
1165 free_extent_map(em);
1168 read_unlock(&em_tree->lock);
1174 * when extent_io.c finds a delayed allocation range in the file,
1175 * the call backs end up in this code. The basic idea is to
1176 * allocate extents on disk for the range, and create ordered data structs
1177 * in ram to track those extents.
1179 * locked_page is the page that writepage had locked already. We use
1180 * it to make sure we don't do extra locks or unlocks.
1182 * *page_started is set to one if we unlock locked_page and do everything
1183 * required to start IO on it. It may be clean and already done with
1184 * IO when we return.
1186 * When unlock == 1, we unlock the pages in successfully allocated regions.
1187 * When unlock == 0, we leave them locked for writing them out.
1189 * However, we unlock all the pages except @locked_page in case of failure.
1191 * In summary, page locking state will be as follow:
1193 * - page_started == 1 (return value)
1194 * - All the pages are unlocked. IO is started.
1195 * - Note that this can happen only on success
1197 * - All the pages except @locked_page are unlocked in any case
1199 * - On success, all the pages are locked for writing out them
1200 * - On failure, all the pages except @locked_page are unlocked
1202 * When a failure happens in the second or later iteration of the
1203 * while-loop, the ordered extents created in previous iterations are kept
1204 * intact. So, the caller must clean them up by calling
1205 * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
1208 static noinline int cow_file_range(struct btrfs_inode *inode,
1209 struct page *locked_page,
1210 u64 start, u64 end, int *page_started,
1211 unsigned long *nr_written, int unlock,
1214 struct btrfs_root *root = inode->root;
1215 struct btrfs_fs_info *fs_info = root->fs_info;
1217 u64 orig_start = start;
1219 unsigned long ram_size;
1220 u64 cur_alloc_size = 0;
1222 u64 blocksize = fs_info->sectorsize;
1223 struct btrfs_key ins;
1224 struct extent_map *em;
1225 unsigned clear_bits;
1226 unsigned long page_ops;
1227 bool extent_reserved = false;
1230 if (btrfs_is_free_space_inode(inode)) {
1235 num_bytes = ALIGN(end - start + 1, blocksize);
1236 num_bytes = max(blocksize, num_bytes);
1237 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1239 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1242 * Due to the page size limit, for subpage we can only trigger the
1243 * writeback for the dirty sectors of page, that means data writeback
1244 * is doing more writeback than what we want.
1246 * This is especially unexpected for some call sites like fallocate,
1247 * where we only increase i_size after everything is done.
1248 * This means we can trigger inline extent even if we didn't want to.
1249 * So here we skip inline extent creation completely.
1251 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
1252 u64 actual_end = min_t(u64, i_size_read(&inode->vfs_inode),
1255 /* lets try to make an inline extent */
1256 ret = cow_file_range_inline(inode, actual_end, 0,
1257 BTRFS_COMPRESS_NONE, NULL, false);
1260 * We use DO_ACCOUNTING here because we need the
1261 * delalloc_release_metadata to be run _after_ we drop
1262 * our outstanding extent for clearing delalloc for this
1265 extent_clear_unlock_delalloc(inode, start, end,
1267 EXTENT_LOCKED | EXTENT_DELALLOC |
1268 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1269 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1270 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1271 *nr_written = *nr_written +
1272 (end - start + PAGE_SIZE) / PAGE_SIZE;
1275 * locked_page is locked by the caller of
1276 * writepage_delalloc(), not locked by
1277 * __process_pages_contig().
1279 * We can't let __process_pages_contig() to unlock it,
1280 * as it doesn't have any subpage::writers recorded.
1282 * Here we manually unlock the page, since the caller
1283 * can't use page_started to determine if it's an
1284 * inline extent or a compressed extent.
1286 unlock_page(locked_page);
1288 } else if (ret < 0) {
1293 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1296 * Relocation relies on the relocated extents to have exactly the same
1297 * size as the original extents. Normally writeback for relocation data
1298 * extents follows a NOCOW path because relocation preallocates the
1299 * extents. However, due to an operation such as scrub turning a block
1300 * group to RO mode, it may fallback to COW mode, so we must make sure
1301 * an extent allocated during COW has exactly the requested size and can
1302 * not be split into smaller extents, otherwise relocation breaks and
1303 * fails during the stage where it updates the bytenr of file extent
1306 if (btrfs_is_data_reloc_root(root))
1307 min_alloc_size = num_bytes;
1309 min_alloc_size = fs_info->sectorsize;
1311 while (num_bytes > 0) {
1312 cur_alloc_size = num_bytes;
1313 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1314 min_alloc_size, 0, alloc_hint,
1318 cur_alloc_size = ins.offset;
1319 extent_reserved = true;
1321 ram_size = ins.offset;
1322 em = create_io_em(inode, start, ins.offset, /* len */
1323 start, /* orig_start */
1324 ins.objectid, /* block_start */
1325 ins.offset, /* block_len */
1326 ins.offset, /* orig_block_len */
1327 ram_size, /* ram_bytes */
1328 BTRFS_COMPRESS_NONE, /* compress_type */
1329 BTRFS_ORDERED_REGULAR /* type */);
1334 free_extent_map(em);
1336 ret = btrfs_add_ordered_extent(inode, start, ram_size, ram_size,
1337 ins.objectid, cur_alloc_size, 0,
1338 1 << BTRFS_ORDERED_REGULAR,
1339 BTRFS_COMPRESS_NONE);
1341 goto out_drop_extent_cache;
1343 if (btrfs_is_data_reloc_root(root)) {
1344 ret = btrfs_reloc_clone_csums(inode, start,
1347 * Only drop cache here, and process as normal.
1349 * We must not allow extent_clear_unlock_delalloc()
1350 * at out_unlock label to free meta of this ordered
1351 * extent, as its meta should be freed by
1352 * btrfs_finish_ordered_io().
1354 * So we must continue until @start is increased to
1355 * skip current ordered extent.
1358 btrfs_drop_extent_map_range(inode, start,
1359 start + ram_size - 1,
1363 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1366 * We're not doing compressed IO, don't unlock the first page
1367 * (which the caller expects to stay locked), don't clear any
1368 * dirty bits and don't set any writeback bits
1370 * Do set the Ordered (Private2) bit so we know this page was
1371 * properly setup for writepage.
1373 page_ops = unlock ? PAGE_UNLOCK : 0;
1374 page_ops |= PAGE_SET_ORDERED;
1376 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1378 EXTENT_LOCKED | EXTENT_DELALLOC,
1380 if (num_bytes < cur_alloc_size)
1383 num_bytes -= cur_alloc_size;
1384 alloc_hint = ins.objectid + ins.offset;
1385 start += cur_alloc_size;
1386 extent_reserved = false;
1389 * btrfs_reloc_clone_csums() error, since start is increased
1390 * extent_clear_unlock_delalloc() at out_unlock label won't
1391 * free metadata of current ordered extent, we're OK to exit.
1399 out_drop_extent_cache:
1400 btrfs_drop_extent_map_range(inode, start, start + ram_size - 1, false);
1402 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1403 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1406 * If done_offset is non-NULL and ret == -EAGAIN, we expect the
1407 * caller to write out the successfully allocated region and retry.
1409 if (done_offset && ret == -EAGAIN) {
1410 if (orig_start < start)
1411 *done_offset = start - 1;
1413 *done_offset = start;
1415 } else if (ret == -EAGAIN) {
1416 /* Convert to -ENOSPC since the caller cannot retry. */
1421 * Now, we have three regions to clean up:
1423 * |-------(1)----|---(2)---|-------------(3)----------|
1424 * `- orig_start `- start `- start + cur_alloc_size `- end
1426 * We process each region below.
1429 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1430 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1431 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1434 * For the range (1). We have already instantiated the ordered extents
1435 * for this region. They are cleaned up by
1436 * btrfs_cleanup_ordered_extents() in e.g,
1437 * btrfs_run_delalloc_range(). EXTENT_LOCKED | EXTENT_DELALLOC are
1438 * already cleared in the above loop. And, EXTENT_DELALLOC_NEW |
1439 * EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV are handled by the cleanup
1442 * However, in case of unlock == 0, we still need to unlock the pages
1443 * (except @locked_page) to ensure all the pages are unlocked.
1445 if (!unlock && orig_start < start) {
1447 mapping_set_error(inode->vfs_inode.i_mapping, ret);
1448 extent_clear_unlock_delalloc(inode, orig_start, start - 1,
1449 locked_page, 0, page_ops);
1453 * For the range (2). If we reserved an extent for our delalloc range
1454 * (or a subrange) and failed to create the respective ordered extent,
1455 * then it means that when we reserved the extent we decremented the
1456 * extent's size from the data space_info's bytes_may_use counter and
1457 * incremented the space_info's bytes_reserved counter by the same
1458 * amount. We must make sure extent_clear_unlock_delalloc() does not try
1459 * to decrement again the data space_info's bytes_may_use counter,
1460 * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
1462 if (extent_reserved) {
1463 extent_clear_unlock_delalloc(inode, start,
1464 start + cur_alloc_size - 1,
1468 start += cur_alloc_size;
1474 * For the range (3). We never touched the region. In addition to the
1475 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1476 * space_info's bytes_may_use counter, reserved in
1477 * btrfs_check_data_free_space().
1479 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1480 clear_bits | EXTENT_CLEAR_DATA_RESV,
1486 * work queue call back to started compression on a file and pages
1488 static noinline void async_cow_start(struct btrfs_work *work)
1490 struct async_chunk *async_chunk;
1491 int compressed_extents;
1493 async_chunk = container_of(work, struct async_chunk, work);
1495 compressed_extents = compress_file_range(async_chunk);
1496 if (compressed_extents == 0) {
1497 btrfs_add_delayed_iput(async_chunk->inode);
1498 async_chunk->inode = NULL;
1503 * work queue call back to submit previously compressed pages
1505 static noinline void async_cow_submit(struct btrfs_work *work)
1507 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1509 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1510 unsigned long nr_pages;
1512 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1516 * ->inode could be NULL if async_chunk_start has failed to compress,
1517 * in which case we don't have anything to submit, yet we need to
1518 * always adjust ->async_delalloc_pages as its paired with the init
1519 * happening in cow_file_range_async
1521 if (async_chunk->inode)
1522 submit_compressed_extents(async_chunk);
1524 /* atomic_sub_return implies a barrier */
1525 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1527 cond_wake_up_nomb(&fs_info->async_submit_wait);
1530 static noinline void async_cow_free(struct btrfs_work *work)
1532 struct async_chunk *async_chunk;
1533 struct async_cow *async_cow;
1535 async_chunk = container_of(work, struct async_chunk, work);
1536 if (async_chunk->inode)
1537 btrfs_add_delayed_iput(async_chunk->inode);
1538 if (async_chunk->blkcg_css)
1539 css_put(async_chunk->blkcg_css);
1541 async_cow = async_chunk->async_cow;
1542 if (atomic_dec_and_test(&async_cow->num_chunks))
1546 static int cow_file_range_async(struct btrfs_inode *inode,
1547 struct writeback_control *wbc,
1548 struct page *locked_page,
1549 u64 start, u64 end, int *page_started,
1550 unsigned long *nr_written)
1552 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1553 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1554 struct async_cow *ctx;
1555 struct async_chunk *async_chunk;
1556 unsigned long nr_pages;
1558 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1560 bool should_compress;
1562 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1564 unlock_extent(&inode->io_tree, start, end, NULL);
1566 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1567 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1569 should_compress = false;
1571 should_compress = true;
1574 nofs_flag = memalloc_nofs_save();
1575 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1576 memalloc_nofs_restore(nofs_flag);
1579 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1580 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1581 EXTENT_DO_ACCOUNTING;
1582 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1583 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1585 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1586 clear_bits, page_ops);
1590 async_chunk = ctx->chunks;
1591 atomic_set(&ctx->num_chunks, num_chunks);
1593 for (i = 0; i < num_chunks; i++) {
1594 if (should_compress)
1595 cur_end = min(end, start + SZ_512K - 1);
1600 * igrab is called higher up in the call chain, take only the
1601 * lightweight reference for the callback lifetime
1603 ihold(&inode->vfs_inode);
1604 async_chunk[i].async_cow = ctx;
1605 async_chunk[i].inode = &inode->vfs_inode;
1606 async_chunk[i].start = start;
1607 async_chunk[i].end = cur_end;
1608 async_chunk[i].write_flags = write_flags;
1609 INIT_LIST_HEAD(&async_chunk[i].extents);
1612 * The locked_page comes all the way from writepage and its
1613 * the original page we were actually given. As we spread
1614 * this large delalloc region across multiple async_chunk
1615 * structs, only the first struct needs a pointer to locked_page
1617 * This way we don't need racey decisions about who is supposed
1622 * Depending on the compressibility, the pages might or
1623 * might not go through async. We want all of them to
1624 * be accounted against wbc once. Let's do it here
1625 * before the paths diverge. wbc accounting is used
1626 * only for foreign writeback detection and doesn't
1627 * need full accuracy. Just account the whole thing
1628 * against the first page.
1630 wbc_account_cgroup_owner(wbc, locked_page,
1632 async_chunk[i].locked_page = locked_page;
1635 async_chunk[i].locked_page = NULL;
1638 if (blkcg_css != blkcg_root_css) {
1640 async_chunk[i].blkcg_css = blkcg_css;
1642 async_chunk[i].blkcg_css = NULL;
1645 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1646 async_cow_submit, async_cow_free);
1648 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1649 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1651 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1653 *nr_written += nr_pages;
1654 start = cur_end + 1;
1660 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1661 struct page *locked_page, u64 start,
1662 u64 end, int *page_started,
1663 unsigned long *nr_written)
1665 u64 done_offset = end;
1667 bool locked_page_done = false;
1669 while (start <= end) {
1670 ret = cow_file_range(inode, locked_page, start, end, page_started,
1671 nr_written, 0, &done_offset);
1672 if (ret && ret != -EAGAIN)
1675 if (*page_started) {
1683 if (done_offset == start) {
1684 wait_on_bit_io(&inode->root->fs_info->flags,
1685 BTRFS_FS_NEED_ZONE_FINISH,
1686 TASK_UNINTERRUPTIBLE);
1690 if (!locked_page_done) {
1691 __set_page_dirty_nobuffers(locked_page);
1692 account_page_redirty(locked_page);
1694 locked_page_done = true;
1695 extent_write_locked_range(&inode->vfs_inode, start, done_offset);
1697 start = done_offset + 1;
1705 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1706 u64 bytenr, u64 num_bytes, bool nowait)
1708 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bytenr);
1709 struct btrfs_ordered_sum *sums;
1713 ret = btrfs_lookup_csums_range(csum_root, bytenr,
1714 bytenr + num_bytes - 1, &list, 0,
1716 if (ret == 0 && list_empty(&list))
1719 while (!list_empty(&list)) {
1720 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1721 list_del(&sums->list);
1729 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1730 const u64 start, const u64 end,
1731 int *page_started, unsigned long *nr_written)
1733 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1734 const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1735 const u64 range_bytes = end + 1 - start;
1736 struct extent_io_tree *io_tree = &inode->io_tree;
1737 u64 range_start = start;
1741 * If EXTENT_NORESERVE is set it means that when the buffered write was
1742 * made we had not enough available data space and therefore we did not
1743 * reserve data space for it, since we though we could do NOCOW for the
1744 * respective file range (either there is prealloc extent or the inode
1745 * has the NOCOW bit set).
1747 * However when we need to fallback to COW mode (because for example the
1748 * block group for the corresponding extent was turned to RO mode by a
1749 * scrub or relocation) we need to do the following:
1751 * 1) We increment the bytes_may_use counter of the data space info.
1752 * If COW succeeds, it allocates a new data extent and after doing
1753 * that it decrements the space info's bytes_may_use counter and
1754 * increments its bytes_reserved counter by the same amount (we do
1755 * this at btrfs_add_reserved_bytes()). So we need to increment the
1756 * bytes_may_use counter to compensate (when space is reserved at
1757 * buffered write time, the bytes_may_use counter is incremented);
1759 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1760 * that if the COW path fails for any reason, it decrements (through
1761 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1762 * data space info, which we incremented in the step above.
1764 * If we need to fallback to cow and the inode corresponds to a free
1765 * space cache inode or an inode of the data relocation tree, we must
1766 * also increment bytes_may_use of the data space_info for the same
1767 * reason. Space caches and relocated data extents always get a prealloc
1768 * extent for them, however scrub or balance may have set the block
1769 * group that contains that extent to RO mode and therefore force COW
1770 * when starting writeback.
1772 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1773 EXTENT_NORESERVE, 0);
1774 if (count > 0 || is_space_ino || is_reloc_ino) {
1776 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1777 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1779 if (is_space_ino || is_reloc_ino)
1780 bytes = range_bytes;
1782 spin_lock(&sinfo->lock);
1783 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1784 spin_unlock(&sinfo->lock);
1787 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1791 return cow_file_range(inode, locked_page, start, end, page_started,
1792 nr_written, 1, NULL);
1795 struct can_nocow_file_extent_args {
1798 /* Start file offset of the range we want to NOCOW. */
1800 /* End file offset (inclusive) of the range we want to NOCOW. */
1802 bool writeback_path;
1805 * Free the path passed to can_nocow_file_extent() once it's not needed
1810 /* Output fields. Only set when can_nocow_file_extent() returns 1. */
1815 /* Number of bytes that can be written to in NOCOW mode. */
1820 * Check if we can NOCOW the file extent that the path points to.
1821 * This function may return with the path released, so the caller should check
1822 * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
1824 * Returns: < 0 on error
1825 * 0 if we can not NOCOW
1828 static int can_nocow_file_extent(struct btrfs_path *path,
1829 struct btrfs_key *key,
1830 struct btrfs_inode *inode,
1831 struct can_nocow_file_extent_args *args)
1833 const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
1834 struct extent_buffer *leaf = path->nodes[0];
1835 struct btrfs_root *root = inode->root;
1836 struct btrfs_file_extent_item *fi;
1841 bool nowait = path->nowait;
1843 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
1844 extent_type = btrfs_file_extent_type(leaf, fi);
1846 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1849 /* Can't access these fields unless we know it's not an inline extent. */
1850 args->disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1851 args->disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1852 args->extent_offset = btrfs_file_extent_offset(leaf, fi);
1854 if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1855 extent_type == BTRFS_FILE_EXTENT_REG)
1859 * If the extent was created before the generation where the last snapshot
1860 * for its subvolume was created, then this implies the extent is shared,
1861 * hence we must COW.
1863 if (!args->strict &&
1864 btrfs_file_extent_generation(leaf, fi) <=
1865 btrfs_root_last_snapshot(&root->root_item))
1868 /* An explicit hole, must COW. */
1869 if (args->disk_bytenr == 0)
1872 /* Compressed/encrypted/encoded extents must be COWed. */
1873 if (btrfs_file_extent_compression(leaf, fi) ||
1874 btrfs_file_extent_encryption(leaf, fi) ||
1875 btrfs_file_extent_other_encoding(leaf, fi))
1878 extent_end = btrfs_file_extent_end(path);
1881 * The following checks can be expensive, as they need to take other
1882 * locks and do btree or rbtree searches, so release the path to avoid
1883 * blocking other tasks for too long.
1885 btrfs_release_path(path);
1887 ret = btrfs_cross_ref_exist(root, btrfs_ino(inode),
1888 key->offset - args->extent_offset,
1889 args->disk_bytenr, false, path);
1890 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1894 if (args->free_path) {
1896 * We don't need the path anymore, plus through the
1897 * csum_exist_in_range() call below we will end up allocating
1898 * another path. So free the path to avoid unnecessary extra
1901 btrfs_free_path(path);
1905 /* If there are pending snapshots for this root, we must COW. */
1906 if (args->writeback_path && !is_freespace_inode &&
1907 atomic_read(&root->snapshot_force_cow))
1910 args->disk_bytenr += args->extent_offset;
1911 args->disk_bytenr += args->start - key->offset;
1912 args->num_bytes = min(args->end + 1, extent_end) - args->start;
1915 * Force COW if csums exist in the range. This ensures that csums for a
1916 * given extent are either valid or do not exist.
1918 ret = csum_exist_in_range(root->fs_info, args->disk_bytenr, args->num_bytes,
1920 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1926 if (args->free_path && path)
1927 btrfs_free_path(path);
1929 return ret < 0 ? ret : can_nocow;
1933 * when nowcow writeback call back. This checks for snapshots or COW copies
1934 * of the extents that exist in the file, and COWs the file as required.
1936 * If no cow copies or snapshots exist, we write directly to the existing
1939 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1940 struct page *locked_page,
1941 const u64 start, const u64 end,
1943 unsigned long *nr_written)
1945 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1946 struct btrfs_root *root = inode->root;
1947 struct btrfs_path *path;
1948 u64 cow_start = (u64)-1;
1949 u64 cur_offset = start;
1951 bool check_prev = true;
1952 u64 ino = btrfs_ino(inode);
1953 struct btrfs_block_group *bg;
1955 struct can_nocow_file_extent_args nocow_args = { 0 };
1957 path = btrfs_alloc_path();
1959 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1960 EXTENT_LOCKED | EXTENT_DELALLOC |
1961 EXTENT_DO_ACCOUNTING |
1962 EXTENT_DEFRAG, PAGE_UNLOCK |
1963 PAGE_START_WRITEBACK |
1964 PAGE_END_WRITEBACK);
1968 nocow_args.end = end;
1969 nocow_args.writeback_path = true;
1972 struct btrfs_key found_key;
1973 struct btrfs_file_extent_item *fi;
1974 struct extent_buffer *leaf;
1982 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1988 * If there is no extent for our range when doing the initial
1989 * search, then go back to the previous slot as it will be the
1990 * one containing the search offset
1992 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1993 leaf = path->nodes[0];
1994 btrfs_item_key_to_cpu(leaf, &found_key,
1995 path->slots[0] - 1);
1996 if (found_key.objectid == ino &&
1997 found_key.type == BTRFS_EXTENT_DATA_KEY)
2002 /* Go to next leaf if we have exhausted the current one */
2003 leaf = path->nodes[0];
2004 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2005 ret = btrfs_next_leaf(root, path);
2007 if (cow_start != (u64)-1)
2008 cur_offset = cow_start;
2013 leaf = path->nodes[0];
2016 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2018 /* Didn't find anything for our INO */
2019 if (found_key.objectid > ino)
2022 * Keep searching until we find an EXTENT_ITEM or there are no
2023 * more extents for this inode
2025 if (WARN_ON_ONCE(found_key.objectid < ino) ||
2026 found_key.type < BTRFS_EXTENT_DATA_KEY) {
2031 /* Found key is not EXTENT_DATA_KEY or starts after req range */
2032 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
2033 found_key.offset > end)
2037 * If the found extent starts after requested offset, then
2038 * adjust extent_end to be right before this extent begins
2040 if (found_key.offset > cur_offset) {
2041 extent_end = found_key.offset;
2047 * Found extent which begins before our range and potentially
2050 fi = btrfs_item_ptr(leaf, path->slots[0],
2051 struct btrfs_file_extent_item);
2052 extent_type = btrfs_file_extent_type(leaf, fi);
2053 /* If this is triggered then we have a memory corruption. */
2054 ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
2055 if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
2059 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
2060 extent_end = btrfs_file_extent_end(path);
2063 * If the extent we got ends before our current offset, skip to
2066 if (extent_end <= cur_offset) {
2071 nocow_args.start = cur_offset;
2072 ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
2074 if (cow_start != (u64)-1)
2075 cur_offset = cow_start;
2077 } else if (ret == 0) {
2082 bg = btrfs_inc_nocow_writers(fs_info, nocow_args.disk_bytenr);
2087 * If nocow is false then record the beginning of the range
2088 * that needs to be COWed
2091 if (cow_start == (u64)-1)
2092 cow_start = cur_offset;
2093 cur_offset = extent_end;
2094 if (cur_offset > end)
2096 if (!path->nodes[0])
2103 * COW range from cow_start to found_key.offset - 1. As the key
2104 * will contain the beginning of the first extent that can be
2105 * NOCOW, following one which needs to be COW'ed
2107 if (cow_start != (u64)-1) {
2108 ret = fallback_to_cow(inode, locked_page,
2109 cow_start, found_key.offset - 1,
2110 page_started, nr_written);
2113 cow_start = (u64)-1;
2116 nocow_end = cur_offset + nocow_args.num_bytes - 1;
2118 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
2119 u64 orig_start = found_key.offset - nocow_args.extent_offset;
2120 struct extent_map *em;
2122 em = create_io_em(inode, cur_offset, nocow_args.num_bytes,
2124 nocow_args.disk_bytenr, /* block_start */
2125 nocow_args.num_bytes, /* block_len */
2126 nocow_args.disk_num_bytes, /* orig_block_len */
2127 ram_bytes, BTRFS_COMPRESS_NONE,
2128 BTRFS_ORDERED_PREALLOC);
2133 free_extent_map(em);
2134 ret = btrfs_add_ordered_extent(inode,
2135 cur_offset, nocow_args.num_bytes,
2136 nocow_args.num_bytes,
2137 nocow_args.disk_bytenr,
2138 nocow_args.num_bytes, 0,
2139 1 << BTRFS_ORDERED_PREALLOC,
2140 BTRFS_COMPRESS_NONE);
2142 btrfs_drop_extent_map_range(inode, cur_offset,
2147 ret = btrfs_add_ordered_extent(inode, cur_offset,
2148 nocow_args.num_bytes,
2149 nocow_args.num_bytes,
2150 nocow_args.disk_bytenr,
2151 nocow_args.num_bytes,
2153 1 << BTRFS_ORDERED_NOCOW,
2154 BTRFS_COMPRESS_NONE);
2160 btrfs_dec_nocow_writers(bg);
2164 if (btrfs_is_data_reloc_root(root))
2166 * Error handled later, as we must prevent
2167 * extent_clear_unlock_delalloc() in error handler
2168 * from freeing metadata of created ordered extent.
2170 ret = btrfs_reloc_clone_csums(inode, cur_offset,
2171 nocow_args.num_bytes);
2173 extent_clear_unlock_delalloc(inode, cur_offset, nocow_end,
2174 locked_page, EXTENT_LOCKED |
2176 EXTENT_CLEAR_DATA_RESV,
2177 PAGE_UNLOCK | PAGE_SET_ORDERED);
2179 cur_offset = extent_end;
2182 * btrfs_reloc_clone_csums() error, now we're OK to call error
2183 * handler, as metadata for created ordered extent will only
2184 * be freed by btrfs_finish_ordered_io().
2188 if (cur_offset > end)
2191 btrfs_release_path(path);
2193 if (cur_offset <= end && cow_start == (u64)-1)
2194 cow_start = cur_offset;
2196 if (cow_start != (u64)-1) {
2198 ret = fallback_to_cow(inode, locked_page, cow_start, end,
2199 page_started, nr_written);
2206 btrfs_dec_nocow_writers(bg);
2208 if (ret && cur_offset < end)
2209 extent_clear_unlock_delalloc(inode, cur_offset, end,
2210 locked_page, EXTENT_LOCKED |
2211 EXTENT_DELALLOC | EXTENT_DEFRAG |
2212 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
2213 PAGE_START_WRITEBACK |
2214 PAGE_END_WRITEBACK);
2215 btrfs_free_path(path);
2219 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
2221 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
2222 if (inode->defrag_bytes &&
2223 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
2232 * Function to process delayed allocation (create CoW) for ranges which are
2233 * being touched for the first time.
2235 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
2236 u64 start, u64 end, int *page_started, unsigned long *nr_written,
2237 struct writeback_control *wbc)
2240 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2243 * The range must cover part of the @locked_page, or the returned
2244 * @page_started can confuse the caller.
2246 ASSERT(!(end <= page_offset(locked_page) ||
2247 start >= page_offset(locked_page) + PAGE_SIZE));
2249 if (should_nocow(inode, start, end)) {
2251 * Normally on a zoned device we're only doing COW writes, but
2252 * in case of relocation on a zoned filesystem we have taken
2253 * precaution, that we're only writing sequentially. It's safe
2254 * to use run_delalloc_nocow() here, like for regular
2255 * preallocated inodes.
2257 ASSERT(!zoned || btrfs_is_data_reloc_root(inode->root));
2258 ret = run_delalloc_nocow(inode, locked_page, start, end,
2259 page_started, nr_written);
2260 } else if (!btrfs_inode_can_compress(inode) ||
2261 !inode_need_compress(inode, start, end)) {
2263 ret = run_delalloc_zoned(inode, locked_page, start, end,
2264 page_started, nr_written);
2266 ret = cow_file_range(inode, locked_page, start, end,
2267 page_started, nr_written, 1, NULL);
2269 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
2270 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
2271 page_started, nr_written);
2275 btrfs_cleanup_ordered_extents(inode, locked_page, start,
2280 void btrfs_split_delalloc_extent(struct inode *inode,
2281 struct extent_state *orig, u64 split)
2283 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2286 /* not delalloc, ignore it */
2287 if (!(orig->state & EXTENT_DELALLOC))
2290 size = orig->end - orig->start + 1;
2291 if (size > fs_info->max_extent_size) {
2296 * See the explanation in btrfs_merge_delalloc_extent, the same
2297 * applies here, just in reverse.
2299 new_size = orig->end - split + 1;
2300 num_extents = count_max_extents(fs_info, new_size);
2301 new_size = split - orig->start;
2302 num_extents += count_max_extents(fs_info, new_size);
2303 if (count_max_extents(fs_info, size) >= num_extents)
2307 spin_lock(&BTRFS_I(inode)->lock);
2308 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
2309 spin_unlock(&BTRFS_I(inode)->lock);
2313 * Handle merged delayed allocation extents so we can keep track of new extents
2314 * that are just merged onto old extents, such as when we are doing sequential
2315 * writes, so we can properly account for the metadata space we'll need.
2317 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
2318 struct extent_state *other)
2320 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2321 u64 new_size, old_size;
2324 /* not delalloc, ignore it */
2325 if (!(other->state & EXTENT_DELALLOC))
2328 if (new->start > other->start)
2329 new_size = new->end - other->start + 1;
2331 new_size = other->end - new->start + 1;
2333 /* we're not bigger than the max, unreserve the space and go */
2334 if (new_size <= fs_info->max_extent_size) {
2335 spin_lock(&BTRFS_I(inode)->lock);
2336 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2337 spin_unlock(&BTRFS_I(inode)->lock);
2342 * We have to add up either side to figure out how many extents were
2343 * accounted for before we merged into one big extent. If the number of
2344 * extents we accounted for is <= the amount we need for the new range
2345 * then we can return, otherwise drop. Think of it like this
2349 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2350 * need 2 outstanding extents, on one side we have 1 and the other side
2351 * we have 1 so they are == and we can return. But in this case
2353 * [MAX_SIZE+4k][MAX_SIZE+4k]
2355 * Each range on their own accounts for 2 extents, but merged together
2356 * they are only 3 extents worth of accounting, so we need to drop in
2359 old_size = other->end - other->start + 1;
2360 num_extents = count_max_extents(fs_info, old_size);
2361 old_size = new->end - new->start + 1;
2362 num_extents += count_max_extents(fs_info, old_size);
2363 if (count_max_extents(fs_info, new_size) >= num_extents)
2366 spin_lock(&BTRFS_I(inode)->lock);
2367 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2368 spin_unlock(&BTRFS_I(inode)->lock);
2371 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2372 struct inode *inode)
2374 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2376 spin_lock(&root->delalloc_lock);
2377 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2378 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2379 &root->delalloc_inodes);
2380 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2381 &BTRFS_I(inode)->runtime_flags);
2382 root->nr_delalloc_inodes++;
2383 if (root->nr_delalloc_inodes == 1) {
2384 spin_lock(&fs_info->delalloc_root_lock);
2385 BUG_ON(!list_empty(&root->delalloc_root));
2386 list_add_tail(&root->delalloc_root,
2387 &fs_info->delalloc_roots);
2388 spin_unlock(&fs_info->delalloc_root_lock);
2391 spin_unlock(&root->delalloc_lock);
2395 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2396 struct btrfs_inode *inode)
2398 struct btrfs_fs_info *fs_info = root->fs_info;
2400 if (!list_empty(&inode->delalloc_inodes)) {
2401 list_del_init(&inode->delalloc_inodes);
2402 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2403 &inode->runtime_flags);
2404 root->nr_delalloc_inodes--;
2405 if (!root->nr_delalloc_inodes) {
2406 ASSERT(list_empty(&root->delalloc_inodes));
2407 spin_lock(&fs_info->delalloc_root_lock);
2408 BUG_ON(list_empty(&root->delalloc_root));
2409 list_del_init(&root->delalloc_root);
2410 spin_unlock(&fs_info->delalloc_root_lock);
2415 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2416 struct btrfs_inode *inode)
2418 spin_lock(&root->delalloc_lock);
2419 __btrfs_del_delalloc_inode(root, inode);
2420 spin_unlock(&root->delalloc_lock);
2424 * Properly track delayed allocation bytes in the inode and to maintain the
2425 * list of inodes that have pending delalloc work to be done.
2427 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2430 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2432 if ((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC))
2435 * set_bit and clear bit hooks normally require _irqsave/restore
2436 * but in this case, we are only testing for the DELALLOC
2437 * bit, which is only set or cleared with irqs on
2439 if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2440 struct btrfs_root *root = BTRFS_I(inode)->root;
2441 u64 len = state->end + 1 - state->start;
2442 u32 num_extents = count_max_extents(fs_info, len);
2443 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2445 spin_lock(&BTRFS_I(inode)->lock);
2446 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2447 spin_unlock(&BTRFS_I(inode)->lock);
2449 /* For sanity tests */
2450 if (btrfs_is_testing(fs_info))
2453 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2454 fs_info->delalloc_batch);
2455 spin_lock(&BTRFS_I(inode)->lock);
2456 BTRFS_I(inode)->delalloc_bytes += len;
2457 if (bits & EXTENT_DEFRAG)
2458 BTRFS_I(inode)->defrag_bytes += len;
2459 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2460 &BTRFS_I(inode)->runtime_flags))
2461 btrfs_add_delalloc_inodes(root, inode);
2462 spin_unlock(&BTRFS_I(inode)->lock);
2465 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2466 (bits & EXTENT_DELALLOC_NEW)) {
2467 spin_lock(&BTRFS_I(inode)->lock);
2468 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2470 spin_unlock(&BTRFS_I(inode)->lock);
2475 * Once a range is no longer delalloc this function ensures that proper
2476 * accounting happens.
2478 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2479 struct extent_state *state, u32 bits)
2481 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2482 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2483 u64 len = state->end + 1 - state->start;
2484 u32 num_extents = count_max_extents(fs_info, len);
2486 if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
2487 spin_lock(&inode->lock);
2488 inode->defrag_bytes -= len;
2489 spin_unlock(&inode->lock);
2493 * set_bit and clear bit hooks normally require _irqsave/restore
2494 * but in this case, we are only testing for the DELALLOC
2495 * bit, which is only set or cleared with irqs on
2497 if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2498 struct btrfs_root *root = inode->root;
2499 bool do_list = !btrfs_is_free_space_inode(inode);
2501 spin_lock(&inode->lock);
2502 btrfs_mod_outstanding_extents(inode, -num_extents);
2503 spin_unlock(&inode->lock);
2506 * We don't reserve metadata space for space cache inodes so we
2507 * don't need to call delalloc_release_metadata if there is an
2510 if (bits & EXTENT_CLEAR_META_RESV &&
2511 root != fs_info->tree_root)
2512 btrfs_delalloc_release_metadata(inode, len, false);
2514 /* For sanity tests. */
2515 if (btrfs_is_testing(fs_info))
2518 if (!btrfs_is_data_reloc_root(root) &&
2519 do_list && !(state->state & EXTENT_NORESERVE) &&
2520 (bits & EXTENT_CLEAR_DATA_RESV))
2521 btrfs_free_reserved_data_space_noquota(fs_info, len);
2523 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2524 fs_info->delalloc_batch);
2525 spin_lock(&inode->lock);
2526 inode->delalloc_bytes -= len;
2527 if (do_list && inode->delalloc_bytes == 0 &&
2528 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2529 &inode->runtime_flags))
2530 btrfs_del_delalloc_inode(root, inode);
2531 spin_unlock(&inode->lock);
2534 if ((state->state & EXTENT_DELALLOC_NEW) &&
2535 (bits & EXTENT_DELALLOC_NEW)) {
2536 spin_lock(&inode->lock);
2537 ASSERT(inode->new_delalloc_bytes >= len);
2538 inode->new_delalloc_bytes -= len;
2539 if (bits & EXTENT_ADD_INODE_BYTES)
2540 inode_add_bytes(&inode->vfs_inode, len);
2541 spin_unlock(&inode->lock);
2546 * in order to insert checksums into the metadata in large chunks,
2547 * we wait until bio submission time. All the pages in the bio are
2548 * checksummed and sums are attached onto the ordered extent record.
2550 * At IO completion time the cums attached on the ordered extent record
2551 * are inserted into the btree
2553 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2554 u64 dio_file_offset)
2556 return btrfs_csum_one_bio(BTRFS_I(inode), bio, (u64)-1, false);
2560 * Split an extent_map at [start, start + len]
2562 * This function is intended to be used only for extract_ordered_extent().
2564 static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
2567 struct extent_map_tree *em_tree = &inode->extent_tree;
2568 struct extent_map *em;
2569 struct extent_map *split_pre = NULL;
2570 struct extent_map *split_mid = NULL;
2571 struct extent_map *split_post = NULL;
2573 unsigned long flags;
2576 if (pre == 0 && post == 0)
2579 split_pre = alloc_extent_map();
2581 split_mid = alloc_extent_map();
2583 split_post = alloc_extent_map();
2584 if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
2589 ASSERT(pre + post < len);
2591 lock_extent(&inode->io_tree, start, start + len - 1, NULL);
2592 write_lock(&em_tree->lock);
2593 em = lookup_extent_mapping(em_tree, start, len);
2599 ASSERT(em->len == len);
2600 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2601 ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
2602 ASSERT(test_bit(EXTENT_FLAG_PINNED, &em->flags));
2603 ASSERT(!test_bit(EXTENT_FLAG_LOGGING, &em->flags));
2604 ASSERT(!list_empty(&em->list));
2607 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
2609 /* First, replace the em with a new extent_map starting from * em->start */
2610 split_pre->start = em->start;
2611 split_pre->len = (pre ? pre : em->len - post);
2612 split_pre->orig_start = split_pre->start;
2613 split_pre->block_start = em->block_start;
2614 split_pre->block_len = split_pre->len;
2615 split_pre->orig_block_len = split_pre->block_len;
2616 split_pre->ram_bytes = split_pre->len;
2617 split_pre->flags = flags;
2618 split_pre->compress_type = em->compress_type;
2619 split_pre->generation = em->generation;
2621 replace_extent_mapping(em_tree, em, split_pre, 1);
2624 * Now we only have an extent_map at:
2625 * [em->start, em->start + pre] if pre != 0
2626 * [em->start, em->start + em->len - post] if pre == 0
2630 /* Insert the middle extent_map */
2631 split_mid->start = em->start + pre;
2632 split_mid->len = em->len - pre - post;
2633 split_mid->orig_start = split_mid->start;
2634 split_mid->block_start = em->block_start + pre;
2635 split_mid->block_len = split_mid->len;
2636 split_mid->orig_block_len = split_mid->block_len;
2637 split_mid->ram_bytes = split_mid->len;
2638 split_mid->flags = flags;
2639 split_mid->compress_type = em->compress_type;
2640 split_mid->generation = em->generation;
2641 add_extent_mapping(em_tree, split_mid, 1);
2645 split_post->start = em->start + em->len - post;
2646 split_post->len = post;
2647 split_post->orig_start = split_post->start;
2648 split_post->block_start = em->block_start + em->len - post;
2649 split_post->block_len = split_post->len;
2650 split_post->orig_block_len = split_post->block_len;
2651 split_post->ram_bytes = split_post->len;
2652 split_post->flags = flags;
2653 split_post->compress_type = em->compress_type;
2654 split_post->generation = em->generation;
2655 add_extent_mapping(em_tree, split_post, 1);
2659 free_extent_map(em);
2660 /* Once for the tree */
2661 free_extent_map(em);
2664 write_unlock(&em_tree->lock);
2665 unlock_extent(&inode->io_tree, start, start + len - 1, NULL);
2667 free_extent_map(split_pre);
2668 free_extent_map(split_mid);
2669 free_extent_map(split_post);
2674 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2675 struct bio *bio, loff_t file_offset)
2677 struct btrfs_ordered_extent *ordered;
2678 u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2680 u64 len = bio->bi_iter.bi_size;
2681 u64 end = start + len;
2686 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2687 if (WARN_ON_ONCE(!ordered))
2688 return BLK_STS_IOERR;
2690 /* No need to split */
2691 if (ordered->disk_num_bytes == len)
2694 /* We cannot split once end_bio'd ordered extent */
2695 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2700 /* We cannot split a compressed ordered extent */
2701 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2706 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2707 /* bio must be in one ordered extent */
2708 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2713 /* Checksum list should be empty */
2714 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2719 file_len = ordered->num_bytes;
2720 pre = start - ordered->disk_bytenr;
2721 post = ordered_end - end;
2723 ret = btrfs_split_ordered_extent(ordered, pre, post);
2726 ret = split_zoned_em(inode, file_offset, file_len, pre, post);
2729 btrfs_put_ordered_extent(ordered);
2731 return errno_to_blk_status(ret);
2734 void btrfs_submit_data_write_bio(struct inode *inode, struct bio *bio, int mirror_num)
2736 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2737 struct btrfs_inode *bi = BTRFS_I(inode);
2740 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2741 ret = extract_ordered_extent(bi, bio,
2742 page_offset(bio_first_bvec_all(bio)->bv_page));
2744 btrfs_bio_end_io(btrfs_bio(bio), ret);
2750 * If we need to checksum, and the I/O is not issued by fsync and
2751 * friends, that is ->sync_writers != 0, defer the submission to a
2752 * workqueue to parallelize it.
2754 * Csum items for reloc roots have already been cloned at this point,
2755 * so they are handled as part of the no-checksum case.
2757 if (!(bi->flags & BTRFS_INODE_NODATASUM) &&
2758 !test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state) &&
2759 !btrfs_is_data_reloc_root(bi->root)) {
2760 if (!atomic_read(&bi->sync_writers) &&
2761 btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
2762 btrfs_submit_bio_start))
2765 ret = btrfs_csum_one_bio(bi, bio, (u64)-1, false);
2767 btrfs_bio_end_io(btrfs_bio(bio), ret);
2771 btrfs_submit_bio(fs_info, bio, mirror_num);
2774 void btrfs_submit_data_read_bio(struct inode *inode, struct bio *bio,
2775 int mirror_num, enum btrfs_compression_type compress_type)
2777 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2780 if (compress_type != BTRFS_COMPRESS_NONE) {
2782 * btrfs_submit_compressed_read will handle completing the bio
2783 * if there were any errors, so just return here.
2785 btrfs_submit_compressed_read(inode, bio, mirror_num);
2789 /* Save the original iter for read repair */
2790 btrfs_bio(bio)->iter = bio->bi_iter;
2793 * Lookup bio sums does extra checks around whether we need to csum or
2794 * not, which is why we ignore skip_sum here.
2796 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2798 btrfs_bio_end_io(btrfs_bio(bio), ret);
2802 btrfs_submit_bio(fs_info, bio, mirror_num);
2806 * given a list of ordered sums record them in the inode. This happens
2807 * at IO completion time based on sums calculated at bio submission time.
2809 static int add_pending_csums(struct btrfs_trans_handle *trans,
2810 struct list_head *list)
2812 struct btrfs_ordered_sum *sum;
2813 struct btrfs_root *csum_root = NULL;
2816 list_for_each_entry(sum, list, list) {
2817 trans->adding_csums = true;
2819 csum_root = btrfs_csum_root(trans->fs_info,
2821 ret = btrfs_csum_file_blocks(trans, csum_root, sum);
2822 trans->adding_csums = false;
2829 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2832 struct extent_state **cached_state)
2834 u64 search_start = start;
2835 const u64 end = start + len - 1;
2837 while (search_start < end) {
2838 const u64 search_len = end - search_start + 1;
2839 struct extent_map *em;
2843 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2847 if (em->block_start != EXTENT_MAP_HOLE)
2851 if (em->start < search_start)
2852 em_len -= search_start - em->start;
2853 if (em_len > search_len)
2854 em_len = search_len;
2856 ret = set_extent_bit(&inode->io_tree, search_start,
2857 search_start + em_len - 1,
2858 EXTENT_DELALLOC_NEW, cached_state,
2861 search_start = extent_map_end(em);
2862 free_extent_map(em);
2869 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2870 unsigned int extra_bits,
2871 struct extent_state **cached_state)
2873 WARN_ON(PAGE_ALIGNED(end));
2875 if (start >= i_size_read(&inode->vfs_inode) &&
2876 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2878 * There can't be any extents following eof in this case so just
2879 * set the delalloc new bit for the range directly.
2881 extra_bits |= EXTENT_DELALLOC_NEW;
2885 ret = btrfs_find_new_delalloc_bytes(inode, start,
2892 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2896 /* see btrfs_writepage_start_hook for details on why this is required */
2897 struct btrfs_writepage_fixup {
2899 struct inode *inode;
2900 struct btrfs_work work;
2903 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2905 struct btrfs_writepage_fixup *fixup;
2906 struct btrfs_ordered_extent *ordered;
2907 struct extent_state *cached_state = NULL;
2908 struct extent_changeset *data_reserved = NULL;
2910 struct btrfs_inode *inode;
2914 bool free_delalloc_space = true;
2916 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2918 inode = BTRFS_I(fixup->inode);
2919 page_start = page_offset(page);
2920 page_end = page_offset(page) + PAGE_SIZE - 1;
2923 * This is similar to page_mkwrite, we need to reserve the space before
2924 * we take the page lock.
2926 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2932 * Before we queued this fixup, we took a reference on the page.
2933 * page->mapping may go NULL, but it shouldn't be moved to a different
2936 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2938 * Unfortunately this is a little tricky, either
2940 * 1) We got here and our page had already been dealt with and
2941 * we reserved our space, thus ret == 0, so we need to just
2942 * drop our space reservation and bail. This can happen the
2943 * first time we come into the fixup worker, or could happen
2944 * while waiting for the ordered extent.
2945 * 2) Our page was already dealt with, but we happened to get an
2946 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2947 * this case we obviously don't have anything to release, but
2948 * because the page was already dealt with we don't want to
2949 * mark the page with an error, so make sure we're resetting
2950 * ret to 0. This is why we have this check _before_ the ret
2951 * check, because we do not want to have a surprise ENOSPC
2952 * when the page was already properly dealt with.
2955 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2956 btrfs_delalloc_release_space(inode, data_reserved,
2957 page_start, PAGE_SIZE,
2965 * We can't mess with the page state unless it is locked, so now that
2966 * it is locked bail if we failed to make our space reservation.
2971 lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2973 /* already ordered? We're done */
2974 if (PageOrdered(page))
2977 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2979 unlock_extent(&inode->io_tree, page_start, page_end,
2982 btrfs_start_ordered_extent(ordered, 1);
2983 btrfs_put_ordered_extent(ordered);
2987 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2993 * Everything went as planned, we're now the owner of a dirty page with
2994 * delayed allocation bits set and space reserved for our COW
2997 * The page was dirty when we started, nothing should have cleaned it.
2999 BUG_ON(!PageDirty(page));
3000 free_delalloc_space = false;
3002 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
3003 if (free_delalloc_space)
3004 btrfs_delalloc_release_space(inode, data_reserved, page_start,
3006 unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
3010 * We hit ENOSPC or other errors. Update the mapping and page
3011 * to reflect the errors and clean the page.
3013 mapping_set_error(page->mapping, ret);
3014 end_extent_writepage(page, ret, page_start, page_end);
3015 clear_page_dirty_for_io(page);
3018 btrfs_page_clear_checked(inode->root->fs_info, page, page_start, PAGE_SIZE);
3022 extent_changeset_free(data_reserved);
3024 * As a precaution, do a delayed iput in case it would be the last iput
3025 * that could need flushing space. Recursing back to fixup worker would
3028 btrfs_add_delayed_iput(&inode->vfs_inode);
3032 * There are a few paths in the higher layers of the kernel that directly
3033 * set the page dirty bit without asking the filesystem if it is a
3034 * good idea. This causes problems because we want to make sure COW
3035 * properly happens and the data=ordered rules are followed.
3037 * In our case any range that doesn't have the ORDERED bit set
3038 * hasn't been properly setup for IO. We kick off an async process
3039 * to fix it up. The async helper will wait for ordered extents, set
3040 * the delalloc bit and make it safe to write the page.
3042 int btrfs_writepage_cow_fixup(struct page *page)
3044 struct inode *inode = page->mapping->host;
3045 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3046 struct btrfs_writepage_fixup *fixup;
3048 /* This page has ordered extent covering it already */
3049 if (PageOrdered(page))
3053 * PageChecked is set below when we create a fixup worker for this page,
3054 * don't try to create another one if we're already PageChecked()
3056 * The extent_io writepage code will redirty the page if we send back
3059 if (PageChecked(page))
3062 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
3067 * We are already holding a reference to this inode from
3068 * write_cache_pages. We need to hold it because the space reservation
3069 * takes place outside of the page lock, and we can't trust
3070 * page->mapping outside of the page lock.
3073 btrfs_page_set_checked(fs_info, page, page_offset(page), PAGE_SIZE);
3075 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
3077 fixup->inode = inode;
3078 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
3083 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
3084 struct btrfs_inode *inode, u64 file_pos,
3085 struct btrfs_file_extent_item *stack_fi,
3086 const bool update_inode_bytes,
3087 u64 qgroup_reserved)
3089 struct btrfs_root *root = inode->root;
3090 const u64 sectorsize = root->fs_info->sectorsize;
3091 struct btrfs_path *path;
3092 struct extent_buffer *leaf;
3093 struct btrfs_key ins;
3094 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
3095 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
3096 u64 offset = btrfs_stack_file_extent_offset(stack_fi);
3097 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
3098 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
3099 struct btrfs_drop_extents_args drop_args = { 0 };
3102 path = btrfs_alloc_path();
3107 * we may be replacing one extent in the tree with another.
3108 * The new extent is pinned in the extent map, and we don't want
3109 * to drop it from the cache until it is completely in the btree.
3111 * So, tell btrfs_drop_extents to leave this extent in the cache.
3112 * the caller is expected to unpin it and allow it to be merged
3115 drop_args.path = path;
3116 drop_args.start = file_pos;
3117 drop_args.end = file_pos + num_bytes;
3118 drop_args.replace_extent = true;
3119 drop_args.extent_item_size = sizeof(*stack_fi);
3120 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
3124 if (!drop_args.extent_inserted) {
3125 ins.objectid = btrfs_ino(inode);
3126 ins.offset = file_pos;
3127 ins.type = BTRFS_EXTENT_DATA_KEY;
3129 ret = btrfs_insert_empty_item(trans, root, path, &ins,
3134 leaf = path->nodes[0];
3135 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
3136 write_extent_buffer(leaf, stack_fi,
3137 btrfs_item_ptr_offset(leaf, path->slots[0]),
3138 sizeof(struct btrfs_file_extent_item));
3140 btrfs_mark_buffer_dirty(leaf);
3141 btrfs_release_path(path);
3144 * If we dropped an inline extent here, we know the range where it is
3145 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
3146 * number of bytes only for that range containing the inline extent.
3147 * The remaining of the range will be processed when clearning the
3148 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
3150 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
3151 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
3153 inline_size = drop_args.bytes_found - inline_size;
3154 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
3155 drop_args.bytes_found -= inline_size;
3156 num_bytes -= sectorsize;
3159 if (update_inode_bytes)
3160 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
3162 ins.objectid = disk_bytenr;
3163 ins.offset = disk_num_bytes;
3164 ins.type = BTRFS_EXTENT_ITEM_KEY;
3166 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
3170 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
3172 qgroup_reserved, &ins);
3174 btrfs_free_path(path);
3179 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
3182 struct btrfs_block_group *cache;
3184 cache = btrfs_lookup_block_group(fs_info, start);
3187 spin_lock(&cache->lock);
3188 cache->delalloc_bytes -= len;
3189 spin_unlock(&cache->lock);
3191 btrfs_put_block_group(cache);
3194 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
3195 struct btrfs_ordered_extent *oe)
3197 struct btrfs_file_extent_item stack_fi;
3198 bool update_inode_bytes;
3199 u64 num_bytes = oe->num_bytes;
3200 u64 ram_bytes = oe->ram_bytes;
3202 memset(&stack_fi, 0, sizeof(stack_fi));
3203 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
3204 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
3205 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
3206 oe->disk_num_bytes);
3207 btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
3208 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags)) {
3209 num_bytes = oe->truncated_len;
3210 ram_bytes = num_bytes;
3212 btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
3213 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
3214 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3215 /* Encryption and other encoding is reserved and all 0 */
3218 * For delalloc, when completing an ordered extent we update the inode's
3219 * bytes when clearing the range in the inode's io tree, so pass false
3220 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3221 * except if the ordered extent was truncated.
3223 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3224 test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
3225 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3227 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
3228 oe->file_offset, &stack_fi,
3229 update_inode_bytes, oe->qgroup_rsv);
3233 * As ordered data IO finishes, this gets called so we can finish
3234 * an ordered extent if the range of bytes in the file it covers are
3237 int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3239 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
3240 struct btrfs_root *root = inode->root;
3241 struct btrfs_fs_info *fs_info = root->fs_info;
3242 struct btrfs_trans_handle *trans = NULL;
3243 struct extent_io_tree *io_tree = &inode->io_tree;
3244 struct extent_state *cached_state = NULL;
3246 int compress_type = 0;
3248 u64 logical_len = ordered_extent->num_bytes;
3249 bool freespace_inode;
3250 bool truncated = false;
3251 bool clear_reserved_extent = true;
3252 unsigned int clear_bits = EXTENT_DEFRAG;
3254 start = ordered_extent->file_offset;
3255 end = start + ordered_extent->num_bytes - 1;
3257 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3258 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3259 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3260 !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3261 clear_bits |= EXTENT_DELALLOC_NEW;
3263 freespace_inode = btrfs_is_free_space_inode(inode);
3264 if (!freespace_inode)
3265 btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
3267 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3272 /* A valid bdev implies a write on a sequential zone */
3273 if (ordered_extent->bdev) {
3274 btrfs_rewrite_logical_zoned(ordered_extent);
3275 btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3276 ordered_extent->disk_num_bytes);
3279 btrfs_free_io_failure_record(inode, start, end);
3281 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3283 logical_len = ordered_extent->truncated_len;
3284 /* Truncated the entire extent, don't bother adding */
3289 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3290 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3292 btrfs_inode_safe_disk_i_size_write(inode, 0);
3293 if (freespace_inode)
3294 trans = btrfs_join_transaction_spacecache(root);
3296 trans = btrfs_join_transaction(root);
3297 if (IS_ERR(trans)) {
3298 ret = PTR_ERR(trans);
3302 trans->block_rsv = &inode->block_rsv;
3303 ret = btrfs_update_inode_fallback(trans, root, inode);
3304 if (ret) /* -ENOMEM or corruption */
3305 btrfs_abort_transaction(trans, ret);
3309 clear_bits |= EXTENT_LOCKED;
3310 lock_extent(io_tree, start, end, &cached_state);
3312 if (freespace_inode)
3313 trans = btrfs_join_transaction_spacecache(root);
3315 trans = btrfs_join_transaction(root);
3316 if (IS_ERR(trans)) {
3317 ret = PTR_ERR(trans);
3322 trans->block_rsv = &inode->block_rsv;
3324 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3325 compress_type = ordered_extent->compress_type;
3326 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3327 BUG_ON(compress_type);
3328 ret = btrfs_mark_extent_written(trans, inode,
3329 ordered_extent->file_offset,
3330 ordered_extent->file_offset +
3332 btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3333 ordered_extent->disk_num_bytes);
3335 BUG_ON(root == fs_info->tree_root);
3336 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3338 clear_reserved_extent = false;
3339 btrfs_release_delalloc_bytes(fs_info,
3340 ordered_extent->disk_bytenr,
3341 ordered_extent->disk_num_bytes);
3344 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3345 ordered_extent->num_bytes, trans->transid);
3347 btrfs_abort_transaction(trans, ret);
3351 ret = add_pending_csums(trans, &ordered_extent->list);
3353 btrfs_abort_transaction(trans, ret);
3358 * If this is a new delalloc range, clear its new delalloc flag to
3359 * update the inode's number of bytes. This needs to be done first
3360 * before updating the inode item.
3362 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3363 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3364 clear_extent_bit(&inode->io_tree, start, end,
3365 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3368 btrfs_inode_safe_disk_i_size_write(inode, 0);
3369 ret = btrfs_update_inode_fallback(trans, root, inode);
3370 if (ret) { /* -ENOMEM or corruption */
3371 btrfs_abort_transaction(trans, ret);
3376 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3380 btrfs_end_transaction(trans);
3382 if (ret || truncated) {
3383 u64 unwritten_start = start;
3386 * If we failed to finish this ordered extent for any reason we
3387 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3388 * extent, and mark the inode with the error if it wasn't
3389 * already set. Any error during writeback would have already
3390 * set the mapping error, so we need to set it if we're the ones
3391 * marking this ordered extent as failed.
3393 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3394 &ordered_extent->flags))
3395 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3398 unwritten_start += logical_len;
3399 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3401 /* Drop extent maps for the part of the extent we didn't write. */
3402 btrfs_drop_extent_map_range(inode, unwritten_start, end, false);
3405 * If the ordered extent had an IOERR or something else went
3406 * wrong we need to return the space for this ordered extent
3407 * back to the allocator. We only free the extent in the
3408 * truncated case if we didn't write out the extent at all.
3410 * If we made it past insert_reserved_file_extent before we
3411 * errored out then we don't need to do this as the accounting
3412 * has already been done.
3414 if ((ret || !logical_len) &&
3415 clear_reserved_extent &&
3416 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3417 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3419 * Discard the range before returning it back to the
3422 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3423 btrfs_discard_extent(fs_info,
3424 ordered_extent->disk_bytenr,
3425 ordered_extent->disk_num_bytes,
3427 btrfs_free_reserved_extent(fs_info,
3428 ordered_extent->disk_bytenr,
3429 ordered_extent->disk_num_bytes, 1);
3434 * This needs to be done to make sure anybody waiting knows we are done
3435 * updating everything for this ordered extent.
3437 btrfs_remove_ordered_extent(inode, ordered_extent);
3440 btrfs_put_ordered_extent(ordered_extent);
3441 /* once for the tree */
3442 btrfs_put_ordered_extent(ordered_extent);
3447 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3448 struct page *page, u64 start,
3449 u64 end, bool uptodate)
3451 trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3453 btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start, uptodate);
3457 * Verify the checksum for a single sector without any extra action that depend
3458 * on the type of I/O.
3460 int btrfs_check_sector_csum(struct btrfs_fs_info *fs_info, struct page *page,
3461 u32 pgoff, u8 *csum, const u8 * const csum_expected)
3463 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3466 ASSERT(pgoff + fs_info->sectorsize <= PAGE_SIZE);
3468 shash->tfm = fs_info->csum_shash;
3470 kaddr = kmap_local_page(page) + pgoff;
3471 crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
3472 kunmap_local(kaddr);
3474 if (memcmp(csum, csum_expected, fs_info->csum_size))
3479 static u8 *btrfs_csum_ptr(const struct btrfs_fs_info *fs_info, u8 *csums, u64 offset)
3481 u64 offset_in_sectors = offset >> fs_info->sectorsize_bits;
3483 return csums + offset_in_sectors * fs_info->csum_size;
3487 * check_data_csum - verify checksum of one sector of uncompressed data
3489 * @bbio: btrfs_bio which contains the csum
3490 * @bio_offset: offset to the beginning of the bio (in bytes)
3491 * @page: page where is the data to be verified
3492 * @pgoff: offset inside the page
3494 * The length of such check is always one sector size.
3496 * When csum mismatch is detected, we will also report the error and fill the
3497 * corrupted range with zero. (Thus it needs the extra parameters)
3499 int btrfs_check_data_csum(struct inode *inode, struct btrfs_bio *bbio,
3500 u32 bio_offset, struct page *page, u32 pgoff)
3502 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3503 u32 len = fs_info->sectorsize;
3505 u8 csum[BTRFS_CSUM_SIZE];
3507 ASSERT(pgoff + len <= PAGE_SIZE);
3509 csum_expected = btrfs_csum_ptr(fs_info, bbio->csum, bio_offset);
3511 if (btrfs_check_sector_csum(fs_info, page, pgoff, csum, csum_expected))
3516 btrfs_print_data_csum_error(BTRFS_I(inode),
3517 bbio->file_offset + bio_offset,
3518 csum, csum_expected, bbio->mirror_num);
3520 btrfs_dev_stat_inc_and_print(bbio->device,
3521 BTRFS_DEV_STAT_CORRUPTION_ERRS);
3522 memzero_page(page, pgoff, len);
3527 * When reads are done, we need to check csums to verify the data is correct.
3528 * if there's a match, we allow the bio to finish. If not, the code in
3529 * extent_io.c will try to find good copies for us.
3531 * @bio_offset: offset to the beginning of the bio (in bytes)
3532 * @start: file offset of the range start
3533 * @end: file offset of the range end (inclusive)
3535 * Return a bitmap where bit set means a csum mismatch, and bit not set means
3538 unsigned int btrfs_verify_data_csum(struct btrfs_bio *bbio,
3539 u32 bio_offset, struct page *page,
3542 struct inode *inode = page->mapping->host;
3543 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3544 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3545 struct btrfs_root *root = BTRFS_I(inode)->root;
3546 const u32 sectorsize = root->fs_info->sectorsize;
3548 unsigned int result = 0;
3551 * This only happens for NODATASUM or compressed read.
3552 * Normally this should be covered by above check for compressed read
3553 * or the next check for NODATASUM. Just do a quicker exit here.
3555 if (bbio->csum == NULL)
3558 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3561 if (unlikely(test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state)))
3564 ASSERT(page_offset(page) <= start &&
3565 end <= page_offset(page) + PAGE_SIZE - 1);
3566 for (pg_off = offset_in_page(start);
3567 pg_off < offset_in_page(end);
3568 pg_off += sectorsize, bio_offset += sectorsize) {
3569 u64 file_offset = pg_off + page_offset(page);
3572 if (btrfs_is_data_reloc_root(root) &&
3573 test_range_bit(io_tree, file_offset,
3574 file_offset + sectorsize - 1,
3575 EXTENT_NODATASUM, 1, NULL)) {
3576 /* Skip the range without csum for data reloc inode */
3577 clear_extent_bits(io_tree, file_offset,
3578 file_offset + sectorsize - 1,
3582 ret = btrfs_check_data_csum(inode, bbio, bio_offset, page, pg_off);
3584 const int nr_bit = (pg_off - offset_in_page(start)) >>
3585 root->fs_info->sectorsize_bits;
3587 result |= (1U << nr_bit);
3594 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3596 * @inode: The inode we want to perform iput on
3598 * This function uses the generic vfs_inode::i_count to track whether we should
3599 * just decrement it (in case it's > 1) or if this is the last iput then link
3600 * the inode to the delayed iput machinery. Delayed iputs are processed at
3601 * transaction commit time/superblock commit/cleaner kthread.
3603 void btrfs_add_delayed_iput(struct inode *inode)
3605 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3606 struct btrfs_inode *binode = BTRFS_I(inode);
3608 if (atomic_add_unless(&inode->i_count, -1, 1))
3611 atomic_inc(&fs_info->nr_delayed_iputs);
3612 spin_lock(&fs_info->delayed_iput_lock);
3613 ASSERT(list_empty(&binode->delayed_iput));
3614 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3615 spin_unlock(&fs_info->delayed_iput_lock);
3616 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3617 wake_up_process(fs_info->cleaner_kthread);
3620 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3621 struct btrfs_inode *inode)
3623 list_del_init(&inode->delayed_iput);
3624 spin_unlock(&fs_info->delayed_iput_lock);
3625 iput(&inode->vfs_inode);
3626 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3627 wake_up(&fs_info->delayed_iputs_wait);
3628 spin_lock(&fs_info->delayed_iput_lock);
3631 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3632 struct btrfs_inode *inode)
3634 if (!list_empty(&inode->delayed_iput)) {
3635 spin_lock(&fs_info->delayed_iput_lock);
3636 if (!list_empty(&inode->delayed_iput))
3637 run_delayed_iput_locked(fs_info, inode);
3638 spin_unlock(&fs_info->delayed_iput_lock);
3642 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3645 spin_lock(&fs_info->delayed_iput_lock);
3646 while (!list_empty(&fs_info->delayed_iputs)) {
3647 struct btrfs_inode *inode;
3649 inode = list_first_entry(&fs_info->delayed_iputs,
3650 struct btrfs_inode, delayed_iput);
3651 run_delayed_iput_locked(fs_info, inode);
3652 cond_resched_lock(&fs_info->delayed_iput_lock);
3654 spin_unlock(&fs_info->delayed_iput_lock);
3658 * Wait for flushing all delayed iputs
3660 * @fs_info: the filesystem
3662 * This will wait on any delayed iputs that are currently running with KILLABLE
3663 * set. Once they are all done running we will return, unless we are killed in
3664 * which case we return EINTR. This helps in user operations like fallocate etc
3665 * that might get blocked on the iputs.
3667 * Return EINTR if we were killed, 0 if nothing's pending
3669 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3671 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3672 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3679 * This creates an orphan entry for the given inode in case something goes wrong
3680 * in the middle of an unlink.
3682 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3683 struct btrfs_inode *inode)
3687 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3688 if (ret && ret != -EEXIST) {
3689 btrfs_abort_transaction(trans, ret);
3697 * We have done the delete so we can go ahead and remove the orphan item for
3698 * this particular inode.
3700 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3701 struct btrfs_inode *inode)
3703 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3707 * this cleans up any orphans that may be left on the list from the last use
3710 int btrfs_orphan_cleanup(struct btrfs_root *root)
3712 struct btrfs_fs_info *fs_info = root->fs_info;
3713 struct btrfs_path *path;
3714 struct extent_buffer *leaf;
3715 struct btrfs_key key, found_key;
3716 struct btrfs_trans_handle *trans;
3717 struct inode *inode;
3718 u64 last_objectid = 0;
3719 int ret = 0, nr_unlink = 0;
3721 if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3724 path = btrfs_alloc_path();
3729 path->reada = READA_BACK;
3731 key.objectid = BTRFS_ORPHAN_OBJECTID;
3732 key.type = BTRFS_ORPHAN_ITEM_KEY;
3733 key.offset = (u64)-1;
3736 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3741 * if ret == 0 means we found what we were searching for, which
3742 * is weird, but possible, so only screw with path if we didn't
3743 * find the key and see if we have stuff that matches
3747 if (path->slots[0] == 0)
3752 /* pull out the item */
3753 leaf = path->nodes[0];
3754 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3756 /* make sure the item matches what we want */
3757 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3759 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3762 /* release the path since we're done with it */
3763 btrfs_release_path(path);
3766 * this is where we are basically btrfs_lookup, without the
3767 * crossing root thing. we store the inode number in the
3768 * offset of the orphan item.
3771 if (found_key.offset == last_objectid) {
3773 "Error removing orphan entry, stopping orphan cleanup");
3778 last_objectid = found_key.offset;
3780 found_key.objectid = found_key.offset;
3781 found_key.type = BTRFS_INODE_ITEM_KEY;
3782 found_key.offset = 0;
3783 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3784 ret = PTR_ERR_OR_ZERO(inode);
3785 if (ret && ret != -ENOENT)
3788 if (ret == -ENOENT && root == fs_info->tree_root) {
3789 struct btrfs_root *dead_root;
3790 int is_dead_root = 0;
3793 * This is an orphan in the tree root. Currently these
3794 * could come from 2 sources:
3795 * a) a root (snapshot/subvolume) deletion in progress
3796 * b) a free space cache inode
3797 * We need to distinguish those two, as the orphan item
3798 * for a root must not get deleted before the deletion
3799 * of the snapshot/subvolume's tree completes.
3801 * btrfs_find_orphan_roots() ran before us, which has
3802 * found all deleted roots and loaded them into
3803 * fs_info->fs_roots_radix. So here we can find if an
3804 * orphan item corresponds to a deleted root by looking
3805 * up the root from that radix tree.
3808 spin_lock(&fs_info->fs_roots_radix_lock);
3809 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3810 (unsigned long)found_key.objectid);
3811 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3813 spin_unlock(&fs_info->fs_roots_radix_lock);
3816 /* prevent this orphan from being found again */
3817 key.offset = found_key.objectid - 1;
3824 * If we have an inode with links, there are a couple of
3827 * 1. We were halfway through creating fsverity metadata for the
3828 * file. In that case, the orphan item represents incomplete
3829 * fsverity metadata which must be cleaned up with
3830 * btrfs_drop_verity_items and deleting the orphan item.
3832 * 2. Old kernels (before v3.12) used to create an
3833 * orphan item for truncate indicating that there were possibly
3834 * extent items past i_size that needed to be deleted. In v3.12,
3835 * truncate was changed to update i_size in sync with the extent
3836 * items, but the (useless) orphan item was still created. Since
3837 * v4.18, we don't create the orphan item for truncate at all.
3839 * So, this item could mean that we need to do a truncate, but
3840 * only if this filesystem was last used on a pre-v3.12 kernel
3841 * and was not cleanly unmounted. The odds of that are quite
3842 * slim, and it's a pain to do the truncate now, so just delete
3845 * It's also possible that this orphan item was supposed to be
3846 * deleted but wasn't. The inode number may have been reused,
3847 * but either way, we can delete the orphan item.
3849 if (ret == -ENOENT || inode->i_nlink) {
3851 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3856 trans = btrfs_start_transaction(root, 1);
3857 if (IS_ERR(trans)) {
3858 ret = PTR_ERR(trans);
3861 btrfs_debug(fs_info, "auto deleting %Lu",
3862 found_key.objectid);
3863 ret = btrfs_del_orphan_item(trans, root,
3864 found_key.objectid);
3865 btrfs_end_transaction(trans);
3873 /* this will do delete_inode and everything for us */
3876 /* release the path since we're done with it */
3877 btrfs_release_path(path);
3879 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3880 trans = btrfs_join_transaction(root);
3882 btrfs_end_transaction(trans);
3886 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3890 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3891 btrfs_free_path(path);
3896 * very simple check to peek ahead in the leaf looking for xattrs. If we
3897 * don't find any xattrs, we know there can't be any acls.
3899 * slot is the slot the inode is in, objectid is the objectid of the inode
3901 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3902 int slot, u64 objectid,
3903 int *first_xattr_slot)
3905 u32 nritems = btrfs_header_nritems(leaf);
3906 struct btrfs_key found_key;
3907 static u64 xattr_access = 0;
3908 static u64 xattr_default = 0;
3911 if (!xattr_access) {
3912 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3913 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3914 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3915 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3919 *first_xattr_slot = -1;
3920 while (slot < nritems) {
3921 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3923 /* we found a different objectid, there must not be acls */
3924 if (found_key.objectid != objectid)
3927 /* we found an xattr, assume we've got an acl */
3928 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3929 if (*first_xattr_slot == -1)
3930 *first_xattr_slot = slot;
3931 if (found_key.offset == xattr_access ||
3932 found_key.offset == xattr_default)
3937 * we found a key greater than an xattr key, there can't
3938 * be any acls later on
3940 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3947 * it goes inode, inode backrefs, xattrs, extents,
3948 * so if there are a ton of hard links to an inode there can
3949 * be a lot of backrefs. Don't waste time searching too hard,
3950 * this is just an optimization
3955 /* we hit the end of the leaf before we found an xattr or
3956 * something larger than an xattr. We have to assume the inode
3959 if (*first_xattr_slot == -1)
3960 *first_xattr_slot = slot;
3965 * read an inode from the btree into the in-memory inode
3967 static int btrfs_read_locked_inode(struct inode *inode,
3968 struct btrfs_path *in_path)
3970 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3971 struct btrfs_path *path = in_path;
3972 struct extent_buffer *leaf;
3973 struct btrfs_inode_item *inode_item;
3974 struct btrfs_root *root = BTRFS_I(inode)->root;
3975 struct btrfs_key location;
3980 bool filled = false;
3981 int first_xattr_slot;
3983 ret = btrfs_fill_inode(inode, &rdev);
3988 path = btrfs_alloc_path();
3993 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3995 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3997 if (path != in_path)
3998 btrfs_free_path(path);
4002 leaf = path->nodes[0];
4007 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4008 struct btrfs_inode_item);
4009 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
4010 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
4011 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
4012 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
4013 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
4014 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
4015 round_up(i_size_read(inode), fs_info->sectorsize));
4017 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
4018 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
4020 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
4021 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
4023 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
4024 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
4026 BTRFS_I(inode)->i_otime.tv_sec =
4027 btrfs_timespec_sec(leaf, &inode_item->otime);
4028 BTRFS_I(inode)->i_otime.tv_nsec =
4029 btrfs_timespec_nsec(leaf, &inode_item->otime);
4031 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
4032 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
4033 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
4035 inode_set_iversion_queried(inode,
4036 btrfs_inode_sequence(leaf, inode_item));
4037 inode->i_generation = BTRFS_I(inode)->generation;
4039 rdev = btrfs_inode_rdev(leaf, inode_item);
4041 BTRFS_I(inode)->index_cnt = (u64)-1;
4042 btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
4043 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
4047 * If we were modified in the current generation and evicted from memory
4048 * and then re-read we need to do a full sync since we don't have any
4049 * idea about which extents were modified before we were evicted from
4052 * This is required for both inode re-read from disk and delayed inode
4053 * in delayed_nodes_tree.
4055 if (BTRFS_I(inode)->last_trans == fs_info->generation)
4056 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4057 &BTRFS_I(inode)->runtime_flags);
4060 * We don't persist the id of the transaction where an unlink operation
4061 * against the inode was last made. So here we assume the inode might
4062 * have been evicted, and therefore the exact value of last_unlink_trans
4063 * lost, and set it to last_trans to avoid metadata inconsistencies
4064 * between the inode and its parent if the inode is fsync'ed and the log
4065 * replayed. For example, in the scenario:
4068 * ln mydir/foo mydir/bar
4071 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
4072 * xfs_io -c fsync mydir/foo
4074 * mount fs, triggers fsync log replay
4076 * We must make sure that when we fsync our inode foo we also log its
4077 * parent inode, otherwise after log replay the parent still has the
4078 * dentry with the "bar" name but our inode foo has a link count of 1
4079 * and doesn't have an inode ref with the name "bar" anymore.
4081 * Setting last_unlink_trans to last_trans is a pessimistic approach,
4082 * but it guarantees correctness at the expense of occasional full
4083 * transaction commits on fsync if our inode is a directory, or if our
4084 * inode is not a directory, logging its parent unnecessarily.
4086 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
4089 * Same logic as for last_unlink_trans. We don't persist the generation
4090 * of the last transaction where this inode was used for a reflink
4091 * operation, so after eviction and reloading the inode we must be
4092 * pessimistic and assume the last transaction that modified the inode.
4094 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
4097 if (inode->i_nlink != 1 ||
4098 path->slots[0] >= btrfs_header_nritems(leaf))
4101 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4102 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
4105 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4106 if (location.type == BTRFS_INODE_REF_KEY) {
4107 struct btrfs_inode_ref *ref;
4109 ref = (struct btrfs_inode_ref *)ptr;
4110 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
4111 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
4112 struct btrfs_inode_extref *extref;
4114 extref = (struct btrfs_inode_extref *)ptr;
4115 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
4120 * try to precache a NULL acl entry for files that don't have
4121 * any xattrs or acls
4123 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
4124 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
4125 if (first_xattr_slot != -1) {
4126 path->slots[0] = first_xattr_slot;
4127 ret = btrfs_load_inode_props(inode, path);
4130 "error loading props for ino %llu (root %llu): %d",
4131 btrfs_ino(BTRFS_I(inode)),
4132 root->root_key.objectid, ret);
4134 if (path != in_path)
4135 btrfs_free_path(path);
4138 cache_no_acl(inode);
4140 switch (inode->i_mode & S_IFMT) {
4142 inode->i_mapping->a_ops = &btrfs_aops;
4143 inode->i_fop = &btrfs_file_operations;
4144 inode->i_op = &btrfs_file_inode_operations;
4147 inode->i_fop = &btrfs_dir_file_operations;
4148 inode->i_op = &btrfs_dir_inode_operations;
4151 inode->i_op = &btrfs_symlink_inode_operations;
4152 inode_nohighmem(inode);
4153 inode->i_mapping->a_ops = &btrfs_aops;
4156 inode->i_op = &btrfs_special_inode_operations;
4157 init_special_inode(inode, inode->i_mode, rdev);
4161 btrfs_sync_inode_flags_to_i_flags(inode);
4166 * given a leaf and an inode, copy the inode fields into the leaf
4168 static void fill_inode_item(struct btrfs_trans_handle *trans,
4169 struct extent_buffer *leaf,
4170 struct btrfs_inode_item *item,
4171 struct inode *inode)
4173 struct btrfs_map_token token;
4176 btrfs_init_map_token(&token, leaf);
4178 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4179 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4180 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
4181 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4182 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4184 btrfs_set_token_timespec_sec(&token, &item->atime,
4185 inode->i_atime.tv_sec);
4186 btrfs_set_token_timespec_nsec(&token, &item->atime,
4187 inode->i_atime.tv_nsec);
4189 btrfs_set_token_timespec_sec(&token, &item->mtime,
4190 inode->i_mtime.tv_sec);
4191 btrfs_set_token_timespec_nsec(&token, &item->mtime,
4192 inode->i_mtime.tv_nsec);
4194 btrfs_set_token_timespec_sec(&token, &item->ctime,
4195 inode->i_ctime.tv_sec);
4196 btrfs_set_token_timespec_nsec(&token, &item->ctime,
4197 inode->i_ctime.tv_nsec);
4199 btrfs_set_token_timespec_sec(&token, &item->otime,
4200 BTRFS_I(inode)->i_otime.tv_sec);
4201 btrfs_set_token_timespec_nsec(&token, &item->otime,
4202 BTRFS_I(inode)->i_otime.tv_nsec);
4204 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
4205 btrfs_set_token_inode_generation(&token, item,
4206 BTRFS_I(inode)->generation);
4207 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4208 btrfs_set_token_inode_transid(&token, item, trans->transid);
4209 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4210 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4211 BTRFS_I(inode)->ro_flags);
4212 btrfs_set_token_inode_flags(&token, item, flags);
4213 btrfs_set_token_inode_block_group(&token, item, 0);
4217 * copy everything in the in-memory inode into the btree.
4219 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4220 struct btrfs_root *root,
4221 struct btrfs_inode *inode)
4223 struct btrfs_inode_item *inode_item;
4224 struct btrfs_path *path;
4225 struct extent_buffer *leaf;
4228 path = btrfs_alloc_path();
4232 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
4239 leaf = path->nodes[0];
4240 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4241 struct btrfs_inode_item);
4243 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4244 btrfs_mark_buffer_dirty(leaf);
4245 btrfs_set_inode_last_trans(trans, inode);
4248 btrfs_free_path(path);
4253 * copy everything in the in-memory inode into the btree.
4255 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4256 struct btrfs_root *root,
4257 struct btrfs_inode *inode)
4259 struct btrfs_fs_info *fs_info = root->fs_info;
4263 * If the inode is a free space inode, we can deadlock during commit
4264 * if we put it into the delayed code.
4266 * The data relocation inode should also be directly updated
4269 if (!btrfs_is_free_space_inode(inode)
4270 && !btrfs_is_data_reloc_root(root)
4271 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4272 btrfs_update_root_times(trans, root);
4274 ret = btrfs_delayed_update_inode(trans, root, inode);
4276 btrfs_set_inode_last_trans(trans, inode);
4280 return btrfs_update_inode_item(trans, root, inode);
4283 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4284 struct btrfs_root *root, struct btrfs_inode *inode)
4288 ret = btrfs_update_inode(trans, root, inode);
4290 return btrfs_update_inode_item(trans, root, inode);
4295 * unlink helper that gets used here in inode.c and in the tree logging
4296 * recovery code. It remove a link in a directory with a given name, and
4297 * also drops the back refs in the inode to the directory
4299 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4300 struct btrfs_inode *dir,
4301 struct btrfs_inode *inode,
4302 const struct fscrypt_str *name,
4303 struct btrfs_rename_ctx *rename_ctx)
4305 struct btrfs_root *root = dir->root;
4306 struct btrfs_fs_info *fs_info = root->fs_info;
4307 struct btrfs_path *path;
4309 struct btrfs_dir_item *di;
4311 u64 ino = btrfs_ino(inode);
4312 u64 dir_ino = btrfs_ino(dir);
4314 path = btrfs_alloc_path();
4320 di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4321 if (IS_ERR_OR_NULL(di)) {
4322 ret = di ? PTR_ERR(di) : -ENOENT;
4325 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4328 btrfs_release_path(path);
4331 * If we don't have dir index, we have to get it by looking up
4332 * the inode ref, since we get the inode ref, remove it directly,
4333 * it is unnecessary to do delayed deletion.
4335 * But if we have dir index, needn't search inode ref to get it.
4336 * Since the inode ref is close to the inode item, it is better
4337 * that we delay to delete it, and just do this deletion when
4338 * we update the inode item.
4340 if (inode->dir_index) {
4341 ret = btrfs_delayed_delete_inode_ref(inode);
4343 index = inode->dir_index;
4348 ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4351 "failed to delete reference to %.*s, inode %llu parent %llu",
4352 name->len, name->name, ino, dir_ino);
4353 btrfs_abort_transaction(trans, ret);
4358 rename_ctx->index = index;
4360 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4362 btrfs_abort_transaction(trans, ret);
4367 * If we are in a rename context, we don't need to update anything in the
4368 * log. That will be done later during the rename by btrfs_log_new_name().
4369 * Besides that, doing it here would only cause extra unnecessary btree
4370 * operations on the log tree, increasing latency for applications.
4373 btrfs_del_inode_ref_in_log(trans, root, name, inode, dir_ino);
4374 btrfs_del_dir_entries_in_log(trans, root, name, dir, index);
4378 * If we have a pending delayed iput we could end up with the final iput
4379 * being run in btrfs-cleaner context. If we have enough of these built
4380 * up we can end up burning a lot of time in btrfs-cleaner without any
4381 * way to throttle the unlinks. Since we're currently holding a ref on
4382 * the inode we can run the delayed iput here without any issues as the
4383 * final iput won't be done until after we drop the ref we're currently
4386 btrfs_run_delayed_iput(fs_info, inode);
4388 btrfs_free_path(path);
4392 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4393 inode_inc_iversion(&inode->vfs_inode);
4394 inode_inc_iversion(&dir->vfs_inode);
4395 inode->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4396 dir->vfs_inode.i_mtime = inode->vfs_inode.i_ctime;
4397 dir->vfs_inode.i_ctime = inode->vfs_inode.i_ctime;
4398 ret = btrfs_update_inode(trans, root, dir);
4403 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4404 struct btrfs_inode *dir, struct btrfs_inode *inode,
4405 const struct fscrypt_str *name)
4409 ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4411 drop_nlink(&inode->vfs_inode);
4412 ret = btrfs_update_inode(trans, inode->root, inode);
4418 * helper to start transaction for unlink and rmdir.
4420 * unlink and rmdir are special in btrfs, they do not always free space, so
4421 * if we cannot make our reservations the normal way try and see if there is
4422 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4423 * allow the unlink to occur.
4425 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4427 struct btrfs_root *root = BTRFS_I(dir)->root;
4430 * 1 for the possible orphan item
4431 * 1 for the dir item
4432 * 1 for the dir index
4433 * 1 for the inode ref
4435 * 1 for the parent inode
4437 return btrfs_start_transaction_fallback_global_rsv(root, 6);
4440 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4442 struct btrfs_trans_handle *trans;
4443 struct inode *inode = d_inode(dentry);
4445 struct fscrypt_name fname;
4447 ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4451 /* This needs to handle no-key deletions later on */
4453 trans = __unlink_start_trans(dir);
4454 if (IS_ERR(trans)) {
4455 ret = PTR_ERR(trans);
4459 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4462 ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4467 if (inode->i_nlink == 0) {
4468 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4474 btrfs_end_transaction(trans);
4475 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4477 fscrypt_free_filename(&fname);
4481 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4482 struct inode *dir, struct dentry *dentry)
4484 struct btrfs_root *root = BTRFS_I(dir)->root;
4485 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4486 struct btrfs_path *path;
4487 struct extent_buffer *leaf;
4488 struct btrfs_dir_item *di;
4489 struct btrfs_key key;
4493 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4494 struct fscrypt_name fname;
4496 ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4500 /* This needs to handle no-key deletions later on */
4502 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4503 objectid = inode->root->root_key.objectid;
4504 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4505 objectid = inode->location.objectid;
4508 fscrypt_free_filename(&fname);
4512 path = btrfs_alloc_path();
4518 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4519 &fname.disk_name, -1);
4520 if (IS_ERR_OR_NULL(di)) {
4521 ret = di ? PTR_ERR(di) : -ENOENT;
4525 leaf = path->nodes[0];
4526 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4527 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4528 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4530 btrfs_abort_transaction(trans, ret);
4533 btrfs_release_path(path);
4536 * This is a placeholder inode for a subvolume we didn't have a
4537 * reference to at the time of the snapshot creation. In the meantime
4538 * we could have renamed the real subvol link into our snapshot, so
4539 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4540 * Instead simply lookup the dir_index_item for this entry so we can
4541 * remove it. Otherwise we know we have a ref to the root and we can
4542 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4544 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4545 di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4546 if (IS_ERR_OR_NULL(di)) {
4551 btrfs_abort_transaction(trans, ret);
4555 leaf = path->nodes[0];
4556 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4558 btrfs_release_path(path);
4560 ret = btrfs_del_root_ref(trans, objectid,
4561 root->root_key.objectid, dir_ino,
4562 &index, &fname.disk_name);
4564 btrfs_abort_transaction(trans, ret);
4569 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4571 btrfs_abort_transaction(trans, ret);
4575 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - fname.disk_name.len * 2);
4576 inode_inc_iversion(dir);
4577 dir->i_mtime = current_time(dir);
4578 dir->i_ctime = dir->i_mtime;
4579 ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4581 btrfs_abort_transaction(trans, ret);
4583 btrfs_free_path(path);
4584 fscrypt_free_filename(&fname);
4589 * Helper to check if the subvolume references other subvolumes or if it's
4592 static noinline int may_destroy_subvol(struct btrfs_root *root)
4594 struct btrfs_fs_info *fs_info = root->fs_info;
4595 struct btrfs_path *path;
4596 struct btrfs_dir_item *di;
4597 struct btrfs_key key;
4598 struct fscrypt_str name = FSTR_INIT("default", 7);
4602 path = btrfs_alloc_path();
4606 /* Make sure this root isn't set as the default subvol */
4607 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4608 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4610 if (di && !IS_ERR(di)) {
4611 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4612 if (key.objectid == root->root_key.objectid) {
4615 "deleting default subvolume %llu is not allowed",
4619 btrfs_release_path(path);
4622 key.objectid = root->root_key.objectid;
4623 key.type = BTRFS_ROOT_REF_KEY;
4624 key.offset = (u64)-1;
4626 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4632 if (path->slots[0] > 0) {
4634 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4635 if (key.objectid == root->root_key.objectid &&
4636 key.type == BTRFS_ROOT_REF_KEY)
4640 btrfs_free_path(path);
4644 /* Delete all dentries for inodes belonging to the root */
4645 static void btrfs_prune_dentries(struct btrfs_root *root)
4647 struct btrfs_fs_info *fs_info = root->fs_info;
4648 struct rb_node *node;
4649 struct rb_node *prev;
4650 struct btrfs_inode *entry;
4651 struct inode *inode;
4654 if (!BTRFS_FS_ERROR(fs_info))
4655 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4657 spin_lock(&root->inode_lock);
4659 node = root->inode_tree.rb_node;
4663 entry = rb_entry(node, struct btrfs_inode, rb_node);
4665 if (objectid < btrfs_ino(entry))
4666 node = node->rb_left;
4667 else if (objectid > btrfs_ino(entry))
4668 node = node->rb_right;
4674 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4675 if (objectid <= btrfs_ino(entry)) {
4679 prev = rb_next(prev);
4683 entry = rb_entry(node, struct btrfs_inode, rb_node);
4684 objectid = btrfs_ino(entry) + 1;
4685 inode = igrab(&entry->vfs_inode);
4687 spin_unlock(&root->inode_lock);
4688 if (atomic_read(&inode->i_count) > 1)
4689 d_prune_aliases(inode);
4691 * btrfs_drop_inode will have it removed from the inode
4692 * cache when its usage count hits zero.
4696 spin_lock(&root->inode_lock);
4700 if (cond_resched_lock(&root->inode_lock))
4703 node = rb_next(node);
4705 spin_unlock(&root->inode_lock);
4708 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4710 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4711 struct btrfs_root *root = BTRFS_I(dir)->root;
4712 struct inode *inode = d_inode(dentry);
4713 struct btrfs_root *dest = BTRFS_I(inode)->root;
4714 struct btrfs_trans_handle *trans;
4715 struct btrfs_block_rsv block_rsv;
4720 * Don't allow to delete a subvolume with send in progress. This is
4721 * inside the inode lock so the error handling that has to drop the bit
4722 * again is not run concurrently.
4724 spin_lock(&dest->root_item_lock);
4725 if (dest->send_in_progress) {
4726 spin_unlock(&dest->root_item_lock);
4728 "attempt to delete subvolume %llu during send",
4729 dest->root_key.objectid);
4732 if (atomic_read(&dest->nr_swapfiles)) {
4733 spin_unlock(&dest->root_item_lock);
4735 "attempt to delete subvolume %llu with active swapfile",
4736 root->root_key.objectid);
4739 root_flags = btrfs_root_flags(&dest->root_item);
4740 btrfs_set_root_flags(&dest->root_item,
4741 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4742 spin_unlock(&dest->root_item_lock);
4744 down_write(&fs_info->subvol_sem);
4746 ret = may_destroy_subvol(dest);
4750 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4752 * One for dir inode,
4753 * two for dir entries,
4754 * two for root ref/backref.
4756 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4760 trans = btrfs_start_transaction(root, 0);
4761 if (IS_ERR(trans)) {
4762 ret = PTR_ERR(trans);
4765 trans->block_rsv = &block_rsv;
4766 trans->bytes_reserved = block_rsv.size;
4768 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4770 ret = btrfs_unlink_subvol(trans, dir, dentry);
4772 btrfs_abort_transaction(trans, ret);
4776 ret = btrfs_record_root_in_trans(trans, dest);
4778 btrfs_abort_transaction(trans, ret);
4782 memset(&dest->root_item.drop_progress, 0,
4783 sizeof(dest->root_item.drop_progress));
4784 btrfs_set_root_drop_level(&dest->root_item, 0);
4785 btrfs_set_root_refs(&dest->root_item, 0);
4787 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4788 ret = btrfs_insert_orphan_item(trans,
4790 dest->root_key.objectid);
4792 btrfs_abort_transaction(trans, ret);
4797 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4798 BTRFS_UUID_KEY_SUBVOL,
4799 dest->root_key.objectid);
4800 if (ret && ret != -ENOENT) {
4801 btrfs_abort_transaction(trans, ret);
4804 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4805 ret = btrfs_uuid_tree_remove(trans,
4806 dest->root_item.received_uuid,
4807 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4808 dest->root_key.objectid);
4809 if (ret && ret != -ENOENT) {
4810 btrfs_abort_transaction(trans, ret);
4815 free_anon_bdev(dest->anon_dev);
4818 trans->block_rsv = NULL;
4819 trans->bytes_reserved = 0;
4820 ret = btrfs_end_transaction(trans);
4821 inode->i_flags |= S_DEAD;
4823 btrfs_subvolume_release_metadata(root, &block_rsv);
4825 up_write(&fs_info->subvol_sem);
4827 spin_lock(&dest->root_item_lock);
4828 root_flags = btrfs_root_flags(&dest->root_item);
4829 btrfs_set_root_flags(&dest->root_item,
4830 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4831 spin_unlock(&dest->root_item_lock);
4833 d_invalidate(dentry);
4834 btrfs_prune_dentries(dest);
4835 ASSERT(dest->send_in_progress == 0);
4841 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4843 struct inode *inode = d_inode(dentry);
4844 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
4846 struct btrfs_trans_handle *trans;
4847 u64 last_unlink_trans;
4848 struct fscrypt_name fname;
4850 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4852 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
4853 if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4855 "extent tree v2 doesn't support snapshot deletion yet");
4858 return btrfs_delete_subvolume(dir, dentry);
4861 err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4865 /* This needs to handle no-key deletions later on */
4867 trans = __unlink_start_trans(dir);
4868 if (IS_ERR(trans)) {
4869 err = PTR_ERR(trans);
4873 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4874 err = btrfs_unlink_subvol(trans, dir, dentry);
4878 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4882 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4884 /* now the directory is empty */
4885 err = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4888 btrfs_i_size_write(BTRFS_I(inode), 0);
4890 * Propagate the last_unlink_trans value of the deleted dir to
4891 * its parent directory. This is to prevent an unrecoverable
4892 * log tree in the case we do something like this:
4894 * 2) create snapshot under dir foo
4895 * 3) delete the snapshot
4898 * 6) fsync foo or some file inside foo
4900 if (last_unlink_trans >= trans->transid)
4901 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4904 btrfs_end_transaction(trans);
4906 btrfs_btree_balance_dirty(fs_info);
4907 fscrypt_free_filename(&fname);
4913 * btrfs_truncate_block - read, zero a chunk and write a block
4914 * @inode - inode that we're zeroing
4915 * @from - the offset to start zeroing
4916 * @len - the length to zero, 0 to zero the entire range respective to the
4918 * @front - zero up to the offset instead of from the offset on
4920 * This will find the block for the "from" offset and cow the block and zero the
4921 * part we want to zero. This is used with truncate and hole punching.
4923 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4926 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4927 struct address_space *mapping = inode->vfs_inode.i_mapping;
4928 struct extent_io_tree *io_tree = &inode->io_tree;
4929 struct btrfs_ordered_extent *ordered;
4930 struct extent_state *cached_state = NULL;
4931 struct extent_changeset *data_reserved = NULL;
4932 bool only_release_metadata = false;
4933 u32 blocksize = fs_info->sectorsize;
4934 pgoff_t index = from >> PAGE_SHIFT;
4935 unsigned offset = from & (blocksize - 1);
4937 gfp_t mask = btrfs_alloc_write_mask(mapping);
4938 size_t write_bytes = blocksize;
4943 if (IS_ALIGNED(offset, blocksize) &&
4944 (!len || IS_ALIGNED(len, blocksize)))
4947 block_start = round_down(from, blocksize);
4948 block_end = block_start + blocksize - 1;
4950 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4953 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
4954 /* For nocow case, no need to reserve data space */
4955 only_release_metadata = true;
4960 ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
4962 if (!only_release_metadata)
4963 btrfs_free_reserved_data_space(inode, data_reserved,
4964 block_start, blocksize);
4968 page = find_or_create_page(mapping, index, mask);
4970 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4972 btrfs_delalloc_release_extents(inode, blocksize);
4976 ret = set_page_extent_mapped(page);
4980 if (!PageUptodate(page)) {
4981 ret = btrfs_read_folio(NULL, page_folio(page));
4983 if (page->mapping != mapping) {
4988 if (!PageUptodate(page)) {
4993 wait_on_page_writeback(page);
4995 lock_extent(io_tree, block_start, block_end, &cached_state);
4997 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4999 unlock_extent(io_tree, block_start, block_end, &cached_state);
5002 btrfs_start_ordered_extent(ordered, 1);
5003 btrfs_put_ordered_extent(ordered);
5007 clear_extent_bit(&inode->io_tree, block_start, block_end,
5008 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5011 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5014 unlock_extent(io_tree, block_start, block_end, &cached_state);
5018 if (offset != blocksize) {
5020 len = blocksize - offset;
5022 memzero_page(page, (block_start - page_offset(page)),
5025 memzero_page(page, (block_start - page_offset(page)) + offset,
5028 btrfs_page_clear_checked(fs_info, page, block_start,
5029 block_end + 1 - block_start);
5030 btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
5031 unlock_extent(io_tree, block_start, block_end, &cached_state);
5033 if (only_release_metadata)
5034 set_extent_bit(&inode->io_tree, block_start, block_end,
5035 EXTENT_NORESERVE, NULL, GFP_NOFS);
5039 if (only_release_metadata)
5040 btrfs_delalloc_release_metadata(inode, blocksize, true);
5042 btrfs_delalloc_release_space(inode, data_reserved,
5043 block_start, blocksize, true);
5045 btrfs_delalloc_release_extents(inode, blocksize);
5049 if (only_release_metadata)
5050 btrfs_check_nocow_unlock(inode);
5051 extent_changeset_free(data_reserved);
5055 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
5056 u64 offset, u64 len)
5058 struct btrfs_fs_info *fs_info = root->fs_info;
5059 struct btrfs_trans_handle *trans;
5060 struct btrfs_drop_extents_args drop_args = { 0 };
5064 * If NO_HOLES is enabled, we don't need to do anything.
5065 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5066 * or btrfs_update_inode() will be called, which guarantee that the next
5067 * fsync will know this inode was changed and needs to be logged.
5069 if (btrfs_fs_incompat(fs_info, NO_HOLES))
5073 * 1 - for the one we're dropping
5074 * 1 - for the one we're adding
5075 * 1 - for updating the inode.
5077 trans = btrfs_start_transaction(root, 3);
5079 return PTR_ERR(trans);
5081 drop_args.start = offset;
5082 drop_args.end = offset + len;
5083 drop_args.drop_cache = true;
5085 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5087 btrfs_abort_transaction(trans, ret);
5088 btrfs_end_transaction(trans);
5092 ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
5094 btrfs_abort_transaction(trans, ret);
5096 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5097 btrfs_update_inode(trans, root, inode);
5099 btrfs_end_transaction(trans);
5104 * This function puts in dummy file extents for the area we're creating a hole
5105 * for. So if we are truncating this file to a larger size we need to insert
5106 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5107 * the range between oldsize and size
5109 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5111 struct btrfs_root *root = inode->root;
5112 struct btrfs_fs_info *fs_info = root->fs_info;
5113 struct extent_io_tree *io_tree = &inode->io_tree;
5114 struct extent_map *em = NULL;
5115 struct extent_state *cached_state = NULL;
5116 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5117 u64 block_end = ALIGN(size, fs_info->sectorsize);
5124 * If our size started in the middle of a block we need to zero out the
5125 * rest of the block before we expand the i_size, otherwise we could
5126 * expose stale data.
5128 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5132 if (size <= hole_start)
5135 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5137 cur_offset = hole_start;
5139 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5140 block_end - cur_offset);
5146 last_byte = min(extent_map_end(em), block_end);
5147 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5148 hole_size = last_byte - cur_offset;
5150 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5151 struct extent_map *hole_em;
5153 err = maybe_insert_hole(root, inode, cur_offset,
5158 err = btrfs_inode_set_file_extent_range(inode,
5159 cur_offset, hole_size);
5163 hole_em = alloc_extent_map();
5165 btrfs_drop_extent_map_range(inode, cur_offset,
5166 cur_offset + hole_size - 1,
5168 btrfs_set_inode_full_sync(inode);
5171 hole_em->start = cur_offset;
5172 hole_em->len = hole_size;
5173 hole_em->orig_start = cur_offset;
5175 hole_em->block_start = EXTENT_MAP_HOLE;
5176 hole_em->block_len = 0;
5177 hole_em->orig_block_len = 0;
5178 hole_em->ram_bytes = hole_size;
5179 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5180 hole_em->generation = fs_info->generation;
5182 err = btrfs_replace_extent_map_range(inode, hole_em, true);
5183 free_extent_map(hole_em);
5185 err = btrfs_inode_set_file_extent_range(inode,
5186 cur_offset, hole_size);
5191 free_extent_map(em);
5193 cur_offset = last_byte;
5194 if (cur_offset >= block_end)
5197 free_extent_map(em);
5198 unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5202 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5204 struct btrfs_root *root = BTRFS_I(inode)->root;
5205 struct btrfs_trans_handle *trans;
5206 loff_t oldsize = i_size_read(inode);
5207 loff_t newsize = attr->ia_size;
5208 int mask = attr->ia_valid;
5212 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5213 * special case where we need to update the times despite not having
5214 * these flags set. For all other operations the VFS set these flags
5215 * explicitly if it wants a timestamp update.
5217 if (newsize != oldsize) {
5218 inode_inc_iversion(inode);
5219 if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5220 inode->i_mtime = current_time(inode);
5221 inode->i_ctime = inode->i_mtime;
5225 if (newsize > oldsize) {
5227 * Don't do an expanding truncate while snapshotting is ongoing.
5228 * This is to ensure the snapshot captures a fully consistent
5229 * state of this file - if the snapshot captures this expanding
5230 * truncation, it must capture all writes that happened before
5233 btrfs_drew_write_lock(&root->snapshot_lock);
5234 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5236 btrfs_drew_write_unlock(&root->snapshot_lock);
5240 trans = btrfs_start_transaction(root, 1);
5241 if (IS_ERR(trans)) {
5242 btrfs_drew_write_unlock(&root->snapshot_lock);
5243 return PTR_ERR(trans);
5246 i_size_write(inode, newsize);
5247 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5248 pagecache_isize_extended(inode, oldsize, newsize);
5249 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5250 btrfs_drew_write_unlock(&root->snapshot_lock);
5251 btrfs_end_transaction(trans);
5253 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5255 if (btrfs_is_zoned(fs_info)) {
5256 ret = btrfs_wait_ordered_range(inode,
5257 ALIGN(newsize, fs_info->sectorsize),
5264 * We're truncating a file that used to have good data down to
5265 * zero. Make sure any new writes to the file get on disk
5269 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5270 &BTRFS_I(inode)->runtime_flags);
5272 truncate_setsize(inode, newsize);
5274 inode_dio_wait(inode);
5276 ret = btrfs_truncate(inode, newsize == oldsize);
5277 if (ret && inode->i_nlink) {
5281 * Truncate failed, so fix up the in-memory size. We
5282 * adjusted disk_i_size down as we removed extents, so
5283 * wait for disk_i_size to be stable and then update the
5284 * in-memory size to match.
5286 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5289 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5296 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5299 struct inode *inode = d_inode(dentry);
5300 struct btrfs_root *root = BTRFS_I(inode)->root;
5303 if (btrfs_root_readonly(root))
5306 err = setattr_prepare(mnt_userns, dentry, attr);
5310 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5311 err = btrfs_setsize(inode, attr);
5316 if (attr->ia_valid) {
5317 setattr_copy(mnt_userns, inode, attr);
5318 inode_inc_iversion(inode);
5319 err = btrfs_dirty_inode(inode);
5321 if (!err && attr->ia_valid & ATTR_MODE)
5322 err = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5329 * While truncating the inode pages during eviction, we get the VFS
5330 * calling btrfs_invalidate_folio() against each folio of the inode. This
5331 * is slow because the calls to btrfs_invalidate_folio() result in a
5332 * huge amount of calls to lock_extent() and clear_extent_bit(),
5333 * which keep merging and splitting extent_state structures over and over,
5334 * wasting lots of time.
5336 * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5337 * skip all those expensive operations on a per folio basis and do only
5338 * the ordered io finishing, while we release here the extent_map and
5339 * extent_state structures, without the excessive merging and splitting.
5341 static void evict_inode_truncate_pages(struct inode *inode)
5343 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5344 struct rb_node *node;
5346 ASSERT(inode->i_state & I_FREEING);
5347 truncate_inode_pages_final(&inode->i_data);
5349 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5352 * Keep looping until we have no more ranges in the io tree.
5353 * We can have ongoing bios started by readahead that have
5354 * their endio callback (extent_io.c:end_bio_extent_readpage)
5355 * still in progress (unlocked the pages in the bio but did not yet
5356 * unlocked the ranges in the io tree). Therefore this means some
5357 * ranges can still be locked and eviction started because before
5358 * submitting those bios, which are executed by a separate task (work
5359 * queue kthread), inode references (inode->i_count) were not taken
5360 * (which would be dropped in the end io callback of each bio).
5361 * Therefore here we effectively end up waiting for those bios and
5362 * anyone else holding locked ranges without having bumped the inode's
5363 * reference count - if we don't do it, when they access the inode's
5364 * io_tree to unlock a range it may be too late, leading to an
5365 * use-after-free issue.
5367 spin_lock(&io_tree->lock);
5368 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5369 struct extent_state *state;
5370 struct extent_state *cached_state = NULL;
5373 unsigned state_flags;
5375 node = rb_first(&io_tree->state);
5376 state = rb_entry(node, struct extent_state, rb_node);
5377 start = state->start;
5379 state_flags = state->state;
5380 spin_unlock(&io_tree->lock);
5382 lock_extent(io_tree, start, end, &cached_state);
5385 * If still has DELALLOC flag, the extent didn't reach disk,
5386 * and its reserved space won't be freed by delayed_ref.
5387 * So we need to free its reserved space here.
5388 * (Refer to comment in btrfs_invalidate_folio, case 2)
5390 * Note, end is the bytenr of last byte, so we need + 1 here.
5392 if (state_flags & EXTENT_DELALLOC)
5393 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5396 clear_extent_bit(io_tree, start, end,
5397 EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5401 spin_lock(&io_tree->lock);
5403 spin_unlock(&io_tree->lock);
5406 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5407 struct btrfs_block_rsv *rsv)
5409 struct btrfs_fs_info *fs_info = root->fs_info;
5410 struct btrfs_trans_handle *trans;
5411 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5415 * Eviction should be taking place at some place safe because of our
5416 * delayed iputs. However the normal flushing code will run delayed
5417 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5419 * We reserve the delayed_refs_extra here again because we can't use
5420 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5421 * above. We reserve our extra bit here because we generate a ton of
5422 * delayed refs activity by truncating.
5424 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5425 * if we fail to make this reservation we can re-try without the
5426 * delayed_refs_extra so we can make some forward progress.
5428 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5429 BTRFS_RESERVE_FLUSH_EVICT);
5431 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5432 BTRFS_RESERVE_FLUSH_EVICT);
5435 "could not allocate space for delete; will truncate on mount");
5436 return ERR_PTR(-ENOSPC);
5438 delayed_refs_extra = 0;
5441 trans = btrfs_join_transaction(root);
5445 if (delayed_refs_extra) {
5446 trans->block_rsv = &fs_info->trans_block_rsv;
5447 trans->bytes_reserved = delayed_refs_extra;
5448 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5449 delayed_refs_extra, 1);
5454 void btrfs_evict_inode(struct inode *inode)
5456 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5457 struct btrfs_trans_handle *trans;
5458 struct btrfs_root *root = BTRFS_I(inode)->root;
5459 struct btrfs_block_rsv *rsv;
5462 trace_btrfs_inode_evict(inode);
5465 fsverity_cleanup_inode(inode);
5470 evict_inode_truncate_pages(inode);
5472 if (inode->i_nlink &&
5473 ((btrfs_root_refs(&root->root_item) != 0 &&
5474 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5475 btrfs_is_free_space_inode(BTRFS_I(inode))))
5478 if (is_bad_inode(inode))
5481 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5483 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5486 if (inode->i_nlink > 0) {
5487 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5488 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5493 * This makes sure the inode item in tree is uptodate and the space for
5494 * the inode update is released.
5496 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5501 * This drops any pending insert or delete operations we have for this
5502 * inode. We could have a delayed dir index deletion queued up, but
5503 * we're removing the inode completely so that'll be taken care of in
5506 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5508 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5511 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5512 rsv->failfast = true;
5514 btrfs_i_size_write(BTRFS_I(inode), 0);
5517 struct btrfs_truncate_control control = {
5518 .inode = BTRFS_I(inode),
5519 .ino = btrfs_ino(BTRFS_I(inode)),
5524 trans = evict_refill_and_join(root, rsv);
5528 trans->block_rsv = rsv;
5530 ret = btrfs_truncate_inode_items(trans, root, &control);
5531 trans->block_rsv = &fs_info->trans_block_rsv;
5532 btrfs_end_transaction(trans);
5533 btrfs_btree_balance_dirty(fs_info);
5534 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5541 * Errors here aren't a big deal, it just means we leave orphan items in
5542 * the tree. They will be cleaned up on the next mount. If the inode
5543 * number gets reused, cleanup deletes the orphan item without doing
5544 * anything, and unlink reuses the existing orphan item.
5546 * If it turns out that we are dropping too many of these, we might want
5547 * to add a mechanism for retrying these after a commit.
5549 trans = evict_refill_and_join(root, rsv);
5550 if (!IS_ERR(trans)) {
5551 trans->block_rsv = rsv;
5552 btrfs_orphan_del(trans, BTRFS_I(inode));
5553 trans->block_rsv = &fs_info->trans_block_rsv;
5554 btrfs_end_transaction(trans);
5558 btrfs_free_block_rsv(fs_info, rsv);
5561 * If we didn't successfully delete, the orphan item will still be in
5562 * the tree and we'll retry on the next mount. Again, we might also want
5563 * to retry these periodically in the future.
5565 btrfs_remove_delayed_node(BTRFS_I(inode));
5566 fsverity_cleanup_inode(inode);
5571 * Return the key found in the dir entry in the location pointer, fill @type
5572 * with BTRFS_FT_*, and return 0.
5574 * If no dir entries were found, returns -ENOENT.
5575 * If found a corrupted location in dir entry, returns -EUCLEAN.
5577 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5578 struct btrfs_key *location, u8 *type)
5580 struct btrfs_dir_item *di;
5581 struct btrfs_path *path;
5582 struct btrfs_root *root = BTRFS_I(dir)->root;
5584 struct fscrypt_name fname;
5586 path = btrfs_alloc_path();
5590 ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
5594 /* This needs to handle no-key deletions later on */
5596 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5597 &fname.disk_name, 0);
5598 if (IS_ERR_OR_NULL(di)) {
5599 ret = di ? PTR_ERR(di) : -ENOENT;
5603 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5604 if (location->type != BTRFS_INODE_ITEM_KEY &&
5605 location->type != BTRFS_ROOT_ITEM_KEY) {
5607 btrfs_warn(root->fs_info,
5608 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5609 __func__, fname.disk_name.name, btrfs_ino(BTRFS_I(dir)),
5610 location->objectid, location->type, location->offset);
5613 *type = btrfs_dir_ftype(path->nodes[0], di);
5615 fscrypt_free_filename(&fname);
5616 btrfs_free_path(path);
5621 * when we hit a tree root in a directory, the btrfs part of the inode
5622 * needs to be changed to reflect the root directory of the tree root. This
5623 * is kind of like crossing a mount point.
5625 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5627 struct dentry *dentry,
5628 struct btrfs_key *location,
5629 struct btrfs_root **sub_root)
5631 struct btrfs_path *path;
5632 struct btrfs_root *new_root;
5633 struct btrfs_root_ref *ref;
5634 struct extent_buffer *leaf;
5635 struct btrfs_key key;
5638 struct fscrypt_name fname;
5640 ret = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
5644 path = btrfs_alloc_path();
5651 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5652 key.type = BTRFS_ROOT_REF_KEY;
5653 key.offset = location->objectid;
5655 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5662 leaf = path->nodes[0];
5663 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5664 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5665 btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5668 ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5669 (unsigned long)(ref + 1), fname.disk_name.len);
5673 btrfs_release_path(path);
5675 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5676 if (IS_ERR(new_root)) {
5677 err = PTR_ERR(new_root);
5681 *sub_root = new_root;
5682 location->objectid = btrfs_root_dirid(&new_root->root_item);
5683 location->type = BTRFS_INODE_ITEM_KEY;
5684 location->offset = 0;
5687 btrfs_free_path(path);
5688 fscrypt_free_filename(&fname);
5692 static void inode_tree_add(struct inode *inode)
5694 struct btrfs_root *root = BTRFS_I(inode)->root;
5695 struct btrfs_inode *entry;
5697 struct rb_node *parent;
5698 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5699 u64 ino = btrfs_ino(BTRFS_I(inode));
5701 if (inode_unhashed(inode))
5704 spin_lock(&root->inode_lock);
5705 p = &root->inode_tree.rb_node;
5708 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5710 if (ino < btrfs_ino(entry))
5711 p = &parent->rb_left;
5712 else if (ino > btrfs_ino(entry))
5713 p = &parent->rb_right;
5715 WARN_ON(!(entry->vfs_inode.i_state &
5716 (I_WILL_FREE | I_FREEING)));
5717 rb_replace_node(parent, new, &root->inode_tree);
5718 RB_CLEAR_NODE(parent);
5719 spin_unlock(&root->inode_lock);
5723 rb_link_node(new, parent, p);
5724 rb_insert_color(new, &root->inode_tree);
5725 spin_unlock(&root->inode_lock);
5728 static void inode_tree_del(struct btrfs_inode *inode)
5730 struct btrfs_root *root = inode->root;
5733 spin_lock(&root->inode_lock);
5734 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5735 rb_erase(&inode->rb_node, &root->inode_tree);
5736 RB_CLEAR_NODE(&inode->rb_node);
5737 empty = RB_EMPTY_ROOT(&root->inode_tree);
5739 spin_unlock(&root->inode_lock);
5741 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5742 spin_lock(&root->inode_lock);
5743 empty = RB_EMPTY_ROOT(&root->inode_tree);
5744 spin_unlock(&root->inode_lock);
5746 btrfs_add_dead_root(root);
5751 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5753 struct btrfs_iget_args *args = p;
5755 inode->i_ino = args->ino;
5756 BTRFS_I(inode)->location.objectid = args->ino;
5757 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5758 BTRFS_I(inode)->location.offset = 0;
5759 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5760 BUG_ON(args->root && !BTRFS_I(inode)->root);
5762 if (args->root && args->root == args->root->fs_info->tree_root &&
5763 args->ino != BTRFS_BTREE_INODE_OBJECTID)
5764 set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5765 &BTRFS_I(inode)->runtime_flags);
5769 static int btrfs_find_actor(struct inode *inode, void *opaque)
5771 struct btrfs_iget_args *args = opaque;
5773 return args->ino == BTRFS_I(inode)->location.objectid &&
5774 args->root == BTRFS_I(inode)->root;
5777 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5778 struct btrfs_root *root)
5780 struct inode *inode;
5781 struct btrfs_iget_args args;
5782 unsigned long hashval = btrfs_inode_hash(ino, root);
5787 inode = iget5_locked(s, hashval, btrfs_find_actor,
5788 btrfs_init_locked_inode,
5794 * Get an inode object given its inode number and corresponding root.
5795 * Path can be preallocated to prevent recursing back to iget through
5796 * allocator. NULL is also valid but may require an additional allocation
5799 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5800 struct btrfs_root *root, struct btrfs_path *path)
5802 struct inode *inode;
5804 inode = btrfs_iget_locked(s, ino, root);
5806 return ERR_PTR(-ENOMEM);
5808 if (inode->i_state & I_NEW) {
5811 ret = btrfs_read_locked_inode(inode, path);
5813 inode_tree_add(inode);
5814 unlock_new_inode(inode);
5818 * ret > 0 can come from btrfs_search_slot called by
5819 * btrfs_read_locked_inode, this means the inode item
5824 inode = ERR_PTR(ret);
5831 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5833 return btrfs_iget_path(s, ino, root, NULL);
5836 static struct inode *new_simple_dir(struct super_block *s,
5837 struct btrfs_key *key,
5838 struct btrfs_root *root)
5840 struct inode *inode = new_inode(s);
5843 return ERR_PTR(-ENOMEM);
5845 BTRFS_I(inode)->root = btrfs_grab_root(root);
5846 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5847 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5849 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5851 * We only need lookup, the rest is read-only and there's no inode
5852 * associated with the dentry
5854 inode->i_op = &simple_dir_inode_operations;
5855 inode->i_opflags &= ~IOP_XATTR;
5856 inode->i_fop = &simple_dir_operations;
5857 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5858 inode->i_mtime = current_time(inode);
5859 inode->i_atime = inode->i_mtime;
5860 inode->i_ctime = inode->i_mtime;
5861 BTRFS_I(inode)->i_otime = inode->i_mtime;
5866 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5867 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5868 static_assert(BTRFS_FT_DIR == FT_DIR);
5869 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5870 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5871 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5872 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5873 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5875 static inline u8 btrfs_inode_type(struct inode *inode)
5877 return fs_umode_to_ftype(inode->i_mode);
5880 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5882 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5883 struct inode *inode;
5884 struct btrfs_root *root = BTRFS_I(dir)->root;
5885 struct btrfs_root *sub_root = root;
5886 struct btrfs_key location;
5890 if (dentry->d_name.len > BTRFS_NAME_LEN)
5891 return ERR_PTR(-ENAMETOOLONG);
5893 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5895 return ERR_PTR(ret);
5897 if (location.type == BTRFS_INODE_ITEM_KEY) {
5898 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5902 /* Do extra check against inode mode with di_type */
5903 if (btrfs_inode_type(inode) != di_type) {
5905 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5906 inode->i_mode, btrfs_inode_type(inode),
5909 return ERR_PTR(-EUCLEAN);
5914 ret = fixup_tree_root_location(fs_info, dir, dentry,
5915 &location, &sub_root);
5918 inode = ERR_PTR(ret);
5920 inode = new_simple_dir(dir->i_sb, &location, root);
5922 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5923 btrfs_put_root(sub_root);
5928 down_read(&fs_info->cleanup_work_sem);
5929 if (!sb_rdonly(inode->i_sb))
5930 ret = btrfs_orphan_cleanup(sub_root);
5931 up_read(&fs_info->cleanup_work_sem);
5934 inode = ERR_PTR(ret);
5941 static int btrfs_dentry_delete(const struct dentry *dentry)
5943 struct btrfs_root *root;
5944 struct inode *inode = d_inode(dentry);
5946 if (!inode && !IS_ROOT(dentry))
5947 inode = d_inode(dentry->d_parent);
5950 root = BTRFS_I(inode)->root;
5951 if (btrfs_root_refs(&root->root_item) == 0)
5954 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5960 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5963 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5965 if (inode == ERR_PTR(-ENOENT))
5967 return d_splice_alias(inode, dentry);
5971 * All this infrastructure exists because dir_emit can fault, and we are holding
5972 * the tree lock when doing readdir. For now just allocate a buffer and copy
5973 * our information into that, and then dir_emit from the buffer. This is
5974 * similar to what NFS does, only we don't keep the buffer around in pagecache
5975 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5976 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5979 static int btrfs_opendir(struct inode *inode, struct file *file)
5981 struct btrfs_file_private *private;
5983 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5986 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5987 if (!private->filldir_buf) {
5991 file->private_data = private;
6002 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6005 struct dir_entry *entry = addr;
6006 char *name = (char *)(entry + 1);
6008 ctx->pos = get_unaligned(&entry->offset);
6009 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6010 get_unaligned(&entry->ino),
6011 get_unaligned(&entry->type)))
6013 addr += sizeof(struct dir_entry) +
6014 get_unaligned(&entry->name_len);
6020 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6022 struct inode *inode = file_inode(file);
6023 struct btrfs_root *root = BTRFS_I(inode)->root;
6024 struct btrfs_file_private *private = file->private_data;
6025 struct btrfs_dir_item *di;
6026 struct btrfs_key key;
6027 struct btrfs_key found_key;
6028 struct btrfs_path *path;
6030 struct list_head ins_list;
6031 struct list_head del_list;
6038 struct btrfs_key location;
6040 if (!dir_emit_dots(file, ctx))
6043 path = btrfs_alloc_path();
6047 addr = private->filldir_buf;
6048 path->reada = READA_FORWARD;
6050 INIT_LIST_HEAD(&ins_list);
6051 INIT_LIST_HEAD(&del_list);
6052 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6055 key.type = BTRFS_DIR_INDEX_KEY;
6056 key.offset = ctx->pos;
6057 key.objectid = btrfs_ino(BTRFS_I(inode));
6059 btrfs_for_each_slot(root, &key, &found_key, path, ret) {
6060 struct dir_entry *entry;
6061 struct extent_buffer *leaf = path->nodes[0];
6064 if (found_key.objectid != key.objectid)
6066 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6068 if (found_key.offset < ctx->pos)
6070 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6072 di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
6073 name_len = btrfs_dir_name_len(leaf, di);
6074 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6076 btrfs_release_path(path);
6077 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6080 addr = private->filldir_buf;
6086 ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
6088 name_ptr = (char *)(entry + 1);
6089 read_extent_buffer(leaf, name_ptr,
6090 (unsigned long)(di + 1), name_len);
6091 put_unaligned(name_len, &entry->name_len);
6092 put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
6093 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6094 put_unaligned(location.objectid, &entry->ino);
6095 put_unaligned(found_key.offset, &entry->offset);
6097 addr += sizeof(struct dir_entry) + name_len;
6098 total_len += sizeof(struct dir_entry) + name_len;
6100 /* Catch error encountered during iteration */
6104 btrfs_release_path(path);
6106 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6110 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6115 * Stop new entries from being returned after we return the last
6118 * New directory entries are assigned a strictly increasing
6119 * offset. This means that new entries created during readdir
6120 * are *guaranteed* to be seen in the future by that readdir.
6121 * This has broken buggy programs which operate on names as
6122 * they're returned by readdir. Until we re-use freed offsets
6123 * we have this hack to stop new entries from being returned
6124 * under the assumption that they'll never reach this huge
6127 * This is being careful not to overflow 32bit loff_t unless the
6128 * last entry requires it because doing so has broken 32bit apps
6131 if (ctx->pos >= INT_MAX)
6132 ctx->pos = LLONG_MAX;
6139 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6140 btrfs_free_path(path);
6145 * This is somewhat expensive, updating the tree every time the
6146 * inode changes. But, it is most likely to find the inode in cache.
6147 * FIXME, needs more benchmarking...there are no reasons other than performance
6148 * to keep or drop this code.
6150 static int btrfs_dirty_inode(struct inode *inode)
6152 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6153 struct btrfs_root *root = BTRFS_I(inode)->root;
6154 struct btrfs_trans_handle *trans;
6157 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6160 trans = btrfs_join_transaction(root);
6162 return PTR_ERR(trans);
6164 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6165 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6166 /* whoops, lets try again with the full transaction */
6167 btrfs_end_transaction(trans);
6168 trans = btrfs_start_transaction(root, 1);
6170 return PTR_ERR(trans);
6172 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6174 btrfs_end_transaction(trans);
6175 if (BTRFS_I(inode)->delayed_node)
6176 btrfs_balance_delayed_items(fs_info);
6182 * This is a copy of file_update_time. We need this so we can return error on
6183 * ENOSPC for updating the inode in the case of file write and mmap writes.
6185 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6188 struct btrfs_root *root = BTRFS_I(inode)->root;
6189 bool dirty = flags & ~S_VERSION;
6191 if (btrfs_root_readonly(root))
6194 if (flags & S_VERSION)
6195 dirty |= inode_maybe_inc_iversion(inode, dirty);
6196 if (flags & S_CTIME)
6197 inode->i_ctime = *now;
6198 if (flags & S_MTIME)
6199 inode->i_mtime = *now;
6200 if (flags & S_ATIME)
6201 inode->i_atime = *now;
6202 return dirty ? btrfs_dirty_inode(inode) : 0;
6206 * find the highest existing sequence number in a directory
6207 * and then set the in-memory index_cnt variable to reflect
6208 * free sequence numbers
6210 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6212 struct btrfs_root *root = inode->root;
6213 struct btrfs_key key, found_key;
6214 struct btrfs_path *path;
6215 struct extent_buffer *leaf;
6218 key.objectid = btrfs_ino(inode);
6219 key.type = BTRFS_DIR_INDEX_KEY;
6220 key.offset = (u64)-1;
6222 path = btrfs_alloc_path();
6226 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6229 /* FIXME: we should be able to handle this */
6234 if (path->slots[0] == 0) {
6235 inode->index_cnt = BTRFS_DIR_START_INDEX;
6241 leaf = path->nodes[0];
6242 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6244 if (found_key.objectid != btrfs_ino(inode) ||
6245 found_key.type != BTRFS_DIR_INDEX_KEY) {
6246 inode->index_cnt = BTRFS_DIR_START_INDEX;
6250 inode->index_cnt = found_key.offset + 1;
6252 btrfs_free_path(path);
6257 * helper to find a free sequence number in a given directory. This current
6258 * code is very simple, later versions will do smarter things in the btree
6260 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6264 if (dir->index_cnt == (u64)-1) {
6265 ret = btrfs_inode_delayed_dir_index_count(dir);
6267 ret = btrfs_set_inode_index_count(dir);
6273 *index = dir->index_cnt;
6279 static int btrfs_insert_inode_locked(struct inode *inode)
6281 struct btrfs_iget_args args;
6283 args.ino = BTRFS_I(inode)->location.objectid;
6284 args.root = BTRFS_I(inode)->root;
6286 return insert_inode_locked4(inode,
6287 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6288 btrfs_find_actor, &args);
6291 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6292 unsigned int *trans_num_items)
6294 struct inode *dir = args->dir;
6295 struct inode *inode = args->inode;
6298 if (!args->orphan) {
6299 ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6305 ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6307 fscrypt_free_filename(&args->fname);
6311 /* 1 to add inode item */
6312 *trans_num_items = 1;
6313 /* 1 to add compression property */
6314 if (BTRFS_I(dir)->prop_compress)
6315 (*trans_num_items)++;
6316 /* 1 to add default ACL xattr */
6317 if (args->default_acl)
6318 (*trans_num_items)++;
6319 /* 1 to add access ACL xattr */
6321 (*trans_num_items)++;
6322 #ifdef CONFIG_SECURITY
6323 /* 1 to add LSM xattr */
6324 if (dir->i_security)
6325 (*trans_num_items)++;
6328 /* 1 to add orphan item */
6329 (*trans_num_items)++;
6333 * 1 to add dir index
6334 * 1 to update parent inode item
6336 * No need for 1 unit for the inode ref item because it is
6337 * inserted in a batch together with the inode item at
6338 * btrfs_create_new_inode().
6340 *trans_num_items += 3;
6345 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6347 posix_acl_release(args->acl);
6348 posix_acl_release(args->default_acl);
6349 fscrypt_free_filename(&args->fname);
6353 * Inherit flags from the parent inode.
6355 * Currently only the compression flags and the cow flags are inherited.
6357 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6361 flags = BTRFS_I(dir)->flags;
6363 if (flags & BTRFS_INODE_NOCOMPRESS) {
6364 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6365 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6366 } else if (flags & BTRFS_INODE_COMPRESS) {
6367 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6368 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6371 if (flags & BTRFS_INODE_NODATACOW) {
6372 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6373 if (S_ISREG(inode->i_mode))
6374 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6377 btrfs_sync_inode_flags_to_i_flags(inode);
6380 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6381 struct btrfs_new_inode_args *args)
6383 struct inode *dir = args->dir;
6384 struct inode *inode = args->inode;
6385 const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6386 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6387 struct btrfs_root *root;
6388 struct btrfs_inode_item *inode_item;
6389 struct btrfs_key *location;
6390 struct btrfs_path *path;
6392 struct btrfs_inode_ref *ref;
6393 struct btrfs_key key[2];
6395 struct btrfs_item_batch batch;
6399 path = btrfs_alloc_path();
6404 BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6405 root = BTRFS_I(inode)->root;
6407 ret = btrfs_get_free_objectid(root, &objectid);
6410 inode->i_ino = objectid;
6414 * O_TMPFILE, set link count to 0, so that after this point, we
6415 * fill in an inode item with the correct link count.
6417 set_nlink(inode, 0);
6419 trace_btrfs_inode_request(dir);
6421 ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6425 /* index_cnt is ignored for everything but a dir. */
6426 BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6427 BTRFS_I(inode)->generation = trans->transid;
6428 inode->i_generation = BTRFS_I(inode)->generation;
6431 * Subvolumes don't inherit flags from their parent directory.
6432 * Originally this was probably by accident, but we probably can't
6433 * change it now without compatibility issues.
6436 btrfs_inherit_iflags(inode, dir);
6438 if (S_ISREG(inode->i_mode)) {
6439 if (btrfs_test_opt(fs_info, NODATASUM))
6440 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6441 if (btrfs_test_opt(fs_info, NODATACOW))
6442 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6443 BTRFS_INODE_NODATASUM;
6446 location = &BTRFS_I(inode)->location;
6447 location->objectid = objectid;
6448 location->offset = 0;
6449 location->type = BTRFS_INODE_ITEM_KEY;
6451 ret = btrfs_insert_inode_locked(inode);
6454 BTRFS_I(dir)->index_cnt--;
6459 * We could have gotten an inode number from somebody who was fsynced
6460 * and then removed in this same transaction, so let's just set full
6461 * sync since it will be a full sync anyway and this will blow away the
6462 * old info in the log.
6464 btrfs_set_inode_full_sync(BTRFS_I(inode));
6466 key[0].objectid = objectid;
6467 key[0].type = BTRFS_INODE_ITEM_KEY;
6470 sizes[0] = sizeof(struct btrfs_inode_item);
6472 if (!args->orphan) {
6474 * Start new inodes with an inode_ref. This is slightly more
6475 * efficient for small numbers of hard links since they will
6476 * be packed into one item. Extended refs will kick in if we
6477 * add more hard links than can fit in the ref item.
6479 key[1].objectid = objectid;
6480 key[1].type = BTRFS_INODE_REF_KEY;
6482 key[1].offset = objectid;
6483 sizes[1] = 2 + sizeof(*ref);
6485 key[1].offset = btrfs_ino(BTRFS_I(dir));
6486 sizes[1] = name->len + sizeof(*ref);
6490 batch.keys = &key[0];
6491 batch.data_sizes = &sizes[0];
6492 batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6493 batch.nr = args->orphan ? 1 : 2;
6494 ret = btrfs_insert_empty_items(trans, root, path, &batch);
6496 btrfs_abort_transaction(trans, ret);
6500 inode->i_mtime = current_time(inode);
6501 inode->i_atime = inode->i_mtime;
6502 inode->i_ctime = inode->i_mtime;
6503 BTRFS_I(inode)->i_otime = inode->i_mtime;
6506 * We're going to fill the inode item now, so at this point the inode
6507 * must be fully initialized.
6510 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6511 struct btrfs_inode_item);
6512 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6513 sizeof(*inode_item));
6514 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6516 if (!args->orphan) {
6517 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6518 struct btrfs_inode_ref);
6519 ptr = (unsigned long)(ref + 1);
6521 btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6522 btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6523 write_extent_buffer(path->nodes[0], "..", ptr, 2);
6525 btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6527 btrfs_set_inode_ref_index(path->nodes[0], ref,
6528 BTRFS_I(inode)->dir_index);
6529 write_extent_buffer(path->nodes[0], name->name, ptr,
6534 btrfs_mark_buffer_dirty(path->nodes[0]);
6536 * We don't need the path anymore, plus inheriting properties, adding
6537 * ACLs, security xattrs, orphan item or adding the link, will result in
6538 * allocating yet another path. So just free our path.
6540 btrfs_free_path(path);
6544 struct inode *parent;
6547 * Subvolumes inherit properties from their parent subvolume,
6548 * not the directory they were created in.
6550 parent = btrfs_iget(fs_info->sb, BTRFS_FIRST_FREE_OBJECTID,
6551 BTRFS_I(dir)->root);
6552 if (IS_ERR(parent)) {
6553 ret = PTR_ERR(parent);
6555 ret = btrfs_inode_inherit_props(trans, inode, parent);
6559 ret = btrfs_inode_inherit_props(trans, inode, dir);
6563 "error inheriting props for ino %llu (root %llu): %d",
6564 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid,
6569 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6572 if (!args->subvol) {
6573 ret = btrfs_init_inode_security(trans, args);
6575 btrfs_abort_transaction(trans, ret);
6580 inode_tree_add(inode);
6582 trace_btrfs_inode_new(inode);
6583 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6585 btrfs_update_root_times(trans, root);
6588 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6590 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6591 0, BTRFS_I(inode)->dir_index);
6594 btrfs_abort_transaction(trans, ret);
6602 * discard_new_inode() calls iput(), but the caller owns the reference
6606 discard_new_inode(inode);
6608 btrfs_free_path(path);
6613 * utility function to add 'inode' into 'parent_inode' with
6614 * a give name and a given sequence number.
6615 * if 'add_backref' is true, also insert a backref from the
6616 * inode to the parent directory.
6618 int btrfs_add_link(struct btrfs_trans_handle *trans,
6619 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6620 const struct fscrypt_str *name, int add_backref, u64 index)
6623 struct btrfs_key key;
6624 struct btrfs_root *root = parent_inode->root;
6625 u64 ino = btrfs_ino(inode);
6626 u64 parent_ino = btrfs_ino(parent_inode);
6628 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6629 memcpy(&key, &inode->root->root_key, sizeof(key));
6632 key.type = BTRFS_INODE_ITEM_KEY;
6636 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6637 ret = btrfs_add_root_ref(trans, key.objectid,
6638 root->root_key.objectid, parent_ino,
6640 } else if (add_backref) {
6641 ret = btrfs_insert_inode_ref(trans, root, name,
6642 ino, parent_ino, index);
6645 /* Nothing to clean up yet */
6649 ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6650 btrfs_inode_type(&inode->vfs_inode), index);
6651 if (ret == -EEXIST || ret == -EOVERFLOW)
6654 btrfs_abort_transaction(trans, ret);
6658 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6660 inode_inc_iversion(&parent_inode->vfs_inode);
6662 * If we are replaying a log tree, we do not want to update the mtime
6663 * and ctime of the parent directory with the current time, since the
6664 * log replay procedure is responsible for setting them to their correct
6665 * values (the ones it had when the fsync was done).
6667 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6668 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6670 parent_inode->vfs_inode.i_mtime = now;
6671 parent_inode->vfs_inode.i_ctime = now;
6673 ret = btrfs_update_inode(trans, root, parent_inode);
6675 btrfs_abort_transaction(trans, ret);
6679 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6682 err = btrfs_del_root_ref(trans, key.objectid,
6683 root->root_key.objectid, parent_ino,
6684 &local_index, name);
6686 btrfs_abort_transaction(trans, err);
6687 } else if (add_backref) {
6691 err = btrfs_del_inode_ref(trans, root, name, ino, parent_ino,
6694 btrfs_abort_transaction(trans, err);
6697 /* Return the original error code */
6701 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6702 struct inode *inode)
6704 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6705 struct btrfs_root *root = BTRFS_I(dir)->root;
6706 struct btrfs_new_inode_args new_inode_args = {
6711 unsigned int trans_num_items;
6712 struct btrfs_trans_handle *trans;
6715 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6719 trans = btrfs_start_transaction(root, trans_num_items);
6720 if (IS_ERR(trans)) {
6721 err = PTR_ERR(trans);
6722 goto out_new_inode_args;
6725 err = btrfs_create_new_inode(trans, &new_inode_args);
6727 d_instantiate_new(dentry, inode);
6729 btrfs_end_transaction(trans);
6730 btrfs_btree_balance_dirty(fs_info);
6732 btrfs_new_inode_args_destroy(&new_inode_args);
6739 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6740 struct dentry *dentry, umode_t mode, dev_t rdev)
6742 struct inode *inode;
6744 inode = new_inode(dir->i_sb);
6747 inode_init_owner(mnt_userns, inode, dir, mode);
6748 inode->i_op = &btrfs_special_inode_operations;
6749 init_special_inode(inode, inode->i_mode, rdev);
6750 return btrfs_create_common(dir, dentry, inode);
6753 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6754 struct dentry *dentry, umode_t mode, bool excl)
6756 struct inode *inode;
6758 inode = new_inode(dir->i_sb);
6761 inode_init_owner(mnt_userns, inode, dir, mode);
6762 inode->i_fop = &btrfs_file_operations;
6763 inode->i_op = &btrfs_file_inode_operations;
6764 inode->i_mapping->a_ops = &btrfs_aops;
6765 return btrfs_create_common(dir, dentry, inode);
6768 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6769 struct dentry *dentry)
6771 struct btrfs_trans_handle *trans = NULL;
6772 struct btrfs_root *root = BTRFS_I(dir)->root;
6773 struct inode *inode = d_inode(old_dentry);
6774 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6775 struct fscrypt_name fname;
6780 /* do not allow sys_link's with other subvols of the same device */
6781 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6784 if (inode->i_nlink >= BTRFS_LINK_MAX)
6787 err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
6791 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6796 * 2 items for inode and inode ref
6797 * 2 items for dir items
6798 * 1 item for parent inode
6799 * 1 item for orphan item deletion if O_TMPFILE
6801 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6802 if (IS_ERR(trans)) {
6803 err = PTR_ERR(trans);
6808 /* There are several dir indexes for this inode, clear the cache. */
6809 BTRFS_I(inode)->dir_index = 0ULL;
6811 inode_inc_iversion(inode);
6812 inode->i_ctime = current_time(inode);
6814 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6816 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6817 &fname.disk_name, 1, index);
6822 struct dentry *parent = dentry->d_parent;
6824 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6827 if (inode->i_nlink == 1) {
6829 * If new hard link count is 1, it's a file created
6830 * with open(2) O_TMPFILE flag.
6832 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6836 d_instantiate(dentry, inode);
6837 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6841 fscrypt_free_filename(&fname);
6843 btrfs_end_transaction(trans);
6845 inode_dec_link_count(inode);
6848 btrfs_btree_balance_dirty(fs_info);
6852 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6853 struct dentry *dentry, umode_t mode)
6855 struct inode *inode;
6857 inode = new_inode(dir->i_sb);
6860 inode_init_owner(mnt_userns, inode, dir, S_IFDIR | mode);
6861 inode->i_op = &btrfs_dir_inode_operations;
6862 inode->i_fop = &btrfs_dir_file_operations;
6863 return btrfs_create_common(dir, dentry, inode);
6866 static noinline int uncompress_inline(struct btrfs_path *path,
6868 struct btrfs_file_extent_item *item)
6871 struct extent_buffer *leaf = path->nodes[0];
6874 unsigned long inline_size;
6878 compress_type = btrfs_file_extent_compression(leaf, item);
6879 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6880 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6881 tmp = kmalloc(inline_size, GFP_NOFS);
6884 ptr = btrfs_file_extent_inline_start(item);
6886 read_extent_buffer(leaf, tmp, ptr, inline_size);
6888 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6889 ret = btrfs_decompress(compress_type, tmp, page, 0, inline_size, max_size);
6892 * decompression code contains a memset to fill in any space between the end
6893 * of the uncompressed data and the end of max_size in case the decompressed
6894 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6895 * the end of an inline extent and the beginning of the next block, so we
6896 * cover that region here.
6899 if (max_size < PAGE_SIZE)
6900 memzero_page(page, max_size, PAGE_SIZE - max_size);
6905 static int read_inline_extent(struct btrfs_inode *inode, struct btrfs_path *path,
6908 struct btrfs_file_extent_item *fi;
6912 if (!page || PageUptodate(page))
6915 ASSERT(page_offset(page) == 0);
6917 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6918 struct btrfs_file_extent_item);
6919 if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
6920 return uncompress_inline(path, page, fi);
6922 copy_size = min_t(u64, PAGE_SIZE,
6923 btrfs_file_extent_ram_bytes(path->nodes[0], fi));
6924 kaddr = kmap_local_page(page);
6925 read_extent_buffer(path->nodes[0], kaddr,
6926 btrfs_file_extent_inline_start(fi), copy_size);
6927 kunmap_local(kaddr);
6928 if (copy_size < PAGE_SIZE)
6929 memzero_page(page, copy_size, PAGE_SIZE - copy_size);
6934 * Lookup the first extent overlapping a range in a file.
6936 * @inode: file to search in
6937 * @page: page to read extent data into if the extent is inline
6938 * @pg_offset: offset into @page to copy to
6939 * @start: file offset
6940 * @len: length of range starting at @start
6942 * Return the first &struct extent_map which overlaps the given range, reading
6943 * it from the B-tree and caching it if necessary. Note that there may be more
6944 * extents which overlap the given range after the returned extent_map.
6946 * If @page is not NULL and the extent is inline, this also reads the extent
6947 * data directly into the page and marks the extent up to date in the io_tree.
6949 * Return: ERR_PTR on error, non-NULL extent_map on success.
6951 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6952 struct page *page, size_t pg_offset,
6955 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6957 u64 extent_start = 0;
6959 u64 objectid = btrfs_ino(inode);
6960 int extent_type = -1;
6961 struct btrfs_path *path = NULL;
6962 struct btrfs_root *root = inode->root;
6963 struct btrfs_file_extent_item *item;
6964 struct extent_buffer *leaf;
6965 struct btrfs_key found_key;
6966 struct extent_map *em = NULL;
6967 struct extent_map_tree *em_tree = &inode->extent_tree;
6969 read_lock(&em_tree->lock);
6970 em = lookup_extent_mapping(em_tree, start, len);
6971 read_unlock(&em_tree->lock);
6974 if (em->start > start || em->start + em->len <= start)
6975 free_extent_map(em);
6976 else if (em->block_start == EXTENT_MAP_INLINE && page)
6977 free_extent_map(em);
6981 em = alloc_extent_map();
6986 em->start = EXTENT_MAP_HOLE;
6987 em->orig_start = EXTENT_MAP_HOLE;
6989 em->block_len = (u64)-1;
6991 path = btrfs_alloc_path();
6997 /* Chances are we'll be called again, so go ahead and do readahead */
6998 path->reada = READA_FORWARD;
7001 * The same explanation in load_free_space_cache applies here as well,
7002 * we only read when we're loading the free space cache, and at that
7003 * point the commit_root has everything we need.
7005 if (btrfs_is_free_space_inode(inode)) {
7006 path->search_commit_root = 1;
7007 path->skip_locking = 1;
7010 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7013 } else if (ret > 0) {
7014 if (path->slots[0] == 0)
7020 leaf = path->nodes[0];
7021 item = btrfs_item_ptr(leaf, path->slots[0],
7022 struct btrfs_file_extent_item);
7023 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7024 if (found_key.objectid != objectid ||
7025 found_key.type != BTRFS_EXTENT_DATA_KEY) {
7027 * If we backup past the first extent we want to move forward
7028 * and see if there is an extent in front of us, otherwise we'll
7029 * say there is a hole for our whole search range which can
7036 extent_type = btrfs_file_extent_type(leaf, item);
7037 extent_start = found_key.offset;
7038 extent_end = btrfs_file_extent_end(path);
7039 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7040 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7041 /* Only regular file could have regular/prealloc extent */
7042 if (!S_ISREG(inode->vfs_inode.i_mode)) {
7045 "regular/prealloc extent found for non-regular inode %llu",
7049 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7051 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7052 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7057 if (start >= extent_end) {
7059 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7060 ret = btrfs_next_leaf(root, path);
7066 leaf = path->nodes[0];
7068 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7069 if (found_key.objectid != objectid ||
7070 found_key.type != BTRFS_EXTENT_DATA_KEY)
7072 if (start + len <= found_key.offset)
7074 if (start > found_key.offset)
7077 /* New extent overlaps with existing one */
7079 em->orig_start = start;
7080 em->len = found_key.offset - start;
7081 em->block_start = EXTENT_MAP_HOLE;
7085 btrfs_extent_item_to_extent_map(inode, path, item, em);
7087 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7088 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7090 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7092 * Inline extent can only exist at file offset 0. This is
7093 * ensured by tree-checker and inline extent creation path.
7094 * Thus all members representing file offsets should be zero.
7096 ASSERT(pg_offset == 0);
7097 ASSERT(extent_start == 0);
7098 ASSERT(em->start == 0);
7101 * btrfs_extent_item_to_extent_map() should have properly
7102 * initialized em members already.
7104 * Other members are not utilized for inline extents.
7106 ASSERT(em->block_start == EXTENT_MAP_INLINE);
7107 ASSERT(em->len = fs_info->sectorsize);
7109 ret = read_inline_extent(inode, path, page);
7116 em->orig_start = start;
7118 em->block_start = EXTENT_MAP_HOLE;
7121 btrfs_release_path(path);
7122 if (em->start > start || extent_map_end(em) <= start) {
7124 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7125 em->start, em->len, start, len);
7130 write_lock(&em_tree->lock);
7131 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7132 write_unlock(&em_tree->lock);
7134 btrfs_free_path(path);
7136 trace_btrfs_get_extent(root, inode, em);
7139 free_extent_map(em);
7140 return ERR_PTR(ret);
7145 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7148 const u64 orig_start,
7149 const u64 block_start,
7150 const u64 block_len,
7151 const u64 orig_block_len,
7152 const u64 ram_bytes,
7155 struct extent_map *em = NULL;
7158 if (type != BTRFS_ORDERED_NOCOW) {
7159 em = create_io_em(inode, start, len, orig_start, block_start,
7160 block_len, orig_block_len, ram_bytes,
7161 BTRFS_COMPRESS_NONE, /* compress_type */
7166 ret = btrfs_add_ordered_extent(inode, start, len, len, block_start,
7169 (1 << BTRFS_ORDERED_DIRECT),
7170 BTRFS_COMPRESS_NONE);
7173 free_extent_map(em);
7174 btrfs_drop_extent_map_range(inode, start,
7175 start + len - 1, false);
7184 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7187 struct btrfs_root *root = inode->root;
7188 struct btrfs_fs_info *fs_info = root->fs_info;
7189 struct extent_map *em;
7190 struct btrfs_key ins;
7194 alloc_hint = get_extent_allocation_hint(inode, start, len);
7195 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7196 0, alloc_hint, &ins, 1, 1);
7198 return ERR_PTR(ret);
7200 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7201 ins.objectid, ins.offset, ins.offset,
7202 ins.offset, BTRFS_ORDERED_REGULAR);
7203 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7205 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7211 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7213 struct btrfs_block_group *block_group;
7214 bool readonly = false;
7216 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7217 if (!block_group || block_group->ro)
7220 btrfs_put_block_group(block_group);
7225 * Check if we can do nocow write into the range [@offset, @offset + @len)
7227 * @offset: File offset
7228 * @len: The length to write, will be updated to the nocow writeable
7230 * @orig_start: (optional) Return the original file offset of the file extent
7231 * @orig_len: (optional) Return the original on-disk length of the file extent
7232 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7233 * @strict: if true, omit optimizations that might force us into unnecessary
7234 * cow. e.g., don't trust generation number.
7237 * >0 and update @len if we can do nocow write
7238 * 0 if we can't do nocow write
7239 * <0 if error happened
7241 * NOTE: This only checks the file extents, caller is responsible to wait for
7242 * any ordered extents.
7244 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7245 u64 *orig_start, u64 *orig_block_len,
7246 u64 *ram_bytes, bool nowait, bool strict)
7248 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7249 struct can_nocow_file_extent_args nocow_args = { 0 };
7250 struct btrfs_path *path;
7252 struct extent_buffer *leaf;
7253 struct btrfs_root *root = BTRFS_I(inode)->root;
7254 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7255 struct btrfs_file_extent_item *fi;
7256 struct btrfs_key key;
7259 path = btrfs_alloc_path();
7262 path->nowait = nowait;
7264 ret = btrfs_lookup_file_extent(NULL, root, path,
7265 btrfs_ino(BTRFS_I(inode)), offset, 0);
7270 if (path->slots[0] == 0) {
7271 /* can't find the item, must cow */
7278 leaf = path->nodes[0];
7279 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7280 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7281 key.type != BTRFS_EXTENT_DATA_KEY) {
7282 /* not our file or wrong item type, must cow */
7286 if (key.offset > offset) {
7287 /* Wrong offset, must cow */
7291 if (btrfs_file_extent_end(path) <= offset)
7294 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7295 found_type = btrfs_file_extent_type(leaf, fi);
7297 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7299 nocow_args.start = offset;
7300 nocow_args.end = offset + *len - 1;
7301 nocow_args.strict = strict;
7302 nocow_args.free_path = true;
7304 ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
7305 /* can_nocow_file_extent() has freed the path. */
7309 /* Treat errors as not being able to NOCOW. */
7315 if (btrfs_extent_readonly(fs_info, nocow_args.disk_bytenr))
7318 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7319 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7322 range_end = round_up(offset + nocow_args.num_bytes,
7323 root->fs_info->sectorsize) - 1;
7324 ret = test_range_bit(io_tree, offset, range_end,
7325 EXTENT_DELALLOC, 0, NULL);
7333 *orig_start = key.offset - nocow_args.extent_offset;
7335 *orig_block_len = nocow_args.disk_num_bytes;
7337 *len = nocow_args.num_bytes;
7340 btrfs_free_path(path);
7344 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7345 struct extent_state **cached_state,
7346 unsigned int iomap_flags)
7348 const bool writing = (iomap_flags & IOMAP_WRITE);
7349 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7350 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7351 struct btrfs_ordered_extent *ordered;
7356 if (!try_lock_extent(io_tree, lockstart, lockend,
7360 lock_extent(io_tree, lockstart, lockend, cached_state);
7363 * We're concerned with the entire range that we're going to be
7364 * doing DIO to, so we need to make sure there's no ordered
7365 * extents in this range.
7367 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7368 lockend - lockstart + 1);
7371 * We need to make sure there are no buffered pages in this
7372 * range either, we could have raced between the invalidate in
7373 * generic_file_direct_write and locking the extent. The
7374 * invalidate needs to happen so that reads after a write do not
7378 (!writing || !filemap_range_has_page(inode->i_mapping,
7379 lockstart, lockend)))
7382 unlock_extent(io_tree, lockstart, lockend, cached_state);
7386 btrfs_put_ordered_extent(ordered);
7391 * If we are doing a DIO read and the ordered extent we
7392 * found is for a buffered write, we can not wait for it
7393 * to complete and retry, because if we do so we can
7394 * deadlock with concurrent buffered writes on page
7395 * locks. This happens only if our DIO read covers more
7396 * than one extent map, if at this point has already
7397 * created an ordered extent for a previous extent map
7398 * and locked its range in the inode's io tree, and a
7399 * concurrent write against that previous extent map's
7400 * range and this range started (we unlock the ranges
7401 * in the io tree only when the bios complete and
7402 * buffered writes always lock pages before attempting
7403 * to lock range in the io tree).
7406 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7407 btrfs_start_ordered_extent(ordered, 1);
7409 ret = nowait ? -EAGAIN : -ENOTBLK;
7410 btrfs_put_ordered_extent(ordered);
7413 * We could trigger writeback for this range (and wait
7414 * for it to complete) and then invalidate the pages for
7415 * this range (through invalidate_inode_pages2_range()),
7416 * but that can lead us to a deadlock with a concurrent
7417 * call to readahead (a buffered read or a defrag call
7418 * triggered a readahead) on a page lock due to an
7419 * ordered dio extent we created before but did not have
7420 * yet a corresponding bio submitted (whence it can not
7421 * complete), which makes readahead wait for that
7422 * ordered extent to complete while holding a lock on
7425 ret = nowait ? -EAGAIN : -ENOTBLK;
7437 /* The callers of this must take lock_extent() */
7438 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7439 u64 len, u64 orig_start, u64 block_start,
7440 u64 block_len, u64 orig_block_len,
7441 u64 ram_bytes, int compress_type,
7444 struct extent_map *em;
7447 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7448 type == BTRFS_ORDERED_COMPRESSED ||
7449 type == BTRFS_ORDERED_NOCOW ||
7450 type == BTRFS_ORDERED_REGULAR);
7452 em = alloc_extent_map();
7454 return ERR_PTR(-ENOMEM);
7457 em->orig_start = orig_start;
7459 em->block_len = block_len;
7460 em->block_start = block_start;
7461 em->orig_block_len = orig_block_len;
7462 em->ram_bytes = ram_bytes;
7463 em->generation = -1;
7464 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7465 if (type == BTRFS_ORDERED_PREALLOC) {
7466 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7467 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7468 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7469 em->compress_type = compress_type;
7472 ret = btrfs_replace_extent_map_range(inode, em, true);
7474 free_extent_map(em);
7475 return ERR_PTR(ret);
7478 /* em got 2 refs now, callers needs to do free_extent_map once. */
7483 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7484 struct inode *inode,
7485 struct btrfs_dio_data *dio_data,
7487 unsigned int iomap_flags)
7489 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7490 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7491 struct extent_map *em = *map;
7493 u64 block_start, orig_start, orig_block_len, ram_bytes;
7494 struct btrfs_block_group *bg;
7495 bool can_nocow = false;
7496 bool space_reserved = false;
7501 * We don't allocate a new extent in the following cases
7503 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7505 * 2) The extent is marked as PREALLOC. We're good to go here and can
7506 * just use the extent.
7509 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7510 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7511 em->block_start != EXTENT_MAP_HOLE)) {
7512 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7513 type = BTRFS_ORDERED_PREALLOC;
7515 type = BTRFS_ORDERED_NOCOW;
7516 len = min(len, em->len - (start - em->start));
7517 block_start = em->block_start + (start - em->start);
7519 if (can_nocow_extent(inode, start, &len, &orig_start,
7520 &orig_block_len, &ram_bytes, false, false) == 1) {
7521 bg = btrfs_inc_nocow_writers(fs_info, block_start);
7529 struct extent_map *em2;
7531 /* We can NOCOW, so only need to reserve metadata space. */
7532 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7535 /* Our caller expects us to free the input extent map. */
7536 free_extent_map(em);
7538 btrfs_dec_nocow_writers(bg);
7539 if (nowait && (ret == -ENOSPC || ret == -EDQUOT))
7543 space_reserved = true;
7545 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7546 orig_start, block_start,
7547 len, orig_block_len,
7549 btrfs_dec_nocow_writers(bg);
7550 if (type == BTRFS_ORDERED_PREALLOC) {
7551 free_extent_map(em);
7561 dio_data->nocow_done = true;
7563 /* Our caller expects us to free the input extent map. */
7564 free_extent_map(em);
7571 * If we could not allocate data space before locking the file
7572 * range and we can't do a NOCOW write, then we have to fail.
7574 if (!dio_data->data_space_reserved)
7578 * We have to COW and we have already reserved data space before,
7579 * so now we reserve only metadata.
7581 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7585 space_reserved = true;
7587 em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7593 len = min(len, em->len - (start - em->start));
7595 btrfs_delalloc_release_metadata(BTRFS_I(inode),
7596 prev_len - len, true);
7600 * We have created our ordered extent, so we can now release our reservation
7601 * for an outstanding extent.
7603 btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
7606 * Need to update the i_size under the extent lock so buffered
7607 * readers will get the updated i_size when we unlock.
7609 if (start + len > i_size_read(inode))
7610 i_size_write(inode, start + len);
7612 if (ret && space_reserved) {
7613 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7614 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7619 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7620 loff_t length, unsigned int flags, struct iomap *iomap,
7621 struct iomap *srcmap)
7623 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7624 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7625 struct extent_map *em;
7626 struct extent_state *cached_state = NULL;
7627 struct btrfs_dio_data *dio_data = iter->private;
7628 u64 lockstart, lockend;
7629 const bool write = !!(flags & IOMAP_WRITE);
7632 const u64 data_alloc_len = length;
7633 bool unlock_extents = false;
7636 * We could potentially fault if we have a buffer > PAGE_SIZE, and if
7637 * we're NOWAIT we may submit a bio for a partial range and return
7638 * EIOCBQUEUED, which would result in an errant short read.
7640 * The best way to handle this would be to allow for partial completions
7641 * of iocb's, so we could submit the partial bio, return and fault in
7642 * the rest of the pages, and then submit the io for the rest of the
7643 * range. However we don't have that currently, so simply return
7644 * -EAGAIN at this point so that the normal path is used.
7646 if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE)
7650 * Cap the size of reads to that usually seen in buffered I/O as we need
7651 * to allocate a contiguous array for the checksums.
7654 len = min_t(u64, len, fs_info->sectorsize * BTRFS_MAX_BIO_SECTORS);
7657 lockend = start + len - 1;
7660 * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
7661 * enough if we've written compressed pages to this area, so we need to
7662 * flush the dirty pages again to make absolutely sure that any
7663 * outstanding dirty pages are on disk - the first flush only starts
7664 * compression on the data, while keeping the pages locked, so by the
7665 * time the second flush returns we know bios for the compressed pages
7666 * were submitted and finished, and the pages no longer under writeback.
7668 * If we have a NOWAIT request and we have any pages in the range that
7669 * are locked, likely due to compression still in progress, we don't want
7670 * to block on page locks. We also don't want to block on pages marked as
7671 * dirty or under writeback (same as for the non-compression case).
7672 * iomap_dio_rw() did the same check, but after that and before we got
7673 * here, mmap'ed writes may have happened or buffered reads started
7674 * (readpage() and readahead(), which lock pages), as we haven't locked
7675 * the file range yet.
7677 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7678 &BTRFS_I(inode)->runtime_flags)) {
7679 if (flags & IOMAP_NOWAIT) {
7680 if (filemap_range_needs_writeback(inode->i_mapping,
7681 lockstart, lockend))
7684 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7685 start + length - 1);
7691 memset(dio_data, 0, sizeof(*dio_data));
7694 * We always try to allocate data space and must do it before locking
7695 * the file range, to avoid deadlocks with concurrent writes to the same
7696 * range if the range has several extents and the writes don't expand the
7697 * current i_size (the inode lock is taken in shared mode). If we fail to
7698 * allocate data space here we continue and later, after locking the
7699 * file range, we fail with ENOSPC only if we figure out we can not do a
7702 if (write && !(flags & IOMAP_NOWAIT)) {
7703 ret = btrfs_check_data_free_space(BTRFS_I(inode),
7704 &dio_data->data_reserved,
7705 start, data_alloc_len, false);
7707 dio_data->data_space_reserved = true;
7708 else if (ret && !(BTRFS_I(inode)->flags &
7709 (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
7714 * If this errors out it's because we couldn't invalidate pagecache for
7715 * this range and we need to fallback to buffered IO, or we are doing a
7716 * NOWAIT read/write and we need to block.
7718 ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags);
7722 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7729 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7730 * io. INLINE is special, and we could probably kludge it in here, but
7731 * it's still buffered so for safety lets just fall back to the generic
7734 * For COMPRESSED we _have_ to read the entire extent in so we can
7735 * decompress it, so there will be buffering required no matter what we
7736 * do, so go ahead and fallback to buffered.
7738 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7739 * to buffered IO. Don't blame me, this is the price we pay for using
7742 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7743 em->block_start == EXTENT_MAP_INLINE) {
7744 free_extent_map(em);
7746 * If we are in a NOWAIT context, return -EAGAIN in order to
7747 * fallback to buffered IO. This is not only because we can
7748 * block with buffered IO (no support for NOWAIT semantics at
7749 * the moment) but also to avoid returning short reads to user
7750 * space - this happens if we were able to read some data from
7751 * previous non-compressed extents and then when we fallback to
7752 * buffered IO, at btrfs_file_read_iter() by calling
7753 * filemap_read(), we fail to fault in pages for the read buffer,
7754 * in which case filemap_read() returns a short read (the number
7755 * of bytes previously read is > 0, so it does not return -EFAULT).
7757 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
7761 len = min(len, em->len - (start - em->start));
7764 * If we have a NOWAIT request and the range contains multiple extents
7765 * (or a mix of extents and holes), then we return -EAGAIN to make the
7766 * caller fallback to a context where it can do a blocking (without
7767 * NOWAIT) request. This way we avoid doing partial IO and returning
7768 * success to the caller, which is not optimal for writes and for reads
7769 * it can result in unexpected behaviour for an application.
7771 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7772 * iomap_dio_rw(), we can end up returning less data then what the caller
7773 * asked for, resulting in an unexpected, and incorrect, short read.
7774 * That is, the caller asked to read N bytes and we return less than that,
7775 * which is wrong unless we are crossing EOF. This happens if we get a
7776 * page fault error when trying to fault in pages for the buffer that is
7777 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7778 * have previously submitted bios for other extents in the range, in
7779 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7780 * those bios have completed by the time we get the page fault error,
7781 * which we return back to our caller - we should only return EIOCBQUEUED
7782 * after we have submitted bios for all the extents in the range.
7784 if ((flags & IOMAP_NOWAIT) && len < length) {
7785 free_extent_map(em);
7791 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7795 unlock_extents = true;
7796 /* Recalc len in case the new em is smaller than requested */
7797 len = min(len, em->len - (start - em->start));
7798 if (dio_data->data_space_reserved) {
7800 u64 release_len = 0;
7802 if (dio_data->nocow_done) {
7803 release_offset = start;
7804 release_len = data_alloc_len;
7805 } else if (len < data_alloc_len) {
7806 release_offset = start + len;
7807 release_len = data_alloc_len - len;
7810 if (release_len > 0)
7811 btrfs_free_reserved_data_space(BTRFS_I(inode),
7812 dio_data->data_reserved,
7818 * We need to unlock only the end area that we aren't using.
7819 * The rest is going to be unlocked by the endio routine.
7821 lockstart = start + len;
7822 if (lockstart < lockend)
7823 unlock_extents = true;
7827 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7830 free_extent_state(cached_state);
7833 * Translate extent map information to iomap.
7834 * We trim the extents (and move the addr) even though iomap code does
7835 * that, since we have locked only the parts we are performing I/O in.
7837 if ((em->block_start == EXTENT_MAP_HOLE) ||
7838 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7839 iomap->addr = IOMAP_NULL_ADDR;
7840 iomap->type = IOMAP_HOLE;
7842 iomap->addr = em->block_start + (start - em->start);
7843 iomap->type = IOMAP_MAPPED;
7845 iomap->offset = start;
7846 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7847 iomap->length = len;
7849 if (write && btrfs_use_zone_append(BTRFS_I(inode), em->block_start))
7850 iomap->flags |= IOMAP_F_ZONE_APPEND;
7852 free_extent_map(em);
7857 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7860 if (dio_data->data_space_reserved) {
7861 btrfs_free_reserved_data_space(BTRFS_I(inode),
7862 dio_data->data_reserved,
7863 start, data_alloc_len);
7864 extent_changeset_free(dio_data->data_reserved);
7870 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7871 ssize_t written, unsigned int flags, struct iomap *iomap)
7873 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7874 struct btrfs_dio_data *dio_data = iter->private;
7875 size_t submitted = dio_data->submitted;
7876 const bool write = !!(flags & IOMAP_WRITE);
7879 if (!write && (iomap->type == IOMAP_HOLE)) {
7880 /* If reading from a hole, unlock and return */
7881 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1,
7886 if (submitted < length) {
7888 length -= submitted;
7890 btrfs_mark_ordered_io_finished(BTRFS_I(inode), NULL,
7891 pos, length, false);
7893 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7894 pos + length - 1, NULL);
7899 extent_changeset_free(dio_data->data_reserved);
7903 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7906 * This implies a barrier so that stores to dio_bio->bi_status before
7907 * this and loads of dio_bio->bi_status after this are fully ordered.
7909 if (!refcount_dec_and_test(&dip->refs))
7912 if (btrfs_op(&dip->bio) == BTRFS_MAP_WRITE) {
7913 btrfs_mark_ordered_io_finished(BTRFS_I(dip->inode), NULL,
7914 dip->file_offset, dip->bytes,
7915 !dip->bio.bi_status);
7917 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7919 dip->file_offset + dip->bytes - 1, NULL);
7923 bio_endio(&dip->bio);
7926 static void submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7928 enum btrfs_compression_type compress_type)
7930 struct btrfs_dio_private *dip = btrfs_bio(bio)->private;
7931 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7933 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7935 refcount_inc(&dip->refs);
7936 btrfs_submit_bio(fs_info, bio, mirror_num);
7939 static blk_status_t btrfs_check_read_dio_bio(struct btrfs_dio_private *dip,
7940 struct btrfs_bio *bbio,
7941 const bool uptodate)
7943 struct inode *inode = dip->inode;
7944 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7945 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7946 blk_status_t err = BLK_STS_OK;
7947 struct bvec_iter iter;
7951 btrfs_bio_for_each_sector(fs_info, bv, bbio, iter, offset) {
7952 u64 start = bbio->file_offset + offset;
7955 (!csum || !btrfs_check_data_csum(inode, bbio, offset, bv.bv_page,
7957 btrfs_clean_io_failure(BTRFS_I(inode), start,
7958 bv.bv_page, bv.bv_offset);
7962 ret = btrfs_repair_one_sector(inode, bbio, offset,
7963 bv.bv_page, bv.bv_offset,
7964 submit_dio_repair_bio);
7966 err = errno_to_blk_status(ret);
7973 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7975 u64 dio_file_offset)
7977 return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, false);
7980 static void btrfs_end_dio_bio(struct btrfs_bio *bbio)
7982 struct btrfs_dio_private *dip = bbio->private;
7983 struct bio *bio = &bbio->bio;
7984 blk_status_t err = bio->bi_status;
7987 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7988 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7989 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7990 bio->bi_opf, bio->bi_iter.bi_sector,
7991 bio->bi_iter.bi_size, err);
7993 if (bio_op(bio) == REQ_OP_READ)
7994 err = btrfs_check_read_dio_bio(dip, bbio, !err);
7997 dip->bio.bi_status = err;
7999 btrfs_record_physical_zoned(dip->inode, bbio->file_offset, bio);
8002 btrfs_dio_private_put(dip);
8005 static void btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8006 u64 file_offset, int async_submit)
8008 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8009 struct btrfs_dio_private *dip = btrfs_bio(bio)->private;
8012 /* Save the original iter for read repair */
8013 if (btrfs_op(bio) == BTRFS_MAP_READ)
8014 btrfs_bio(bio)->iter = bio->bi_iter;
8016 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8019 if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
8020 /* Check btrfs_submit_data_write_bio() for async submit rules */
8021 if (async_submit && !atomic_read(&BTRFS_I(inode)->sync_writers) &&
8022 btrfs_wq_submit_bio(inode, bio, 0, file_offset,
8023 btrfs_submit_bio_start_direct_io))
8027 * If we aren't doing async submit, calculate the csum of the
8030 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, false);
8032 btrfs_bio_end_io(btrfs_bio(bio), ret);
8036 btrfs_bio(bio)->csum = btrfs_csum_ptr(fs_info, dip->csums,
8037 file_offset - dip->file_offset);
8040 btrfs_submit_bio(fs_info, bio, 0);
8043 static void btrfs_submit_direct(const struct iomap_iter *iter,
8044 struct bio *dio_bio, loff_t file_offset)
8046 struct btrfs_dio_private *dip =
8047 container_of(dio_bio, struct btrfs_dio_private, bio);
8048 struct inode *inode = iter->inode;
8049 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8050 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8051 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
8052 BTRFS_BLOCK_GROUP_RAID56_MASK);
8055 int async_submit = 0;
8057 u64 clone_offset = 0;
8061 blk_status_t status;
8062 struct btrfs_io_geometry geom;
8063 struct btrfs_dio_data *dio_data = iter->private;
8064 struct extent_map *em = NULL;
8067 dip->file_offset = file_offset;
8068 dip->bytes = dio_bio->bi_iter.bi_size;
8069 refcount_set(&dip->refs, 1);
8072 if (!write && !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
8073 unsigned int nr_sectors =
8074 (dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits);
8077 * Load the csums up front to reduce csum tree searches and
8078 * contention when submitting bios.
8080 status = BLK_STS_RESOURCE;
8081 dip->csums = kcalloc(nr_sectors, fs_info->csum_size, GFP_NOFS);
8085 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8086 if (status != BLK_STS_OK)
8090 start_sector = dio_bio->bi_iter.bi_sector;
8091 submit_len = dio_bio->bi_iter.bi_size;
8094 logical = start_sector << 9;
8095 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8097 status = errno_to_blk_status(PTR_ERR(em));
8101 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8104 status = errno_to_blk_status(ret);
8108 clone_len = min(submit_len, geom.len);
8109 ASSERT(clone_len <= UINT_MAX);
8112 * This will never fail as it's passing GPF_NOFS and
8113 * the allocation is backed by btrfs_bioset.
8115 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len,
8116 btrfs_end_dio_bio, dip);
8117 btrfs_bio(bio)->file_offset = file_offset;
8119 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8120 status = extract_ordered_extent(BTRFS_I(inode), bio,
8128 ASSERT(submit_len >= clone_len);
8129 submit_len -= clone_len;
8132 * Increase the count before we submit the bio so we know
8133 * the end IO handler won't happen before we increase the
8134 * count. Otherwise, the dip might get freed before we're
8135 * done setting it up.
8137 * We transfer the initial reference to the last bio, so we
8138 * don't need to increment the reference count for the last one.
8140 if (submit_len > 0) {
8141 refcount_inc(&dip->refs);
8143 * If we are submitting more than one bio, submit them
8144 * all asynchronously. The exception is RAID 5 or 6, as
8145 * asynchronous checksums make it difficult to collect
8146 * full stripe writes.
8152 btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8154 dio_data->submitted += clone_len;
8155 clone_offset += clone_len;
8156 start_sector += clone_len >> 9;
8157 file_offset += clone_len;
8159 free_extent_map(em);
8160 } while (submit_len > 0);
8164 free_extent_map(em);
8166 dio_bio->bi_status = status;
8167 btrfs_dio_private_put(dip);
8170 static const struct iomap_ops btrfs_dio_iomap_ops = {
8171 .iomap_begin = btrfs_dio_iomap_begin,
8172 .iomap_end = btrfs_dio_iomap_end,
8175 static const struct iomap_dio_ops btrfs_dio_ops = {
8176 .submit_io = btrfs_submit_direct,
8177 .bio_set = &btrfs_dio_bioset,
8180 ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, size_t done_before)
8182 struct btrfs_dio_data data;
8184 return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
8185 IOMAP_DIO_PARTIAL, &data, done_before);
8188 struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
8191 struct btrfs_dio_data data;
8193 return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
8194 IOMAP_DIO_PARTIAL, &data, done_before);
8197 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8202 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8207 * fiemap_prep() called filemap_write_and_wait() for the whole possible
8208 * file range (0 to LLONG_MAX), but that is not enough if we have
8209 * compression enabled. The first filemap_fdatawrite_range() only kicks
8210 * in the compression of data (in an async thread) and will return
8211 * before the compression is done and writeback is started. A second
8212 * filemap_fdatawrite_range() is needed to wait for the compression to
8213 * complete and writeback to start. We also need to wait for ordered
8214 * extents to complete, because our fiemap implementation uses mainly
8215 * file extent items to list the extents, searching for extent maps
8216 * only for file ranges with holes or prealloc extents to figure out
8217 * if we have delalloc in those ranges.
8219 if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
8220 ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
8225 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8228 static int btrfs_writepages(struct address_space *mapping,
8229 struct writeback_control *wbc)
8231 return extent_writepages(mapping, wbc);
8234 static void btrfs_readahead(struct readahead_control *rac)
8236 extent_readahead(rac);
8240 * For release_folio() and invalidate_folio() we have a race window where
8241 * folio_end_writeback() is called but the subpage spinlock is not yet released.
8242 * If we continue to release/invalidate the page, we could cause use-after-free
8243 * for subpage spinlock. So this function is to spin and wait for subpage
8246 static void wait_subpage_spinlock(struct page *page)
8248 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
8249 struct btrfs_subpage *subpage;
8251 if (!btrfs_is_subpage(fs_info, page))
8254 ASSERT(PagePrivate(page) && page->private);
8255 subpage = (struct btrfs_subpage *)page->private;
8258 * This may look insane as we just acquire the spinlock and release it,
8259 * without doing anything. But we just want to make sure no one is
8260 * still holding the subpage spinlock.
8261 * And since the page is not dirty nor writeback, and we have page
8262 * locked, the only possible way to hold a spinlock is from the endio
8263 * function to clear page writeback.
8265 * Here we just acquire the spinlock so that all existing callers
8266 * should exit and we're safe to release/invalidate the page.
8268 spin_lock_irq(&subpage->lock);
8269 spin_unlock_irq(&subpage->lock);
8272 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
8274 int ret = try_release_extent_mapping(&folio->page, gfp_flags);
8277 wait_subpage_spinlock(&folio->page);
8278 clear_page_extent_mapped(&folio->page);
8283 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
8285 if (folio_test_writeback(folio) || folio_test_dirty(folio))
8287 return __btrfs_release_folio(folio, gfp_flags);
8290 #ifdef CONFIG_MIGRATION
8291 static int btrfs_migrate_folio(struct address_space *mapping,
8292 struct folio *dst, struct folio *src,
8293 enum migrate_mode mode)
8295 int ret = filemap_migrate_folio(mapping, dst, src, mode);
8297 if (ret != MIGRATEPAGE_SUCCESS)
8300 if (folio_test_ordered(src)) {
8301 folio_clear_ordered(src);
8302 folio_set_ordered(dst);
8305 return MIGRATEPAGE_SUCCESS;
8308 #define btrfs_migrate_folio NULL
8311 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
8314 struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
8315 struct btrfs_fs_info *fs_info = inode->root->fs_info;
8316 struct extent_io_tree *tree = &inode->io_tree;
8317 struct extent_state *cached_state = NULL;
8318 u64 page_start = folio_pos(folio);
8319 u64 page_end = page_start + folio_size(folio) - 1;
8321 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8324 * We have folio locked so no new ordered extent can be created on this
8325 * page, nor bio can be submitted for this folio.
8327 * But already submitted bio can still be finished on this folio.
8328 * Furthermore, endio function won't skip folio which has Ordered
8329 * (Private2) already cleared, so it's possible for endio and
8330 * invalidate_folio to do the same ordered extent accounting twice
8333 * So here we wait for any submitted bios to finish, so that we won't
8334 * do double ordered extent accounting on the same folio.
8336 folio_wait_writeback(folio);
8337 wait_subpage_spinlock(&folio->page);
8340 * For subpage case, we have call sites like
8341 * btrfs_punch_hole_lock_range() which passes range not aligned to
8343 * If the range doesn't cover the full folio, we don't need to and
8344 * shouldn't clear page extent mapped, as folio->private can still
8345 * record subpage dirty bits for other part of the range.
8347 * For cases that invalidate the full folio even the range doesn't
8348 * cover the full folio, like invalidating the last folio, we're
8349 * still safe to wait for ordered extent to finish.
8351 if (!(offset == 0 && length == folio_size(folio))) {
8352 btrfs_release_folio(folio, GFP_NOFS);
8356 if (!inode_evicting)
8357 lock_extent(tree, page_start, page_end, &cached_state);
8360 while (cur < page_end) {
8361 struct btrfs_ordered_extent *ordered;
8364 u32 extra_flags = 0;
8366 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8367 page_end + 1 - cur);
8369 range_end = page_end;
8371 * No ordered extent covering this range, we are safe
8372 * to delete all extent states in the range.
8374 extra_flags = EXTENT_CLEAR_ALL_BITS;
8377 if (ordered->file_offset > cur) {
8379 * There is a range between [cur, oe->file_offset) not
8380 * covered by any ordered extent.
8381 * We are safe to delete all extent states, and handle
8382 * the ordered extent in the next iteration.
8384 range_end = ordered->file_offset - 1;
8385 extra_flags = EXTENT_CLEAR_ALL_BITS;
8389 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8391 ASSERT(range_end + 1 - cur < U32_MAX);
8392 range_len = range_end + 1 - cur;
8393 if (!btrfs_page_test_ordered(fs_info, &folio->page, cur, range_len)) {
8395 * If Ordered (Private2) is cleared, it means endio has
8396 * already been executed for the range.
8397 * We can't delete the extent states as
8398 * btrfs_finish_ordered_io() may still use some of them.
8402 btrfs_page_clear_ordered(fs_info, &folio->page, cur, range_len);
8405 * IO on this page will never be started, so we need to account
8406 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8407 * here, must leave that up for the ordered extent completion.
8409 * This will also unlock the range for incoming
8410 * btrfs_finish_ordered_io().
8412 if (!inode_evicting)
8413 clear_extent_bit(tree, cur, range_end,
8415 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8416 EXTENT_DEFRAG, &cached_state);
8418 spin_lock_irq(&inode->ordered_tree.lock);
8419 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8420 ordered->truncated_len = min(ordered->truncated_len,
8421 cur - ordered->file_offset);
8422 spin_unlock_irq(&inode->ordered_tree.lock);
8425 * If the ordered extent has finished, we're safe to delete all
8426 * the extent states of the range, otherwise
8427 * btrfs_finish_ordered_io() will get executed by endio for
8428 * other pages, so we can't delete extent states.
8430 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8431 cur, range_end + 1 - cur)) {
8432 btrfs_finish_ordered_io(ordered);
8434 * The ordered extent has finished, now we're again
8435 * safe to delete all extent states of the range.
8437 extra_flags = EXTENT_CLEAR_ALL_BITS;
8441 btrfs_put_ordered_extent(ordered);
8443 * Qgroup reserved space handler
8444 * Sector(s) here will be either:
8446 * 1) Already written to disk or bio already finished
8447 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8448 * Qgroup will be handled by its qgroup_record then.
8449 * btrfs_qgroup_free_data() call will do nothing here.
8451 * 2) Not written to disk yet
8452 * Then btrfs_qgroup_free_data() call will clear the
8453 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8454 * reserved data space.
8455 * Since the IO will never happen for this page.
8457 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8458 if (!inode_evicting) {
8459 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8460 EXTENT_DELALLOC | EXTENT_UPTODATE |
8461 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
8462 extra_flags, &cached_state);
8464 cur = range_end + 1;
8467 * We have iterated through all ordered extents of the page, the page
8468 * should not have Ordered (Private2) anymore, or the above iteration
8469 * did something wrong.
8471 ASSERT(!folio_test_ordered(folio));
8472 btrfs_page_clear_checked(fs_info, &folio->page, folio_pos(folio), folio_size(folio));
8473 if (!inode_evicting)
8474 __btrfs_release_folio(folio, GFP_NOFS);
8475 clear_page_extent_mapped(&folio->page);
8479 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8480 * called from a page fault handler when a page is first dirtied. Hence we must
8481 * be careful to check for EOF conditions here. We set the page up correctly
8482 * for a written page which means we get ENOSPC checking when writing into
8483 * holes and correct delalloc and unwritten extent mapping on filesystems that
8484 * support these features.
8486 * We are not allowed to take the i_mutex here so we have to play games to
8487 * protect against truncate races as the page could now be beyond EOF. Because
8488 * truncate_setsize() writes the inode size before removing pages, once we have
8489 * the page lock we can determine safely if the page is beyond EOF. If it is not
8490 * beyond EOF, then the page is guaranteed safe against truncation until we
8493 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8495 struct page *page = vmf->page;
8496 struct inode *inode = file_inode(vmf->vma->vm_file);
8497 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8498 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8499 struct btrfs_ordered_extent *ordered;
8500 struct extent_state *cached_state = NULL;
8501 struct extent_changeset *data_reserved = NULL;
8502 unsigned long zero_start;
8512 reserved_space = PAGE_SIZE;
8514 sb_start_pagefault(inode->i_sb);
8515 page_start = page_offset(page);
8516 page_end = page_start + PAGE_SIZE - 1;
8520 * Reserving delalloc space after obtaining the page lock can lead to
8521 * deadlock. For example, if a dirty page is locked by this function
8522 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8523 * dirty page write out, then the btrfs_writepages() function could
8524 * end up waiting indefinitely to get a lock on the page currently
8525 * being processed by btrfs_page_mkwrite() function.
8527 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8528 page_start, reserved_space);
8530 ret2 = file_update_time(vmf->vma->vm_file);
8534 ret = vmf_error(ret2);
8540 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8542 down_read(&BTRFS_I(inode)->i_mmap_lock);
8544 size = i_size_read(inode);
8546 if ((page->mapping != inode->i_mapping) ||
8547 (page_start >= size)) {
8548 /* page got truncated out from underneath us */
8551 wait_on_page_writeback(page);
8553 lock_extent(io_tree, page_start, page_end, &cached_state);
8554 ret2 = set_page_extent_mapped(page);
8556 ret = vmf_error(ret2);
8557 unlock_extent(io_tree, page_start, page_end, &cached_state);
8562 * we can't set the delalloc bits if there are pending ordered
8563 * extents. Drop our locks and wait for them to finish
8565 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8568 unlock_extent(io_tree, page_start, page_end, &cached_state);
8570 up_read(&BTRFS_I(inode)->i_mmap_lock);
8571 btrfs_start_ordered_extent(ordered, 1);
8572 btrfs_put_ordered_extent(ordered);
8576 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8577 reserved_space = round_up(size - page_start,
8578 fs_info->sectorsize);
8579 if (reserved_space < PAGE_SIZE) {
8580 end = page_start + reserved_space - 1;
8581 btrfs_delalloc_release_space(BTRFS_I(inode),
8582 data_reserved, page_start,
8583 PAGE_SIZE - reserved_space, true);
8588 * page_mkwrite gets called when the page is firstly dirtied after it's
8589 * faulted in, but write(2) could also dirty a page and set delalloc
8590 * bits, thus in this case for space account reason, we still need to
8591 * clear any delalloc bits within this page range since we have to
8592 * reserve data&meta space before lock_page() (see above comments).
8594 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8595 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8596 EXTENT_DEFRAG, &cached_state);
8598 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8601 unlock_extent(io_tree, page_start, page_end, &cached_state);
8602 ret = VM_FAULT_SIGBUS;
8606 /* page is wholly or partially inside EOF */
8607 if (page_start + PAGE_SIZE > size)
8608 zero_start = offset_in_page(size);
8610 zero_start = PAGE_SIZE;
8612 if (zero_start != PAGE_SIZE)
8613 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8615 btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
8616 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8617 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8619 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8621 unlock_extent(io_tree, page_start, page_end, &cached_state);
8622 up_read(&BTRFS_I(inode)->i_mmap_lock);
8624 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8625 sb_end_pagefault(inode->i_sb);
8626 extent_changeset_free(data_reserved);
8627 return VM_FAULT_LOCKED;
8631 up_read(&BTRFS_I(inode)->i_mmap_lock);
8633 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8634 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8635 reserved_space, (ret != 0));
8637 sb_end_pagefault(inode->i_sb);
8638 extent_changeset_free(data_reserved);
8642 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8644 struct btrfs_truncate_control control = {
8645 .inode = BTRFS_I(inode),
8646 .ino = btrfs_ino(BTRFS_I(inode)),
8647 .min_type = BTRFS_EXTENT_DATA_KEY,
8648 .clear_extent_range = true,
8650 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8651 struct btrfs_root *root = BTRFS_I(inode)->root;
8652 struct btrfs_block_rsv *rsv;
8654 struct btrfs_trans_handle *trans;
8655 u64 mask = fs_info->sectorsize - 1;
8656 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8658 if (!skip_writeback) {
8659 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8666 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8667 * things going on here:
8669 * 1) We need to reserve space to update our inode.
8671 * 2) We need to have something to cache all the space that is going to
8672 * be free'd up by the truncate operation, but also have some slack
8673 * space reserved in case it uses space during the truncate (thank you
8674 * very much snapshotting).
8676 * And we need these to be separate. The fact is we can use a lot of
8677 * space doing the truncate, and we have no earthly idea how much space
8678 * we will use, so we need the truncate reservation to be separate so it
8679 * doesn't end up using space reserved for updating the inode. We also
8680 * need to be able to stop the transaction and start a new one, which
8681 * means we need to be able to update the inode several times, and we
8682 * have no idea of knowing how many times that will be, so we can't just
8683 * reserve 1 item for the entirety of the operation, so that has to be
8684 * done separately as well.
8686 * So that leaves us with
8688 * 1) rsv - for the truncate reservation, which we will steal from the
8689 * transaction reservation.
8690 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8691 * updating the inode.
8693 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8696 rsv->size = min_size;
8697 rsv->failfast = true;
8700 * 1 for the truncate slack space
8701 * 1 for updating the inode.
8703 trans = btrfs_start_transaction(root, 2);
8704 if (IS_ERR(trans)) {
8705 ret = PTR_ERR(trans);
8709 /* Migrate the slack space for the truncate to our reserve */
8710 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8714 trans->block_rsv = rsv;
8717 struct extent_state *cached_state = NULL;
8718 const u64 new_size = inode->i_size;
8719 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8721 control.new_size = new_size;
8722 lock_extent(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
8725 * We want to drop from the next block forward in case this new
8726 * size is not block aligned since we will be keeping the last
8727 * block of the extent just the way it is.
8729 btrfs_drop_extent_map_range(BTRFS_I(inode),
8730 ALIGN(new_size, fs_info->sectorsize),
8733 ret = btrfs_truncate_inode_items(trans, root, &control);
8735 inode_sub_bytes(inode, control.sub_bytes);
8736 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), control.last_size);
8738 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
8741 trans->block_rsv = &fs_info->trans_block_rsv;
8742 if (ret != -ENOSPC && ret != -EAGAIN)
8745 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8749 btrfs_end_transaction(trans);
8750 btrfs_btree_balance_dirty(fs_info);
8752 trans = btrfs_start_transaction(root, 2);
8753 if (IS_ERR(trans)) {
8754 ret = PTR_ERR(trans);
8759 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8760 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8761 rsv, min_size, false);
8762 BUG_ON(ret); /* shouldn't happen */
8763 trans->block_rsv = rsv;
8767 * We can't call btrfs_truncate_block inside a trans handle as we could
8768 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8769 * know we've truncated everything except the last little bit, and can
8770 * do btrfs_truncate_block and then update the disk_i_size.
8772 if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8773 btrfs_end_transaction(trans);
8774 btrfs_btree_balance_dirty(fs_info);
8776 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8779 trans = btrfs_start_transaction(root, 1);
8780 if (IS_ERR(trans)) {
8781 ret = PTR_ERR(trans);
8784 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8790 trans->block_rsv = &fs_info->trans_block_rsv;
8791 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8795 ret2 = btrfs_end_transaction(trans);
8798 btrfs_btree_balance_dirty(fs_info);
8801 btrfs_free_block_rsv(fs_info, rsv);
8803 * So if we truncate and then write and fsync we normally would just
8804 * write the extents that changed, which is a problem if we need to
8805 * first truncate that entire inode. So set this flag so we write out
8806 * all of the extents in the inode to the sync log so we're completely
8809 * If no extents were dropped or trimmed we don't need to force the next
8810 * fsync to truncate all the inode's items from the log and re-log them
8811 * all. This means the truncate operation did not change the file size,
8812 * or changed it to a smaller size but there was only an implicit hole
8813 * between the old i_size and the new i_size, and there were no prealloc
8814 * extents beyond i_size to drop.
8816 if (control.extents_found > 0)
8817 btrfs_set_inode_full_sync(BTRFS_I(inode));
8822 struct inode *btrfs_new_subvol_inode(struct user_namespace *mnt_userns,
8825 struct inode *inode;
8827 inode = new_inode(dir->i_sb);
8830 * Subvolumes don't inherit the sgid bit or the parent's gid if
8831 * the parent's sgid bit is set. This is probably a bug.
8833 inode_init_owner(mnt_userns, inode, NULL,
8834 S_IFDIR | (~current_umask() & S_IRWXUGO));
8835 inode->i_op = &btrfs_dir_inode_operations;
8836 inode->i_fop = &btrfs_dir_file_operations;
8841 struct inode *btrfs_alloc_inode(struct super_block *sb)
8843 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8844 struct btrfs_inode *ei;
8845 struct inode *inode;
8847 ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8854 ei->last_sub_trans = 0;
8855 ei->logged_trans = 0;
8856 ei->delalloc_bytes = 0;
8857 ei->new_delalloc_bytes = 0;
8858 ei->defrag_bytes = 0;
8859 ei->disk_i_size = 0;
8863 ei->index_cnt = (u64)-1;
8865 ei->last_unlink_trans = 0;
8866 ei->last_reflink_trans = 0;
8867 ei->last_log_commit = 0;
8869 spin_lock_init(&ei->lock);
8870 spin_lock_init(&ei->io_failure_lock);
8871 ei->outstanding_extents = 0;
8872 if (sb->s_magic != BTRFS_TEST_MAGIC)
8873 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8874 BTRFS_BLOCK_RSV_DELALLOC);
8875 ei->runtime_flags = 0;
8876 ei->prop_compress = BTRFS_COMPRESS_NONE;
8877 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8879 ei->delayed_node = NULL;
8881 ei->i_otime.tv_sec = 0;
8882 ei->i_otime.tv_nsec = 0;
8884 inode = &ei->vfs_inode;
8885 extent_map_tree_init(&ei->extent_tree);
8886 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8887 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8888 IO_TREE_INODE_FILE_EXTENT, NULL);
8889 ei->io_failure_tree = RB_ROOT;
8890 atomic_set(&ei->sync_writers, 0);
8891 mutex_init(&ei->log_mutex);
8892 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8893 INIT_LIST_HEAD(&ei->delalloc_inodes);
8894 INIT_LIST_HEAD(&ei->delayed_iput);
8895 RB_CLEAR_NODE(&ei->rb_node);
8896 init_rwsem(&ei->i_mmap_lock);
8901 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8902 void btrfs_test_destroy_inode(struct inode *inode)
8904 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8905 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8909 void btrfs_free_inode(struct inode *inode)
8911 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8914 void btrfs_destroy_inode(struct inode *vfs_inode)
8916 struct btrfs_ordered_extent *ordered;
8917 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8918 struct btrfs_root *root = inode->root;
8919 bool freespace_inode;
8921 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8922 WARN_ON(vfs_inode->i_data.nrpages);
8923 WARN_ON(inode->block_rsv.reserved);
8924 WARN_ON(inode->block_rsv.size);
8925 WARN_ON(inode->outstanding_extents);
8926 if (!S_ISDIR(vfs_inode->i_mode)) {
8927 WARN_ON(inode->delalloc_bytes);
8928 WARN_ON(inode->new_delalloc_bytes);
8930 WARN_ON(inode->csum_bytes);
8931 WARN_ON(inode->defrag_bytes);
8934 * This can happen where we create an inode, but somebody else also
8935 * created the same inode and we need to destroy the one we already
8942 * If this is a free space inode do not take the ordered extents lockdep
8945 freespace_inode = btrfs_is_free_space_inode(inode);
8948 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8952 btrfs_err(root->fs_info,
8953 "found ordered extent %llu %llu on inode cleanup",
8954 ordered->file_offset, ordered->num_bytes);
8956 if (!freespace_inode)
8957 btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
8959 btrfs_remove_ordered_extent(inode, ordered);
8960 btrfs_put_ordered_extent(ordered);
8961 btrfs_put_ordered_extent(ordered);
8964 btrfs_qgroup_check_reserved_leak(inode);
8965 inode_tree_del(inode);
8966 btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
8967 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8968 btrfs_put_root(inode->root);
8971 int btrfs_drop_inode(struct inode *inode)
8973 struct btrfs_root *root = BTRFS_I(inode)->root;
8978 /* the snap/subvol tree is on deleting */
8979 if (btrfs_root_refs(&root->root_item) == 0)
8982 return generic_drop_inode(inode);
8985 static void init_once(void *foo)
8987 struct btrfs_inode *ei = foo;
8989 inode_init_once(&ei->vfs_inode);
8992 void __cold btrfs_destroy_cachep(void)
8995 * Make sure all delayed rcu free inodes are flushed before we
8999 bioset_exit(&btrfs_dio_bioset);
9000 kmem_cache_destroy(btrfs_inode_cachep);
9003 int __init btrfs_init_cachep(void)
9005 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9006 sizeof(struct btrfs_inode), 0,
9007 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9009 if (!btrfs_inode_cachep)
9012 if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE,
9013 offsetof(struct btrfs_dio_private, bio),
9019 btrfs_destroy_cachep();
9023 static int btrfs_getattr(struct user_namespace *mnt_userns,
9024 const struct path *path, struct kstat *stat,
9025 u32 request_mask, unsigned int flags)
9029 struct inode *inode = d_inode(path->dentry);
9030 u32 blocksize = inode->i_sb->s_blocksize;
9031 u32 bi_flags = BTRFS_I(inode)->flags;
9032 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
9034 stat->result_mask |= STATX_BTIME;
9035 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9036 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9037 if (bi_flags & BTRFS_INODE_APPEND)
9038 stat->attributes |= STATX_ATTR_APPEND;
9039 if (bi_flags & BTRFS_INODE_COMPRESS)
9040 stat->attributes |= STATX_ATTR_COMPRESSED;
9041 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9042 stat->attributes |= STATX_ATTR_IMMUTABLE;
9043 if (bi_flags & BTRFS_INODE_NODUMP)
9044 stat->attributes |= STATX_ATTR_NODUMP;
9045 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
9046 stat->attributes |= STATX_ATTR_VERITY;
9048 stat->attributes_mask |= (STATX_ATTR_APPEND |
9049 STATX_ATTR_COMPRESSED |
9050 STATX_ATTR_IMMUTABLE |
9053 generic_fillattr(mnt_userns, inode, stat);
9054 stat->dev = BTRFS_I(inode)->root->anon_dev;
9056 spin_lock(&BTRFS_I(inode)->lock);
9057 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9058 inode_bytes = inode_get_bytes(inode);
9059 spin_unlock(&BTRFS_I(inode)->lock);
9060 stat->blocks = (ALIGN(inode_bytes, blocksize) +
9061 ALIGN(delalloc_bytes, blocksize)) >> 9;
9065 static int btrfs_rename_exchange(struct inode *old_dir,
9066 struct dentry *old_dentry,
9067 struct inode *new_dir,
9068 struct dentry *new_dentry)
9070 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9071 struct btrfs_trans_handle *trans;
9072 unsigned int trans_num_items;
9073 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9074 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9075 struct inode *new_inode = new_dentry->d_inode;
9076 struct inode *old_inode = old_dentry->d_inode;
9077 struct timespec64 ctime = current_time(old_inode);
9078 struct btrfs_rename_ctx old_rename_ctx;
9079 struct btrfs_rename_ctx new_rename_ctx;
9080 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9081 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9086 bool need_abort = false;
9087 struct fscrypt_name old_fname, new_fname;
9088 struct fscrypt_str *old_name, *new_name;
9091 * For non-subvolumes allow exchange only within one subvolume, in the
9092 * same inode namespace. Two subvolumes (represented as directory) can
9093 * be exchanged as they're a logical link and have a fixed inode number.
9096 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
9097 new_ino != BTRFS_FIRST_FREE_OBJECTID))
9100 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
9104 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
9106 fscrypt_free_filename(&old_fname);
9110 old_name = &old_fname.disk_name;
9111 new_name = &new_fname.disk_name;
9113 /* close the race window with snapshot create/destroy ioctl */
9114 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9115 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9116 down_read(&fs_info->subvol_sem);
9120 * 1 to remove old dir item
9121 * 1 to remove old dir index
9122 * 1 to add new dir item
9123 * 1 to add new dir index
9124 * 1 to update parent inode
9126 * If the parents are the same, we only need to account for one
9128 trans_num_items = (old_dir == new_dir ? 9 : 10);
9129 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9131 * 1 to remove old root ref
9132 * 1 to remove old root backref
9133 * 1 to add new root ref
9134 * 1 to add new root backref
9136 trans_num_items += 4;
9139 * 1 to update inode item
9140 * 1 to remove old inode ref
9141 * 1 to add new inode ref
9143 trans_num_items += 3;
9145 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9146 trans_num_items += 4;
9148 trans_num_items += 3;
9149 trans = btrfs_start_transaction(root, trans_num_items);
9150 if (IS_ERR(trans)) {
9151 ret = PTR_ERR(trans);
9156 ret = btrfs_record_root_in_trans(trans, dest);
9162 * We need to find a free sequence number both in the source and
9163 * in the destination directory for the exchange.
9165 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9168 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9172 BTRFS_I(old_inode)->dir_index = 0ULL;
9173 BTRFS_I(new_inode)->dir_index = 0ULL;
9175 /* Reference for the source. */
9176 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9177 /* force full log commit if subvolume involved. */
9178 btrfs_set_log_full_commit(trans);
9180 ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
9181 btrfs_ino(BTRFS_I(new_dir)),
9188 /* And now for the dest. */
9189 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9190 /* force full log commit if subvolume involved. */
9191 btrfs_set_log_full_commit(trans);
9193 ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
9194 btrfs_ino(BTRFS_I(old_dir)),
9198 btrfs_abort_transaction(trans, ret);
9203 /* Update inode version and ctime/mtime. */
9204 inode_inc_iversion(old_dir);
9205 inode_inc_iversion(new_dir);
9206 inode_inc_iversion(old_inode);
9207 inode_inc_iversion(new_inode);
9208 old_dir->i_mtime = ctime;
9209 old_dir->i_ctime = ctime;
9210 new_dir->i_mtime = ctime;
9211 new_dir->i_ctime = ctime;
9212 old_inode->i_ctime = ctime;
9213 new_inode->i_ctime = ctime;
9215 if (old_dentry->d_parent != new_dentry->d_parent) {
9216 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9217 BTRFS_I(old_inode), 1);
9218 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9219 BTRFS_I(new_inode), 1);
9222 /* src is a subvolume */
9223 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9224 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9225 } else { /* src is an inode */
9226 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9227 BTRFS_I(old_dentry->d_inode),
9228 old_name, &old_rename_ctx);
9230 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9233 btrfs_abort_transaction(trans, ret);
9237 /* dest is a subvolume */
9238 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9239 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9240 } else { /* dest is an inode */
9241 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9242 BTRFS_I(new_dentry->d_inode),
9243 new_name, &new_rename_ctx);
9245 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9248 btrfs_abort_transaction(trans, ret);
9252 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9253 new_name, 0, old_idx);
9255 btrfs_abort_transaction(trans, ret);
9259 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9260 old_name, 0, new_idx);
9262 btrfs_abort_transaction(trans, ret);
9266 if (old_inode->i_nlink == 1)
9267 BTRFS_I(old_inode)->dir_index = old_idx;
9268 if (new_inode->i_nlink == 1)
9269 BTRFS_I(new_inode)->dir_index = new_idx;
9272 * Now pin the logs of the roots. We do it to ensure that no other task
9273 * can sync the logs while we are in progress with the rename, because
9274 * that could result in an inconsistency in case any of the inodes that
9275 * are part of this rename operation were logged before.
9277 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9278 btrfs_pin_log_trans(root);
9279 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9280 btrfs_pin_log_trans(dest);
9282 /* Do the log updates for all inodes. */
9283 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9284 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9285 old_rename_ctx.index, new_dentry->d_parent);
9286 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9287 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
9288 new_rename_ctx.index, old_dentry->d_parent);
9290 /* Now unpin the logs. */
9291 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9292 btrfs_end_log_trans(root);
9293 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9294 btrfs_end_log_trans(dest);
9296 ret2 = btrfs_end_transaction(trans);
9297 ret = ret ? ret : ret2;
9299 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9300 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9301 up_read(&fs_info->subvol_sem);
9303 fscrypt_free_filename(&new_fname);
9304 fscrypt_free_filename(&old_fname);
9308 static struct inode *new_whiteout_inode(struct user_namespace *mnt_userns,
9311 struct inode *inode;
9313 inode = new_inode(dir->i_sb);
9315 inode_init_owner(mnt_userns, inode, dir,
9316 S_IFCHR | WHITEOUT_MODE);
9317 inode->i_op = &btrfs_special_inode_operations;
9318 init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
9323 static int btrfs_rename(struct user_namespace *mnt_userns,
9324 struct inode *old_dir, struct dentry *old_dentry,
9325 struct inode *new_dir, struct dentry *new_dentry,
9328 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9329 struct btrfs_new_inode_args whiteout_args = {
9331 .dentry = old_dentry,
9333 struct btrfs_trans_handle *trans;
9334 unsigned int trans_num_items;
9335 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9336 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9337 struct inode *new_inode = d_inode(new_dentry);
9338 struct inode *old_inode = d_inode(old_dentry);
9339 struct btrfs_rename_ctx rename_ctx;
9343 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9344 struct fscrypt_name old_fname, new_fname;
9346 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9349 /* we only allow rename subvolume link between subvolumes */
9350 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9353 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9354 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9357 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9358 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9361 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
9365 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
9367 fscrypt_free_filename(&old_fname);
9371 /* check for collisions, even if the name isn't there */
9372 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
9374 if (ret == -EEXIST) {
9376 * eexist without a new_inode */
9377 if (WARN_ON(!new_inode)) {
9378 goto out_fscrypt_names;
9381 /* maybe -EOVERFLOW */
9382 goto out_fscrypt_names;
9388 * we're using rename to replace one file with another. Start IO on it
9389 * now so we don't add too much work to the end of the transaction
9391 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9392 filemap_flush(old_inode->i_mapping);
9394 if (flags & RENAME_WHITEOUT) {
9395 whiteout_args.inode = new_whiteout_inode(mnt_userns, old_dir);
9396 if (!whiteout_args.inode)
9398 ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
9400 goto out_whiteout_inode;
9402 /* 1 to update the old parent inode. */
9403 trans_num_items = 1;
9406 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9407 /* Close the race window with snapshot create/destroy ioctl */
9408 down_read(&fs_info->subvol_sem);
9410 * 1 to remove old root ref
9411 * 1 to remove old root backref
9412 * 1 to add new root ref
9413 * 1 to add new root backref
9415 trans_num_items += 4;
9419 * 1 to remove old inode ref
9420 * 1 to add new inode ref
9422 trans_num_items += 3;
9425 * 1 to remove old dir item
9426 * 1 to remove old dir index
9427 * 1 to add new dir item
9428 * 1 to add new dir index
9430 trans_num_items += 4;
9431 /* 1 to update new parent inode if it's not the same as the old parent */
9432 if (new_dir != old_dir)
9437 * 1 to remove inode ref
9438 * 1 to remove dir item
9439 * 1 to remove dir index
9440 * 1 to possibly add orphan item
9442 trans_num_items += 5;
9444 trans = btrfs_start_transaction(root, trans_num_items);
9445 if (IS_ERR(trans)) {
9446 ret = PTR_ERR(trans);
9451 ret = btrfs_record_root_in_trans(trans, dest);
9456 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9460 BTRFS_I(old_inode)->dir_index = 0ULL;
9461 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9462 /* force full log commit if subvolume involved. */
9463 btrfs_set_log_full_commit(trans);
9465 ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
9466 old_ino, btrfs_ino(BTRFS_I(new_dir)),
9472 inode_inc_iversion(old_dir);
9473 inode_inc_iversion(new_dir);
9474 inode_inc_iversion(old_inode);
9475 old_dir->i_mtime = current_time(old_dir);
9476 old_dir->i_ctime = old_dir->i_mtime;
9477 new_dir->i_mtime = old_dir->i_mtime;
9478 new_dir->i_ctime = old_dir->i_mtime;
9479 old_inode->i_ctime = old_dir->i_mtime;
9481 if (old_dentry->d_parent != new_dentry->d_parent)
9482 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9483 BTRFS_I(old_inode), 1);
9485 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9486 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9488 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9489 BTRFS_I(d_inode(old_dentry)),
9490 &old_fname.disk_name, &rename_ctx);
9492 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9495 btrfs_abort_transaction(trans, ret);
9500 inode_inc_iversion(new_inode);
9501 new_inode->i_ctime = current_time(new_inode);
9502 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9503 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9504 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9505 BUG_ON(new_inode->i_nlink == 0);
9507 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9508 BTRFS_I(d_inode(new_dentry)),
9509 &new_fname.disk_name);
9511 if (!ret && new_inode->i_nlink == 0)
9512 ret = btrfs_orphan_add(trans,
9513 BTRFS_I(d_inode(new_dentry)));
9515 btrfs_abort_transaction(trans, ret);
9520 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9521 &new_fname.disk_name, 0, index);
9523 btrfs_abort_transaction(trans, ret);
9527 if (old_inode->i_nlink == 1)
9528 BTRFS_I(old_inode)->dir_index = index;
9530 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9531 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9532 rename_ctx.index, new_dentry->d_parent);
9534 if (flags & RENAME_WHITEOUT) {
9535 ret = btrfs_create_new_inode(trans, &whiteout_args);
9537 btrfs_abort_transaction(trans, ret);
9540 unlock_new_inode(whiteout_args.inode);
9541 iput(whiteout_args.inode);
9542 whiteout_args.inode = NULL;
9546 ret2 = btrfs_end_transaction(trans);
9547 ret = ret ? ret : ret2;
9549 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9550 up_read(&fs_info->subvol_sem);
9551 if (flags & RENAME_WHITEOUT)
9552 btrfs_new_inode_args_destroy(&whiteout_args);
9554 if (flags & RENAME_WHITEOUT)
9555 iput(whiteout_args.inode);
9557 fscrypt_free_filename(&old_fname);
9558 fscrypt_free_filename(&new_fname);
9562 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9563 struct dentry *old_dentry, struct inode *new_dir,
9564 struct dentry *new_dentry, unsigned int flags)
9568 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9571 if (flags & RENAME_EXCHANGE)
9572 ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9575 ret = btrfs_rename(mnt_userns, old_dir, old_dentry, new_dir,
9578 btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
9583 struct btrfs_delalloc_work {
9584 struct inode *inode;
9585 struct completion completion;
9586 struct list_head list;
9587 struct btrfs_work work;
9590 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9592 struct btrfs_delalloc_work *delalloc_work;
9593 struct inode *inode;
9595 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9597 inode = delalloc_work->inode;
9598 filemap_flush(inode->i_mapping);
9599 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9600 &BTRFS_I(inode)->runtime_flags))
9601 filemap_flush(inode->i_mapping);
9604 complete(&delalloc_work->completion);
9607 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9609 struct btrfs_delalloc_work *work;
9611 work = kmalloc(sizeof(*work), GFP_NOFS);
9615 init_completion(&work->completion);
9616 INIT_LIST_HEAD(&work->list);
9617 work->inode = inode;
9618 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9624 * some fairly slow code that needs optimization. This walks the list
9625 * of all the inodes with pending delalloc and forces them to disk.
9627 static int start_delalloc_inodes(struct btrfs_root *root,
9628 struct writeback_control *wbc, bool snapshot,
9629 bool in_reclaim_context)
9631 struct btrfs_inode *binode;
9632 struct inode *inode;
9633 struct btrfs_delalloc_work *work, *next;
9634 struct list_head works;
9635 struct list_head splice;
9637 bool full_flush = wbc->nr_to_write == LONG_MAX;
9639 INIT_LIST_HEAD(&works);
9640 INIT_LIST_HEAD(&splice);
9642 mutex_lock(&root->delalloc_mutex);
9643 spin_lock(&root->delalloc_lock);
9644 list_splice_init(&root->delalloc_inodes, &splice);
9645 while (!list_empty(&splice)) {
9646 binode = list_entry(splice.next, struct btrfs_inode,
9649 list_move_tail(&binode->delalloc_inodes,
9650 &root->delalloc_inodes);
9652 if (in_reclaim_context &&
9653 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9656 inode = igrab(&binode->vfs_inode);
9658 cond_resched_lock(&root->delalloc_lock);
9661 spin_unlock(&root->delalloc_lock);
9664 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9665 &binode->runtime_flags);
9667 work = btrfs_alloc_delalloc_work(inode);
9673 list_add_tail(&work->list, &works);
9674 btrfs_queue_work(root->fs_info->flush_workers,
9677 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9678 btrfs_add_delayed_iput(inode);
9679 if (ret || wbc->nr_to_write <= 0)
9683 spin_lock(&root->delalloc_lock);
9685 spin_unlock(&root->delalloc_lock);
9688 list_for_each_entry_safe(work, next, &works, list) {
9689 list_del_init(&work->list);
9690 wait_for_completion(&work->completion);
9694 if (!list_empty(&splice)) {
9695 spin_lock(&root->delalloc_lock);
9696 list_splice_tail(&splice, &root->delalloc_inodes);
9697 spin_unlock(&root->delalloc_lock);
9699 mutex_unlock(&root->delalloc_mutex);
9703 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9705 struct writeback_control wbc = {
9706 .nr_to_write = LONG_MAX,
9707 .sync_mode = WB_SYNC_NONE,
9709 .range_end = LLONG_MAX,
9711 struct btrfs_fs_info *fs_info = root->fs_info;
9713 if (BTRFS_FS_ERROR(fs_info))
9716 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9719 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9720 bool in_reclaim_context)
9722 struct writeback_control wbc = {
9724 .sync_mode = WB_SYNC_NONE,
9726 .range_end = LLONG_MAX,
9728 struct btrfs_root *root;
9729 struct list_head splice;
9732 if (BTRFS_FS_ERROR(fs_info))
9735 INIT_LIST_HEAD(&splice);
9737 mutex_lock(&fs_info->delalloc_root_mutex);
9738 spin_lock(&fs_info->delalloc_root_lock);
9739 list_splice_init(&fs_info->delalloc_roots, &splice);
9740 while (!list_empty(&splice)) {
9742 * Reset nr_to_write here so we know that we're doing a full
9746 wbc.nr_to_write = LONG_MAX;
9748 root = list_first_entry(&splice, struct btrfs_root,
9750 root = btrfs_grab_root(root);
9752 list_move_tail(&root->delalloc_root,
9753 &fs_info->delalloc_roots);
9754 spin_unlock(&fs_info->delalloc_root_lock);
9756 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9757 btrfs_put_root(root);
9758 if (ret < 0 || wbc.nr_to_write <= 0)
9760 spin_lock(&fs_info->delalloc_root_lock);
9762 spin_unlock(&fs_info->delalloc_root_lock);
9766 if (!list_empty(&splice)) {
9767 spin_lock(&fs_info->delalloc_root_lock);
9768 list_splice_tail(&splice, &fs_info->delalloc_roots);
9769 spin_unlock(&fs_info->delalloc_root_lock);
9771 mutex_unlock(&fs_info->delalloc_root_mutex);
9775 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9776 struct dentry *dentry, const char *symname)
9778 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9779 struct btrfs_trans_handle *trans;
9780 struct btrfs_root *root = BTRFS_I(dir)->root;
9781 struct btrfs_path *path;
9782 struct btrfs_key key;
9783 struct inode *inode;
9784 struct btrfs_new_inode_args new_inode_args = {
9788 unsigned int trans_num_items;
9793 struct btrfs_file_extent_item *ei;
9794 struct extent_buffer *leaf;
9796 name_len = strlen(symname);
9797 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9798 return -ENAMETOOLONG;
9800 inode = new_inode(dir->i_sb);
9803 inode_init_owner(mnt_userns, inode, dir, S_IFLNK | S_IRWXUGO);
9804 inode->i_op = &btrfs_symlink_inode_operations;
9805 inode_nohighmem(inode);
9806 inode->i_mapping->a_ops = &btrfs_aops;
9807 btrfs_i_size_write(BTRFS_I(inode), name_len);
9808 inode_set_bytes(inode, name_len);
9810 new_inode_args.inode = inode;
9811 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9814 /* 1 additional item for the inline extent */
9817 trans = btrfs_start_transaction(root, trans_num_items);
9818 if (IS_ERR(trans)) {
9819 err = PTR_ERR(trans);
9820 goto out_new_inode_args;
9823 err = btrfs_create_new_inode(trans, &new_inode_args);
9827 path = btrfs_alloc_path();
9830 btrfs_abort_transaction(trans, err);
9831 discard_new_inode(inode);
9835 key.objectid = btrfs_ino(BTRFS_I(inode));
9837 key.type = BTRFS_EXTENT_DATA_KEY;
9838 datasize = btrfs_file_extent_calc_inline_size(name_len);
9839 err = btrfs_insert_empty_item(trans, root, path, &key,
9842 btrfs_abort_transaction(trans, err);
9843 btrfs_free_path(path);
9844 discard_new_inode(inode);
9848 leaf = path->nodes[0];
9849 ei = btrfs_item_ptr(leaf, path->slots[0],
9850 struct btrfs_file_extent_item);
9851 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9852 btrfs_set_file_extent_type(leaf, ei,
9853 BTRFS_FILE_EXTENT_INLINE);
9854 btrfs_set_file_extent_encryption(leaf, ei, 0);
9855 btrfs_set_file_extent_compression(leaf, ei, 0);
9856 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9857 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9859 ptr = btrfs_file_extent_inline_start(ei);
9860 write_extent_buffer(leaf, symname, ptr, name_len);
9861 btrfs_mark_buffer_dirty(leaf);
9862 btrfs_free_path(path);
9864 d_instantiate_new(dentry, inode);
9867 btrfs_end_transaction(trans);
9868 btrfs_btree_balance_dirty(fs_info);
9870 btrfs_new_inode_args_destroy(&new_inode_args);
9877 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9878 struct btrfs_trans_handle *trans_in,
9879 struct btrfs_inode *inode,
9880 struct btrfs_key *ins,
9883 struct btrfs_file_extent_item stack_fi;
9884 struct btrfs_replace_extent_info extent_info;
9885 struct btrfs_trans_handle *trans = trans_in;
9886 struct btrfs_path *path;
9887 u64 start = ins->objectid;
9888 u64 len = ins->offset;
9889 int qgroup_released;
9892 memset(&stack_fi, 0, sizeof(stack_fi));
9894 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9895 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9896 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9897 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9898 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9899 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9900 /* Encryption and other encoding is reserved and all 0 */
9902 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9903 if (qgroup_released < 0)
9904 return ERR_PTR(qgroup_released);
9907 ret = insert_reserved_file_extent(trans, inode,
9908 file_offset, &stack_fi,
9909 true, qgroup_released);
9915 extent_info.disk_offset = start;
9916 extent_info.disk_len = len;
9917 extent_info.data_offset = 0;
9918 extent_info.data_len = len;
9919 extent_info.file_offset = file_offset;
9920 extent_info.extent_buf = (char *)&stack_fi;
9921 extent_info.is_new_extent = true;
9922 extent_info.update_times = true;
9923 extent_info.qgroup_reserved = qgroup_released;
9924 extent_info.insertions = 0;
9926 path = btrfs_alloc_path();
9932 ret = btrfs_replace_file_extents(inode, path, file_offset,
9933 file_offset + len - 1, &extent_info,
9935 btrfs_free_path(path);
9942 * We have released qgroup data range at the beginning of the function,
9943 * and normally qgroup_released bytes will be freed when committing
9945 * But if we error out early, we have to free what we have released
9946 * or we leak qgroup data reservation.
9948 btrfs_qgroup_free_refroot(inode->root->fs_info,
9949 inode->root->root_key.objectid, qgroup_released,
9950 BTRFS_QGROUP_RSV_DATA);
9951 return ERR_PTR(ret);
9954 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9955 u64 start, u64 num_bytes, u64 min_size,
9956 loff_t actual_len, u64 *alloc_hint,
9957 struct btrfs_trans_handle *trans)
9959 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9960 struct extent_map *em;
9961 struct btrfs_root *root = BTRFS_I(inode)->root;
9962 struct btrfs_key ins;
9963 u64 cur_offset = start;
9964 u64 clear_offset = start;
9967 u64 last_alloc = (u64)-1;
9969 bool own_trans = true;
9970 u64 end = start + num_bytes - 1;
9974 while (num_bytes > 0) {
9975 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9976 cur_bytes = max(cur_bytes, min_size);
9978 * If we are severely fragmented we could end up with really
9979 * small allocations, so if the allocator is returning small
9980 * chunks lets make its job easier by only searching for those
9983 cur_bytes = min(cur_bytes, last_alloc);
9984 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9985 min_size, 0, *alloc_hint, &ins, 1, 0);
9990 * We've reserved this space, and thus converted it from
9991 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9992 * from here on out we will only need to clear our reservation
9993 * for the remaining unreserved area, so advance our
9994 * clear_offset by our extent size.
9996 clear_offset += ins.offset;
9998 last_alloc = ins.offset;
9999 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
10002 * Now that we inserted the prealloc extent we can finally
10003 * decrement the number of reservations in the block group.
10004 * If we did it before, we could race with relocation and have
10005 * relocation miss the reserved extent, making it fail later.
10007 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10008 if (IS_ERR(trans)) {
10009 ret = PTR_ERR(trans);
10010 btrfs_free_reserved_extent(fs_info, ins.objectid,
10015 em = alloc_extent_map();
10017 btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
10018 cur_offset + ins.offset - 1, false);
10019 btrfs_set_inode_full_sync(BTRFS_I(inode));
10023 em->start = cur_offset;
10024 em->orig_start = cur_offset;
10025 em->len = ins.offset;
10026 em->block_start = ins.objectid;
10027 em->block_len = ins.offset;
10028 em->orig_block_len = ins.offset;
10029 em->ram_bytes = ins.offset;
10030 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10031 em->generation = trans->transid;
10033 ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
10034 free_extent_map(em);
10036 num_bytes -= ins.offset;
10037 cur_offset += ins.offset;
10038 *alloc_hint = ins.objectid + ins.offset;
10040 inode_inc_iversion(inode);
10041 inode->i_ctime = current_time(inode);
10042 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10043 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10044 (actual_len > inode->i_size) &&
10045 (cur_offset > inode->i_size)) {
10046 if (cur_offset > actual_len)
10047 i_size = actual_len;
10049 i_size = cur_offset;
10050 i_size_write(inode, i_size);
10051 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10054 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10057 btrfs_abort_transaction(trans, ret);
10059 btrfs_end_transaction(trans);
10064 btrfs_end_transaction(trans);
10068 if (clear_offset < end)
10069 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10070 end - clear_offset + 1);
10074 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10075 u64 start, u64 num_bytes, u64 min_size,
10076 loff_t actual_len, u64 *alloc_hint)
10078 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10079 min_size, actual_len, alloc_hint,
10083 int btrfs_prealloc_file_range_trans(struct inode *inode,
10084 struct btrfs_trans_handle *trans, int mode,
10085 u64 start, u64 num_bytes, u64 min_size,
10086 loff_t actual_len, u64 *alloc_hint)
10088 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10089 min_size, actual_len, alloc_hint, trans);
10092 static int btrfs_permission(struct user_namespace *mnt_userns,
10093 struct inode *inode, int mask)
10095 struct btrfs_root *root = BTRFS_I(inode)->root;
10096 umode_t mode = inode->i_mode;
10098 if (mask & MAY_WRITE &&
10099 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10100 if (btrfs_root_readonly(root))
10102 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10105 return generic_permission(mnt_userns, inode, mask);
10108 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10109 struct file *file, umode_t mode)
10111 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10112 struct btrfs_trans_handle *trans;
10113 struct btrfs_root *root = BTRFS_I(dir)->root;
10114 struct inode *inode;
10115 struct btrfs_new_inode_args new_inode_args = {
10117 .dentry = file->f_path.dentry,
10120 unsigned int trans_num_items;
10123 inode = new_inode(dir->i_sb);
10126 inode_init_owner(mnt_userns, inode, dir, mode);
10127 inode->i_fop = &btrfs_file_operations;
10128 inode->i_op = &btrfs_file_inode_operations;
10129 inode->i_mapping->a_ops = &btrfs_aops;
10131 new_inode_args.inode = inode;
10132 ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
10136 trans = btrfs_start_transaction(root, trans_num_items);
10137 if (IS_ERR(trans)) {
10138 ret = PTR_ERR(trans);
10139 goto out_new_inode_args;
10142 ret = btrfs_create_new_inode(trans, &new_inode_args);
10145 * We set number of links to 0 in btrfs_create_new_inode(), and here we
10146 * set it to 1 because d_tmpfile() will issue a warning if the count is
10149 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10151 set_nlink(inode, 1);
10154 d_tmpfile(file, inode);
10155 unlock_new_inode(inode);
10156 mark_inode_dirty(inode);
10159 btrfs_end_transaction(trans);
10160 btrfs_btree_balance_dirty(fs_info);
10161 out_new_inode_args:
10162 btrfs_new_inode_args_destroy(&new_inode_args);
10166 return finish_open_simple(file, ret);
10169 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
10171 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10172 unsigned long index = start >> PAGE_SHIFT;
10173 unsigned long end_index = end >> PAGE_SHIFT;
10177 ASSERT(end + 1 - start <= U32_MAX);
10178 len = end + 1 - start;
10179 while (index <= end_index) {
10180 page = find_get_page(inode->vfs_inode.i_mapping, index);
10181 ASSERT(page); /* Pages should be in the extent_io_tree */
10183 btrfs_page_set_writeback(fs_info, page, start, len);
10189 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
10192 switch (compress_type) {
10193 case BTRFS_COMPRESS_NONE:
10194 return BTRFS_ENCODED_IO_COMPRESSION_NONE;
10195 case BTRFS_COMPRESS_ZLIB:
10196 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
10197 case BTRFS_COMPRESS_LZO:
10199 * The LZO format depends on the sector size. 64K is the maximum
10200 * sector size that we support.
10202 if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
10204 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
10205 (fs_info->sectorsize_bits - 12);
10206 case BTRFS_COMPRESS_ZSTD:
10207 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
10213 static ssize_t btrfs_encoded_read_inline(
10214 struct kiocb *iocb,
10215 struct iov_iter *iter, u64 start,
10217 struct extent_state **cached_state,
10218 u64 extent_start, size_t count,
10219 struct btrfs_ioctl_encoded_io_args *encoded,
10222 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10223 struct btrfs_root *root = inode->root;
10224 struct btrfs_fs_info *fs_info = root->fs_info;
10225 struct extent_io_tree *io_tree = &inode->io_tree;
10226 struct btrfs_path *path;
10227 struct extent_buffer *leaf;
10228 struct btrfs_file_extent_item *item;
10234 path = btrfs_alloc_path();
10239 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
10243 /* The extent item disappeared? */
10248 leaf = path->nodes[0];
10249 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10251 ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
10252 ptr = btrfs_file_extent_inline_start(item);
10254 encoded->len = min_t(u64, extent_start + ram_bytes,
10255 inode->vfs_inode.i_size) - iocb->ki_pos;
10256 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10257 btrfs_file_extent_compression(leaf, item));
10260 encoded->compression = ret;
10261 if (encoded->compression) {
10262 size_t inline_size;
10264 inline_size = btrfs_file_extent_inline_item_len(leaf,
10266 if (inline_size > count) {
10270 count = inline_size;
10271 encoded->unencoded_len = ram_bytes;
10272 encoded->unencoded_offset = iocb->ki_pos - extent_start;
10274 count = min_t(u64, count, encoded->len);
10275 encoded->len = count;
10276 encoded->unencoded_len = count;
10277 ptr += iocb->ki_pos - extent_start;
10280 tmp = kmalloc(count, GFP_NOFS);
10285 read_extent_buffer(leaf, tmp, ptr, count);
10286 btrfs_release_path(path);
10287 unlock_extent(io_tree, start, lockend, cached_state);
10288 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10291 ret = copy_to_iter(tmp, count, iter);
10296 btrfs_free_path(path);
10300 struct btrfs_encoded_read_private {
10301 struct btrfs_inode *inode;
10303 wait_queue_head_t wait;
10305 blk_status_t status;
10309 static blk_status_t submit_encoded_read_bio(struct btrfs_inode *inode,
10310 struct bio *bio, int mirror_num)
10312 struct btrfs_encoded_read_private *priv = btrfs_bio(bio)->private;
10313 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10316 if (!priv->skip_csum) {
10317 ret = btrfs_lookup_bio_sums(&inode->vfs_inode, bio, NULL);
10322 atomic_inc(&priv->pending);
10323 btrfs_submit_bio(fs_info, bio, mirror_num);
10327 static blk_status_t btrfs_encoded_read_verify_csum(struct btrfs_bio *bbio)
10329 const bool uptodate = (bbio->bio.bi_status == BLK_STS_OK);
10330 struct btrfs_encoded_read_private *priv = bbio->private;
10331 struct btrfs_inode *inode = priv->inode;
10332 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10333 u32 sectorsize = fs_info->sectorsize;
10334 struct bio_vec *bvec;
10335 struct bvec_iter_all iter_all;
10336 u32 bio_offset = 0;
10338 if (priv->skip_csum || !uptodate)
10339 return bbio->bio.bi_status;
10341 bio_for_each_segment_all(bvec, &bbio->bio, iter_all) {
10342 unsigned int i, nr_sectors, pgoff;
10344 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
10345 pgoff = bvec->bv_offset;
10346 for (i = 0; i < nr_sectors; i++) {
10347 ASSERT(pgoff < PAGE_SIZE);
10348 if (btrfs_check_data_csum(&inode->vfs_inode, bbio, bio_offset,
10349 bvec->bv_page, pgoff))
10350 return BLK_STS_IOERR;
10351 bio_offset += sectorsize;
10352 pgoff += sectorsize;
10358 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
10360 struct btrfs_encoded_read_private *priv = bbio->private;
10361 blk_status_t status;
10363 status = btrfs_encoded_read_verify_csum(bbio);
10366 * The memory barrier implied by the atomic_dec_return() here
10367 * pairs with the memory barrier implied by the
10368 * atomic_dec_return() or io_wait_event() in
10369 * btrfs_encoded_read_regular_fill_pages() to ensure that this
10370 * write is observed before the load of status in
10371 * btrfs_encoded_read_regular_fill_pages().
10373 WRITE_ONCE(priv->status, status);
10375 if (!atomic_dec_return(&priv->pending))
10376 wake_up(&priv->wait);
10377 btrfs_bio_free_csum(bbio);
10378 bio_put(&bbio->bio);
10381 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
10382 u64 file_offset, u64 disk_bytenr,
10383 u64 disk_io_size, struct page **pages)
10385 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10386 struct btrfs_encoded_read_private priv = {
10388 .file_offset = file_offset,
10389 .pending = ATOMIC_INIT(1),
10390 .skip_csum = (inode->flags & BTRFS_INODE_NODATASUM),
10392 unsigned long i = 0;
10396 init_waitqueue_head(&priv.wait);
10398 * Submit bios for the extent, splitting due to bio or stripe limits as
10401 while (cur < disk_io_size) {
10402 struct extent_map *em;
10403 struct btrfs_io_geometry geom;
10404 struct bio *bio = NULL;
10407 em = btrfs_get_chunk_map(fs_info, disk_bytenr + cur,
10408 disk_io_size - cur);
10412 ret = btrfs_get_io_geometry(fs_info, em, BTRFS_MAP_READ,
10413 disk_bytenr + cur, &geom);
10414 free_extent_map(em);
10417 WRITE_ONCE(priv.status, errno_to_blk_status(ret));
10420 remaining = min(geom.len, disk_io_size - cur);
10421 while (bio || remaining) {
10422 size_t bytes = min_t(u64, remaining, PAGE_SIZE);
10425 bio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ,
10426 btrfs_encoded_read_endio,
10428 bio->bi_iter.bi_sector =
10429 (disk_bytenr + cur) >> SECTOR_SHIFT;
10433 bio_add_page(bio, pages[i], bytes, 0) < bytes) {
10434 blk_status_t status;
10436 status = submit_encoded_read_bio(inode, bio, 0);
10438 WRITE_ONCE(priv.status, status);
10448 remaining -= bytes;
10453 if (atomic_dec_return(&priv.pending))
10454 io_wait_event(priv.wait, !atomic_read(&priv.pending));
10455 /* See btrfs_encoded_read_endio() for ordering. */
10456 return blk_status_to_errno(READ_ONCE(priv.status));
10459 static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
10460 struct iov_iter *iter,
10461 u64 start, u64 lockend,
10462 struct extent_state **cached_state,
10463 u64 disk_bytenr, u64 disk_io_size,
10464 size_t count, bool compressed,
10467 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10468 struct extent_io_tree *io_tree = &inode->io_tree;
10469 struct page **pages;
10470 unsigned long nr_pages, i;
10472 size_t page_offset;
10475 nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
10476 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
10479 ret = btrfs_alloc_page_array(nr_pages, pages);
10485 ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
10486 disk_io_size, pages);
10490 unlock_extent(io_tree, start, lockend, cached_state);
10491 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10498 i = (iocb->ki_pos - start) >> PAGE_SHIFT;
10499 page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
10502 while (cur < count) {
10503 size_t bytes = min_t(size_t, count - cur,
10504 PAGE_SIZE - page_offset);
10506 if (copy_page_to_iter(pages[i], page_offset, bytes,
10517 for (i = 0; i < nr_pages; i++) {
10519 __free_page(pages[i]);
10525 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
10526 struct btrfs_ioctl_encoded_io_args *encoded)
10528 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10529 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10530 struct extent_io_tree *io_tree = &inode->io_tree;
10532 size_t count = iov_iter_count(iter);
10533 u64 start, lockend, disk_bytenr, disk_io_size;
10534 struct extent_state *cached_state = NULL;
10535 struct extent_map *em;
10536 bool unlocked = false;
10538 file_accessed(iocb->ki_filp);
10540 btrfs_inode_lock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10542 if (iocb->ki_pos >= inode->vfs_inode.i_size) {
10543 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10546 start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
10548 * We don't know how long the extent containing iocb->ki_pos is, but if
10549 * it's compressed we know that it won't be longer than this.
10551 lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
10554 struct btrfs_ordered_extent *ordered;
10556 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
10557 lockend - start + 1);
10559 goto out_unlock_inode;
10560 lock_extent(io_tree, start, lockend, &cached_state);
10561 ordered = btrfs_lookup_ordered_range(inode, start,
10562 lockend - start + 1);
10565 btrfs_put_ordered_extent(ordered);
10566 unlock_extent(io_tree, start, lockend, &cached_state);
10570 em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
10573 goto out_unlock_extent;
10576 if (em->block_start == EXTENT_MAP_INLINE) {
10577 u64 extent_start = em->start;
10580 * For inline extents we get everything we need out of the
10583 free_extent_map(em);
10585 ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
10586 &cached_state, extent_start,
10587 count, encoded, &unlocked);
10592 * We only want to return up to EOF even if the extent extends beyond
10595 encoded->len = min_t(u64, extent_map_end(em),
10596 inode->vfs_inode.i_size) - iocb->ki_pos;
10597 if (em->block_start == EXTENT_MAP_HOLE ||
10598 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
10599 disk_bytenr = EXTENT_MAP_HOLE;
10600 count = min_t(u64, count, encoded->len);
10601 encoded->len = count;
10602 encoded->unencoded_len = count;
10603 } else if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10604 disk_bytenr = em->block_start;
10606 * Bail if the buffer isn't large enough to return the whole
10607 * compressed extent.
10609 if (em->block_len > count) {
10613 disk_io_size = em->block_len;
10614 count = em->block_len;
10615 encoded->unencoded_len = em->ram_bytes;
10616 encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
10617 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10618 em->compress_type);
10621 encoded->compression = ret;
10623 disk_bytenr = em->block_start + (start - em->start);
10624 if (encoded->len > count)
10625 encoded->len = count;
10627 * Don't read beyond what we locked. This also limits the page
10628 * allocations that we'll do.
10630 disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
10631 count = start + disk_io_size - iocb->ki_pos;
10632 encoded->len = count;
10633 encoded->unencoded_len = count;
10634 disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
10636 free_extent_map(em);
10639 if (disk_bytenr == EXTENT_MAP_HOLE) {
10640 unlock_extent(io_tree, start, lockend, &cached_state);
10641 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10643 ret = iov_iter_zero(count, iter);
10647 ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
10648 &cached_state, disk_bytenr,
10649 disk_io_size, count,
10650 encoded->compression,
10656 iocb->ki_pos += encoded->len;
10658 free_extent_map(em);
10661 unlock_extent(io_tree, start, lockend, &cached_state);
10664 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10668 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
10669 const struct btrfs_ioctl_encoded_io_args *encoded)
10671 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10672 struct btrfs_root *root = inode->root;
10673 struct btrfs_fs_info *fs_info = root->fs_info;
10674 struct extent_io_tree *io_tree = &inode->io_tree;
10675 struct extent_changeset *data_reserved = NULL;
10676 struct extent_state *cached_state = NULL;
10680 u64 num_bytes, ram_bytes, disk_num_bytes;
10681 unsigned long nr_pages, i;
10682 struct page **pages;
10683 struct btrfs_key ins;
10684 bool extent_reserved = false;
10685 struct extent_map *em;
10688 switch (encoded->compression) {
10689 case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
10690 compression = BTRFS_COMPRESS_ZLIB;
10692 case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
10693 compression = BTRFS_COMPRESS_ZSTD;
10695 case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
10696 case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
10697 case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
10698 case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
10699 case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
10700 /* The sector size must match for LZO. */
10701 if (encoded->compression -
10702 BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
10703 fs_info->sectorsize_bits)
10705 compression = BTRFS_COMPRESS_LZO;
10710 if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
10713 orig_count = iov_iter_count(from);
10715 /* The extent size must be sane. */
10716 if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
10717 orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
10721 * The compressed data must be smaller than the decompressed data.
10723 * It's of course possible for data to compress to larger or the same
10724 * size, but the buffered I/O path falls back to no compression for such
10725 * data, and we don't want to break any assumptions by creating these
10728 * Note that this is less strict than the current check we have that the
10729 * compressed data must be at least one sector smaller than the
10730 * decompressed data. We only want to enforce the weaker requirement
10731 * from old kernels that it is at least one byte smaller.
10733 if (orig_count >= encoded->unencoded_len)
10736 /* The extent must start on a sector boundary. */
10737 start = iocb->ki_pos;
10738 if (!IS_ALIGNED(start, fs_info->sectorsize))
10742 * The extent must end on a sector boundary. However, we allow a write
10743 * which ends at or extends i_size to have an unaligned length; we round
10744 * up the extent size and set i_size to the unaligned end.
10746 if (start + encoded->len < inode->vfs_inode.i_size &&
10747 !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
10750 /* Finally, the offset in the unencoded data must be sector-aligned. */
10751 if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
10754 num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10755 ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10756 end = start + num_bytes - 1;
10759 * If the extent cannot be inline, the compressed data on disk must be
10760 * sector-aligned. For convenience, we extend it with zeroes if it
10763 disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10764 nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
10765 pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
10768 for (i = 0; i < nr_pages; i++) {
10769 size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
10772 pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
10777 kaddr = kmap_local_page(pages[i]);
10778 if (copy_from_iter(kaddr, bytes, from) != bytes) {
10779 kunmap_local(kaddr);
10783 if (bytes < PAGE_SIZE)
10784 memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
10785 kunmap_local(kaddr);
10789 struct btrfs_ordered_extent *ordered;
10791 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
10794 ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10795 start >> PAGE_SHIFT,
10796 end >> PAGE_SHIFT);
10799 lock_extent(io_tree, start, end, &cached_state);
10800 ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10802 !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10805 btrfs_put_ordered_extent(ordered);
10806 unlock_extent(io_tree, start, end, &cached_state);
10811 * We don't use the higher-level delalloc space functions because our
10812 * num_bytes and disk_num_bytes are different.
10814 ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10817 ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10819 goto out_free_data_space;
10820 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10823 goto out_qgroup_free_data;
10825 /* Try an inline extent first. */
10826 if (start == 0 && encoded->unencoded_len == encoded->len &&
10827 encoded->unencoded_offset == 0) {
10828 ret = cow_file_range_inline(inode, encoded->len, orig_count,
10829 compression, pages, true);
10833 goto out_delalloc_release;
10837 ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10838 disk_num_bytes, 0, 0, &ins, 1, 1);
10840 goto out_delalloc_release;
10841 extent_reserved = true;
10843 em = create_io_em(inode, start, num_bytes,
10844 start - encoded->unencoded_offset, ins.objectid,
10845 ins.offset, ins.offset, ram_bytes, compression,
10846 BTRFS_ORDERED_COMPRESSED);
10849 goto out_free_reserved;
10851 free_extent_map(em);
10853 ret = btrfs_add_ordered_extent(inode, start, num_bytes, ram_bytes,
10854 ins.objectid, ins.offset,
10855 encoded->unencoded_offset,
10856 (1 << BTRFS_ORDERED_ENCODED) |
10857 (1 << BTRFS_ORDERED_COMPRESSED),
10860 btrfs_drop_extent_map_range(inode, start, end, false);
10861 goto out_free_reserved;
10863 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10865 if (start + encoded->len > inode->vfs_inode.i_size)
10866 i_size_write(&inode->vfs_inode, start + encoded->len);
10868 unlock_extent(io_tree, start, end, &cached_state);
10870 btrfs_delalloc_release_extents(inode, num_bytes);
10872 if (btrfs_submit_compressed_write(inode, start, num_bytes, ins.objectid,
10873 ins.offset, pages, nr_pages, 0, NULL,
10875 btrfs_writepage_endio_finish_ordered(inode, pages[0], start, end, 0);
10883 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10884 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
10885 out_delalloc_release:
10886 btrfs_delalloc_release_extents(inode, num_bytes);
10887 btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10888 out_qgroup_free_data:
10890 btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes);
10891 out_free_data_space:
10893 * If btrfs_reserve_extent() succeeded, then we already decremented
10896 if (!extent_reserved)
10897 btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
10899 unlock_extent(io_tree, start, end, &cached_state);
10901 for (i = 0; i < nr_pages; i++) {
10903 __free_page(pages[i]);
10908 iocb->ki_pos += encoded->len;
10914 * Add an entry indicating a block group or device which is pinned by a
10915 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10916 * negative errno on failure.
10918 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10919 bool is_block_group)
10921 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10922 struct btrfs_swapfile_pin *sp, *entry;
10923 struct rb_node **p;
10924 struct rb_node *parent = NULL;
10926 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10931 sp->is_block_group = is_block_group;
10932 sp->bg_extent_count = 1;
10934 spin_lock(&fs_info->swapfile_pins_lock);
10935 p = &fs_info->swapfile_pins.rb_node;
10938 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10939 if (sp->ptr < entry->ptr ||
10940 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10941 p = &(*p)->rb_left;
10942 } else if (sp->ptr > entry->ptr ||
10943 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10944 p = &(*p)->rb_right;
10946 if (is_block_group)
10947 entry->bg_extent_count++;
10948 spin_unlock(&fs_info->swapfile_pins_lock);
10953 rb_link_node(&sp->node, parent, p);
10954 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10955 spin_unlock(&fs_info->swapfile_pins_lock);
10959 /* Free all of the entries pinned by this swapfile. */
10960 static void btrfs_free_swapfile_pins(struct inode *inode)
10962 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10963 struct btrfs_swapfile_pin *sp;
10964 struct rb_node *node, *next;
10966 spin_lock(&fs_info->swapfile_pins_lock);
10967 node = rb_first(&fs_info->swapfile_pins);
10969 next = rb_next(node);
10970 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10971 if (sp->inode == inode) {
10972 rb_erase(&sp->node, &fs_info->swapfile_pins);
10973 if (sp->is_block_group) {
10974 btrfs_dec_block_group_swap_extents(sp->ptr,
10975 sp->bg_extent_count);
10976 btrfs_put_block_group(sp->ptr);
10982 spin_unlock(&fs_info->swapfile_pins_lock);
10985 struct btrfs_swap_info {
10991 unsigned long nr_pages;
10995 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10996 struct btrfs_swap_info *bsi)
10998 unsigned long nr_pages;
10999 unsigned long max_pages;
11000 u64 first_ppage, first_ppage_reported, next_ppage;
11004 * Our swapfile may have had its size extended after the swap header was
11005 * written. In that case activating the swapfile should not go beyond
11006 * the max size set in the swap header.
11008 if (bsi->nr_pages >= sis->max)
11011 max_pages = sis->max - bsi->nr_pages;
11012 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
11013 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
11014 PAGE_SIZE) >> PAGE_SHIFT;
11016 if (first_ppage >= next_ppage)
11018 nr_pages = next_ppage - first_ppage;
11019 nr_pages = min(nr_pages, max_pages);
11021 first_ppage_reported = first_ppage;
11022 if (bsi->start == 0)
11023 first_ppage_reported++;
11024 if (bsi->lowest_ppage > first_ppage_reported)
11025 bsi->lowest_ppage = first_ppage_reported;
11026 if (bsi->highest_ppage < (next_ppage - 1))
11027 bsi->highest_ppage = next_ppage - 1;
11029 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
11032 bsi->nr_extents += ret;
11033 bsi->nr_pages += nr_pages;
11037 static void btrfs_swap_deactivate(struct file *file)
11039 struct inode *inode = file_inode(file);
11041 btrfs_free_swapfile_pins(inode);
11042 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
11045 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
11048 struct inode *inode = file_inode(file);
11049 struct btrfs_root *root = BTRFS_I(inode)->root;
11050 struct btrfs_fs_info *fs_info = root->fs_info;
11051 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
11052 struct extent_state *cached_state = NULL;
11053 struct extent_map *em = NULL;
11054 struct btrfs_device *device = NULL;
11055 struct btrfs_swap_info bsi = {
11056 .lowest_ppage = (sector_t)-1ULL,
11063 * If the swap file was just created, make sure delalloc is done. If the
11064 * file changes again after this, the user is doing something stupid and
11065 * we don't really care.
11067 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
11072 * The inode is locked, so these flags won't change after we check them.
11074 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
11075 btrfs_warn(fs_info, "swapfile must not be compressed");
11078 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
11079 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
11082 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
11083 btrfs_warn(fs_info, "swapfile must not be checksummed");
11088 * Balance or device remove/replace/resize can move stuff around from
11089 * under us. The exclop protection makes sure they aren't running/won't
11090 * run concurrently while we are mapping the swap extents, and
11091 * fs_info->swapfile_pins prevents them from running while the swap
11092 * file is active and moving the extents. Note that this also prevents
11093 * a concurrent device add which isn't actually necessary, but it's not
11094 * really worth the trouble to allow it.
11096 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
11097 btrfs_warn(fs_info,
11098 "cannot activate swapfile while exclusive operation is running");
11103 * Prevent snapshot creation while we are activating the swap file.
11104 * We do not want to race with snapshot creation. If snapshot creation
11105 * already started before we bumped nr_swapfiles from 0 to 1 and
11106 * completes before the first write into the swap file after it is
11107 * activated, than that write would fallback to COW.
11109 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
11110 btrfs_exclop_finish(fs_info);
11111 btrfs_warn(fs_info,
11112 "cannot activate swapfile because snapshot creation is in progress");
11116 * Snapshots can create extents which require COW even if NODATACOW is
11117 * set. We use this counter to prevent snapshots. We must increment it
11118 * before walking the extents because we don't want a concurrent
11119 * snapshot to run after we've already checked the extents.
11121 * It is possible that subvolume is marked for deletion but still not
11122 * removed yet. To prevent this race, we check the root status before
11123 * activating the swapfile.
11125 spin_lock(&root->root_item_lock);
11126 if (btrfs_root_dead(root)) {
11127 spin_unlock(&root->root_item_lock);
11129 btrfs_exclop_finish(fs_info);
11130 btrfs_warn(fs_info,
11131 "cannot activate swapfile because subvolume %llu is being deleted",
11132 root->root_key.objectid);
11135 atomic_inc(&root->nr_swapfiles);
11136 spin_unlock(&root->root_item_lock);
11138 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
11140 lock_extent(io_tree, 0, isize - 1, &cached_state);
11142 while (start < isize) {
11143 u64 logical_block_start, physical_block_start;
11144 struct btrfs_block_group *bg;
11145 u64 len = isize - start;
11147 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
11153 if (em->block_start == EXTENT_MAP_HOLE) {
11154 btrfs_warn(fs_info, "swapfile must not have holes");
11158 if (em->block_start == EXTENT_MAP_INLINE) {
11160 * It's unlikely we'll ever actually find ourselves
11161 * here, as a file small enough to fit inline won't be
11162 * big enough to store more than the swap header, but in
11163 * case something changes in the future, let's catch it
11164 * here rather than later.
11166 btrfs_warn(fs_info, "swapfile must not be inline");
11170 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
11171 btrfs_warn(fs_info, "swapfile must not be compressed");
11176 logical_block_start = em->block_start + (start - em->start);
11177 len = min(len, em->len - (start - em->start));
11178 free_extent_map(em);
11181 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, false, true);
11187 btrfs_warn(fs_info,
11188 "swapfile must not be copy-on-write");
11193 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
11199 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
11200 btrfs_warn(fs_info,
11201 "swapfile must have single data profile");
11206 if (device == NULL) {
11207 device = em->map_lookup->stripes[0].dev;
11208 ret = btrfs_add_swapfile_pin(inode, device, false);
11213 } else if (device != em->map_lookup->stripes[0].dev) {
11214 btrfs_warn(fs_info, "swapfile must be on one device");
11219 physical_block_start = (em->map_lookup->stripes[0].physical +
11220 (logical_block_start - em->start));
11221 len = min(len, em->len - (logical_block_start - em->start));
11222 free_extent_map(em);
11225 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
11227 btrfs_warn(fs_info,
11228 "could not find block group containing swapfile");
11233 if (!btrfs_inc_block_group_swap_extents(bg)) {
11234 btrfs_warn(fs_info,
11235 "block group for swapfile at %llu is read-only%s",
11237 atomic_read(&fs_info->scrubs_running) ?
11238 " (scrub running)" : "");
11239 btrfs_put_block_group(bg);
11244 ret = btrfs_add_swapfile_pin(inode, bg, true);
11246 btrfs_put_block_group(bg);
11253 if (bsi.block_len &&
11254 bsi.block_start + bsi.block_len == physical_block_start) {
11255 bsi.block_len += len;
11257 if (bsi.block_len) {
11258 ret = btrfs_add_swap_extent(sis, &bsi);
11263 bsi.block_start = physical_block_start;
11264 bsi.block_len = len;
11271 ret = btrfs_add_swap_extent(sis, &bsi);
11274 if (!IS_ERR_OR_NULL(em))
11275 free_extent_map(em);
11277 unlock_extent(io_tree, 0, isize - 1, &cached_state);
11280 btrfs_swap_deactivate(file);
11282 btrfs_drew_write_unlock(&root->snapshot_lock);
11284 btrfs_exclop_finish(fs_info);
11290 sis->bdev = device->bdev;
11291 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
11292 sis->max = bsi.nr_pages;
11293 sis->pages = bsi.nr_pages - 1;
11294 sis->highest_bit = bsi.nr_pages - 1;
11295 return bsi.nr_extents;
11298 static void btrfs_swap_deactivate(struct file *file)
11302 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
11305 return -EOPNOTSUPP;
11310 * Update the number of bytes used in the VFS' inode. When we replace extents in
11311 * a range (clone, dedupe, fallocate's zero range), we must update the number of
11312 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
11313 * always get a correct value.
11315 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
11316 const u64 add_bytes,
11317 const u64 del_bytes)
11319 if (add_bytes == del_bytes)
11322 spin_lock(&inode->lock);
11324 inode_sub_bytes(&inode->vfs_inode, del_bytes);
11326 inode_add_bytes(&inode->vfs_inode, add_bytes);
11327 spin_unlock(&inode->lock);
11331 * Verify that there are no ordered extents for a given file range.
11333 * @inode: The target inode.
11334 * @start: Start offset of the file range, should be sector size aligned.
11335 * @end: End offset (inclusive) of the file range, its value +1 should be
11336 * sector size aligned.
11338 * This should typically be used for cases where we locked an inode's VFS lock in
11339 * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
11340 * we have flushed all delalloc in the range, we have waited for all ordered
11341 * extents in the range to complete and finally we have locked the file range in
11342 * the inode's io_tree.
11344 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
11346 struct btrfs_root *root = inode->root;
11347 struct btrfs_ordered_extent *ordered;
11349 if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
11352 ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
11354 btrfs_err(root->fs_info,
11355 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
11356 start, end, btrfs_ino(inode), root->root_key.objectid,
11357 ordered->file_offset,
11358 ordered->file_offset + ordered->num_bytes - 1);
11359 btrfs_put_ordered_extent(ordered);
11362 ASSERT(ordered == NULL);
11365 static const struct inode_operations btrfs_dir_inode_operations = {
11366 .getattr = btrfs_getattr,
11367 .lookup = btrfs_lookup,
11368 .create = btrfs_create,
11369 .unlink = btrfs_unlink,
11370 .link = btrfs_link,
11371 .mkdir = btrfs_mkdir,
11372 .rmdir = btrfs_rmdir,
11373 .rename = btrfs_rename2,
11374 .symlink = btrfs_symlink,
11375 .setattr = btrfs_setattr,
11376 .mknod = btrfs_mknod,
11377 .listxattr = btrfs_listxattr,
11378 .permission = btrfs_permission,
11379 .get_acl = btrfs_get_acl,
11380 .set_acl = btrfs_set_acl,
11381 .update_time = btrfs_update_time,
11382 .tmpfile = btrfs_tmpfile,
11383 .fileattr_get = btrfs_fileattr_get,
11384 .fileattr_set = btrfs_fileattr_set,
11387 static const struct file_operations btrfs_dir_file_operations = {
11388 .llseek = generic_file_llseek,
11389 .read = generic_read_dir,
11390 .iterate_shared = btrfs_real_readdir,
11391 .open = btrfs_opendir,
11392 .unlocked_ioctl = btrfs_ioctl,
11393 #ifdef CONFIG_COMPAT
11394 .compat_ioctl = btrfs_compat_ioctl,
11396 .release = btrfs_release_file,
11397 .fsync = btrfs_sync_file,
11401 * btrfs doesn't support the bmap operation because swapfiles
11402 * use bmap to make a mapping of extents in the file. They assume
11403 * these extents won't change over the life of the file and they
11404 * use the bmap result to do IO directly to the drive.
11406 * the btrfs bmap call would return logical addresses that aren't
11407 * suitable for IO and they also will change frequently as COW
11408 * operations happen. So, swapfile + btrfs == corruption.
11410 * For now we're avoiding this by dropping bmap.
11412 static const struct address_space_operations btrfs_aops = {
11413 .read_folio = btrfs_read_folio,
11414 .writepages = btrfs_writepages,
11415 .readahead = btrfs_readahead,
11416 .direct_IO = noop_direct_IO,
11417 .invalidate_folio = btrfs_invalidate_folio,
11418 .release_folio = btrfs_release_folio,
11419 .migrate_folio = btrfs_migrate_folio,
11420 .dirty_folio = filemap_dirty_folio,
11421 .error_remove_page = generic_error_remove_page,
11422 .swap_activate = btrfs_swap_activate,
11423 .swap_deactivate = btrfs_swap_deactivate,
11426 static const struct inode_operations btrfs_file_inode_operations = {
11427 .getattr = btrfs_getattr,
11428 .setattr = btrfs_setattr,
11429 .listxattr = btrfs_listxattr,
11430 .permission = btrfs_permission,
11431 .fiemap = btrfs_fiemap,
11432 .get_acl = btrfs_get_acl,
11433 .set_acl = btrfs_set_acl,
11434 .update_time = btrfs_update_time,
11435 .fileattr_get = btrfs_fileattr_get,
11436 .fileattr_set = btrfs_fileattr_set,
11438 static const struct inode_operations btrfs_special_inode_operations = {
11439 .getattr = btrfs_getattr,
11440 .setattr = btrfs_setattr,
11441 .permission = btrfs_permission,
11442 .listxattr = btrfs_listxattr,
11443 .get_acl = btrfs_get_acl,
11444 .set_acl = btrfs_set_acl,
11445 .update_time = btrfs_update_time,
11447 static const struct inode_operations btrfs_symlink_inode_operations = {
11448 .get_link = page_get_link,
11449 .getattr = btrfs_getattr,
11450 .setattr = btrfs_setattr,
11451 .permission = btrfs_permission,
11452 .listxattr = btrfs_listxattr,
11453 .update_time = btrfs_update_time,
11456 const struct dentry_operations btrfs_dentry_operations = {
11457 .d_delete = btrfs_dentry_delete,