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 {
91 /* This must be last */
92 struct btrfs_bio bbio;
95 static struct bio_set btrfs_dio_bioset;
97 struct btrfs_rename_ctx {
98 /* Output field. Stores the index number of the old directory entry. */
102 static const struct inode_operations btrfs_dir_inode_operations;
103 static const struct inode_operations btrfs_symlink_inode_operations;
104 static const struct inode_operations btrfs_special_inode_operations;
105 static const struct inode_operations btrfs_file_inode_operations;
106 static const struct address_space_operations btrfs_aops;
107 static const struct file_operations btrfs_dir_file_operations;
109 static struct kmem_cache *btrfs_inode_cachep;
111 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
112 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback);
113 static noinline int cow_file_range(struct btrfs_inode *inode,
114 struct page *locked_page,
115 u64 start, u64 end, int *page_started,
116 unsigned long *nr_written, int unlock,
118 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
119 u64 len, u64 orig_start, u64 block_start,
120 u64 block_len, u64 orig_block_len,
121 u64 ram_bytes, int compress_type,
124 static void __cold btrfs_print_data_csum_error(struct btrfs_inode *inode,
125 u64 logical_start, u8 *csum, u8 *csum_expected, int mirror_num)
127 struct btrfs_root *root = inode->root;
128 const u32 csum_size = root->fs_info->csum_size;
130 /* Output without objectid, which is more meaningful */
131 if (root->root_key.objectid >= BTRFS_LAST_FREE_OBJECTID) {
132 btrfs_warn_rl(root->fs_info,
133 "csum failed root %lld ino %lld off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
134 root->root_key.objectid, btrfs_ino(inode),
136 CSUM_FMT_VALUE(csum_size, csum),
137 CSUM_FMT_VALUE(csum_size, csum_expected),
140 btrfs_warn_rl(root->fs_info,
141 "csum failed root %llu ino %llu off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
142 root->root_key.objectid, btrfs_ino(inode),
144 CSUM_FMT_VALUE(csum_size, csum),
145 CSUM_FMT_VALUE(csum_size, csum_expected),
151 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
153 * ilock_flags can have the following bit set:
155 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
156 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
158 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
160 int btrfs_inode_lock(struct btrfs_inode *inode, unsigned int ilock_flags)
162 if (ilock_flags & BTRFS_ILOCK_SHARED) {
163 if (ilock_flags & BTRFS_ILOCK_TRY) {
164 if (!inode_trylock_shared(&inode->vfs_inode))
169 inode_lock_shared(&inode->vfs_inode);
171 if (ilock_flags & BTRFS_ILOCK_TRY) {
172 if (!inode_trylock(&inode->vfs_inode))
177 inode_lock(&inode->vfs_inode);
179 if (ilock_flags & BTRFS_ILOCK_MMAP)
180 down_write(&inode->i_mmap_lock);
185 * btrfs_inode_unlock - unock inode i_rwsem
187 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
188 * to decide whether the lock acquired is shared or exclusive.
190 void btrfs_inode_unlock(struct btrfs_inode *inode, unsigned int ilock_flags)
192 if (ilock_flags & BTRFS_ILOCK_MMAP)
193 up_write(&inode->i_mmap_lock);
194 if (ilock_flags & BTRFS_ILOCK_SHARED)
195 inode_unlock_shared(&inode->vfs_inode);
197 inode_unlock(&inode->vfs_inode);
201 * Cleanup all submitted ordered extents in specified range to handle errors
202 * from the btrfs_run_delalloc_range() callback.
204 * NOTE: caller must ensure that when an error happens, it can not call
205 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
206 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
207 * to be released, which we want to happen only when finishing the ordered
208 * extent (btrfs_finish_ordered_io()).
210 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
211 struct page *locked_page,
212 u64 offset, u64 bytes)
214 unsigned long index = offset >> PAGE_SHIFT;
215 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
216 u64 page_start = 0, page_end = 0;
220 page_start = page_offset(locked_page);
221 page_end = page_start + PAGE_SIZE - 1;
224 while (index <= end_index) {
226 * For locked page, we will call end_extent_writepage() on it
227 * in run_delalloc_range() for the error handling. That
228 * end_extent_writepage() function will call
229 * btrfs_mark_ordered_io_finished() to clear page Ordered and
230 * run the ordered extent accounting.
232 * Here we can't just clear the Ordered bit, or
233 * btrfs_mark_ordered_io_finished() would skip the accounting
234 * for the page range, and the ordered extent will never finish.
236 if (locked_page && index == (page_start >> PAGE_SHIFT)) {
240 page = find_get_page(inode->vfs_inode.i_mapping, index);
246 * Here we just clear all Ordered bits for every page in the
247 * range, then btrfs_mark_ordered_io_finished() will handle
248 * the ordered extent accounting for the range.
250 btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
256 /* The locked page covers the full range, nothing needs to be done */
257 if (bytes + offset <= page_start + PAGE_SIZE)
260 * In case this page belongs to the delalloc range being
261 * instantiated then skip it, since the first page of a range is
262 * going to be properly cleaned up by the caller of
265 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
266 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
267 offset = page_offset(locked_page) + PAGE_SIZE;
271 return btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes, false);
274 static int btrfs_dirty_inode(struct btrfs_inode *inode);
276 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
277 struct btrfs_new_inode_args *args)
281 if (args->default_acl) {
282 err = __btrfs_set_acl(trans, args->inode, args->default_acl,
288 err = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
292 if (!args->default_acl && !args->acl)
293 cache_no_acl(args->inode);
294 return btrfs_xattr_security_init(trans, args->inode, args->dir,
295 &args->dentry->d_name);
299 * this does all the hard work for inserting an inline extent into
300 * the btree. The caller should have done a btrfs_drop_extents so that
301 * no overlapping inline items exist in the btree
303 static int insert_inline_extent(struct btrfs_trans_handle *trans,
304 struct btrfs_path *path,
305 struct btrfs_inode *inode, bool extent_inserted,
306 size_t size, size_t compressed_size,
308 struct page **compressed_pages,
311 struct btrfs_root *root = inode->root;
312 struct extent_buffer *leaf;
313 struct page *page = NULL;
316 struct btrfs_file_extent_item *ei;
318 size_t cur_size = size;
321 ASSERT((compressed_size > 0 && compressed_pages) ||
322 (compressed_size == 0 && !compressed_pages));
324 if (compressed_size && compressed_pages)
325 cur_size = compressed_size;
327 if (!extent_inserted) {
328 struct btrfs_key key;
331 key.objectid = btrfs_ino(inode);
333 key.type = BTRFS_EXTENT_DATA_KEY;
335 datasize = btrfs_file_extent_calc_inline_size(cur_size);
336 ret = btrfs_insert_empty_item(trans, root, path, &key,
341 leaf = path->nodes[0];
342 ei = btrfs_item_ptr(leaf, path->slots[0],
343 struct btrfs_file_extent_item);
344 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
345 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
346 btrfs_set_file_extent_encryption(leaf, ei, 0);
347 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
348 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
349 ptr = btrfs_file_extent_inline_start(ei);
351 if (compress_type != BTRFS_COMPRESS_NONE) {
354 while (compressed_size > 0) {
355 cpage = compressed_pages[i];
356 cur_size = min_t(unsigned long, compressed_size,
359 kaddr = kmap_local_page(cpage);
360 write_extent_buffer(leaf, kaddr, ptr, cur_size);
365 compressed_size -= cur_size;
367 btrfs_set_file_extent_compression(leaf, ei,
370 page = find_get_page(inode->vfs_inode.i_mapping, 0);
371 btrfs_set_file_extent_compression(leaf, ei, 0);
372 kaddr = kmap_local_page(page);
373 write_extent_buffer(leaf, kaddr, ptr, size);
377 btrfs_mark_buffer_dirty(leaf);
378 btrfs_release_path(path);
381 * We align size to sectorsize for inline extents just for simplicity
384 ret = btrfs_inode_set_file_extent_range(inode, 0,
385 ALIGN(size, root->fs_info->sectorsize));
390 * We're an inline extent, so nobody can extend the file past i_size
391 * without locking a page we already have locked.
393 * We must do any i_size and inode updates before we unlock the pages.
394 * Otherwise we could end up racing with unlink.
396 i_size = i_size_read(&inode->vfs_inode);
397 if (update_i_size && size > i_size) {
398 i_size_write(&inode->vfs_inode, size);
401 inode->disk_i_size = i_size;
409 * conditionally insert an inline extent into the file. This
410 * does the checks required to make sure the data is small enough
411 * to fit as an inline extent.
413 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 size,
414 size_t compressed_size,
416 struct page **compressed_pages,
419 struct btrfs_drop_extents_args drop_args = { 0 };
420 struct btrfs_root *root = inode->root;
421 struct btrfs_fs_info *fs_info = root->fs_info;
422 struct btrfs_trans_handle *trans;
423 u64 data_len = (compressed_size ?: size);
425 struct btrfs_path *path;
428 * We can create an inline extent if it ends at or beyond the current
429 * i_size, is no larger than a sector (decompressed), and the (possibly
430 * compressed) data fits in a leaf and the configured maximum inline
433 if (size < i_size_read(&inode->vfs_inode) ||
434 size > fs_info->sectorsize ||
435 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
436 data_len > fs_info->max_inline)
439 path = btrfs_alloc_path();
443 trans = btrfs_join_transaction(root);
445 btrfs_free_path(path);
446 return PTR_ERR(trans);
448 trans->block_rsv = &inode->block_rsv;
450 drop_args.path = path;
452 drop_args.end = fs_info->sectorsize;
453 drop_args.drop_cache = true;
454 drop_args.replace_extent = true;
455 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
456 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
458 btrfs_abort_transaction(trans, ret);
462 ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
463 size, compressed_size, compress_type,
464 compressed_pages, update_i_size);
465 if (ret && ret != -ENOSPC) {
466 btrfs_abort_transaction(trans, ret);
468 } else if (ret == -ENOSPC) {
473 btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
474 ret = btrfs_update_inode(trans, root, inode);
475 if (ret && ret != -ENOSPC) {
476 btrfs_abort_transaction(trans, ret);
478 } else if (ret == -ENOSPC) {
483 btrfs_set_inode_full_sync(inode);
486 * Don't forget to free the reserved space, as for inlined extent
487 * it won't count as data extent, free them directly here.
488 * And at reserve time, it's always aligned to page size, so
489 * just free one page here.
491 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
492 btrfs_free_path(path);
493 btrfs_end_transaction(trans);
497 struct async_extent {
502 unsigned long nr_pages;
504 struct list_head list;
508 struct btrfs_inode *inode;
509 struct page *locked_page;
512 blk_opf_t write_flags;
513 struct list_head extents;
514 struct cgroup_subsys_state *blkcg_css;
515 struct btrfs_work work;
516 struct async_cow *async_cow;
521 struct async_chunk chunks[];
524 static noinline int add_async_extent(struct async_chunk *cow,
525 u64 start, u64 ram_size,
528 unsigned long nr_pages,
531 struct async_extent *async_extent;
533 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
534 BUG_ON(!async_extent); /* -ENOMEM */
535 async_extent->start = start;
536 async_extent->ram_size = ram_size;
537 async_extent->compressed_size = compressed_size;
538 async_extent->pages = pages;
539 async_extent->nr_pages = nr_pages;
540 async_extent->compress_type = compress_type;
541 list_add_tail(&async_extent->list, &cow->extents);
546 * Check if the inode needs to be submitted to compression, based on mount
547 * options, defragmentation, properties or heuristics.
549 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
552 struct btrfs_fs_info *fs_info = inode->root->fs_info;
554 if (!btrfs_inode_can_compress(inode)) {
555 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
556 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
561 * Special check for subpage.
563 * We lock the full page then run each delalloc range in the page, thus
564 * for the following case, we will hit some subpage specific corner case:
567 * | |///////| |///////|
570 * In above case, both range A and range B will try to unlock the full
571 * page [0, 64K), causing the one finished later will have page
572 * unlocked already, triggering various page lock requirement BUG_ON()s.
574 * So here we add an artificial limit that subpage compression can only
575 * if the range is fully page aligned.
577 * In theory we only need to ensure the first page is fully covered, but
578 * the tailing partial page will be locked until the full compression
579 * finishes, delaying the write of other range.
581 * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
582 * first to prevent any submitted async extent to unlock the full page.
583 * By this, we can ensure for subpage case that only the last async_cow
584 * will unlock the full page.
586 if (fs_info->sectorsize < PAGE_SIZE) {
587 if (!PAGE_ALIGNED(start) ||
588 !PAGE_ALIGNED(end + 1))
593 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
596 if (inode->defrag_compress)
598 /* bad compression ratios */
599 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
601 if (btrfs_test_opt(fs_info, COMPRESS) ||
602 inode->flags & BTRFS_INODE_COMPRESS ||
603 inode->prop_compress)
604 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
608 static inline void inode_should_defrag(struct btrfs_inode *inode,
609 u64 start, u64 end, u64 num_bytes, u32 small_write)
611 /* If this is a small write inside eof, kick off a defrag */
612 if (num_bytes < small_write &&
613 (start > 0 || end + 1 < inode->disk_i_size))
614 btrfs_add_inode_defrag(NULL, inode, small_write);
618 * we create compressed extents in two phases. The first
619 * phase compresses a range of pages that have already been
620 * locked (both pages and state bits are locked).
622 * This is done inside an ordered work queue, and the compression
623 * is spread across many cpus. The actual IO submission is step
624 * two, and the ordered work queue takes care of making sure that
625 * happens in the same order things were put onto the queue by
626 * writepages and friends.
628 * If this code finds it can't get good compression, it puts an
629 * entry onto the work queue to write the uncompressed bytes. This
630 * makes sure that both compressed inodes and uncompressed inodes
631 * are written in the same order that the flusher thread sent them
634 static noinline int compress_file_range(struct async_chunk *async_chunk)
636 struct btrfs_inode *inode = async_chunk->inode;
637 struct btrfs_fs_info *fs_info = inode->root->fs_info;
638 u64 blocksize = fs_info->sectorsize;
639 u64 start = async_chunk->start;
640 u64 end = async_chunk->end;
644 struct page **pages = NULL;
645 unsigned long nr_pages;
646 unsigned long total_compressed = 0;
647 unsigned long total_in = 0;
650 int compress_type = fs_info->compress_type;
651 int compressed_extents = 0;
654 inode_should_defrag(inode, start, end, end - start + 1, SZ_16K);
657 * We need to save i_size before now because it could change in between
658 * us evaluating the size and assigning it. This is because we lock and
659 * unlock the page in truncate and fallocate, and then modify the i_size
662 * The barriers are to emulate READ_ONCE, remove that once i_size_read
666 i_size = i_size_read(&inode->vfs_inode);
668 actual_end = min_t(u64, i_size, end + 1);
671 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
672 nr_pages = min_t(unsigned long, nr_pages,
673 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
676 * we don't want to send crud past the end of i_size through
677 * compression, that's just a waste of CPU time. So, if the
678 * end of the file is before the start of our current
679 * requested range of bytes, we bail out to the uncompressed
680 * cleanup code that can deal with all of this.
682 * It isn't really the fastest way to fix things, but this is a
683 * very uncommon corner.
685 if (actual_end <= start)
686 goto cleanup_and_bail_uncompressed;
688 total_compressed = actual_end - start;
691 * Skip compression for a small file range(<=blocksize) that
692 * isn't an inline extent, since it doesn't save disk space at all.
694 if (total_compressed <= blocksize &&
695 (start > 0 || end + 1 < inode->disk_i_size))
696 goto cleanup_and_bail_uncompressed;
699 * For subpage case, we require full page alignment for the sector
701 * Thus we must also check against @actual_end, not just @end.
703 if (blocksize < PAGE_SIZE) {
704 if (!PAGE_ALIGNED(start) ||
705 !PAGE_ALIGNED(round_up(actual_end, blocksize)))
706 goto cleanup_and_bail_uncompressed;
709 total_compressed = min_t(unsigned long, total_compressed,
710 BTRFS_MAX_UNCOMPRESSED);
715 * we do compression for mount -o compress and when the
716 * inode has not been flagged as nocompress. This flag can
717 * change at any time if we discover bad compression ratios.
719 if (inode_need_compress(inode, start, end)) {
721 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
723 /* just bail out to the uncompressed code */
728 if (inode->defrag_compress)
729 compress_type = inode->defrag_compress;
730 else if (inode->prop_compress)
731 compress_type = inode->prop_compress;
734 * we need to call clear_page_dirty_for_io on each
735 * page in the range. Otherwise applications with the file
736 * mmap'd can wander in and change the page contents while
737 * we are compressing them.
739 * If the compression fails for any reason, we set the pages
740 * dirty again later on.
742 * Note that the remaining part is redirtied, the start pointer
743 * has moved, the end is the original one.
746 extent_range_clear_dirty_for_io(&inode->vfs_inode, start, end);
750 /* Compression level is applied here and only here */
751 ret = btrfs_compress_pages(
752 compress_type | (fs_info->compress_level << 4),
753 inode->vfs_inode.i_mapping, start,
760 unsigned long offset = offset_in_page(total_compressed);
761 struct page *page = pages[nr_pages - 1];
763 /* zero the tail end of the last page, we might be
764 * sending it down to disk
767 memzero_page(page, offset, PAGE_SIZE - offset);
773 * Check cow_file_range() for why we don't even try to create inline
774 * extent for subpage case.
776 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
777 /* lets try to make an inline extent */
778 if (ret || total_in < actual_end) {
779 /* we didn't compress the entire range, try
780 * to make an uncompressed inline extent.
782 ret = cow_file_range_inline(inode, actual_end,
783 0, BTRFS_COMPRESS_NONE,
786 /* try making a compressed inline extent */
787 ret = cow_file_range_inline(inode, actual_end,
789 compress_type, pages,
793 unsigned long clear_flags = EXTENT_DELALLOC |
794 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
795 EXTENT_DO_ACCOUNTING;
796 unsigned long page_error_op;
798 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
801 * inline extent creation worked or returned error,
802 * we don't need to create any more async work items.
803 * Unlock and free up our temp pages.
805 * We use DO_ACCOUNTING here because we need the
806 * delalloc_release_metadata to be done _after_ we drop
807 * our outstanding extent for clearing delalloc for this
810 extent_clear_unlock_delalloc(inode, start, end,
814 PAGE_START_WRITEBACK |
819 * Ensure we only free the compressed pages if we have
820 * them allocated, as we can still reach here with
821 * inode_need_compress() == false.
824 for (i = 0; i < nr_pages; i++) {
825 WARN_ON(pages[i]->mapping);
836 * we aren't doing an inline extent round the compressed size
837 * up to a block size boundary so the allocator does sane
840 total_compressed = ALIGN(total_compressed, blocksize);
843 * one last check to make sure the compression is really a
844 * win, compare the page count read with the blocks on disk,
845 * compression must free at least one sector size
847 total_in = round_up(total_in, fs_info->sectorsize);
848 if (total_compressed + blocksize <= total_in) {
849 compressed_extents++;
852 * The async work queues will take care of doing actual
853 * allocation on disk for these compressed pages, and
854 * will submit them to the elevator.
856 add_async_extent(async_chunk, start, total_in,
857 total_compressed, pages, nr_pages,
860 if (start + total_in < end) {
866 return compressed_extents;
871 * the compression code ran but failed to make things smaller,
872 * free any pages it allocated and our page pointer array
874 for (i = 0; i < nr_pages; i++) {
875 WARN_ON(pages[i]->mapping);
880 total_compressed = 0;
883 /* flag the file so we don't compress in the future */
884 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
885 !(inode->prop_compress)) {
886 inode->flags |= BTRFS_INODE_NOCOMPRESS;
889 cleanup_and_bail_uncompressed:
891 * No compression, but we still need to write the pages in the file
892 * we've been given so far. redirty the locked page if it corresponds
893 * to our extent and set things up for the async work queue to run
894 * cow_file_range to do the normal delalloc dance.
896 if (async_chunk->locked_page &&
897 (page_offset(async_chunk->locked_page) >= start &&
898 page_offset(async_chunk->locked_page)) <= end) {
899 __set_page_dirty_nobuffers(async_chunk->locked_page);
900 /* unlocked later on in the async handlers */
904 extent_range_redirty_for_io(&inode->vfs_inode, start, end);
905 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
906 BTRFS_COMPRESS_NONE);
907 compressed_extents++;
909 return compressed_extents;
912 static void free_async_extent_pages(struct async_extent *async_extent)
916 if (!async_extent->pages)
919 for (i = 0; i < async_extent->nr_pages; i++) {
920 WARN_ON(async_extent->pages[i]->mapping);
921 put_page(async_extent->pages[i]);
923 kfree(async_extent->pages);
924 async_extent->nr_pages = 0;
925 async_extent->pages = NULL;
928 static int submit_uncompressed_range(struct btrfs_inode *inode,
929 struct async_extent *async_extent,
930 struct page *locked_page)
932 u64 start = async_extent->start;
933 u64 end = async_extent->start + async_extent->ram_size - 1;
934 unsigned long nr_written = 0;
935 int page_started = 0;
939 * Call cow_file_range() to run the delalloc range directly, since we
940 * won't go to NOCOW or async path again.
942 * Also we call cow_file_range() with @unlock_page == 0, so that we
943 * can directly submit them without interruption.
945 ret = cow_file_range(inode, locked_page, start, end, &page_started,
946 &nr_written, 0, NULL);
947 /* Inline extent inserted, page gets unlocked and everything is done */
953 btrfs_cleanup_ordered_extents(inode, locked_page, start, end - start + 1);
955 const u64 page_start = page_offset(locked_page);
956 const u64 page_end = page_start + PAGE_SIZE - 1;
958 btrfs_page_set_error(inode->root->fs_info, locked_page,
959 page_start, PAGE_SIZE);
960 set_page_writeback(locked_page);
961 end_page_writeback(locked_page);
962 end_extent_writepage(locked_page, ret, page_start, page_end);
963 unlock_page(locked_page);
968 ret = extent_write_locked_range(&inode->vfs_inode, start, end);
969 /* All pages will be unlocked, including @locked_page */
975 static int submit_one_async_extent(struct btrfs_inode *inode,
976 struct async_chunk *async_chunk,
977 struct async_extent *async_extent,
980 struct extent_io_tree *io_tree = &inode->io_tree;
981 struct btrfs_root *root = inode->root;
982 struct btrfs_fs_info *fs_info = root->fs_info;
983 struct btrfs_key ins;
984 struct page *locked_page = NULL;
985 struct extent_map *em;
987 u64 start = async_extent->start;
988 u64 end = async_extent->start + async_extent->ram_size - 1;
991 * If async_chunk->locked_page is in the async_extent range, we need to
994 if (async_chunk->locked_page) {
995 u64 locked_page_start = page_offset(async_chunk->locked_page);
996 u64 locked_page_end = locked_page_start + PAGE_SIZE - 1;
998 if (!(start >= locked_page_end || end <= locked_page_start))
999 locked_page = async_chunk->locked_page;
1001 lock_extent(io_tree, start, end, NULL);
1003 /* We have fall back to uncompressed write */
1004 if (!async_extent->pages)
1005 return submit_uncompressed_range(inode, async_extent, locked_page);
1007 ret = btrfs_reserve_extent(root, async_extent->ram_size,
1008 async_extent->compressed_size,
1009 async_extent->compressed_size,
1010 0, *alloc_hint, &ins, 1, 1);
1012 free_async_extent_pages(async_extent);
1014 * Here we used to try again by going back to non-compressed
1015 * path for ENOSPC. But we can't reserve space even for
1016 * compressed size, how could it work for uncompressed size
1017 * which requires larger size? So here we directly go error
1023 /* Here we're doing allocation and writeback of the compressed pages */
1024 em = create_io_em(inode, start,
1025 async_extent->ram_size, /* len */
1026 start, /* orig_start */
1027 ins.objectid, /* block_start */
1028 ins.offset, /* block_len */
1029 ins.offset, /* orig_block_len */
1030 async_extent->ram_size, /* ram_bytes */
1031 async_extent->compress_type,
1032 BTRFS_ORDERED_COMPRESSED);
1035 goto out_free_reserve;
1037 free_extent_map(em);
1039 ret = btrfs_add_ordered_extent(inode, start, /* file_offset */
1040 async_extent->ram_size, /* num_bytes */
1041 async_extent->ram_size, /* ram_bytes */
1042 ins.objectid, /* disk_bytenr */
1043 ins.offset, /* disk_num_bytes */
1045 1 << BTRFS_ORDERED_COMPRESSED,
1046 async_extent->compress_type);
1048 btrfs_drop_extent_map_range(inode, start, end, false);
1049 goto out_free_reserve;
1051 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1053 /* Clear dirty, set writeback and unlock the pages. */
1054 extent_clear_unlock_delalloc(inode, start, end,
1055 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
1056 PAGE_UNLOCK | PAGE_START_WRITEBACK);
1057 if (btrfs_submit_compressed_write(inode, start, /* file_offset */
1058 async_extent->ram_size, /* num_bytes */
1059 ins.objectid, /* disk_bytenr */
1060 ins.offset, /* compressed_len */
1061 async_extent->pages, /* compressed_pages */
1062 async_extent->nr_pages,
1063 async_chunk->write_flags,
1064 async_chunk->blkcg_css, true)) {
1065 const u64 start = async_extent->start;
1066 const u64 end = start + async_extent->ram_size - 1;
1068 btrfs_writepage_endio_finish_ordered(inode, NULL, start, end, 0);
1070 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
1071 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1072 free_async_extent_pages(async_extent);
1074 *alloc_hint = ins.objectid + ins.offset;
1075 kfree(async_extent);
1079 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1080 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1082 extent_clear_unlock_delalloc(inode, start, end,
1083 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
1084 EXTENT_DELALLOC_NEW |
1085 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
1086 PAGE_UNLOCK | PAGE_START_WRITEBACK |
1087 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1088 free_async_extent_pages(async_extent);
1089 kfree(async_extent);
1094 * Phase two of compressed writeback. This is the ordered portion of the code,
1095 * which only gets called in the order the work was queued. We walk all the
1096 * async extents created by compress_file_range and send them down to the disk.
1098 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
1100 struct btrfs_inode *inode = async_chunk->inode;
1101 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1102 struct async_extent *async_extent;
1106 while (!list_empty(&async_chunk->extents)) {
1110 async_extent = list_entry(async_chunk->extents.next,
1111 struct async_extent, list);
1112 list_del(&async_extent->list);
1113 extent_start = async_extent->start;
1114 ram_size = async_extent->ram_size;
1116 ret = submit_one_async_extent(inode, async_chunk, async_extent,
1118 btrfs_debug(fs_info,
1119 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1120 inode->root->root_key.objectid,
1121 btrfs_ino(inode), extent_start, ram_size, ret);
1125 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1128 struct extent_map_tree *em_tree = &inode->extent_tree;
1129 struct extent_map *em;
1132 read_lock(&em_tree->lock);
1133 em = search_extent_mapping(em_tree, start, num_bytes);
1136 * if block start isn't an actual block number then find the
1137 * first block in this inode and use that as a hint. If that
1138 * block is also bogus then just don't worry about it.
1140 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1141 free_extent_map(em);
1142 em = search_extent_mapping(em_tree, 0, 0);
1143 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1144 alloc_hint = em->block_start;
1146 free_extent_map(em);
1148 alloc_hint = em->block_start;
1149 free_extent_map(em);
1152 read_unlock(&em_tree->lock);
1158 * when extent_io.c finds a delayed allocation range in the file,
1159 * the call backs end up in this code. The basic idea is to
1160 * allocate extents on disk for the range, and create ordered data structs
1161 * in ram to track those extents.
1163 * locked_page is the page that writepage had locked already. We use
1164 * it to make sure we don't do extra locks or unlocks.
1166 * *page_started is set to one if we unlock locked_page and do everything
1167 * required to start IO on it. It may be clean and already done with
1168 * IO when we return.
1170 * When unlock == 1, we unlock the pages in successfully allocated regions.
1171 * When unlock == 0, we leave them locked for writing them out.
1173 * However, we unlock all the pages except @locked_page in case of failure.
1175 * In summary, page locking state will be as follow:
1177 * - page_started == 1 (return value)
1178 * - All the pages are unlocked. IO is started.
1179 * - Note that this can happen only on success
1181 * - All the pages except @locked_page are unlocked in any case
1183 * - On success, all the pages are locked for writing out them
1184 * - On failure, all the pages except @locked_page are unlocked
1186 * When a failure happens in the second or later iteration of the
1187 * while-loop, the ordered extents created in previous iterations are kept
1188 * intact. So, the caller must clean them up by calling
1189 * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
1192 static noinline int cow_file_range(struct btrfs_inode *inode,
1193 struct page *locked_page,
1194 u64 start, u64 end, int *page_started,
1195 unsigned long *nr_written, int unlock,
1198 struct btrfs_root *root = inode->root;
1199 struct btrfs_fs_info *fs_info = root->fs_info;
1201 u64 orig_start = start;
1203 unsigned long ram_size;
1204 u64 cur_alloc_size = 0;
1206 u64 blocksize = fs_info->sectorsize;
1207 struct btrfs_key ins;
1208 struct extent_map *em;
1209 unsigned clear_bits;
1210 unsigned long page_ops;
1211 bool extent_reserved = false;
1214 if (btrfs_is_free_space_inode(inode)) {
1219 num_bytes = ALIGN(end - start + 1, blocksize);
1220 num_bytes = max(blocksize, num_bytes);
1221 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1223 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1226 * Due to the page size limit, for subpage we can only trigger the
1227 * writeback for the dirty sectors of page, that means data writeback
1228 * is doing more writeback than what we want.
1230 * This is especially unexpected for some call sites like fallocate,
1231 * where we only increase i_size after everything is done.
1232 * This means we can trigger inline extent even if we didn't want to.
1233 * So here we skip inline extent creation completely.
1235 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
1236 u64 actual_end = min_t(u64, i_size_read(&inode->vfs_inode),
1239 /* lets try to make an inline extent */
1240 ret = cow_file_range_inline(inode, actual_end, 0,
1241 BTRFS_COMPRESS_NONE, NULL, false);
1244 * We use DO_ACCOUNTING here because we need the
1245 * delalloc_release_metadata to be run _after_ we drop
1246 * our outstanding extent for clearing delalloc for this
1249 extent_clear_unlock_delalloc(inode, start, end,
1251 EXTENT_LOCKED | EXTENT_DELALLOC |
1252 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1253 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1254 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1255 *nr_written = *nr_written +
1256 (end - start + PAGE_SIZE) / PAGE_SIZE;
1259 * locked_page is locked by the caller of
1260 * writepage_delalloc(), not locked by
1261 * __process_pages_contig().
1263 * We can't let __process_pages_contig() to unlock it,
1264 * as it doesn't have any subpage::writers recorded.
1266 * Here we manually unlock the page, since the caller
1267 * can't use page_started to determine if it's an
1268 * inline extent or a compressed extent.
1270 unlock_page(locked_page);
1272 } else if (ret < 0) {
1277 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1280 * Relocation relies on the relocated extents to have exactly the same
1281 * size as the original extents. Normally writeback for relocation data
1282 * extents follows a NOCOW path because relocation preallocates the
1283 * extents. However, due to an operation such as scrub turning a block
1284 * group to RO mode, it may fallback to COW mode, so we must make sure
1285 * an extent allocated during COW has exactly the requested size and can
1286 * not be split into smaller extents, otherwise relocation breaks and
1287 * fails during the stage where it updates the bytenr of file extent
1290 if (btrfs_is_data_reloc_root(root))
1291 min_alloc_size = num_bytes;
1293 min_alloc_size = fs_info->sectorsize;
1295 while (num_bytes > 0) {
1296 cur_alloc_size = num_bytes;
1297 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1298 min_alloc_size, 0, alloc_hint,
1302 cur_alloc_size = ins.offset;
1303 extent_reserved = true;
1305 ram_size = ins.offset;
1306 em = create_io_em(inode, start, ins.offset, /* len */
1307 start, /* orig_start */
1308 ins.objectid, /* block_start */
1309 ins.offset, /* block_len */
1310 ins.offset, /* orig_block_len */
1311 ram_size, /* ram_bytes */
1312 BTRFS_COMPRESS_NONE, /* compress_type */
1313 BTRFS_ORDERED_REGULAR /* type */);
1318 free_extent_map(em);
1320 ret = btrfs_add_ordered_extent(inode, start, ram_size, ram_size,
1321 ins.objectid, cur_alloc_size, 0,
1322 1 << BTRFS_ORDERED_REGULAR,
1323 BTRFS_COMPRESS_NONE);
1325 goto out_drop_extent_cache;
1327 if (btrfs_is_data_reloc_root(root)) {
1328 ret = btrfs_reloc_clone_csums(inode, start,
1331 * Only drop cache here, and process as normal.
1333 * We must not allow extent_clear_unlock_delalloc()
1334 * at out_unlock label to free meta of this ordered
1335 * extent, as its meta should be freed by
1336 * btrfs_finish_ordered_io().
1338 * So we must continue until @start is increased to
1339 * skip current ordered extent.
1342 btrfs_drop_extent_map_range(inode, start,
1343 start + ram_size - 1,
1347 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1350 * We're not doing compressed IO, don't unlock the first page
1351 * (which the caller expects to stay locked), don't clear any
1352 * dirty bits and don't set any writeback bits
1354 * Do set the Ordered (Private2) bit so we know this page was
1355 * properly setup for writepage.
1357 page_ops = unlock ? PAGE_UNLOCK : 0;
1358 page_ops |= PAGE_SET_ORDERED;
1360 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1362 EXTENT_LOCKED | EXTENT_DELALLOC,
1364 if (num_bytes < cur_alloc_size)
1367 num_bytes -= cur_alloc_size;
1368 alloc_hint = ins.objectid + ins.offset;
1369 start += cur_alloc_size;
1370 extent_reserved = false;
1373 * btrfs_reloc_clone_csums() error, since start is increased
1374 * extent_clear_unlock_delalloc() at out_unlock label won't
1375 * free metadata of current ordered extent, we're OK to exit.
1383 out_drop_extent_cache:
1384 btrfs_drop_extent_map_range(inode, start, start + ram_size - 1, false);
1386 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1387 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1390 * If done_offset is non-NULL and ret == -EAGAIN, we expect the
1391 * caller to write out the successfully allocated region and retry.
1393 if (done_offset && ret == -EAGAIN) {
1394 if (orig_start < start)
1395 *done_offset = start - 1;
1397 *done_offset = start;
1399 } else if (ret == -EAGAIN) {
1400 /* Convert to -ENOSPC since the caller cannot retry. */
1405 * Now, we have three regions to clean up:
1407 * |-------(1)----|---(2)---|-------------(3)----------|
1408 * `- orig_start `- start `- start + cur_alloc_size `- end
1410 * We process each region below.
1413 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1414 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1415 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1418 * For the range (1). We have already instantiated the ordered extents
1419 * for this region. They are cleaned up by
1420 * btrfs_cleanup_ordered_extents() in e.g,
1421 * btrfs_run_delalloc_range(). EXTENT_LOCKED | EXTENT_DELALLOC are
1422 * already cleared in the above loop. And, EXTENT_DELALLOC_NEW |
1423 * EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV are handled by the cleanup
1426 * However, in case of unlock == 0, we still need to unlock the pages
1427 * (except @locked_page) to ensure all the pages are unlocked.
1429 if (!unlock && orig_start < start) {
1431 mapping_set_error(inode->vfs_inode.i_mapping, ret);
1432 extent_clear_unlock_delalloc(inode, orig_start, start - 1,
1433 locked_page, 0, page_ops);
1437 * For the range (2). If we reserved an extent for our delalloc range
1438 * (or a subrange) and failed to create the respective ordered extent,
1439 * then it means that when we reserved the extent we decremented the
1440 * extent's size from the data space_info's bytes_may_use counter and
1441 * incremented the space_info's bytes_reserved counter by the same
1442 * amount. We must make sure extent_clear_unlock_delalloc() does not try
1443 * to decrement again the data space_info's bytes_may_use counter,
1444 * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
1446 if (extent_reserved) {
1447 extent_clear_unlock_delalloc(inode, start,
1448 start + cur_alloc_size - 1,
1452 start += cur_alloc_size;
1458 * For the range (3). We never touched the region. In addition to the
1459 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1460 * space_info's bytes_may_use counter, reserved in
1461 * btrfs_check_data_free_space().
1463 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1464 clear_bits | EXTENT_CLEAR_DATA_RESV,
1470 * work queue call back to started compression on a file and pages
1472 static noinline void async_cow_start(struct btrfs_work *work)
1474 struct async_chunk *async_chunk;
1475 int compressed_extents;
1477 async_chunk = container_of(work, struct async_chunk, work);
1479 compressed_extents = compress_file_range(async_chunk);
1480 if (compressed_extents == 0) {
1481 btrfs_add_delayed_iput(async_chunk->inode);
1482 async_chunk->inode = NULL;
1487 * work queue call back to submit previously compressed pages
1489 static noinline void async_cow_submit(struct btrfs_work *work)
1491 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1493 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1494 unsigned long nr_pages;
1496 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1500 * ->inode could be NULL if async_chunk_start has failed to compress,
1501 * in which case we don't have anything to submit, yet we need to
1502 * always adjust ->async_delalloc_pages as its paired with the init
1503 * happening in cow_file_range_async
1505 if (async_chunk->inode)
1506 submit_compressed_extents(async_chunk);
1508 /* atomic_sub_return implies a barrier */
1509 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1511 cond_wake_up_nomb(&fs_info->async_submit_wait);
1514 static noinline void async_cow_free(struct btrfs_work *work)
1516 struct async_chunk *async_chunk;
1517 struct async_cow *async_cow;
1519 async_chunk = container_of(work, struct async_chunk, work);
1520 if (async_chunk->inode)
1521 btrfs_add_delayed_iput(async_chunk->inode);
1522 if (async_chunk->blkcg_css)
1523 css_put(async_chunk->blkcg_css);
1525 async_cow = async_chunk->async_cow;
1526 if (atomic_dec_and_test(&async_cow->num_chunks))
1530 static int cow_file_range_async(struct btrfs_inode *inode,
1531 struct writeback_control *wbc,
1532 struct page *locked_page,
1533 u64 start, u64 end, int *page_started,
1534 unsigned long *nr_written)
1536 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1537 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1538 struct async_cow *ctx;
1539 struct async_chunk *async_chunk;
1540 unsigned long nr_pages;
1542 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1544 bool should_compress;
1546 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1548 unlock_extent(&inode->io_tree, start, end, NULL);
1550 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1551 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1553 should_compress = false;
1555 should_compress = true;
1558 nofs_flag = memalloc_nofs_save();
1559 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1560 memalloc_nofs_restore(nofs_flag);
1563 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1564 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1565 EXTENT_DO_ACCOUNTING;
1566 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1567 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1569 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1570 clear_bits, page_ops);
1574 async_chunk = ctx->chunks;
1575 atomic_set(&ctx->num_chunks, num_chunks);
1577 for (i = 0; i < num_chunks; i++) {
1578 if (should_compress)
1579 cur_end = min(end, start + SZ_512K - 1);
1584 * igrab is called higher up in the call chain, take only the
1585 * lightweight reference for the callback lifetime
1587 ihold(&inode->vfs_inode);
1588 async_chunk[i].async_cow = ctx;
1589 async_chunk[i].inode = inode;
1590 async_chunk[i].start = start;
1591 async_chunk[i].end = cur_end;
1592 async_chunk[i].write_flags = write_flags;
1593 INIT_LIST_HEAD(&async_chunk[i].extents);
1596 * The locked_page comes all the way from writepage and its
1597 * the original page we were actually given. As we spread
1598 * this large delalloc region across multiple async_chunk
1599 * structs, only the first struct needs a pointer to locked_page
1601 * This way we don't need racey decisions about who is supposed
1606 * Depending on the compressibility, the pages might or
1607 * might not go through async. We want all of them to
1608 * be accounted against wbc once. Let's do it here
1609 * before the paths diverge. wbc accounting is used
1610 * only for foreign writeback detection and doesn't
1611 * need full accuracy. Just account the whole thing
1612 * against the first page.
1614 wbc_account_cgroup_owner(wbc, locked_page,
1616 async_chunk[i].locked_page = locked_page;
1619 async_chunk[i].locked_page = NULL;
1622 if (blkcg_css != blkcg_root_css) {
1624 async_chunk[i].blkcg_css = blkcg_css;
1626 async_chunk[i].blkcg_css = NULL;
1629 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1630 async_cow_submit, async_cow_free);
1632 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1633 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1635 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1637 *nr_written += nr_pages;
1638 start = cur_end + 1;
1644 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1645 struct page *locked_page, u64 start,
1646 u64 end, int *page_started,
1647 unsigned long *nr_written)
1649 u64 done_offset = end;
1651 bool locked_page_done = false;
1653 while (start <= end) {
1654 ret = cow_file_range(inode, locked_page, start, end, page_started,
1655 nr_written, 0, &done_offset);
1656 if (ret && ret != -EAGAIN)
1659 if (*page_started) {
1667 if (done_offset == start) {
1668 wait_on_bit_io(&inode->root->fs_info->flags,
1669 BTRFS_FS_NEED_ZONE_FINISH,
1670 TASK_UNINTERRUPTIBLE);
1674 if (!locked_page_done) {
1675 __set_page_dirty_nobuffers(locked_page);
1676 account_page_redirty(locked_page);
1678 locked_page_done = true;
1679 extent_write_locked_range(&inode->vfs_inode, start, done_offset);
1681 start = done_offset + 1;
1689 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1690 u64 bytenr, u64 num_bytes, bool nowait)
1692 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bytenr);
1693 struct btrfs_ordered_sum *sums;
1697 ret = btrfs_lookup_csums_list(csum_root, bytenr, bytenr + num_bytes - 1,
1699 if (ret == 0 && list_empty(&list))
1702 while (!list_empty(&list)) {
1703 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1704 list_del(&sums->list);
1712 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1713 const u64 start, const u64 end,
1714 int *page_started, unsigned long *nr_written)
1716 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1717 const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1718 const u64 range_bytes = end + 1 - start;
1719 struct extent_io_tree *io_tree = &inode->io_tree;
1720 u64 range_start = start;
1724 * If EXTENT_NORESERVE is set it means that when the buffered write was
1725 * made we had not enough available data space and therefore we did not
1726 * reserve data space for it, since we though we could do NOCOW for the
1727 * respective file range (either there is prealloc extent or the inode
1728 * has the NOCOW bit set).
1730 * However when we need to fallback to COW mode (because for example the
1731 * block group for the corresponding extent was turned to RO mode by a
1732 * scrub or relocation) we need to do the following:
1734 * 1) We increment the bytes_may_use counter of the data space info.
1735 * If COW succeeds, it allocates a new data extent and after doing
1736 * that it decrements the space info's bytes_may_use counter and
1737 * increments its bytes_reserved counter by the same amount (we do
1738 * this at btrfs_add_reserved_bytes()). So we need to increment the
1739 * bytes_may_use counter to compensate (when space is reserved at
1740 * buffered write time, the bytes_may_use counter is incremented);
1742 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1743 * that if the COW path fails for any reason, it decrements (through
1744 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1745 * data space info, which we incremented in the step above.
1747 * If we need to fallback to cow and the inode corresponds to a free
1748 * space cache inode or an inode of the data relocation tree, we must
1749 * also increment bytes_may_use of the data space_info for the same
1750 * reason. Space caches and relocated data extents always get a prealloc
1751 * extent for them, however scrub or balance may have set the block
1752 * group that contains that extent to RO mode and therefore force COW
1753 * when starting writeback.
1755 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1756 EXTENT_NORESERVE, 0, NULL);
1757 if (count > 0 || is_space_ino || is_reloc_ino) {
1759 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1760 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1762 if (is_space_ino || is_reloc_ino)
1763 bytes = range_bytes;
1765 spin_lock(&sinfo->lock);
1766 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1767 spin_unlock(&sinfo->lock);
1770 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1774 return cow_file_range(inode, locked_page, start, end, page_started,
1775 nr_written, 1, NULL);
1778 struct can_nocow_file_extent_args {
1781 /* Start file offset of the range we want to NOCOW. */
1783 /* End file offset (inclusive) of the range we want to NOCOW. */
1785 bool writeback_path;
1788 * Free the path passed to can_nocow_file_extent() once it's not needed
1793 /* Output fields. Only set when can_nocow_file_extent() returns 1. */
1798 /* Number of bytes that can be written to in NOCOW mode. */
1803 * Check if we can NOCOW the file extent that the path points to.
1804 * This function may return with the path released, so the caller should check
1805 * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
1807 * Returns: < 0 on error
1808 * 0 if we can not NOCOW
1811 static int can_nocow_file_extent(struct btrfs_path *path,
1812 struct btrfs_key *key,
1813 struct btrfs_inode *inode,
1814 struct can_nocow_file_extent_args *args)
1816 const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
1817 struct extent_buffer *leaf = path->nodes[0];
1818 struct btrfs_root *root = inode->root;
1819 struct btrfs_file_extent_item *fi;
1824 bool nowait = path->nowait;
1826 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
1827 extent_type = btrfs_file_extent_type(leaf, fi);
1829 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1832 /* Can't access these fields unless we know it's not an inline extent. */
1833 args->disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1834 args->disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1835 args->extent_offset = btrfs_file_extent_offset(leaf, fi);
1837 if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1838 extent_type == BTRFS_FILE_EXTENT_REG)
1842 * If the extent was created before the generation where the last snapshot
1843 * for its subvolume was created, then this implies the extent is shared,
1844 * hence we must COW.
1846 if (!args->strict &&
1847 btrfs_file_extent_generation(leaf, fi) <=
1848 btrfs_root_last_snapshot(&root->root_item))
1851 /* An explicit hole, must COW. */
1852 if (args->disk_bytenr == 0)
1855 /* Compressed/encrypted/encoded extents must be COWed. */
1856 if (btrfs_file_extent_compression(leaf, fi) ||
1857 btrfs_file_extent_encryption(leaf, fi) ||
1858 btrfs_file_extent_other_encoding(leaf, fi))
1861 extent_end = btrfs_file_extent_end(path);
1864 * The following checks can be expensive, as they need to take other
1865 * locks and do btree or rbtree searches, so release the path to avoid
1866 * blocking other tasks for too long.
1868 btrfs_release_path(path);
1870 ret = btrfs_cross_ref_exist(root, btrfs_ino(inode),
1871 key->offset - args->extent_offset,
1872 args->disk_bytenr, false, path);
1873 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1877 if (args->free_path) {
1879 * We don't need the path anymore, plus through the
1880 * csum_exist_in_range() call below we will end up allocating
1881 * another path. So free the path to avoid unnecessary extra
1884 btrfs_free_path(path);
1888 /* If there are pending snapshots for this root, we must COW. */
1889 if (args->writeback_path && !is_freespace_inode &&
1890 atomic_read(&root->snapshot_force_cow))
1893 args->disk_bytenr += args->extent_offset;
1894 args->disk_bytenr += args->start - key->offset;
1895 args->num_bytes = min(args->end + 1, extent_end) - args->start;
1898 * Force COW if csums exist in the range. This ensures that csums for a
1899 * given extent are either valid or do not exist.
1901 ret = csum_exist_in_range(root->fs_info, args->disk_bytenr, args->num_bytes,
1903 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1909 if (args->free_path && path)
1910 btrfs_free_path(path);
1912 return ret < 0 ? ret : can_nocow;
1916 * when nowcow writeback call back. This checks for snapshots or COW copies
1917 * of the extents that exist in the file, and COWs the file as required.
1919 * If no cow copies or snapshots exist, we write directly to the existing
1922 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1923 struct page *locked_page,
1924 const u64 start, const u64 end,
1926 unsigned long *nr_written)
1928 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1929 struct btrfs_root *root = inode->root;
1930 struct btrfs_path *path;
1931 u64 cow_start = (u64)-1;
1932 u64 cur_offset = start;
1934 bool check_prev = true;
1935 u64 ino = btrfs_ino(inode);
1936 struct btrfs_block_group *bg;
1938 struct can_nocow_file_extent_args nocow_args = { 0 };
1940 path = btrfs_alloc_path();
1942 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1943 EXTENT_LOCKED | EXTENT_DELALLOC |
1944 EXTENT_DO_ACCOUNTING |
1945 EXTENT_DEFRAG, PAGE_UNLOCK |
1946 PAGE_START_WRITEBACK |
1947 PAGE_END_WRITEBACK);
1951 nocow_args.end = end;
1952 nocow_args.writeback_path = true;
1955 struct btrfs_key found_key;
1956 struct btrfs_file_extent_item *fi;
1957 struct extent_buffer *leaf;
1965 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1971 * If there is no extent for our range when doing the initial
1972 * search, then go back to the previous slot as it will be the
1973 * one containing the search offset
1975 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1976 leaf = path->nodes[0];
1977 btrfs_item_key_to_cpu(leaf, &found_key,
1978 path->slots[0] - 1);
1979 if (found_key.objectid == ino &&
1980 found_key.type == BTRFS_EXTENT_DATA_KEY)
1985 /* Go to next leaf if we have exhausted the current one */
1986 leaf = path->nodes[0];
1987 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1988 ret = btrfs_next_leaf(root, path);
1990 if (cow_start != (u64)-1)
1991 cur_offset = cow_start;
1996 leaf = path->nodes[0];
1999 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2001 /* Didn't find anything for our INO */
2002 if (found_key.objectid > ino)
2005 * Keep searching until we find an EXTENT_ITEM or there are no
2006 * more extents for this inode
2008 if (WARN_ON_ONCE(found_key.objectid < ino) ||
2009 found_key.type < BTRFS_EXTENT_DATA_KEY) {
2014 /* Found key is not EXTENT_DATA_KEY or starts after req range */
2015 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
2016 found_key.offset > end)
2020 * If the found extent starts after requested offset, then
2021 * adjust extent_end to be right before this extent begins
2023 if (found_key.offset > cur_offset) {
2024 extent_end = found_key.offset;
2030 * Found extent which begins before our range and potentially
2033 fi = btrfs_item_ptr(leaf, path->slots[0],
2034 struct btrfs_file_extent_item);
2035 extent_type = btrfs_file_extent_type(leaf, fi);
2036 /* If this is triggered then we have a memory corruption. */
2037 ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
2038 if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
2042 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
2043 extent_end = btrfs_file_extent_end(path);
2046 * If the extent we got ends before our current offset, skip to
2049 if (extent_end <= cur_offset) {
2054 nocow_args.start = cur_offset;
2055 ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
2057 if (cow_start != (u64)-1)
2058 cur_offset = cow_start;
2060 } else if (ret == 0) {
2065 bg = btrfs_inc_nocow_writers(fs_info, nocow_args.disk_bytenr);
2070 * If nocow is false then record the beginning of the range
2071 * that needs to be COWed
2074 if (cow_start == (u64)-1)
2075 cow_start = cur_offset;
2076 cur_offset = extent_end;
2077 if (cur_offset > end)
2079 if (!path->nodes[0])
2086 * COW range from cow_start to found_key.offset - 1. As the key
2087 * will contain the beginning of the first extent that can be
2088 * NOCOW, following one which needs to be COW'ed
2090 if (cow_start != (u64)-1) {
2091 ret = fallback_to_cow(inode, locked_page,
2092 cow_start, found_key.offset - 1,
2093 page_started, nr_written);
2096 cow_start = (u64)-1;
2099 nocow_end = cur_offset + nocow_args.num_bytes - 1;
2101 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
2102 u64 orig_start = found_key.offset - nocow_args.extent_offset;
2103 struct extent_map *em;
2105 em = create_io_em(inode, cur_offset, nocow_args.num_bytes,
2107 nocow_args.disk_bytenr, /* block_start */
2108 nocow_args.num_bytes, /* block_len */
2109 nocow_args.disk_num_bytes, /* orig_block_len */
2110 ram_bytes, BTRFS_COMPRESS_NONE,
2111 BTRFS_ORDERED_PREALLOC);
2116 free_extent_map(em);
2117 ret = btrfs_add_ordered_extent(inode,
2118 cur_offset, nocow_args.num_bytes,
2119 nocow_args.num_bytes,
2120 nocow_args.disk_bytenr,
2121 nocow_args.num_bytes, 0,
2122 1 << BTRFS_ORDERED_PREALLOC,
2123 BTRFS_COMPRESS_NONE);
2125 btrfs_drop_extent_map_range(inode, cur_offset,
2130 ret = btrfs_add_ordered_extent(inode, cur_offset,
2131 nocow_args.num_bytes,
2132 nocow_args.num_bytes,
2133 nocow_args.disk_bytenr,
2134 nocow_args.num_bytes,
2136 1 << BTRFS_ORDERED_NOCOW,
2137 BTRFS_COMPRESS_NONE);
2143 btrfs_dec_nocow_writers(bg);
2147 if (btrfs_is_data_reloc_root(root))
2149 * Error handled later, as we must prevent
2150 * extent_clear_unlock_delalloc() in error handler
2151 * from freeing metadata of created ordered extent.
2153 ret = btrfs_reloc_clone_csums(inode, cur_offset,
2154 nocow_args.num_bytes);
2156 extent_clear_unlock_delalloc(inode, cur_offset, nocow_end,
2157 locked_page, EXTENT_LOCKED |
2159 EXTENT_CLEAR_DATA_RESV,
2160 PAGE_UNLOCK | PAGE_SET_ORDERED);
2162 cur_offset = extent_end;
2165 * btrfs_reloc_clone_csums() error, now we're OK to call error
2166 * handler, as metadata for created ordered extent will only
2167 * be freed by btrfs_finish_ordered_io().
2171 if (cur_offset > end)
2174 btrfs_release_path(path);
2176 if (cur_offset <= end && cow_start == (u64)-1)
2177 cow_start = cur_offset;
2179 if (cow_start != (u64)-1) {
2181 ret = fallback_to_cow(inode, locked_page, cow_start, end,
2182 page_started, nr_written);
2189 btrfs_dec_nocow_writers(bg);
2191 if (ret && cur_offset < end)
2192 extent_clear_unlock_delalloc(inode, cur_offset, end,
2193 locked_page, EXTENT_LOCKED |
2194 EXTENT_DELALLOC | EXTENT_DEFRAG |
2195 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
2196 PAGE_START_WRITEBACK |
2197 PAGE_END_WRITEBACK);
2198 btrfs_free_path(path);
2202 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
2204 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
2205 if (inode->defrag_bytes &&
2206 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
2215 * Function to process delayed allocation (create CoW) for ranges which are
2216 * being touched for the first time.
2218 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
2219 u64 start, u64 end, int *page_started, unsigned long *nr_written,
2220 struct writeback_control *wbc)
2223 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2226 * The range must cover part of the @locked_page, or the returned
2227 * @page_started can confuse the caller.
2229 ASSERT(!(end <= page_offset(locked_page) ||
2230 start >= page_offset(locked_page) + PAGE_SIZE));
2232 if (should_nocow(inode, start, end)) {
2234 * Normally on a zoned device we're only doing COW writes, but
2235 * in case of relocation on a zoned filesystem we have taken
2236 * precaution, that we're only writing sequentially. It's safe
2237 * to use run_delalloc_nocow() here, like for regular
2238 * preallocated inodes.
2240 ASSERT(!zoned || btrfs_is_data_reloc_root(inode->root));
2241 ret = run_delalloc_nocow(inode, locked_page, start, end,
2242 page_started, nr_written);
2243 } else if (!btrfs_inode_can_compress(inode) ||
2244 !inode_need_compress(inode, start, end)) {
2246 ret = run_delalloc_zoned(inode, locked_page, start, end,
2247 page_started, nr_written);
2249 ret = cow_file_range(inode, locked_page, start, end,
2250 page_started, nr_written, 1, NULL);
2252 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
2253 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
2254 page_started, nr_written);
2258 btrfs_cleanup_ordered_extents(inode, locked_page, start,
2263 void btrfs_split_delalloc_extent(struct btrfs_inode *inode,
2264 struct extent_state *orig, u64 split)
2266 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2269 /* not delalloc, ignore it */
2270 if (!(orig->state & EXTENT_DELALLOC))
2273 size = orig->end - orig->start + 1;
2274 if (size > fs_info->max_extent_size) {
2279 * See the explanation in btrfs_merge_delalloc_extent, the same
2280 * applies here, just in reverse.
2282 new_size = orig->end - split + 1;
2283 num_extents = count_max_extents(fs_info, new_size);
2284 new_size = split - orig->start;
2285 num_extents += count_max_extents(fs_info, new_size);
2286 if (count_max_extents(fs_info, size) >= num_extents)
2290 spin_lock(&inode->lock);
2291 btrfs_mod_outstanding_extents(inode, 1);
2292 spin_unlock(&inode->lock);
2296 * Handle merged delayed allocation extents so we can keep track of new extents
2297 * that are just merged onto old extents, such as when we are doing sequential
2298 * writes, so we can properly account for the metadata space we'll need.
2300 void btrfs_merge_delalloc_extent(struct btrfs_inode *inode, struct extent_state *new,
2301 struct extent_state *other)
2303 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2304 u64 new_size, old_size;
2307 /* not delalloc, ignore it */
2308 if (!(other->state & EXTENT_DELALLOC))
2311 if (new->start > other->start)
2312 new_size = new->end - other->start + 1;
2314 new_size = other->end - new->start + 1;
2316 /* we're not bigger than the max, unreserve the space and go */
2317 if (new_size <= fs_info->max_extent_size) {
2318 spin_lock(&inode->lock);
2319 btrfs_mod_outstanding_extents(inode, -1);
2320 spin_unlock(&inode->lock);
2325 * We have to add up either side to figure out how many extents were
2326 * accounted for before we merged into one big extent. If the number of
2327 * extents we accounted for is <= the amount we need for the new range
2328 * then we can return, otherwise drop. Think of it like this
2332 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2333 * need 2 outstanding extents, on one side we have 1 and the other side
2334 * we have 1 so they are == and we can return. But in this case
2336 * [MAX_SIZE+4k][MAX_SIZE+4k]
2338 * Each range on their own accounts for 2 extents, but merged together
2339 * they are only 3 extents worth of accounting, so we need to drop in
2342 old_size = other->end - other->start + 1;
2343 num_extents = count_max_extents(fs_info, old_size);
2344 old_size = new->end - new->start + 1;
2345 num_extents += count_max_extents(fs_info, old_size);
2346 if (count_max_extents(fs_info, new_size) >= num_extents)
2349 spin_lock(&inode->lock);
2350 btrfs_mod_outstanding_extents(inode, -1);
2351 spin_unlock(&inode->lock);
2354 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2355 struct btrfs_inode *inode)
2357 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2359 spin_lock(&root->delalloc_lock);
2360 if (list_empty(&inode->delalloc_inodes)) {
2361 list_add_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
2362 set_bit(BTRFS_INODE_IN_DELALLOC_LIST, &inode->runtime_flags);
2363 root->nr_delalloc_inodes++;
2364 if (root->nr_delalloc_inodes == 1) {
2365 spin_lock(&fs_info->delalloc_root_lock);
2366 BUG_ON(!list_empty(&root->delalloc_root));
2367 list_add_tail(&root->delalloc_root,
2368 &fs_info->delalloc_roots);
2369 spin_unlock(&fs_info->delalloc_root_lock);
2372 spin_unlock(&root->delalloc_lock);
2375 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2376 struct btrfs_inode *inode)
2378 struct btrfs_fs_info *fs_info = root->fs_info;
2380 if (!list_empty(&inode->delalloc_inodes)) {
2381 list_del_init(&inode->delalloc_inodes);
2382 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2383 &inode->runtime_flags);
2384 root->nr_delalloc_inodes--;
2385 if (!root->nr_delalloc_inodes) {
2386 ASSERT(list_empty(&root->delalloc_inodes));
2387 spin_lock(&fs_info->delalloc_root_lock);
2388 BUG_ON(list_empty(&root->delalloc_root));
2389 list_del_init(&root->delalloc_root);
2390 spin_unlock(&fs_info->delalloc_root_lock);
2395 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2396 struct btrfs_inode *inode)
2398 spin_lock(&root->delalloc_lock);
2399 __btrfs_del_delalloc_inode(root, inode);
2400 spin_unlock(&root->delalloc_lock);
2404 * Properly track delayed allocation bytes in the inode and to maintain the
2405 * list of inodes that have pending delalloc work to be done.
2407 void btrfs_set_delalloc_extent(struct btrfs_inode *inode, struct extent_state *state,
2410 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2412 if ((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC))
2415 * set_bit and clear bit hooks normally require _irqsave/restore
2416 * but in this case, we are only testing for the DELALLOC
2417 * bit, which is only set or cleared with irqs on
2419 if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2420 struct btrfs_root *root = inode->root;
2421 u64 len = state->end + 1 - state->start;
2422 u32 num_extents = count_max_extents(fs_info, len);
2423 bool do_list = !btrfs_is_free_space_inode(inode);
2425 spin_lock(&inode->lock);
2426 btrfs_mod_outstanding_extents(inode, num_extents);
2427 spin_unlock(&inode->lock);
2429 /* For sanity tests */
2430 if (btrfs_is_testing(fs_info))
2433 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2434 fs_info->delalloc_batch);
2435 spin_lock(&inode->lock);
2436 inode->delalloc_bytes += len;
2437 if (bits & EXTENT_DEFRAG)
2438 inode->defrag_bytes += len;
2439 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2440 &inode->runtime_flags))
2441 btrfs_add_delalloc_inodes(root, inode);
2442 spin_unlock(&inode->lock);
2445 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2446 (bits & EXTENT_DELALLOC_NEW)) {
2447 spin_lock(&inode->lock);
2448 inode->new_delalloc_bytes += state->end + 1 - state->start;
2449 spin_unlock(&inode->lock);
2454 * Once a range is no longer delalloc this function ensures that proper
2455 * accounting happens.
2457 void btrfs_clear_delalloc_extent(struct btrfs_inode *inode,
2458 struct extent_state *state, u32 bits)
2460 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2461 u64 len = state->end + 1 - state->start;
2462 u32 num_extents = count_max_extents(fs_info, len);
2464 if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
2465 spin_lock(&inode->lock);
2466 inode->defrag_bytes -= len;
2467 spin_unlock(&inode->lock);
2471 * set_bit and clear bit hooks normally require _irqsave/restore
2472 * but in this case, we are only testing for the DELALLOC
2473 * bit, which is only set or cleared with irqs on
2475 if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2476 struct btrfs_root *root = inode->root;
2477 bool do_list = !btrfs_is_free_space_inode(inode);
2479 spin_lock(&inode->lock);
2480 btrfs_mod_outstanding_extents(inode, -num_extents);
2481 spin_unlock(&inode->lock);
2484 * We don't reserve metadata space for space cache inodes so we
2485 * don't need to call delalloc_release_metadata if there is an
2488 if (bits & EXTENT_CLEAR_META_RESV &&
2489 root != fs_info->tree_root)
2490 btrfs_delalloc_release_metadata(inode, len, false);
2492 /* For sanity tests. */
2493 if (btrfs_is_testing(fs_info))
2496 if (!btrfs_is_data_reloc_root(root) &&
2497 do_list && !(state->state & EXTENT_NORESERVE) &&
2498 (bits & EXTENT_CLEAR_DATA_RESV))
2499 btrfs_free_reserved_data_space_noquota(fs_info, len);
2501 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2502 fs_info->delalloc_batch);
2503 spin_lock(&inode->lock);
2504 inode->delalloc_bytes -= len;
2505 if (do_list && inode->delalloc_bytes == 0 &&
2506 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2507 &inode->runtime_flags))
2508 btrfs_del_delalloc_inode(root, inode);
2509 spin_unlock(&inode->lock);
2512 if ((state->state & EXTENT_DELALLOC_NEW) &&
2513 (bits & EXTENT_DELALLOC_NEW)) {
2514 spin_lock(&inode->lock);
2515 ASSERT(inode->new_delalloc_bytes >= len);
2516 inode->new_delalloc_bytes -= len;
2517 if (bits & EXTENT_ADD_INODE_BYTES)
2518 inode_add_bytes(&inode->vfs_inode, len);
2519 spin_unlock(&inode->lock);
2524 * Split an extent_map at [start, start + len]
2526 * This function is intended to be used only for extract_ordered_extent().
2528 static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
2531 struct extent_map_tree *em_tree = &inode->extent_tree;
2532 struct extent_map *em;
2533 struct extent_map *split_pre = NULL;
2534 struct extent_map *split_mid = NULL;
2535 struct extent_map *split_post = NULL;
2537 unsigned long flags;
2540 if (pre == 0 && post == 0)
2543 split_pre = alloc_extent_map();
2545 split_mid = alloc_extent_map();
2547 split_post = alloc_extent_map();
2548 if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
2553 ASSERT(pre + post < len);
2555 lock_extent(&inode->io_tree, start, start + len - 1, NULL);
2556 write_lock(&em_tree->lock);
2557 em = lookup_extent_mapping(em_tree, start, len);
2563 ASSERT(em->len == len);
2564 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2565 ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
2566 ASSERT(test_bit(EXTENT_FLAG_PINNED, &em->flags));
2567 ASSERT(!test_bit(EXTENT_FLAG_LOGGING, &em->flags));
2568 ASSERT(!list_empty(&em->list));
2571 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
2573 /* First, replace the em with a new extent_map starting from * em->start */
2574 split_pre->start = em->start;
2575 split_pre->len = (pre ? pre : em->len - post);
2576 split_pre->orig_start = split_pre->start;
2577 split_pre->block_start = em->block_start;
2578 split_pre->block_len = split_pre->len;
2579 split_pre->orig_block_len = split_pre->block_len;
2580 split_pre->ram_bytes = split_pre->len;
2581 split_pre->flags = flags;
2582 split_pre->compress_type = em->compress_type;
2583 split_pre->generation = em->generation;
2585 replace_extent_mapping(em_tree, em, split_pre, 1);
2588 * Now we only have an extent_map at:
2589 * [em->start, em->start + pre] if pre != 0
2590 * [em->start, em->start + em->len - post] if pre == 0
2594 /* Insert the middle extent_map */
2595 split_mid->start = em->start + pre;
2596 split_mid->len = em->len - pre - post;
2597 split_mid->orig_start = split_mid->start;
2598 split_mid->block_start = em->block_start + pre;
2599 split_mid->block_len = split_mid->len;
2600 split_mid->orig_block_len = split_mid->block_len;
2601 split_mid->ram_bytes = split_mid->len;
2602 split_mid->flags = flags;
2603 split_mid->compress_type = em->compress_type;
2604 split_mid->generation = em->generation;
2605 add_extent_mapping(em_tree, split_mid, 1);
2609 split_post->start = em->start + em->len - post;
2610 split_post->len = post;
2611 split_post->orig_start = split_post->start;
2612 split_post->block_start = em->block_start + em->len - post;
2613 split_post->block_len = split_post->len;
2614 split_post->orig_block_len = split_post->block_len;
2615 split_post->ram_bytes = split_post->len;
2616 split_post->flags = flags;
2617 split_post->compress_type = em->compress_type;
2618 split_post->generation = em->generation;
2619 add_extent_mapping(em_tree, split_post, 1);
2623 free_extent_map(em);
2624 /* Once for the tree */
2625 free_extent_map(em);
2628 write_unlock(&em_tree->lock);
2629 unlock_extent(&inode->io_tree, start, start + len - 1, NULL);
2631 free_extent_map(split_pre);
2632 free_extent_map(split_mid);
2633 free_extent_map(split_post);
2638 blk_status_t btrfs_extract_ordered_extent(struct btrfs_bio *bbio)
2640 u64 start = (u64)bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT;
2641 u64 len = bbio->bio.bi_iter.bi_size;
2642 struct btrfs_inode *inode = bbio->inode;
2643 struct btrfs_ordered_extent *ordered;
2645 u64 end = start + len;
2650 ordered = btrfs_lookup_ordered_extent(inode, bbio->file_offset);
2651 if (WARN_ON_ONCE(!ordered))
2652 return BLK_STS_IOERR;
2654 /* No need to split */
2655 if (ordered->disk_num_bytes == len)
2658 /* We cannot split once end_bio'd ordered extent */
2659 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2664 /* We cannot split a compressed ordered extent */
2665 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2670 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2671 /* bio must be in one ordered extent */
2672 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2677 /* Checksum list should be empty */
2678 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2683 file_len = ordered->num_bytes;
2684 pre = start - ordered->disk_bytenr;
2685 post = ordered_end - end;
2687 ret = btrfs_split_ordered_extent(ordered, pre, post);
2690 ret = split_zoned_em(inode, bbio->file_offset, file_len, pre, post);
2693 btrfs_put_ordered_extent(ordered);
2695 return errno_to_blk_status(ret);
2699 * given a list of ordered sums record them in the inode. This happens
2700 * at IO completion time based on sums calculated at bio submission time.
2702 static int add_pending_csums(struct btrfs_trans_handle *trans,
2703 struct list_head *list)
2705 struct btrfs_ordered_sum *sum;
2706 struct btrfs_root *csum_root = NULL;
2709 list_for_each_entry(sum, list, list) {
2710 trans->adding_csums = true;
2712 csum_root = btrfs_csum_root(trans->fs_info,
2714 ret = btrfs_csum_file_blocks(trans, csum_root, sum);
2715 trans->adding_csums = false;
2722 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2725 struct extent_state **cached_state)
2727 u64 search_start = start;
2728 const u64 end = start + len - 1;
2730 while (search_start < end) {
2731 const u64 search_len = end - search_start + 1;
2732 struct extent_map *em;
2736 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2740 if (em->block_start != EXTENT_MAP_HOLE)
2744 if (em->start < search_start)
2745 em_len -= search_start - em->start;
2746 if (em_len > search_len)
2747 em_len = search_len;
2749 ret = set_extent_bit(&inode->io_tree, search_start,
2750 search_start + em_len - 1,
2751 EXTENT_DELALLOC_NEW, cached_state,
2754 search_start = extent_map_end(em);
2755 free_extent_map(em);
2762 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2763 unsigned int extra_bits,
2764 struct extent_state **cached_state)
2766 WARN_ON(PAGE_ALIGNED(end));
2768 if (start >= i_size_read(&inode->vfs_inode) &&
2769 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2771 * There can't be any extents following eof in this case so just
2772 * set the delalloc new bit for the range directly.
2774 extra_bits |= EXTENT_DELALLOC_NEW;
2778 ret = btrfs_find_new_delalloc_bytes(inode, start,
2785 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2789 /* see btrfs_writepage_start_hook for details on why this is required */
2790 struct btrfs_writepage_fixup {
2792 struct btrfs_inode *inode;
2793 struct btrfs_work work;
2796 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2798 struct btrfs_writepage_fixup *fixup;
2799 struct btrfs_ordered_extent *ordered;
2800 struct extent_state *cached_state = NULL;
2801 struct extent_changeset *data_reserved = NULL;
2803 struct btrfs_inode *inode;
2807 bool free_delalloc_space = true;
2809 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2811 inode = fixup->inode;
2812 page_start = page_offset(page);
2813 page_end = page_offset(page) + PAGE_SIZE - 1;
2816 * This is similar to page_mkwrite, we need to reserve the space before
2817 * we take the page lock.
2819 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2825 * Before we queued this fixup, we took a reference on the page.
2826 * page->mapping may go NULL, but it shouldn't be moved to a different
2829 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2831 * Unfortunately this is a little tricky, either
2833 * 1) We got here and our page had already been dealt with and
2834 * we reserved our space, thus ret == 0, so we need to just
2835 * drop our space reservation and bail. This can happen the
2836 * first time we come into the fixup worker, or could happen
2837 * while waiting for the ordered extent.
2838 * 2) Our page was already dealt with, but we happened to get an
2839 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2840 * this case we obviously don't have anything to release, but
2841 * because the page was already dealt with we don't want to
2842 * mark the page with an error, so make sure we're resetting
2843 * ret to 0. This is why we have this check _before_ the ret
2844 * check, because we do not want to have a surprise ENOSPC
2845 * when the page was already properly dealt with.
2848 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2849 btrfs_delalloc_release_space(inode, data_reserved,
2850 page_start, PAGE_SIZE,
2858 * We can't mess with the page state unless it is locked, so now that
2859 * it is locked bail if we failed to make our space reservation.
2864 lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2866 /* already ordered? We're done */
2867 if (PageOrdered(page))
2870 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2872 unlock_extent(&inode->io_tree, page_start, page_end,
2875 btrfs_start_ordered_extent(ordered);
2876 btrfs_put_ordered_extent(ordered);
2880 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2886 * Everything went as planned, we're now the owner of a dirty page with
2887 * delayed allocation bits set and space reserved for our COW
2890 * The page was dirty when we started, nothing should have cleaned it.
2892 BUG_ON(!PageDirty(page));
2893 free_delalloc_space = false;
2895 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2896 if (free_delalloc_space)
2897 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2899 unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2903 * We hit ENOSPC or other errors. Update the mapping and page
2904 * to reflect the errors and clean the page.
2906 mapping_set_error(page->mapping, ret);
2907 end_extent_writepage(page, ret, page_start, page_end);
2908 clear_page_dirty_for_io(page);
2911 btrfs_page_clear_checked(inode->root->fs_info, page, page_start, PAGE_SIZE);
2915 extent_changeset_free(data_reserved);
2917 * As a precaution, do a delayed iput in case it would be the last iput
2918 * that could need flushing space. Recursing back to fixup worker would
2921 btrfs_add_delayed_iput(inode);
2925 * There are a few paths in the higher layers of the kernel that directly
2926 * set the page dirty bit without asking the filesystem if it is a
2927 * good idea. This causes problems because we want to make sure COW
2928 * properly happens and the data=ordered rules are followed.
2930 * In our case any range that doesn't have the ORDERED bit set
2931 * hasn't been properly setup for IO. We kick off an async process
2932 * to fix it up. The async helper will wait for ordered extents, set
2933 * the delalloc bit and make it safe to write the page.
2935 int btrfs_writepage_cow_fixup(struct page *page)
2937 struct inode *inode = page->mapping->host;
2938 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2939 struct btrfs_writepage_fixup *fixup;
2941 /* This page has ordered extent covering it already */
2942 if (PageOrdered(page))
2946 * PageChecked is set below when we create a fixup worker for this page,
2947 * don't try to create another one if we're already PageChecked()
2949 * The extent_io writepage code will redirty the page if we send back
2952 if (PageChecked(page))
2955 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2960 * We are already holding a reference to this inode from
2961 * write_cache_pages. We need to hold it because the space reservation
2962 * takes place outside of the page lock, and we can't trust
2963 * page->mapping outside of the page lock.
2966 btrfs_page_set_checked(fs_info, page, page_offset(page), PAGE_SIZE);
2968 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2970 fixup->inode = BTRFS_I(inode);
2971 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2976 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2977 struct btrfs_inode *inode, u64 file_pos,
2978 struct btrfs_file_extent_item *stack_fi,
2979 const bool update_inode_bytes,
2980 u64 qgroup_reserved)
2982 struct btrfs_root *root = inode->root;
2983 const u64 sectorsize = root->fs_info->sectorsize;
2984 struct btrfs_path *path;
2985 struct extent_buffer *leaf;
2986 struct btrfs_key ins;
2987 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2988 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2989 u64 offset = btrfs_stack_file_extent_offset(stack_fi);
2990 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2991 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2992 struct btrfs_drop_extents_args drop_args = { 0 };
2995 path = btrfs_alloc_path();
3000 * we may be replacing one extent in the tree with another.
3001 * The new extent is pinned in the extent map, and we don't want
3002 * to drop it from the cache until it is completely in the btree.
3004 * So, tell btrfs_drop_extents to leave this extent in the cache.
3005 * the caller is expected to unpin it and allow it to be merged
3008 drop_args.path = path;
3009 drop_args.start = file_pos;
3010 drop_args.end = file_pos + num_bytes;
3011 drop_args.replace_extent = true;
3012 drop_args.extent_item_size = sizeof(*stack_fi);
3013 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
3017 if (!drop_args.extent_inserted) {
3018 ins.objectid = btrfs_ino(inode);
3019 ins.offset = file_pos;
3020 ins.type = BTRFS_EXTENT_DATA_KEY;
3022 ret = btrfs_insert_empty_item(trans, root, path, &ins,
3027 leaf = path->nodes[0];
3028 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
3029 write_extent_buffer(leaf, stack_fi,
3030 btrfs_item_ptr_offset(leaf, path->slots[0]),
3031 sizeof(struct btrfs_file_extent_item));
3033 btrfs_mark_buffer_dirty(leaf);
3034 btrfs_release_path(path);
3037 * If we dropped an inline extent here, we know the range where it is
3038 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
3039 * number of bytes only for that range containing the inline extent.
3040 * The remaining of the range will be processed when clearning the
3041 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
3043 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
3044 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
3046 inline_size = drop_args.bytes_found - inline_size;
3047 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
3048 drop_args.bytes_found -= inline_size;
3049 num_bytes -= sectorsize;
3052 if (update_inode_bytes)
3053 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
3055 ins.objectid = disk_bytenr;
3056 ins.offset = disk_num_bytes;
3057 ins.type = BTRFS_EXTENT_ITEM_KEY;
3059 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
3063 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
3065 qgroup_reserved, &ins);
3067 btrfs_free_path(path);
3072 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
3075 struct btrfs_block_group *cache;
3077 cache = btrfs_lookup_block_group(fs_info, start);
3080 spin_lock(&cache->lock);
3081 cache->delalloc_bytes -= len;
3082 spin_unlock(&cache->lock);
3084 btrfs_put_block_group(cache);
3087 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
3088 struct btrfs_ordered_extent *oe)
3090 struct btrfs_file_extent_item stack_fi;
3091 bool update_inode_bytes;
3092 u64 num_bytes = oe->num_bytes;
3093 u64 ram_bytes = oe->ram_bytes;
3095 memset(&stack_fi, 0, sizeof(stack_fi));
3096 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
3097 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
3098 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
3099 oe->disk_num_bytes);
3100 btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
3101 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags)) {
3102 num_bytes = oe->truncated_len;
3103 ram_bytes = num_bytes;
3105 btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
3106 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
3107 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3108 /* Encryption and other encoding is reserved and all 0 */
3111 * For delalloc, when completing an ordered extent we update the inode's
3112 * bytes when clearing the range in the inode's io tree, so pass false
3113 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3114 * except if the ordered extent was truncated.
3116 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3117 test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
3118 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3120 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
3121 oe->file_offset, &stack_fi,
3122 update_inode_bytes, oe->qgroup_rsv);
3126 * As ordered data IO finishes, this gets called so we can finish
3127 * an ordered extent if the range of bytes in the file it covers are
3130 int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3132 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
3133 struct btrfs_root *root = inode->root;
3134 struct btrfs_fs_info *fs_info = root->fs_info;
3135 struct btrfs_trans_handle *trans = NULL;
3136 struct extent_io_tree *io_tree = &inode->io_tree;
3137 struct extent_state *cached_state = NULL;
3139 int compress_type = 0;
3141 u64 logical_len = ordered_extent->num_bytes;
3142 bool freespace_inode;
3143 bool truncated = false;
3144 bool clear_reserved_extent = true;
3145 unsigned int clear_bits = EXTENT_DEFRAG;
3147 start = ordered_extent->file_offset;
3148 end = start + ordered_extent->num_bytes - 1;
3150 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3151 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3152 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3153 !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3154 clear_bits |= EXTENT_DELALLOC_NEW;
3156 freespace_inode = btrfs_is_free_space_inode(inode);
3157 if (!freespace_inode)
3158 btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
3160 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3165 /* A valid ->physical implies a write on a sequential zone. */
3166 if (ordered_extent->physical != (u64)-1) {
3167 btrfs_rewrite_logical_zoned(ordered_extent);
3168 btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3169 ordered_extent->disk_num_bytes);
3172 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3174 logical_len = ordered_extent->truncated_len;
3175 /* Truncated the entire extent, don't bother adding */
3180 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3181 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3183 btrfs_inode_safe_disk_i_size_write(inode, 0);
3184 if (freespace_inode)
3185 trans = btrfs_join_transaction_spacecache(root);
3187 trans = btrfs_join_transaction(root);
3188 if (IS_ERR(trans)) {
3189 ret = PTR_ERR(trans);
3193 trans->block_rsv = &inode->block_rsv;
3194 ret = btrfs_update_inode_fallback(trans, root, inode);
3195 if (ret) /* -ENOMEM or corruption */
3196 btrfs_abort_transaction(trans, ret);
3200 clear_bits |= EXTENT_LOCKED;
3201 lock_extent(io_tree, start, end, &cached_state);
3203 if (freespace_inode)
3204 trans = btrfs_join_transaction_spacecache(root);
3206 trans = btrfs_join_transaction(root);
3207 if (IS_ERR(trans)) {
3208 ret = PTR_ERR(trans);
3213 trans->block_rsv = &inode->block_rsv;
3215 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3216 compress_type = ordered_extent->compress_type;
3217 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3218 BUG_ON(compress_type);
3219 ret = btrfs_mark_extent_written(trans, inode,
3220 ordered_extent->file_offset,
3221 ordered_extent->file_offset +
3223 btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3224 ordered_extent->disk_num_bytes);
3226 BUG_ON(root == fs_info->tree_root);
3227 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3229 clear_reserved_extent = false;
3230 btrfs_release_delalloc_bytes(fs_info,
3231 ordered_extent->disk_bytenr,
3232 ordered_extent->disk_num_bytes);
3235 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3236 ordered_extent->num_bytes, trans->transid);
3238 btrfs_abort_transaction(trans, ret);
3242 ret = add_pending_csums(trans, &ordered_extent->list);
3244 btrfs_abort_transaction(trans, ret);
3249 * If this is a new delalloc range, clear its new delalloc flag to
3250 * update the inode's number of bytes. This needs to be done first
3251 * before updating the inode item.
3253 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3254 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3255 clear_extent_bit(&inode->io_tree, start, end,
3256 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3259 btrfs_inode_safe_disk_i_size_write(inode, 0);
3260 ret = btrfs_update_inode_fallback(trans, root, inode);
3261 if (ret) { /* -ENOMEM or corruption */
3262 btrfs_abort_transaction(trans, ret);
3267 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3271 btrfs_end_transaction(trans);
3273 if (ret || truncated) {
3274 u64 unwritten_start = start;
3277 * If we failed to finish this ordered extent for any reason we
3278 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3279 * extent, and mark the inode with the error if it wasn't
3280 * already set. Any error during writeback would have already
3281 * set the mapping error, so we need to set it if we're the ones
3282 * marking this ordered extent as failed.
3284 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3285 &ordered_extent->flags))
3286 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3289 unwritten_start += logical_len;
3290 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3292 /* Drop extent maps for the part of the extent we didn't write. */
3293 btrfs_drop_extent_map_range(inode, unwritten_start, end, false);
3296 * If the ordered extent had an IOERR or something else went
3297 * wrong we need to return the space for this ordered extent
3298 * back to the allocator. We only free the extent in the
3299 * truncated case if we didn't write out the extent at all.
3301 * If we made it past insert_reserved_file_extent before we
3302 * errored out then we don't need to do this as the accounting
3303 * has already been done.
3305 if ((ret || !logical_len) &&
3306 clear_reserved_extent &&
3307 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3308 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3310 * Discard the range before returning it back to the
3313 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3314 btrfs_discard_extent(fs_info,
3315 ordered_extent->disk_bytenr,
3316 ordered_extent->disk_num_bytes,
3318 btrfs_free_reserved_extent(fs_info,
3319 ordered_extent->disk_bytenr,
3320 ordered_extent->disk_num_bytes, 1);
3325 * This needs to be done to make sure anybody waiting knows we are done
3326 * updating everything for this ordered extent.
3328 btrfs_remove_ordered_extent(inode, ordered_extent);
3331 btrfs_put_ordered_extent(ordered_extent);
3332 /* once for the tree */
3333 btrfs_put_ordered_extent(ordered_extent);
3338 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3339 struct page *page, u64 start,
3340 u64 end, bool uptodate)
3342 trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3344 btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start, uptodate);
3348 * Verify the checksum for a single sector without any extra action that depend
3349 * on the type of I/O.
3351 int btrfs_check_sector_csum(struct btrfs_fs_info *fs_info, struct page *page,
3352 u32 pgoff, u8 *csum, const u8 * const csum_expected)
3354 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3357 ASSERT(pgoff + fs_info->sectorsize <= PAGE_SIZE);
3359 shash->tfm = fs_info->csum_shash;
3361 kaddr = kmap_local_page(page) + pgoff;
3362 crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
3363 kunmap_local(kaddr);
3365 if (memcmp(csum, csum_expected, fs_info->csum_size))
3370 static u8 *btrfs_csum_ptr(const struct btrfs_fs_info *fs_info, u8 *csums, u64 offset)
3372 u64 offset_in_sectors = offset >> fs_info->sectorsize_bits;
3374 return csums + offset_in_sectors * fs_info->csum_size;
3378 * Verify the checksum of a single data sector.
3380 * @bbio: btrfs_io_bio which contains the csum
3381 * @dev: device the sector is on
3382 * @bio_offset: offset to the beginning of the bio (in bytes)
3383 * @bv: bio_vec to check
3385 * Check if the checksum on a data block is valid. When a checksum mismatch is
3386 * detected, report the error and fill the corrupted range with zero.
3388 * Return %true if the sector is ok or had no checksum to start with, else %false.
3390 bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev,
3391 u32 bio_offset, struct bio_vec *bv)
3393 struct btrfs_inode *inode = bbio->inode;
3394 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3395 u64 file_offset = bbio->file_offset + bio_offset;
3396 u64 end = file_offset + bv->bv_len - 1;
3398 u8 csum[BTRFS_CSUM_SIZE];
3400 ASSERT(bv->bv_len == fs_info->sectorsize);
3405 if (btrfs_is_data_reloc_root(inode->root) &&
3406 test_range_bit(&inode->io_tree, file_offset, end, EXTENT_NODATASUM,
3408 /* Skip the range without csum for data reloc inode */
3409 clear_extent_bits(&inode->io_tree, file_offset, end,
3414 csum_expected = btrfs_csum_ptr(fs_info, bbio->csum, bio_offset);
3415 if (btrfs_check_sector_csum(fs_info, bv->bv_page, bv->bv_offset, csum,
3421 btrfs_print_data_csum_error(inode, file_offset, csum, csum_expected,
3424 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
3430 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3432 * @inode: The inode we want to perform iput on
3434 * This function uses the generic vfs_inode::i_count to track whether we should
3435 * just decrement it (in case it's > 1) or if this is the last iput then link
3436 * the inode to the delayed iput machinery. Delayed iputs are processed at
3437 * transaction commit time/superblock commit/cleaner kthread.
3439 void btrfs_add_delayed_iput(struct btrfs_inode *inode)
3441 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3443 if (atomic_add_unless(&inode->vfs_inode.i_count, -1, 1))
3446 atomic_inc(&fs_info->nr_delayed_iputs);
3447 spin_lock(&fs_info->delayed_iput_lock);
3448 ASSERT(list_empty(&inode->delayed_iput));
3449 list_add_tail(&inode->delayed_iput, &fs_info->delayed_iputs);
3450 spin_unlock(&fs_info->delayed_iput_lock);
3451 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3452 wake_up_process(fs_info->cleaner_kthread);
3455 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3456 struct btrfs_inode *inode)
3458 list_del_init(&inode->delayed_iput);
3459 spin_unlock(&fs_info->delayed_iput_lock);
3460 iput(&inode->vfs_inode);
3461 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3462 wake_up(&fs_info->delayed_iputs_wait);
3463 spin_lock(&fs_info->delayed_iput_lock);
3466 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3467 struct btrfs_inode *inode)
3469 if (!list_empty(&inode->delayed_iput)) {
3470 spin_lock(&fs_info->delayed_iput_lock);
3471 if (!list_empty(&inode->delayed_iput))
3472 run_delayed_iput_locked(fs_info, inode);
3473 spin_unlock(&fs_info->delayed_iput_lock);
3477 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3480 spin_lock(&fs_info->delayed_iput_lock);
3481 while (!list_empty(&fs_info->delayed_iputs)) {
3482 struct btrfs_inode *inode;
3484 inode = list_first_entry(&fs_info->delayed_iputs,
3485 struct btrfs_inode, delayed_iput);
3486 run_delayed_iput_locked(fs_info, inode);
3487 cond_resched_lock(&fs_info->delayed_iput_lock);
3489 spin_unlock(&fs_info->delayed_iput_lock);
3493 * Wait for flushing all delayed iputs
3495 * @fs_info: the filesystem
3497 * This will wait on any delayed iputs that are currently running with KILLABLE
3498 * set. Once they are all done running we will return, unless we are killed in
3499 * which case we return EINTR. This helps in user operations like fallocate etc
3500 * that might get blocked on the iputs.
3502 * Return EINTR if we were killed, 0 if nothing's pending
3504 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3506 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3507 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3514 * This creates an orphan entry for the given inode in case something goes wrong
3515 * in the middle of an unlink.
3517 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3518 struct btrfs_inode *inode)
3522 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3523 if (ret && ret != -EEXIST) {
3524 btrfs_abort_transaction(trans, ret);
3532 * We have done the delete so we can go ahead and remove the orphan item for
3533 * this particular inode.
3535 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3536 struct btrfs_inode *inode)
3538 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3542 * this cleans up any orphans that may be left on the list from the last use
3545 int btrfs_orphan_cleanup(struct btrfs_root *root)
3547 struct btrfs_fs_info *fs_info = root->fs_info;
3548 struct btrfs_path *path;
3549 struct extent_buffer *leaf;
3550 struct btrfs_key key, found_key;
3551 struct btrfs_trans_handle *trans;
3552 struct inode *inode;
3553 u64 last_objectid = 0;
3554 int ret = 0, nr_unlink = 0;
3556 if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3559 path = btrfs_alloc_path();
3564 path->reada = READA_BACK;
3566 key.objectid = BTRFS_ORPHAN_OBJECTID;
3567 key.type = BTRFS_ORPHAN_ITEM_KEY;
3568 key.offset = (u64)-1;
3571 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3576 * if ret == 0 means we found what we were searching for, which
3577 * is weird, but possible, so only screw with path if we didn't
3578 * find the key and see if we have stuff that matches
3582 if (path->slots[0] == 0)
3587 /* pull out the item */
3588 leaf = path->nodes[0];
3589 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3591 /* make sure the item matches what we want */
3592 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3594 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3597 /* release the path since we're done with it */
3598 btrfs_release_path(path);
3601 * this is where we are basically btrfs_lookup, without the
3602 * crossing root thing. we store the inode number in the
3603 * offset of the orphan item.
3606 if (found_key.offset == last_objectid) {
3608 "Error removing orphan entry, stopping orphan cleanup");
3613 last_objectid = found_key.offset;
3615 found_key.objectid = found_key.offset;
3616 found_key.type = BTRFS_INODE_ITEM_KEY;
3617 found_key.offset = 0;
3618 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3619 ret = PTR_ERR_OR_ZERO(inode);
3620 if (ret && ret != -ENOENT)
3623 if (ret == -ENOENT && root == fs_info->tree_root) {
3624 struct btrfs_root *dead_root;
3625 int is_dead_root = 0;
3628 * This is an orphan in the tree root. Currently these
3629 * could come from 2 sources:
3630 * a) a root (snapshot/subvolume) deletion in progress
3631 * b) a free space cache inode
3632 * We need to distinguish those two, as the orphan item
3633 * for a root must not get deleted before the deletion
3634 * of the snapshot/subvolume's tree completes.
3636 * btrfs_find_orphan_roots() ran before us, which has
3637 * found all deleted roots and loaded them into
3638 * fs_info->fs_roots_radix. So here we can find if an
3639 * orphan item corresponds to a deleted root by looking
3640 * up the root from that radix tree.
3643 spin_lock(&fs_info->fs_roots_radix_lock);
3644 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3645 (unsigned long)found_key.objectid);
3646 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3648 spin_unlock(&fs_info->fs_roots_radix_lock);
3651 /* prevent this orphan from being found again */
3652 key.offset = found_key.objectid - 1;
3659 * If we have an inode with links, there are a couple of
3662 * 1. We were halfway through creating fsverity metadata for the
3663 * file. In that case, the orphan item represents incomplete
3664 * fsverity metadata which must be cleaned up with
3665 * btrfs_drop_verity_items and deleting the orphan item.
3667 * 2. Old kernels (before v3.12) used to create an
3668 * orphan item for truncate indicating that there were possibly
3669 * extent items past i_size that needed to be deleted. In v3.12,
3670 * truncate was changed to update i_size in sync with the extent
3671 * items, but the (useless) orphan item was still created. Since
3672 * v4.18, we don't create the orphan item for truncate at all.
3674 * So, this item could mean that we need to do a truncate, but
3675 * only if this filesystem was last used on a pre-v3.12 kernel
3676 * and was not cleanly unmounted. The odds of that are quite
3677 * slim, and it's a pain to do the truncate now, so just delete
3680 * It's also possible that this orphan item was supposed to be
3681 * deleted but wasn't. The inode number may have been reused,
3682 * but either way, we can delete the orphan item.
3684 if (ret == -ENOENT || inode->i_nlink) {
3686 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3691 trans = btrfs_start_transaction(root, 1);
3692 if (IS_ERR(trans)) {
3693 ret = PTR_ERR(trans);
3696 btrfs_debug(fs_info, "auto deleting %Lu",
3697 found_key.objectid);
3698 ret = btrfs_del_orphan_item(trans, root,
3699 found_key.objectid);
3700 btrfs_end_transaction(trans);
3708 /* this will do delete_inode and everything for us */
3711 /* release the path since we're done with it */
3712 btrfs_release_path(path);
3714 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3715 trans = btrfs_join_transaction(root);
3717 btrfs_end_transaction(trans);
3721 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3725 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3726 btrfs_free_path(path);
3731 * very simple check to peek ahead in the leaf looking for xattrs. If we
3732 * don't find any xattrs, we know there can't be any acls.
3734 * slot is the slot the inode is in, objectid is the objectid of the inode
3736 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3737 int slot, u64 objectid,
3738 int *first_xattr_slot)
3740 u32 nritems = btrfs_header_nritems(leaf);
3741 struct btrfs_key found_key;
3742 static u64 xattr_access = 0;
3743 static u64 xattr_default = 0;
3746 if (!xattr_access) {
3747 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3748 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3749 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3750 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3754 *first_xattr_slot = -1;
3755 while (slot < nritems) {
3756 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3758 /* we found a different objectid, there must not be acls */
3759 if (found_key.objectid != objectid)
3762 /* we found an xattr, assume we've got an acl */
3763 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3764 if (*first_xattr_slot == -1)
3765 *first_xattr_slot = slot;
3766 if (found_key.offset == xattr_access ||
3767 found_key.offset == xattr_default)
3772 * we found a key greater than an xattr key, there can't
3773 * be any acls later on
3775 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3782 * it goes inode, inode backrefs, xattrs, extents,
3783 * so if there are a ton of hard links to an inode there can
3784 * be a lot of backrefs. Don't waste time searching too hard,
3785 * this is just an optimization
3790 /* we hit the end of the leaf before we found an xattr or
3791 * something larger than an xattr. We have to assume the inode
3794 if (*first_xattr_slot == -1)
3795 *first_xattr_slot = slot;
3800 * read an inode from the btree into the in-memory inode
3802 static int btrfs_read_locked_inode(struct inode *inode,
3803 struct btrfs_path *in_path)
3805 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3806 struct btrfs_path *path = in_path;
3807 struct extent_buffer *leaf;
3808 struct btrfs_inode_item *inode_item;
3809 struct btrfs_root *root = BTRFS_I(inode)->root;
3810 struct btrfs_key location;
3815 bool filled = false;
3816 int first_xattr_slot;
3818 ret = btrfs_fill_inode(inode, &rdev);
3823 path = btrfs_alloc_path();
3828 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3830 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3832 if (path != in_path)
3833 btrfs_free_path(path);
3837 leaf = path->nodes[0];
3842 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3843 struct btrfs_inode_item);
3844 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3845 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3846 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3847 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3848 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3849 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3850 round_up(i_size_read(inode), fs_info->sectorsize));
3852 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3853 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3855 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3856 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3858 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3859 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3861 BTRFS_I(inode)->i_otime.tv_sec =
3862 btrfs_timespec_sec(leaf, &inode_item->otime);
3863 BTRFS_I(inode)->i_otime.tv_nsec =
3864 btrfs_timespec_nsec(leaf, &inode_item->otime);
3866 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3867 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3868 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3870 inode_set_iversion_queried(inode,
3871 btrfs_inode_sequence(leaf, inode_item));
3872 inode->i_generation = BTRFS_I(inode)->generation;
3874 rdev = btrfs_inode_rdev(leaf, inode_item);
3876 BTRFS_I(inode)->index_cnt = (u64)-1;
3877 btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
3878 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
3882 * If we were modified in the current generation and evicted from memory
3883 * and then re-read we need to do a full sync since we don't have any
3884 * idea about which extents were modified before we were evicted from
3887 * This is required for both inode re-read from disk and delayed inode
3888 * in delayed_nodes_tree.
3890 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3891 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3892 &BTRFS_I(inode)->runtime_flags);
3895 * We don't persist the id of the transaction where an unlink operation
3896 * against the inode was last made. So here we assume the inode might
3897 * have been evicted, and therefore the exact value of last_unlink_trans
3898 * lost, and set it to last_trans to avoid metadata inconsistencies
3899 * between the inode and its parent if the inode is fsync'ed and the log
3900 * replayed. For example, in the scenario:
3903 * ln mydir/foo mydir/bar
3906 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3907 * xfs_io -c fsync mydir/foo
3909 * mount fs, triggers fsync log replay
3911 * We must make sure that when we fsync our inode foo we also log its
3912 * parent inode, otherwise after log replay the parent still has the
3913 * dentry with the "bar" name but our inode foo has a link count of 1
3914 * and doesn't have an inode ref with the name "bar" anymore.
3916 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3917 * but it guarantees correctness at the expense of occasional full
3918 * transaction commits on fsync if our inode is a directory, or if our
3919 * inode is not a directory, logging its parent unnecessarily.
3921 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3924 * Same logic as for last_unlink_trans. We don't persist the generation
3925 * of the last transaction where this inode was used for a reflink
3926 * operation, so after eviction and reloading the inode we must be
3927 * pessimistic and assume the last transaction that modified the inode.
3929 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3932 if (inode->i_nlink != 1 ||
3933 path->slots[0] >= btrfs_header_nritems(leaf))
3936 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3937 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3940 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3941 if (location.type == BTRFS_INODE_REF_KEY) {
3942 struct btrfs_inode_ref *ref;
3944 ref = (struct btrfs_inode_ref *)ptr;
3945 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3946 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3947 struct btrfs_inode_extref *extref;
3949 extref = (struct btrfs_inode_extref *)ptr;
3950 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3955 * try to precache a NULL acl entry for files that don't have
3956 * any xattrs or acls
3958 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3959 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3960 if (first_xattr_slot != -1) {
3961 path->slots[0] = first_xattr_slot;
3962 ret = btrfs_load_inode_props(inode, path);
3965 "error loading props for ino %llu (root %llu): %d",
3966 btrfs_ino(BTRFS_I(inode)),
3967 root->root_key.objectid, ret);
3969 if (path != in_path)
3970 btrfs_free_path(path);
3973 cache_no_acl(inode);
3975 switch (inode->i_mode & S_IFMT) {
3977 inode->i_mapping->a_ops = &btrfs_aops;
3978 inode->i_fop = &btrfs_file_operations;
3979 inode->i_op = &btrfs_file_inode_operations;
3982 inode->i_fop = &btrfs_dir_file_operations;
3983 inode->i_op = &btrfs_dir_inode_operations;
3986 inode->i_op = &btrfs_symlink_inode_operations;
3987 inode_nohighmem(inode);
3988 inode->i_mapping->a_ops = &btrfs_aops;
3991 inode->i_op = &btrfs_special_inode_operations;
3992 init_special_inode(inode, inode->i_mode, rdev);
3996 btrfs_sync_inode_flags_to_i_flags(inode);
4001 * given a leaf and an inode, copy the inode fields into the leaf
4003 static void fill_inode_item(struct btrfs_trans_handle *trans,
4004 struct extent_buffer *leaf,
4005 struct btrfs_inode_item *item,
4006 struct inode *inode)
4008 struct btrfs_map_token token;
4011 btrfs_init_map_token(&token, leaf);
4013 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4014 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4015 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
4016 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4017 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4019 btrfs_set_token_timespec_sec(&token, &item->atime,
4020 inode->i_atime.tv_sec);
4021 btrfs_set_token_timespec_nsec(&token, &item->atime,
4022 inode->i_atime.tv_nsec);
4024 btrfs_set_token_timespec_sec(&token, &item->mtime,
4025 inode->i_mtime.tv_sec);
4026 btrfs_set_token_timespec_nsec(&token, &item->mtime,
4027 inode->i_mtime.tv_nsec);
4029 btrfs_set_token_timespec_sec(&token, &item->ctime,
4030 inode->i_ctime.tv_sec);
4031 btrfs_set_token_timespec_nsec(&token, &item->ctime,
4032 inode->i_ctime.tv_nsec);
4034 btrfs_set_token_timespec_sec(&token, &item->otime,
4035 BTRFS_I(inode)->i_otime.tv_sec);
4036 btrfs_set_token_timespec_nsec(&token, &item->otime,
4037 BTRFS_I(inode)->i_otime.tv_nsec);
4039 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
4040 btrfs_set_token_inode_generation(&token, item,
4041 BTRFS_I(inode)->generation);
4042 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4043 btrfs_set_token_inode_transid(&token, item, trans->transid);
4044 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4045 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4046 BTRFS_I(inode)->ro_flags);
4047 btrfs_set_token_inode_flags(&token, item, flags);
4048 btrfs_set_token_inode_block_group(&token, item, 0);
4052 * copy everything in the in-memory inode into the btree.
4054 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4055 struct btrfs_root *root,
4056 struct btrfs_inode *inode)
4058 struct btrfs_inode_item *inode_item;
4059 struct btrfs_path *path;
4060 struct extent_buffer *leaf;
4063 path = btrfs_alloc_path();
4067 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
4074 leaf = path->nodes[0];
4075 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4076 struct btrfs_inode_item);
4078 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4079 btrfs_mark_buffer_dirty(leaf);
4080 btrfs_set_inode_last_trans(trans, inode);
4083 btrfs_free_path(path);
4088 * copy everything in the in-memory inode into the btree.
4090 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4091 struct btrfs_root *root,
4092 struct btrfs_inode *inode)
4094 struct btrfs_fs_info *fs_info = root->fs_info;
4098 * If the inode is a free space inode, we can deadlock during commit
4099 * if we put it into the delayed code.
4101 * The data relocation inode should also be directly updated
4104 if (!btrfs_is_free_space_inode(inode)
4105 && !btrfs_is_data_reloc_root(root)
4106 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4107 btrfs_update_root_times(trans, root);
4109 ret = btrfs_delayed_update_inode(trans, root, inode);
4111 btrfs_set_inode_last_trans(trans, inode);
4115 return btrfs_update_inode_item(trans, root, inode);
4118 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4119 struct btrfs_root *root, struct btrfs_inode *inode)
4123 ret = btrfs_update_inode(trans, root, inode);
4125 return btrfs_update_inode_item(trans, root, inode);
4130 * unlink helper that gets used here in inode.c and in the tree logging
4131 * recovery code. It remove a link in a directory with a given name, and
4132 * also drops the back refs in the inode to the directory
4134 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4135 struct btrfs_inode *dir,
4136 struct btrfs_inode *inode,
4137 const struct fscrypt_str *name,
4138 struct btrfs_rename_ctx *rename_ctx)
4140 struct btrfs_root *root = dir->root;
4141 struct btrfs_fs_info *fs_info = root->fs_info;
4142 struct btrfs_path *path;
4144 struct btrfs_dir_item *di;
4146 u64 ino = btrfs_ino(inode);
4147 u64 dir_ino = btrfs_ino(dir);
4149 path = btrfs_alloc_path();
4155 di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4156 if (IS_ERR_OR_NULL(di)) {
4157 ret = di ? PTR_ERR(di) : -ENOENT;
4160 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4163 btrfs_release_path(path);
4166 * If we don't have dir index, we have to get it by looking up
4167 * the inode ref, since we get the inode ref, remove it directly,
4168 * it is unnecessary to do delayed deletion.
4170 * But if we have dir index, needn't search inode ref to get it.
4171 * Since the inode ref is close to the inode item, it is better
4172 * that we delay to delete it, and just do this deletion when
4173 * we update the inode item.
4175 if (inode->dir_index) {
4176 ret = btrfs_delayed_delete_inode_ref(inode);
4178 index = inode->dir_index;
4183 ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4186 "failed to delete reference to %.*s, inode %llu parent %llu",
4187 name->len, name->name, ino, dir_ino);
4188 btrfs_abort_transaction(trans, ret);
4193 rename_ctx->index = index;
4195 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4197 btrfs_abort_transaction(trans, ret);
4202 * If we are in a rename context, we don't need to update anything in the
4203 * log. That will be done later during the rename by btrfs_log_new_name().
4204 * Besides that, doing it here would only cause extra unnecessary btree
4205 * operations on the log tree, increasing latency for applications.
4208 btrfs_del_inode_ref_in_log(trans, root, name, inode, dir_ino);
4209 btrfs_del_dir_entries_in_log(trans, root, name, dir, index);
4213 * If we have a pending delayed iput we could end up with the final iput
4214 * being run in btrfs-cleaner context. If we have enough of these built
4215 * up we can end up burning a lot of time in btrfs-cleaner without any
4216 * way to throttle the unlinks. Since we're currently holding a ref on
4217 * the inode we can run the delayed iput here without any issues as the
4218 * final iput won't be done until after we drop the ref we're currently
4221 btrfs_run_delayed_iput(fs_info, inode);
4223 btrfs_free_path(path);
4227 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4228 inode_inc_iversion(&inode->vfs_inode);
4229 inode_inc_iversion(&dir->vfs_inode);
4230 inode->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4231 dir->vfs_inode.i_mtime = inode->vfs_inode.i_ctime;
4232 dir->vfs_inode.i_ctime = inode->vfs_inode.i_ctime;
4233 ret = btrfs_update_inode(trans, root, dir);
4238 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4239 struct btrfs_inode *dir, struct btrfs_inode *inode,
4240 const struct fscrypt_str *name)
4244 ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4246 drop_nlink(&inode->vfs_inode);
4247 ret = btrfs_update_inode(trans, inode->root, inode);
4253 * helper to start transaction for unlink and rmdir.
4255 * unlink and rmdir are special in btrfs, they do not always free space, so
4256 * if we cannot make our reservations the normal way try and see if there is
4257 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4258 * allow the unlink to occur.
4260 static struct btrfs_trans_handle *__unlink_start_trans(struct btrfs_inode *dir)
4262 struct btrfs_root *root = dir->root;
4265 * 1 for the possible orphan item
4266 * 1 for the dir item
4267 * 1 for the dir index
4268 * 1 for the inode ref
4270 * 1 for the parent inode
4272 return btrfs_start_transaction_fallback_global_rsv(root, 6);
4275 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4277 struct btrfs_trans_handle *trans;
4278 struct inode *inode = d_inode(dentry);
4280 struct fscrypt_name fname;
4282 ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4286 /* This needs to handle no-key deletions later on */
4288 trans = __unlink_start_trans(BTRFS_I(dir));
4289 if (IS_ERR(trans)) {
4290 ret = PTR_ERR(trans);
4294 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4297 ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4302 if (inode->i_nlink == 0) {
4303 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4309 btrfs_end_transaction(trans);
4310 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4312 fscrypt_free_filename(&fname);
4316 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4317 struct btrfs_inode *dir, struct dentry *dentry)
4319 struct btrfs_root *root = dir->root;
4320 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4321 struct btrfs_path *path;
4322 struct extent_buffer *leaf;
4323 struct btrfs_dir_item *di;
4324 struct btrfs_key key;
4328 u64 dir_ino = btrfs_ino(dir);
4329 struct fscrypt_name fname;
4331 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
4335 /* This needs to handle no-key deletions later on */
4337 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4338 objectid = inode->root->root_key.objectid;
4339 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4340 objectid = inode->location.objectid;
4343 fscrypt_free_filename(&fname);
4347 path = btrfs_alloc_path();
4353 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4354 &fname.disk_name, -1);
4355 if (IS_ERR_OR_NULL(di)) {
4356 ret = di ? PTR_ERR(di) : -ENOENT;
4360 leaf = path->nodes[0];
4361 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4362 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4363 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4365 btrfs_abort_transaction(trans, ret);
4368 btrfs_release_path(path);
4371 * This is a placeholder inode for a subvolume we didn't have a
4372 * reference to at the time of the snapshot creation. In the meantime
4373 * we could have renamed the real subvol link into our snapshot, so
4374 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4375 * Instead simply lookup the dir_index_item for this entry so we can
4376 * remove it. Otherwise we know we have a ref to the root and we can
4377 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4379 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4380 di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4381 if (IS_ERR_OR_NULL(di)) {
4386 btrfs_abort_transaction(trans, ret);
4390 leaf = path->nodes[0];
4391 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4393 btrfs_release_path(path);
4395 ret = btrfs_del_root_ref(trans, objectid,
4396 root->root_key.objectid, dir_ino,
4397 &index, &fname.disk_name);
4399 btrfs_abort_transaction(trans, ret);
4404 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4406 btrfs_abort_transaction(trans, ret);
4410 btrfs_i_size_write(dir, dir->vfs_inode.i_size - fname.disk_name.len * 2);
4411 inode_inc_iversion(&dir->vfs_inode);
4412 dir->vfs_inode.i_mtime = current_time(&dir->vfs_inode);
4413 dir->vfs_inode.i_ctime = dir->vfs_inode.i_mtime;
4414 ret = btrfs_update_inode_fallback(trans, root, dir);
4416 btrfs_abort_transaction(trans, ret);
4418 btrfs_free_path(path);
4419 fscrypt_free_filename(&fname);
4424 * Helper to check if the subvolume references other subvolumes or if it's
4427 static noinline int may_destroy_subvol(struct btrfs_root *root)
4429 struct btrfs_fs_info *fs_info = root->fs_info;
4430 struct btrfs_path *path;
4431 struct btrfs_dir_item *di;
4432 struct btrfs_key key;
4433 struct fscrypt_str name = FSTR_INIT("default", 7);
4437 path = btrfs_alloc_path();
4441 /* Make sure this root isn't set as the default subvol */
4442 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4443 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4445 if (di && !IS_ERR(di)) {
4446 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4447 if (key.objectid == root->root_key.objectid) {
4450 "deleting default subvolume %llu is not allowed",
4454 btrfs_release_path(path);
4457 key.objectid = root->root_key.objectid;
4458 key.type = BTRFS_ROOT_REF_KEY;
4459 key.offset = (u64)-1;
4461 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4467 if (path->slots[0] > 0) {
4469 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4470 if (key.objectid == root->root_key.objectid &&
4471 key.type == BTRFS_ROOT_REF_KEY)
4475 btrfs_free_path(path);
4479 /* Delete all dentries for inodes belonging to the root */
4480 static void btrfs_prune_dentries(struct btrfs_root *root)
4482 struct btrfs_fs_info *fs_info = root->fs_info;
4483 struct rb_node *node;
4484 struct rb_node *prev;
4485 struct btrfs_inode *entry;
4486 struct inode *inode;
4489 if (!BTRFS_FS_ERROR(fs_info))
4490 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4492 spin_lock(&root->inode_lock);
4494 node = root->inode_tree.rb_node;
4498 entry = rb_entry(node, struct btrfs_inode, rb_node);
4500 if (objectid < btrfs_ino(entry))
4501 node = node->rb_left;
4502 else if (objectid > btrfs_ino(entry))
4503 node = node->rb_right;
4509 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4510 if (objectid <= btrfs_ino(entry)) {
4514 prev = rb_next(prev);
4518 entry = rb_entry(node, struct btrfs_inode, rb_node);
4519 objectid = btrfs_ino(entry) + 1;
4520 inode = igrab(&entry->vfs_inode);
4522 spin_unlock(&root->inode_lock);
4523 if (atomic_read(&inode->i_count) > 1)
4524 d_prune_aliases(inode);
4526 * btrfs_drop_inode will have it removed from the inode
4527 * cache when its usage count hits zero.
4531 spin_lock(&root->inode_lock);
4535 if (cond_resched_lock(&root->inode_lock))
4538 node = rb_next(node);
4540 spin_unlock(&root->inode_lock);
4543 int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry)
4545 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4546 struct btrfs_root *root = dir->root;
4547 struct inode *inode = d_inode(dentry);
4548 struct btrfs_root *dest = BTRFS_I(inode)->root;
4549 struct btrfs_trans_handle *trans;
4550 struct btrfs_block_rsv block_rsv;
4555 * Don't allow to delete a subvolume with send in progress. This is
4556 * inside the inode lock so the error handling that has to drop the bit
4557 * again is not run concurrently.
4559 spin_lock(&dest->root_item_lock);
4560 if (dest->send_in_progress) {
4561 spin_unlock(&dest->root_item_lock);
4563 "attempt to delete subvolume %llu during send",
4564 dest->root_key.objectid);
4567 if (atomic_read(&dest->nr_swapfiles)) {
4568 spin_unlock(&dest->root_item_lock);
4570 "attempt to delete subvolume %llu with active swapfile",
4571 root->root_key.objectid);
4574 root_flags = btrfs_root_flags(&dest->root_item);
4575 btrfs_set_root_flags(&dest->root_item,
4576 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4577 spin_unlock(&dest->root_item_lock);
4579 down_write(&fs_info->subvol_sem);
4581 ret = may_destroy_subvol(dest);
4585 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4587 * One for dir inode,
4588 * two for dir entries,
4589 * two for root ref/backref.
4591 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4595 trans = btrfs_start_transaction(root, 0);
4596 if (IS_ERR(trans)) {
4597 ret = PTR_ERR(trans);
4600 trans->block_rsv = &block_rsv;
4601 trans->bytes_reserved = block_rsv.size;
4603 btrfs_record_snapshot_destroy(trans, dir);
4605 ret = btrfs_unlink_subvol(trans, dir, dentry);
4607 btrfs_abort_transaction(trans, ret);
4611 ret = btrfs_record_root_in_trans(trans, dest);
4613 btrfs_abort_transaction(trans, ret);
4617 memset(&dest->root_item.drop_progress, 0,
4618 sizeof(dest->root_item.drop_progress));
4619 btrfs_set_root_drop_level(&dest->root_item, 0);
4620 btrfs_set_root_refs(&dest->root_item, 0);
4622 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4623 ret = btrfs_insert_orphan_item(trans,
4625 dest->root_key.objectid);
4627 btrfs_abort_transaction(trans, ret);
4632 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4633 BTRFS_UUID_KEY_SUBVOL,
4634 dest->root_key.objectid);
4635 if (ret && ret != -ENOENT) {
4636 btrfs_abort_transaction(trans, ret);
4639 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4640 ret = btrfs_uuid_tree_remove(trans,
4641 dest->root_item.received_uuid,
4642 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4643 dest->root_key.objectid);
4644 if (ret && ret != -ENOENT) {
4645 btrfs_abort_transaction(trans, ret);
4650 free_anon_bdev(dest->anon_dev);
4653 trans->block_rsv = NULL;
4654 trans->bytes_reserved = 0;
4655 ret = btrfs_end_transaction(trans);
4656 inode->i_flags |= S_DEAD;
4658 btrfs_subvolume_release_metadata(root, &block_rsv);
4660 up_write(&fs_info->subvol_sem);
4662 spin_lock(&dest->root_item_lock);
4663 root_flags = btrfs_root_flags(&dest->root_item);
4664 btrfs_set_root_flags(&dest->root_item,
4665 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4666 spin_unlock(&dest->root_item_lock);
4668 d_invalidate(dentry);
4669 btrfs_prune_dentries(dest);
4670 ASSERT(dest->send_in_progress == 0);
4676 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4678 struct inode *inode = d_inode(dentry);
4679 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
4681 struct btrfs_trans_handle *trans;
4682 u64 last_unlink_trans;
4683 struct fscrypt_name fname;
4685 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4687 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
4688 if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4690 "extent tree v2 doesn't support snapshot deletion yet");
4693 return btrfs_delete_subvolume(BTRFS_I(dir), dentry);
4696 err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4700 /* This needs to handle no-key deletions later on */
4702 trans = __unlink_start_trans(BTRFS_I(dir));
4703 if (IS_ERR(trans)) {
4704 err = PTR_ERR(trans);
4708 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4709 err = btrfs_unlink_subvol(trans, BTRFS_I(dir), dentry);
4713 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4717 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4719 /* now the directory is empty */
4720 err = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4723 btrfs_i_size_write(BTRFS_I(inode), 0);
4725 * Propagate the last_unlink_trans value of the deleted dir to
4726 * its parent directory. This is to prevent an unrecoverable
4727 * log tree in the case we do something like this:
4729 * 2) create snapshot under dir foo
4730 * 3) delete the snapshot
4733 * 6) fsync foo or some file inside foo
4735 if (last_unlink_trans >= trans->transid)
4736 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4739 btrfs_end_transaction(trans);
4741 btrfs_btree_balance_dirty(fs_info);
4742 fscrypt_free_filename(&fname);
4748 * btrfs_truncate_block - read, zero a chunk and write a block
4749 * @inode - inode that we're zeroing
4750 * @from - the offset to start zeroing
4751 * @len - the length to zero, 0 to zero the entire range respective to the
4753 * @front - zero up to the offset instead of from the offset on
4755 * This will find the block for the "from" offset and cow the block and zero the
4756 * part we want to zero. This is used with truncate and hole punching.
4758 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4761 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4762 struct address_space *mapping = inode->vfs_inode.i_mapping;
4763 struct extent_io_tree *io_tree = &inode->io_tree;
4764 struct btrfs_ordered_extent *ordered;
4765 struct extent_state *cached_state = NULL;
4766 struct extent_changeset *data_reserved = NULL;
4767 bool only_release_metadata = false;
4768 u32 blocksize = fs_info->sectorsize;
4769 pgoff_t index = from >> PAGE_SHIFT;
4770 unsigned offset = from & (blocksize - 1);
4772 gfp_t mask = btrfs_alloc_write_mask(mapping);
4773 size_t write_bytes = blocksize;
4778 if (IS_ALIGNED(offset, blocksize) &&
4779 (!len || IS_ALIGNED(len, blocksize)))
4782 block_start = round_down(from, blocksize);
4783 block_end = block_start + blocksize - 1;
4785 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4788 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
4789 /* For nocow case, no need to reserve data space */
4790 only_release_metadata = true;
4795 ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
4797 if (!only_release_metadata)
4798 btrfs_free_reserved_data_space(inode, data_reserved,
4799 block_start, blocksize);
4803 page = find_or_create_page(mapping, index, mask);
4805 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4807 btrfs_delalloc_release_extents(inode, blocksize);
4811 ret = set_page_extent_mapped(page);
4815 if (!PageUptodate(page)) {
4816 ret = btrfs_read_folio(NULL, page_folio(page));
4818 if (page->mapping != mapping) {
4823 if (!PageUptodate(page)) {
4828 wait_on_page_writeback(page);
4830 lock_extent(io_tree, block_start, block_end, &cached_state);
4832 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4834 unlock_extent(io_tree, block_start, block_end, &cached_state);
4837 btrfs_start_ordered_extent(ordered);
4838 btrfs_put_ordered_extent(ordered);
4842 clear_extent_bit(&inode->io_tree, block_start, block_end,
4843 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4846 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4849 unlock_extent(io_tree, block_start, block_end, &cached_state);
4853 if (offset != blocksize) {
4855 len = blocksize - offset;
4857 memzero_page(page, (block_start - page_offset(page)),
4860 memzero_page(page, (block_start - page_offset(page)) + offset,
4863 btrfs_page_clear_checked(fs_info, page, block_start,
4864 block_end + 1 - block_start);
4865 btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
4866 unlock_extent(io_tree, block_start, block_end, &cached_state);
4868 if (only_release_metadata)
4869 set_extent_bit(&inode->io_tree, block_start, block_end,
4870 EXTENT_NORESERVE, NULL, GFP_NOFS);
4874 if (only_release_metadata)
4875 btrfs_delalloc_release_metadata(inode, blocksize, true);
4877 btrfs_delalloc_release_space(inode, data_reserved,
4878 block_start, blocksize, true);
4880 btrfs_delalloc_release_extents(inode, blocksize);
4884 if (only_release_metadata)
4885 btrfs_check_nocow_unlock(inode);
4886 extent_changeset_free(data_reserved);
4890 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4891 u64 offset, u64 len)
4893 struct btrfs_fs_info *fs_info = root->fs_info;
4894 struct btrfs_trans_handle *trans;
4895 struct btrfs_drop_extents_args drop_args = { 0 };
4899 * If NO_HOLES is enabled, we don't need to do anything.
4900 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
4901 * or btrfs_update_inode() will be called, which guarantee that the next
4902 * fsync will know this inode was changed and needs to be logged.
4904 if (btrfs_fs_incompat(fs_info, NO_HOLES))
4908 * 1 - for the one we're dropping
4909 * 1 - for the one we're adding
4910 * 1 - for updating the inode.
4912 trans = btrfs_start_transaction(root, 3);
4914 return PTR_ERR(trans);
4916 drop_args.start = offset;
4917 drop_args.end = offset + len;
4918 drop_args.drop_cache = true;
4920 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4922 btrfs_abort_transaction(trans, ret);
4923 btrfs_end_transaction(trans);
4927 ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
4929 btrfs_abort_transaction(trans, ret);
4931 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
4932 btrfs_update_inode(trans, root, inode);
4934 btrfs_end_transaction(trans);
4939 * This function puts in dummy file extents for the area we're creating a hole
4940 * for. So if we are truncating this file to a larger size we need to insert
4941 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4942 * the range between oldsize and size
4944 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
4946 struct btrfs_root *root = inode->root;
4947 struct btrfs_fs_info *fs_info = root->fs_info;
4948 struct extent_io_tree *io_tree = &inode->io_tree;
4949 struct extent_map *em = NULL;
4950 struct extent_state *cached_state = NULL;
4951 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4952 u64 block_end = ALIGN(size, fs_info->sectorsize);
4959 * If our size started in the middle of a block we need to zero out the
4960 * rest of the block before we expand the i_size, otherwise we could
4961 * expose stale data.
4963 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4967 if (size <= hole_start)
4970 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
4972 cur_offset = hole_start;
4974 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4975 block_end - cur_offset);
4981 last_byte = min(extent_map_end(em), block_end);
4982 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4983 hole_size = last_byte - cur_offset;
4985 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4986 struct extent_map *hole_em;
4988 err = maybe_insert_hole(root, inode, cur_offset,
4993 err = btrfs_inode_set_file_extent_range(inode,
4994 cur_offset, hole_size);
4998 hole_em = alloc_extent_map();
5000 btrfs_drop_extent_map_range(inode, cur_offset,
5001 cur_offset + hole_size - 1,
5003 btrfs_set_inode_full_sync(inode);
5006 hole_em->start = cur_offset;
5007 hole_em->len = hole_size;
5008 hole_em->orig_start = cur_offset;
5010 hole_em->block_start = EXTENT_MAP_HOLE;
5011 hole_em->block_len = 0;
5012 hole_em->orig_block_len = 0;
5013 hole_em->ram_bytes = hole_size;
5014 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5015 hole_em->generation = fs_info->generation;
5017 err = btrfs_replace_extent_map_range(inode, hole_em, true);
5018 free_extent_map(hole_em);
5020 err = btrfs_inode_set_file_extent_range(inode,
5021 cur_offset, hole_size);
5026 free_extent_map(em);
5028 cur_offset = last_byte;
5029 if (cur_offset >= block_end)
5032 free_extent_map(em);
5033 unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5037 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5039 struct btrfs_root *root = BTRFS_I(inode)->root;
5040 struct btrfs_trans_handle *trans;
5041 loff_t oldsize = i_size_read(inode);
5042 loff_t newsize = attr->ia_size;
5043 int mask = attr->ia_valid;
5047 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5048 * special case where we need to update the times despite not having
5049 * these flags set. For all other operations the VFS set these flags
5050 * explicitly if it wants a timestamp update.
5052 if (newsize != oldsize) {
5053 inode_inc_iversion(inode);
5054 if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5055 inode->i_mtime = current_time(inode);
5056 inode->i_ctime = inode->i_mtime;
5060 if (newsize > oldsize) {
5062 * Don't do an expanding truncate while snapshotting is ongoing.
5063 * This is to ensure the snapshot captures a fully consistent
5064 * state of this file - if the snapshot captures this expanding
5065 * truncation, it must capture all writes that happened before
5068 btrfs_drew_write_lock(&root->snapshot_lock);
5069 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5071 btrfs_drew_write_unlock(&root->snapshot_lock);
5075 trans = btrfs_start_transaction(root, 1);
5076 if (IS_ERR(trans)) {
5077 btrfs_drew_write_unlock(&root->snapshot_lock);
5078 return PTR_ERR(trans);
5081 i_size_write(inode, newsize);
5082 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5083 pagecache_isize_extended(inode, oldsize, newsize);
5084 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5085 btrfs_drew_write_unlock(&root->snapshot_lock);
5086 btrfs_end_transaction(trans);
5088 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5090 if (btrfs_is_zoned(fs_info)) {
5091 ret = btrfs_wait_ordered_range(inode,
5092 ALIGN(newsize, fs_info->sectorsize),
5099 * We're truncating a file that used to have good data down to
5100 * zero. Make sure any new writes to the file get on disk
5104 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5105 &BTRFS_I(inode)->runtime_flags);
5107 truncate_setsize(inode, newsize);
5109 inode_dio_wait(inode);
5111 ret = btrfs_truncate(BTRFS_I(inode), newsize == oldsize);
5112 if (ret && inode->i_nlink) {
5116 * Truncate failed, so fix up the in-memory size. We
5117 * adjusted disk_i_size down as we removed extents, so
5118 * wait for disk_i_size to be stable and then update the
5119 * in-memory size to match.
5121 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5124 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5131 static int btrfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5134 struct inode *inode = d_inode(dentry);
5135 struct btrfs_root *root = BTRFS_I(inode)->root;
5138 if (btrfs_root_readonly(root))
5141 err = setattr_prepare(idmap, dentry, attr);
5145 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5146 err = btrfs_setsize(inode, attr);
5151 if (attr->ia_valid) {
5152 setattr_copy(idmap, inode, attr);
5153 inode_inc_iversion(inode);
5154 err = btrfs_dirty_inode(BTRFS_I(inode));
5156 if (!err && attr->ia_valid & ATTR_MODE)
5157 err = posix_acl_chmod(idmap, dentry, inode->i_mode);
5164 * While truncating the inode pages during eviction, we get the VFS
5165 * calling btrfs_invalidate_folio() against each folio of the inode. This
5166 * is slow because the calls to btrfs_invalidate_folio() result in a
5167 * huge amount of calls to lock_extent() and clear_extent_bit(),
5168 * which keep merging and splitting extent_state structures over and over,
5169 * wasting lots of time.
5171 * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5172 * skip all those expensive operations on a per folio basis and do only
5173 * the ordered io finishing, while we release here the extent_map and
5174 * extent_state structures, without the excessive merging and splitting.
5176 static void evict_inode_truncate_pages(struct inode *inode)
5178 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5179 struct rb_node *node;
5181 ASSERT(inode->i_state & I_FREEING);
5182 truncate_inode_pages_final(&inode->i_data);
5184 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5187 * Keep looping until we have no more ranges in the io tree.
5188 * We can have ongoing bios started by readahead that have
5189 * their endio callback (extent_io.c:end_bio_extent_readpage)
5190 * still in progress (unlocked the pages in the bio but did not yet
5191 * unlocked the ranges in the io tree). Therefore this means some
5192 * ranges can still be locked and eviction started because before
5193 * submitting those bios, which are executed by a separate task (work
5194 * queue kthread), inode references (inode->i_count) were not taken
5195 * (which would be dropped in the end io callback of each bio).
5196 * Therefore here we effectively end up waiting for those bios and
5197 * anyone else holding locked ranges without having bumped the inode's
5198 * reference count - if we don't do it, when they access the inode's
5199 * io_tree to unlock a range it may be too late, leading to an
5200 * use-after-free issue.
5202 spin_lock(&io_tree->lock);
5203 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5204 struct extent_state *state;
5205 struct extent_state *cached_state = NULL;
5208 unsigned state_flags;
5210 node = rb_first(&io_tree->state);
5211 state = rb_entry(node, struct extent_state, rb_node);
5212 start = state->start;
5214 state_flags = state->state;
5215 spin_unlock(&io_tree->lock);
5217 lock_extent(io_tree, start, end, &cached_state);
5220 * If still has DELALLOC flag, the extent didn't reach disk,
5221 * and its reserved space won't be freed by delayed_ref.
5222 * So we need to free its reserved space here.
5223 * (Refer to comment in btrfs_invalidate_folio, case 2)
5225 * Note, end is the bytenr of last byte, so we need + 1 here.
5227 if (state_flags & EXTENT_DELALLOC)
5228 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5231 clear_extent_bit(io_tree, start, end,
5232 EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5236 spin_lock(&io_tree->lock);
5238 spin_unlock(&io_tree->lock);
5241 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5242 struct btrfs_block_rsv *rsv)
5244 struct btrfs_fs_info *fs_info = root->fs_info;
5245 struct btrfs_trans_handle *trans;
5246 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5250 * Eviction should be taking place at some place safe because of our
5251 * delayed iputs. However the normal flushing code will run delayed
5252 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5254 * We reserve the delayed_refs_extra here again because we can't use
5255 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5256 * above. We reserve our extra bit here because we generate a ton of
5257 * delayed refs activity by truncating.
5259 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5260 * if we fail to make this reservation we can re-try without the
5261 * delayed_refs_extra so we can make some forward progress.
5263 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5264 BTRFS_RESERVE_FLUSH_EVICT);
5266 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5267 BTRFS_RESERVE_FLUSH_EVICT);
5270 "could not allocate space for delete; will truncate on mount");
5271 return ERR_PTR(-ENOSPC);
5273 delayed_refs_extra = 0;
5276 trans = btrfs_join_transaction(root);
5280 if (delayed_refs_extra) {
5281 trans->block_rsv = &fs_info->trans_block_rsv;
5282 trans->bytes_reserved = delayed_refs_extra;
5283 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5284 delayed_refs_extra, 1);
5289 void btrfs_evict_inode(struct inode *inode)
5291 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5292 struct btrfs_trans_handle *trans;
5293 struct btrfs_root *root = BTRFS_I(inode)->root;
5294 struct btrfs_block_rsv *rsv;
5297 trace_btrfs_inode_evict(inode);
5300 fsverity_cleanup_inode(inode);
5305 evict_inode_truncate_pages(inode);
5307 if (inode->i_nlink &&
5308 ((btrfs_root_refs(&root->root_item) != 0 &&
5309 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5310 btrfs_is_free_space_inode(BTRFS_I(inode))))
5313 if (is_bad_inode(inode))
5316 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5319 if (inode->i_nlink > 0) {
5320 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5321 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5326 * This makes sure the inode item in tree is uptodate and the space for
5327 * the inode update is released.
5329 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5334 * This drops any pending insert or delete operations we have for this
5335 * inode. We could have a delayed dir index deletion queued up, but
5336 * we're removing the inode completely so that'll be taken care of in
5339 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5341 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5344 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5345 rsv->failfast = true;
5347 btrfs_i_size_write(BTRFS_I(inode), 0);
5350 struct btrfs_truncate_control control = {
5351 .inode = BTRFS_I(inode),
5352 .ino = btrfs_ino(BTRFS_I(inode)),
5357 trans = evict_refill_and_join(root, rsv);
5361 trans->block_rsv = rsv;
5363 ret = btrfs_truncate_inode_items(trans, root, &control);
5364 trans->block_rsv = &fs_info->trans_block_rsv;
5365 btrfs_end_transaction(trans);
5366 btrfs_btree_balance_dirty(fs_info);
5367 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5374 * Errors here aren't a big deal, it just means we leave orphan items in
5375 * the tree. They will be cleaned up on the next mount. If the inode
5376 * number gets reused, cleanup deletes the orphan item without doing
5377 * anything, and unlink reuses the existing orphan item.
5379 * If it turns out that we are dropping too many of these, we might want
5380 * to add a mechanism for retrying these after a commit.
5382 trans = evict_refill_and_join(root, rsv);
5383 if (!IS_ERR(trans)) {
5384 trans->block_rsv = rsv;
5385 btrfs_orphan_del(trans, BTRFS_I(inode));
5386 trans->block_rsv = &fs_info->trans_block_rsv;
5387 btrfs_end_transaction(trans);
5391 btrfs_free_block_rsv(fs_info, rsv);
5394 * If we didn't successfully delete, the orphan item will still be in
5395 * the tree and we'll retry on the next mount. Again, we might also want
5396 * to retry these periodically in the future.
5398 btrfs_remove_delayed_node(BTRFS_I(inode));
5399 fsverity_cleanup_inode(inode);
5404 * Return the key found in the dir entry in the location pointer, fill @type
5405 * with BTRFS_FT_*, and return 0.
5407 * If no dir entries were found, returns -ENOENT.
5408 * If found a corrupted location in dir entry, returns -EUCLEAN.
5410 static int btrfs_inode_by_name(struct btrfs_inode *dir, struct dentry *dentry,
5411 struct btrfs_key *location, u8 *type)
5413 struct btrfs_dir_item *di;
5414 struct btrfs_path *path;
5415 struct btrfs_root *root = dir->root;
5417 struct fscrypt_name fname;
5419 path = btrfs_alloc_path();
5423 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
5427 /* This needs to handle no-key deletions later on */
5429 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
5430 &fname.disk_name, 0);
5431 if (IS_ERR_OR_NULL(di)) {
5432 ret = di ? PTR_ERR(di) : -ENOENT;
5436 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5437 if (location->type != BTRFS_INODE_ITEM_KEY &&
5438 location->type != BTRFS_ROOT_ITEM_KEY) {
5440 btrfs_warn(root->fs_info,
5441 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5442 __func__, fname.disk_name.name, btrfs_ino(dir),
5443 location->objectid, location->type, location->offset);
5446 *type = btrfs_dir_ftype(path->nodes[0], di);
5448 fscrypt_free_filename(&fname);
5449 btrfs_free_path(path);
5454 * when we hit a tree root in a directory, the btrfs part of the inode
5455 * needs to be changed to reflect the root directory of the tree root. This
5456 * is kind of like crossing a mount point.
5458 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5459 struct btrfs_inode *dir,
5460 struct dentry *dentry,
5461 struct btrfs_key *location,
5462 struct btrfs_root **sub_root)
5464 struct btrfs_path *path;
5465 struct btrfs_root *new_root;
5466 struct btrfs_root_ref *ref;
5467 struct extent_buffer *leaf;
5468 struct btrfs_key key;
5471 struct fscrypt_name fname;
5473 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
5477 path = btrfs_alloc_path();
5484 key.objectid = dir->root->root_key.objectid;
5485 key.type = BTRFS_ROOT_REF_KEY;
5486 key.offset = location->objectid;
5488 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5495 leaf = path->nodes[0];
5496 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5497 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5498 btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5501 ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5502 (unsigned long)(ref + 1), fname.disk_name.len);
5506 btrfs_release_path(path);
5508 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5509 if (IS_ERR(new_root)) {
5510 err = PTR_ERR(new_root);
5514 *sub_root = new_root;
5515 location->objectid = btrfs_root_dirid(&new_root->root_item);
5516 location->type = BTRFS_INODE_ITEM_KEY;
5517 location->offset = 0;
5520 btrfs_free_path(path);
5521 fscrypt_free_filename(&fname);
5525 static void inode_tree_add(struct btrfs_inode *inode)
5527 struct btrfs_root *root = inode->root;
5528 struct btrfs_inode *entry;
5530 struct rb_node *parent;
5531 struct rb_node *new = &inode->rb_node;
5532 u64 ino = btrfs_ino(inode);
5534 if (inode_unhashed(&inode->vfs_inode))
5537 spin_lock(&root->inode_lock);
5538 p = &root->inode_tree.rb_node;
5541 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5543 if (ino < btrfs_ino(entry))
5544 p = &parent->rb_left;
5545 else if (ino > btrfs_ino(entry))
5546 p = &parent->rb_right;
5548 WARN_ON(!(entry->vfs_inode.i_state &
5549 (I_WILL_FREE | I_FREEING)));
5550 rb_replace_node(parent, new, &root->inode_tree);
5551 RB_CLEAR_NODE(parent);
5552 spin_unlock(&root->inode_lock);
5556 rb_link_node(new, parent, p);
5557 rb_insert_color(new, &root->inode_tree);
5558 spin_unlock(&root->inode_lock);
5561 static void inode_tree_del(struct btrfs_inode *inode)
5563 struct btrfs_root *root = inode->root;
5566 spin_lock(&root->inode_lock);
5567 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5568 rb_erase(&inode->rb_node, &root->inode_tree);
5569 RB_CLEAR_NODE(&inode->rb_node);
5570 empty = RB_EMPTY_ROOT(&root->inode_tree);
5572 spin_unlock(&root->inode_lock);
5574 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5575 spin_lock(&root->inode_lock);
5576 empty = RB_EMPTY_ROOT(&root->inode_tree);
5577 spin_unlock(&root->inode_lock);
5579 btrfs_add_dead_root(root);
5584 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5586 struct btrfs_iget_args *args = p;
5588 inode->i_ino = args->ino;
5589 BTRFS_I(inode)->location.objectid = args->ino;
5590 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5591 BTRFS_I(inode)->location.offset = 0;
5592 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5593 BUG_ON(args->root && !BTRFS_I(inode)->root);
5595 if (args->root && args->root == args->root->fs_info->tree_root &&
5596 args->ino != BTRFS_BTREE_INODE_OBJECTID)
5597 set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5598 &BTRFS_I(inode)->runtime_flags);
5602 static int btrfs_find_actor(struct inode *inode, void *opaque)
5604 struct btrfs_iget_args *args = opaque;
5606 return args->ino == BTRFS_I(inode)->location.objectid &&
5607 args->root == BTRFS_I(inode)->root;
5610 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5611 struct btrfs_root *root)
5613 struct inode *inode;
5614 struct btrfs_iget_args args;
5615 unsigned long hashval = btrfs_inode_hash(ino, root);
5620 inode = iget5_locked(s, hashval, btrfs_find_actor,
5621 btrfs_init_locked_inode,
5627 * Get an inode object given its inode number and corresponding root.
5628 * Path can be preallocated to prevent recursing back to iget through
5629 * allocator. NULL is also valid but may require an additional allocation
5632 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5633 struct btrfs_root *root, struct btrfs_path *path)
5635 struct inode *inode;
5637 inode = btrfs_iget_locked(s, ino, root);
5639 return ERR_PTR(-ENOMEM);
5641 if (inode->i_state & I_NEW) {
5644 ret = btrfs_read_locked_inode(inode, path);
5646 inode_tree_add(BTRFS_I(inode));
5647 unlock_new_inode(inode);
5651 * ret > 0 can come from btrfs_search_slot called by
5652 * btrfs_read_locked_inode, this means the inode item
5657 inode = ERR_PTR(ret);
5664 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5666 return btrfs_iget_path(s, ino, root, NULL);
5669 static struct inode *new_simple_dir(struct super_block *s,
5670 struct btrfs_key *key,
5671 struct btrfs_root *root)
5673 struct inode *inode = new_inode(s);
5676 return ERR_PTR(-ENOMEM);
5678 BTRFS_I(inode)->root = btrfs_grab_root(root);
5679 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5680 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5682 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5684 * We only need lookup, the rest is read-only and there's no inode
5685 * associated with the dentry
5687 inode->i_op = &simple_dir_inode_operations;
5688 inode->i_opflags &= ~IOP_XATTR;
5689 inode->i_fop = &simple_dir_operations;
5690 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5691 inode->i_mtime = current_time(inode);
5692 inode->i_atime = inode->i_mtime;
5693 inode->i_ctime = inode->i_mtime;
5694 BTRFS_I(inode)->i_otime = inode->i_mtime;
5699 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5700 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5701 static_assert(BTRFS_FT_DIR == FT_DIR);
5702 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5703 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5704 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5705 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5706 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5708 static inline u8 btrfs_inode_type(struct inode *inode)
5710 return fs_umode_to_ftype(inode->i_mode);
5713 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5715 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5716 struct inode *inode;
5717 struct btrfs_root *root = BTRFS_I(dir)->root;
5718 struct btrfs_root *sub_root = root;
5719 struct btrfs_key location;
5723 if (dentry->d_name.len > BTRFS_NAME_LEN)
5724 return ERR_PTR(-ENAMETOOLONG);
5726 ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
5728 return ERR_PTR(ret);
5730 if (location.type == BTRFS_INODE_ITEM_KEY) {
5731 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5735 /* Do extra check against inode mode with di_type */
5736 if (btrfs_inode_type(inode) != di_type) {
5738 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5739 inode->i_mode, btrfs_inode_type(inode),
5742 return ERR_PTR(-EUCLEAN);
5747 ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
5748 &location, &sub_root);
5751 inode = ERR_PTR(ret);
5753 inode = new_simple_dir(dir->i_sb, &location, root);
5755 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5756 btrfs_put_root(sub_root);
5761 down_read(&fs_info->cleanup_work_sem);
5762 if (!sb_rdonly(inode->i_sb))
5763 ret = btrfs_orphan_cleanup(sub_root);
5764 up_read(&fs_info->cleanup_work_sem);
5767 inode = ERR_PTR(ret);
5774 static int btrfs_dentry_delete(const struct dentry *dentry)
5776 struct btrfs_root *root;
5777 struct inode *inode = d_inode(dentry);
5779 if (!inode && !IS_ROOT(dentry))
5780 inode = d_inode(dentry->d_parent);
5783 root = BTRFS_I(inode)->root;
5784 if (btrfs_root_refs(&root->root_item) == 0)
5787 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5793 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5796 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5798 if (inode == ERR_PTR(-ENOENT))
5800 return d_splice_alias(inode, dentry);
5804 * All this infrastructure exists because dir_emit can fault, and we are holding
5805 * the tree lock when doing readdir. For now just allocate a buffer and copy
5806 * our information into that, and then dir_emit from the buffer. This is
5807 * similar to what NFS does, only we don't keep the buffer around in pagecache
5808 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5809 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5812 static int btrfs_opendir(struct inode *inode, struct file *file)
5814 struct btrfs_file_private *private;
5816 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5819 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5820 if (!private->filldir_buf) {
5824 file->private_data = private;
5835 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5838 struct dir_entry *entry = addr;
5839 char *name = (char *)(entry + 1);
5841 ctx->pos = get_unaligned(&entry->offset);
5842 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5843 get_unaligned(&entry->ino),
5844 get_unaligned(&entry->type)))
5846 addr += sizeof(struct dir_entry) +
5847 get_unaligned(&entry->name_len);
5853 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5855 struct inode *inode = file_inode(file);
5856 struct btrfs_root *root = BTRFS_I(inode)->root;
5857 struct btrfs_file_private *private = file->private_data;
5858 struct btrfs_dir_item *di;
5859 struct btrfs_key key;
5860 struct btrfs_key found_key;
5861 struct btrfs_path *path;
5863 struct list_head ins_list;
5864 struct list_head del_list;
5871 struct btrfs_key location;
5873 if (!dir_emit_dots(file, ctx))
5876 path = btrfs_alloc_path();
5880 addr = private->filldir_buf;
5881 path->reada = READA_FORWARD;
5883 INIT_LIST_HEAD(&ins_list);
5884 INIT_LIST_HEAD(&del_list);
5885 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5888 key.type = BTRFS_DIR_INDEX_KEY;
5889 key.offset = ctx->pos;
5890 key.objectid = btrfs_ino(BTRFS_I(inode));
5892 btrfs_for_each_slot(root, &key, &found_key, path, ret) {
5893 struct dir_entry *entry;
5894 struct extent_buffer *leaf = path->nodes[0];
5897 if (found_key.objectid != key.objectid)
5899 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5901 if (found_key.offset < ctx->pos)
5903 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5905 di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
5906 name_len = btrfs_dir_name_len(leaf, di);
5907 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5909 btrfs_release_path(path);
5910 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5913 addr = private->filldir_buf;
5919 ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
5921 name_ptr = (char *)(entry + 1);
5922 read_extent_buffer(leaf, name_ptr,
5923 (unsigned long)(di + 1), name_len);
5924 put_unaligned(name_len, &entry->name_len);
5925 put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
5926 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5927 put_unaligned(location.objectid, &entry->ino);
5928 put_unaligned(found_key.offset, &entry->offset);
5930 addr += sizeof(struct dir_entry) + name_len;
5931 total_len += sizeof(struct dir_entry) + name_len;
5933 /* Catch error encountered during iteration */
5937 btrfs_release_path(path);
5939 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5943 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5948 * Stop new entries from being returned after we return the last
5951 * New directory entries are assigned a strictly increasing
5952 * offset. This means that new entries created during readdir
5953 * are *guaranteed* to be seen in the future by that readdir.
5954 * This has broken buggy programs which operate on names as
5955 * they're returned by readdir. Until we re-use freed offsets
5956 * we have this hack to stop new entries from being returned
5957 * under the assumption that they'll never reach this huge
5960 * This is being careful not to overflow 32bit loff_t unless the
5961 * last entry requires it because doing so has broken 32bit apps
5964 if (ctx->pos >= INT_MAX)
5965 ctx->pos = LLONG_MAX;
5972 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5973 btrfs_free_path(path);
5978 * This is somewhat expensive, updating the tree every time the
5979 * inode changes. But, it is most likely to find the inode in cache.
5980 * FIXME, needs more benchmarking...there are no reasons other than performance
5981 * to keep or drop this code.
5983 static int btrfs_dirty_inode(struct btrfs_inode *inode)
5985 struct btrfs_root *root = inode->root;
5986 struct btrfs_fs_info *fs_info = root->fs_info;
5987 struct btrfs_trans_handle *trans;
5990 if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
5993 trans = btrfs_join_transaction(root);
5995 return PTR_ERR(trans);
5997 ret = btrfs_update_inode(trans, root, inode);
5998 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
5999 /* whoops, lets try again with the full transaction */
6000 btrfs_end_transaction(trans);
6001 trans = btrfs_start_transaction(root, 1);
6003 return PTR_ERR(trans);
6005 ret = btrfs_update_inode(trans, root, inode);
6007 btrfs_end_transaction(trans);
6008 if (inode->delayed_node)
6009 btrfs_balance_delayed_items(fs_info);
6015 * This is a copy of file_update_time. We need this so we can return error on
6016 * ENOSPC for updating the inode in the case of file write and mmap writes.
6018 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6021 struct btrfs_root *root = BTRFS_I(inode)->root;
6022 bool dirty = flags & ~S_VERSION;
6024 if (btrfs_root_readonly(root))
6027 if (flags & S_VERSION)
6028 dirty |= inode_maybe_inc_iversion(inode, dirty);
6029 if (flags & S_CTIME)
6030 inode->i_ctime = *now;
6031 if (flags & S_MTIME)
6032 inode->i_mtime = *now;
6033 if (flags & S_ATIME)
6034 inode->i_atime = *now;
6035 return dirty ? btrfs_dirty_inode(BTRFS_I(inode)) : 0;
6039 * find the highest existing sequence number in a directory
6040 * and then set the in-memory index_cnt variable to reflect
6041 * free sequence numbers
6043 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6045 struct btrfs_root *root = inode->root;
6046 struct btrfs_key key, found_key;
6047 struct btrfs_path *path;
6048 struct extent_buffer *leaf;
6051 key.objectid = btrfs_ino(inode);
6052 key.type = BTRFS_DIR_INDEX_KEY;
6053 key.offset = (u64)-1;
6055 path = btrfs_alloc_path();
6059 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6062 /* FIXME: we should be able to handle this */
6067 if (path->slots[0] == 0) {
6068 inode->index_cnt = BTRFS_DIR_START_INDEX;
6074 leaf = path->nodes[0];
6075 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6077 if (found_key.objectid != btrfs_ino(inode) ||
6078 found_key.type != BTRFS_DIR_INDEX_KEY) {
6079 inode->index_cnt = BTRFS_DIR_START_INDEX;
6083 inode->index_cnt = found_key.offset + 1;
6085 btrfs_free_path(path);
6090 * helper to find a free sequence number in a given directory. This current
6091 * code is very simple, later versions will do smarter things in the btree
6093 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6097 if (dir->index_cnt == (u64)-1) {
6098 ret = btrfs_inode_delayed_dir_index_count(dir);
6100 ret = btrfs_set_inode_index_count(dir);
6106 *index = dir->index_cnt;
6112 static int btrfs_insert_inode_locked(struct inode *inode)
6114 struct btrfs_iget_args args;
6116 args.ino = BTRFS_I(inode)->location.objectid;
6117 args.root = BTRFS_I(inode)->root;
6119 return insert_inode_locked4(inode,
6120 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6121 btrfs_find_actor, &args);
6124 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6125 unsigned int *trans_num_items)
6127 struct inode *dir = args->dir;
6128 struct inode *inode = args->inode;
6131 if (!args->orphan) {
6132 ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6138 ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6140 fscrypt_free_filename(&args->fname);
6144 /* 1 to add inode item */
6145 *trans_num_items = 1;
6146 /* 1 to add compression property */
6147 if (BTRFS_I(dir)->prop_compress)
6148 (*trans_num_items)++;
6149 /* 1 to add default ACL xattr */
6150 if (args->default_acl)
6151 (*trans_num_items)++;
6152 /* 1 to add access ACL xattr */
6154 (*trans_num_items)++;
6155 #ifdef CONFIG_SECURITY
6156 /* 1 to add LSM xattr */
6157 if (dir->i_security)
6158 (*trans_num_items)++;
6161 /* 1 to add orphan item */
6162 (*trans_num_items)++;
6166 * 1 to add dir index
6167 * 1 to update parent inode item
6169 * No need for 1 unit for the inode ref item because it is
6170 * inserted in a batch together with the inode item at
6171 * btrfs_create_new_inode().
6173 *trans_num_items += 3;
6178 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6180 posix_acl_release(args->acl);
6181 posix_acl_release(args->default_acl);
6182 fscrypt_free_filename(&args->fname);
6186 * Inherit flags from the parent inode.
6188 * Currently only the compression flags and the cow flags are inherited.
6190 static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
6196 if (flags & BTRFS_INODE_NOCOMPRESS) {
6197 inode->flags &= ~BTRFS_INODE_COMPRESS;
6198 inode->flags |= BTRFS_INODE_NOCOMPRESS;
6199 } else if (flags & BTRFS_INODE_COMPRESS) {
6200 inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
6201 inode->flags |= BTRFS_INODE_COMPRESS;
6204 if (flags & BTRFS_INODE_NODATACOW) {
6205 inode->flags |= BTRFS_INODE_NODATACOW;
6206 if (S_ISREG(inode->vfs_inode.i_mode))
6207 inode->flags |= BTRFS_INODE_NODATASUM;
6210 btrfs_sync_inode_flags_to_i_flags(&inode->vfs_inode);
6213 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6214 struct btrfs_new_inode_args *args)
6216 struct inode *dir = args->dir;
6217 struct inode *inode = args->inode;
6218 const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6219 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6220 struct btrfs_root *root;
6221 struct btrfs_inode_item *inode_item;
6222 struct btrfs_key *location;
6223 struct btrfs_path *path;
6225 struct btrfs_inode_ref *ref;
6226 struct btrfs_key key[2];
6228 struct btrfs_item_batch batch;
6232 path = btrfs_alloc_path();
6237 BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6238 root = BTRFS_I(inode)->root;
6240 ret = btrfs_get_free_objectid(root, &objectid);
6243 inode->i_ino = objectid;
6247 * O_TMPFILE, set link count to 0, so that after this point, we
6248 * fill in an inode item with the correct link count.
6250 set_nlink(inode, 0);
6252 trace_btrfs_inode_request(dir);
6254 ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6258 /* index_cnt is ignored for everything but a dir. */
6259 BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6260 BTRFS_I(inode)->generation = trans->transid;
6261 inode->i_generation = BTRFS_I(inode)->generation;
6264 * Subvolumes don't inherit flags from their parent directory.
6265 * Originally this was probably by accident, but we probably can't
6266 * change it now without compatibility issues.
6269 btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
6271 if (S_ISREG(inode->i_mode)) {
6272 if (btrfs_test_opt(fs_info, NODATASUM))
6273 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6274 if (btrfs_test_opt(fs_info, NODATACOW))
6275 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6276 BTRFS_INODE_NODATASUM;
6279 location = &BTRFS_I(inode)->location;
6280 location->objectid = objectid;
6281 location->offset = 0;
6282 location->type = BTRFS_INODE_ITEM_KEY;
6284 ret = btrfs_insert_inode_locked(inode);
6287 BTRFS_I(dir)->index_cnt--;
6292 * We could have gotten an inode number from somebody who was fsynced
6293 * and then removed in this same transaction, so let's just set full
6294 * sync since it will be a full sync anyway and this will blow away the
6295 * old info in the log.
6297 btrfs_set_inode_full_sync(BTRFS_I(inode));
6299 key[0].objectid = objectid;
6300 key[0].type = BTRFS_INODE_ITEM_KEY;
6303 sizes[0] = sizeof(struct btrfs_inode_item);
6305 if (!args->orphan) {
6307 * Start new inodes with an inode_ref. This is slightly more
6308 * efficient for small numbers of hard links since they will
6309 * be packed into one item. Extended refs will kick in if we
6310 * add more hard links than can fit in the ref item.
6312 key[1].objectid = objectid;
6313 key[1].type = BTRFS_INODE_REF_KEY;
6315 key[1].offset = objectid;
6316 sizes[1] = 2 + sizeof(*ref);
6318 key[1].offset = btrfs_ino(BTRFS_I(dir));
6319 sizes[1] = name->len + sizeof(*ref);
6323 batch.keys = &key[0];
6324 batch.data_sizes = &sizes[0];
6325 batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6326 batch.nr = args->orphan ? 1 : 2;
6327 ret = btrfs_insert_empty_items(trans, root, path, &batch);
6329 btrfs_abort_transaction(trans, ret);
6333 inode->i_mtime = current_time(inode);
6334 inode->i_atime = inode->i_mtime;
6335 inode->i_ctime = inode->i_mtime;
6336 BTRFS_I(inode)->i_otime = inode->i_mtime;
6339 * We're going to fill the inode item now, so at this point the inode
6340 * must be fully initialized.
6343 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6344 struct btrfs_inode_item);
6345 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6346 sizeof(*inode_item));
6347 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6349 if (!args->orphan) {
6350 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6351 struct btrfs_inode_ref);
6352 ptr = (unsigned long)(ref + 1);
6354 btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6355 btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6356 write_extent_buffer(path->nodes[0], "..", ptr, 2);
6358 btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6360 btrfs_set_inode_ref_index(path->nodes[0], ref,
6361 BTRFS_I(inode)->dir_index);
6362 write_extent_buffer(path->nodes[0], name->name, ptr,
6367 btrfs_mark_buffer_dirty(path->nodes[0]);
6369 * We don't need the path anymore, plus inheriting properties, adding
6370 * ACLs, security xattrs, orphan item or adding the link, will result in
6371 * allocating yet another path. So just free our path.
6373 btrfs_free_path(path);
6377 struct inode *parent;
6380 * Subvolumes inherit properties from their parent subvolume,
6381 * not the directory they were created in.
6383 parent = btrfs_iget(fs_info->sb, BTRFS_FIRST_FREE_OBJECTID,
6384 BTRFS_I(dir)->root);
6385 if (IS_ERR(parent)) {
6386 ret = PTR_ERR(parent);
6388 ret = btrfs_inode_inherit_props(trans, inode, parent);
6392 ret = btrfs_inode_inherit_props(trans, inode, dir);
6396 "error inheriting props for ino %llu (root %llu): %d",
6397 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid,
6402 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6405 if (!args->subvol) {
6406 ret = btrfs_init_inode_security(trans, args);
6408 btrfs_abort_transaction(trans, ret);
6413 inode_tree_add(BTRFS_I(inode));
6415 trace_btrfs_inode_new(inode);
6416 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6418 btrfs_update_root_times(trans, root);
6421 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6423 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6424 0, BTRFS_I(inode)->dir_index);
6427 btrfs_abort_transaction(trans, ret);
6435 * discard_new_inode() calls iput(), but the caller owns the reference
6439 discard_new_inode(inode);
6441 btrfs_free_path(path);
6446 * utility function to add 'inode' into 'parent_inode' with
6447 * a give name and a given sequence number.
6448 * if 'add_backref' is true, also insert a backref from the
6449 * inode to the parent directory.
6451 int btrfs_add_link(struct btrfs_trans_handle *trans,
6452 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6453 const struct fscrypt_str *name, int add_backref, u64 index)
6456 struct btrfs_key key;
6457 struct btrfs_root *root = parent_inode->root;
6458 u64 ino = btrfs_ino(inode);
6459 u64 parent_ino = btrfs_ino(parent_inode);
6461 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6462 memcpy(&key, &inode->root->root_key, sizeof(key));
6465 key.type = BTRFS_INODE_ITEM_KEY;
6469 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6470 ret = btrfs_add_root_ref(trans, key.objectid,
6471 root->root_key.objectid, parent_ino,
6473 } else if (add_backref) {
6474 ret = btrfs_insert_inode_ref(trans, root, name,
6475 ino, parent_ino, index);
6478 /* Nothing to clean up yet */
6482 ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6483 btrfs_inode_type(&inode->vfs_inode), index);
6484 if (ret == -EEXIST || ret == -EOVERFLOW)
6487 btrfs_abort_transaction(trans, ret);
6491 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6493 inode_inc_iversion(&parent_inode->vfs_inode);
6495 * If we are replaying a log tree, we do not want to update the mtime
6496 * and ctime of the parent directory with the current time, since the
6497 * log replay procedure is responsible for setting them to their correct
6498 * values (the ones it had when the fsync was done).
6500 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6501 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6503 parent_inode->vfs_inode.i_mtime = now;
6504 parent_inode->vfs_inode.i_ctime = now;
6506 ret = btrfs_update_inode(trans, root, parent_inode);
6508 btrfs_abort_transaction(trans, ret);
6512 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6515 err = btrfs_del_root_ref(trans, key.objectid,
6516 root->root_key.objectid, parent_ino,
6517 &local_index, name);
6519 btrfs_abort_transaction(trans, err);
6520 } else if (add_backref) {
6524 err = btrfs_del_inode_ref(trans, root, name, ino, parent_ino,
6527 btrfs_abort_transaction(trans, err);
6530 /* Return the original error code */
6534 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6535 struct inode *inode)
6537 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6538 struct btrfs_root *root = BTRFS_I(dir)->root;
6539 struct btrfs_new_inode_args new_inode_args = {
6544 unsigned int trans_num_items;
6545 struct btrfs_trans_handle *trans;
6548 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6552 trans = btrfs_start_transaction(root, trans_num_items);
6553 if (IS_ERR(trans)) {
6554 err = PTR_ERR(trans);
6555 goto out_new_inode_args;
6558 err = btrfs_create_new_inode(trans, &new_inode_args);
6560 d_instantiate_new(dentry, inode);
6562 btrfs_end_transaction(trans);
6563 btrfs_btree_balance_dirty(fs_info);
6565 btrfs_new_inode_args_destroy(&new_inode_args);
6572 static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
6573 struct dentry *dentry, umode_t mode, dev_t rdev)
6575 struct inode *inode;
6577 inode = new_inode(dir->i_sb);
6580 inode_init_owner(idmap, inode, dir, mode);
6581 inode->i_op = &btrfs_special_inode_operations;
6582 init_special_inode(inode, inode->i_mode, rdev);
6583 return btrfs_create_common(dir, dentry, inode);
6586 static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
6587 struct dentry *dentry, umode_t mode, bool excl)
6589 struct inode *inode;
6591 inode = new_inode(dir->i_sb);
6594 inode_init_owner(idmap, inode, dir, mode);
6595 inode->i_fop = &btrfs_file_operations;
6596 inode->i_op = &btrfs_file_inode_operations;
6597 inode->i_mapping->a_ops = &btrfs_aops;
6598 return btrfs_create_common(dir, dentry, inode);
6601 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6602 struct dentry *dentry)
6604 struct btrfs_trans_handle *trans = NULL;
6605 struct btrfs_root *root = BTRFS_I(dir)->root;
6606 struct inode *inode = d_inode(old_dentry);
6607 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6608 struct fscrypt_name fname;
6613 /* do not allow sys_link's with other subvols of the same device */
6614 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6617 if (inode->i_nlink >= BTRFS_LINK_MAX)
6620 err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
6624 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6629 * 2 items for inode and inode ref
6630 * 2 items for dir items
6631 * 1 item for parent inode
6632 * 1 item for orphan item deletion if O_TMPFILE
6634 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6635 if (IS_ERR(trans)) {
6636 err = PTR_ERR(trans);
6641 /* There are several dir indexes for this inode, clear the cache. */
6642 BTRFS_I(inode)->dir_index = 0ULL;
6644 inode_inc_iversion(inode);
6645 inode->i_ctime = current_time(inode);
6647 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6649 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6650 &fname.disk_name, 1, index);
6655 struct dentry *parent = dentry->d_parent;
6657 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6660 if (inode->i_nlink == 1) {
6662 * If new hard link count is 1, it's a file created
6663 * with open(2) O_TMPFILE flag.
6665 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6669 d_instantiate(dentry, inode);
6670 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6674 fscrypt_free_filename(&fname);
6676 btrfs_end_transaction(trans);
6678 inode_dec_link_count(inode);
6681 btrfs_btree_balance_dirty(fs_info);
6685 static int btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
6686 struct dentry *dentry, umode_t mode)
6688 struct inode *inode;
6690 inode = new_inode(dir->i_sb);
6693 inode_init_owner(idmap, inode, dir, S_IFDIR | mode);
6694 inode->i_op = &btrfs_dir_inode_operations;
6695 inode->i_fop = &btrfs_dir_file_operations;
6696 return btrfs_create_common(dir, dentry, inode);
6699 static noinline int uncompress_inline(struct btrfs_path *path,
6701 struct btrfs_file_extent_item *item)
6704 struct extent_buffer *leaf = path->nodes[0];
6707 unsigned long inline_size;
6711 compress_type = btrfs_file_extent_compression(leaf, item);
6712 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6713 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6714 tmp = kmalloc(inline_size, GFP_NOFS);
6717 ptr = btrfs_file_extent_inline_start(item);
6719 read_extent_buffer(leaf, tmp, ptr, inline_size);
6721 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6722 ret = btrfs_decompress(compress_type, tmp, page, 0, inline_size, max_size);
6725 * decompression code contains a memset to fill in any space between the end
6726 * of the uncompressed data and the end of max_size in case the decompressed
6727 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6728 * the end of an inline extent and the beginning of the next block, so we
6729 * cover that region here.
6732 if (max_size < PAGE_SIZE)
6733 memzero_page(page, max_size, PAGE_SIZE - max_size);
6738 static int read_inline_extent(struct btrfs_inode *inode, struct btrfs_path *path,
6741 struct btrfs_file_extent_item *fi;
6745 if (!page || PageUptodate(page))
6748 ASSERT(page_offset(page) == 0);
6750 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6751 struct btrfs_file_extent_item);
6752 if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
6753 return uncompress_inline(path, page, fi);
6755 copy_size = min_t(u64, PAGE_SIZE,
6756 btrfs_file_extent_ram_bytes(path->nodes[0], fi));
6757 kaddr = kmap_local_page(page);
6758 read_extent_buffer(path->nodes[0], kaddr,
6759 btrfs_file_extent_inline_start(fi), copy_size);
6760 kunmap_local(kaddr);
6761 if (copy_size < PAGE_SIZE)
6762 memzero_page(page, copy_size, PAGE_SIZE - copy_size);
6767 * Lookup the first extent overlapping a range in a file.
6769 * @inode: file to search in
6770 * @page: page to read extent data into if the extent is inline
6771 * @pg_offset: offset into @page to copy to
6772 * @start: file offset
6773 * @len: length of range starting at @start
6775 * Return the first &struct extent_map which overlaps the given range, reading
6776 * it from the B-tree and caching it if necessary. Note that there may be more
6777 * extents which overlap the given range after the returned extent_map.
6779 * If @page is not NULL and the extent is inline, this also reads the extent
6780 * data directly into the page and marks the extent up to date in the io_tree.
6782 * Return: ERR_PTR on error, non-NULL extent_map on success.
6784 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6785 struct page *page, size_t pg_offset,
6788 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6790 u64 extent_start = 0;
6792 u64 objectid = btrfs_ino(inode);
6793 int extent_type = -1;
6794 struct btrfs_path *path = NULL;
6795 struct btrfs_root *root = inode->root;
6796 struct btrfs_file_extent_item *item;
6797 struct extent_buffer *leaf;
6798 struct btrfs_key found_key;
6799 struct extent_map *em = NULL;
6800 struct extent_map_tree *em_tree = &inode->extent_tree;
6802 read_lock(&em_tree->lock);
6803 em = lookup_extent_mapping(em_tree, start, len);
6804 read_unlock(&em_tree->lock);
6807 if (em->start > start || em->start + em->len <= start)
6808 free_extent_map(em);
6809 else if (em->block_start == EXTENT_MAP_INLINE && page)
6810 free_extent_map(em);
6814 em = alloc_extent_map();
6819 em->start = EXTENT_MAP_HOLE;
6820 em->orig_start = EXTENT_MAP_HOLE;
6822 em->block_len = (u64)-1;
6824 path = btrfs_alloc_path();
6830 /* Chances are we'll be called again, so go ahead and do readahead */
6831 path->reada = READA_FORWARD;
6834 * The same explanation in load_free_space_cache applies here as well,
6835 * we only read when we're loading the free space cache, and at that
6836 * point the commit_root has everything we need.
6838 if (btrfs_is_free_space_inode(inode)) {
6839 path->search_commit_root = 1;
6840 path->skip_locking = 1;
6843 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6846 } else if (ret > 0) {
6847 if (path->slots[0] == 0)
6853 leaf = path->nodes[0];
6854 item = btrfs_item_ptr(leaf, path->slots[0],
6855 struct btrfs_file_extent_item);
6856 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6857 if (found_key.objectid != objectid ||
6858 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6860 * If we backup past the first extent we want to move forward
6861 * and see if there is an extent in front of us, otherwise we'll
6862 * say there is a hole for our whole search range which can
6869 extent_type = btrfs_file_extent_type(leaf, item);
6870 extent_start = found_key.offset;
6871 extent_end = btrfs_file_extent_end(path);
6872 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6873 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6874 /* Only regular file could have regular/prealloc extent */
6875 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6878 "regular/prealloc extent found for non-regular inode %llu",
6882 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6884 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6885 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6890 if (start >= extent_end) {
6892 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6893 ret = btrfs_next_leaf(root, path);
6899 leaf = path->nodes[0];
6901 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6902 if (found_key.objectid != objectid ||
6903 found_key.type != BTRFS_EXTENT_DATA_KEY)
6905 if (start + len <= found_key.offset)
6907 if (start > found_key.offset)
6910 /* New extent overlaps with existing one */
6912 em->orig_start = start;
6913 em->len = found_key.offset - start;
6914 em->block_start = EXTENT_MAP_HOLE;
6918 btrfs_extent_item_to_extent_map(inode, path, item, em);
6920 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6921 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6923 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6925 * Inline extent can only exist at file offset 0. This is
6926 * ensured by tree-checker and inline extent creation path.
6927 * Thus all members representing file offsets should be zero.
6929 ASSERT(pg_offset == 0);
6930 ASSERT(extent_start == 0);
6931 ASSERT(em->start == 0);
6934 * btrfs_extent_item_to_extent_map() should have properly
6935 * initialized em members already.
6937 * Other members are not utilized for inline extents.
6939 ASSERT(em->block_start == EXTENT_MAP_INLINE);
6940 ASSERT(em->len == fs_info->sectorsize);
6942 ret = read_inline_extent(inode, path, page);
6949 em->orig_start = start;
6951 em->block_start = EXTENT_MAP_HOLE;
6954 btrfs_release_path(path);
6955 if (em->start > start || extent_map_end(em) <= start) {
6957 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6958 em->start, em->len, start, len);
6963 write_lock(&em_tree->lock);
6964 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6965 write_unlock(&em_tree->lock);
6967 btrfs_free_path(path);
6969 trace_btrfs_get_extent(root, inode, em);
6972 free_extent_map(em);
6973 return ERR_PTR(ret);
6978 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
6981 const u64 orig_start,
6982 const u64 block_start,
6983 const u64 block_len,
6984 const u64 orig_block_len,
6985 const u64 ram_bytes,
6988 struct extent_map *em = NULL;
6991 if (type != BTRFS_ORDERED_NOCOW) {
6992 em = create_io_em(inode, start, len, orig_start, block_start,
6993 block_len, orig_block_len, ram_bytes,
6994 BTRFS_COMPRESS_NONE, /* compress_type */
6999 ret = btrfs_add_ordered_extent(inode, start, len, len, block_start,
7002 (1 << BTRFS_ORDERED_DIRECT),
7003 BTRFS_COMPRESS_NONE);
7006 free_extent_map(em);
7007 btrfs_drop_extent_map_range(inode, start,
7008 start + len - 1, false);
7017 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7020 struct btrfs_root *root = inode->root;
7021 struct btrfs_fs_info *fs_info = root->fs_info;
7022 struct extent_map *em;
7023 struct btrfs_key ins;
7027 alloc_hint = get_extent_allocation_hint(inode, start, len);
7028 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7029 0, alloc_hint, &ins, 1, 1);
7031 return ERR_PTR(ret);
7033 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7034 ins.objectid, ins.offset, ins.offset,
7035 ins.offset, BTRFS_ORDERED_REGULAR);
7036 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7038 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7044 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7046 struct btrfs_block_group *block_group;
7047 bool readonly = false;
7049 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7050 if (!block_group || block_group->ro)
7053 btrfs_put_block_group(block_group);
7058 * Check if we can do nocow write into the range [@offset, @offset + @len)
7060 * @offset: File offset
7061 * @len: The length to write, will be updated to the nocow writeable
7063 * @orig_start: (optional) Return the original file offset of the file extent
7064 * @orig_len: (optional) Return the original on-disk length of the file extent
7065 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7066 * @strict: if true, omit optimizations that might force us into unnecessary
7067 * cow. e.g., don't trust generation number.
7070 * >0 and update @len if we can do nocow write
7071 * 0 if we can't do nocow write
7072 * <0 if error happened
7074 * NOTE: This only checks the file extents, caller is responsible to wait for
7075 * any ordered extents.
7077 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7078 u64 *orig_start, u64 *orig_block_len,
7079 u64 *ram_bytes, bool nowait, bool strict)
7081 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7082 struct can_nocow_file_extent_args nocow_args = { 0 };
7083 struct btrfs_path *path;
7085 struct extent_buffer *leaf;
7086 struct btrfs_root *root = BTRFS_I(inode)->root;
7087 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7088 struct btrfs_file_extent_item *fi;
7089 struct btrfs_key key;
7092 path = btrfs_alloc_path();
7095 path->nowait = nowait;
7097 ret = btrfs_lookup_file_extent(NULL, root, path,
7098 btrfs_ino(BTRFS_I(inode)), offset, 0);
7103 if (path->slots[0] == 0) {
7104 /* can't find the item, must cow */
7111 leaf = path->nodes[0];
7112 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7113 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7114 key.type != BTRFS_EXTENT_DATA_KEY) {
7115 /* not our file or wrong item type, must cow */
7119 if (key.offset > offset) {
7120 /* Wrong offset, must cow */
7124 if (btrfs_file_extent_end(path) <= offset)
7127 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7128 found_type = btrfs_file_extent_type(leaf, fi);
7130 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7132 nocow_args.start = offset;
7133 nocow_args.end = offset + *len - 1;
7134 nocow_args.strict = strict;
7135 nocow_args.free_path = true;
7137 ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
7138 /* can_nocow_file_extent() has freed the path. */
7142 /* Treat errors as not being able to NOCOW. */
7148 if (btrfs_extent_readonly(fs_info, nocow_args.disk_bytenr))
7151 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7152 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7155 range_end = round_up(offset + nocow_args.num_bytes,
7156 root->fs_info->sectorsize) - 1;
7157 ret = test_range_bit(io_tree, offset, range_end,
7158 EXTENT_DELALLOC, 0, NULL);
7166 *orig_start = key.offset - nocow_args.extent_offset;
7168 *orig_block_len = nocow_args.disk_num_bytes;
7170 *len = nocow_args.num_bytes;
7173 btrfs_free_path(path);
7177 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7178 struct extent_state **cached_state,
7179 unsigned int iomap_flags)
7181 const bool writing = (iomap_flags & IOMAP_WRITE);
7182 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7183 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7184 struct btrfs_ordered_extent *ordered;
7189 if (!try_lock_extent(io_tree, lockstart, lockend,
7193 lock_extent(io_tree, lockstart, lockend, cached_state);
7196 * We're concerned with the entire range that we're going to be
7197 * doing DIO to, so we need to make sure there's no ordered
7198 * extents in this range.
7200 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7201 lockend - lockstart + 1);
7204 * We need to make sure there are no buffered pages in this
7205 * range either, we could have raced between the invalidate in
7206 * generic_file_direct_write and locking the extent. The
7207 * invalidate needs to happen so that reads after a write do not
7211 (!writing || !filemap_range_has_page(inode->i_mapping,
7212 lockstart, lockend)))
7215 unlock_extent(io_tree, lockstart, lockend, cached_state);
7219 btrfs_put_ordered_extent(ordered);
7224 * If we are doing a DIO read and the ordered extent we
7225 * found is for a buffered write, we can not wait for it
7226 * to complete and retry, because if we do so we can
7227 * deadlock with concurrent buffered writes on page
7228 * locks. This happens only if our DIO read covers more
7229 * than one extent map, if at this point has already
7230 * created an ordered extent for a previous extent map
7231 * and locked its range in the inode's io tree, and a
7232 * concurrent write against that previous extent map's
7233 * range and this range started (we unlock the ranges
7234 * in the io tree only when the bios complete and
7235 * buffered writes always lock pages before attempting
7236 * to lock range in the io tree).
7239 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7240 btrfs_start_ordered_extent(ordered);
7242 ret = nowait ? -EAGAIN : -ENOTBLK;
7243 btrfs_put_ordered_extent(ordered);
7246 * We could trigger writeback for this range (and wait
7247 * for it to complete) and then invalidate the pages for
7248 * this range (through invalidate_inode_pages2_range()),
7249 * but that can lead us to a deadlock with a concurrent
7250 * call to readahead (a buffered read or a defrag call
7251 * triggered a readahead) on a page lock due to an
7252 * ordered dio extent we created before but did not have
7253 * yet a corresponding bio submitted (whence it can not
7254 * complete), which makes readahead wait for that
7255 * ordered extent to complete while holding a lock on
7258 ret = nowait ? -EAGAIN : -ENOTBLK;
7270 /* The callers of this must take lock_extent() */
7271 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7272 u64 len, u64 orig_start, u64 block_start,
7273 u64 block_len, u64 orig_block_len,
7274 u64 ram_bytes, int compress_type,
7277 struct extent_map *em;
7280 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7281 type == BTRFS_ORDERED_COMPRESSED ||
7282 type == BTRFS_ORDERED_NOCOW ||
7283 type == BTRFS_ORDERED_REGULAR);
7285 em = alloc_extent_map();
7287 return ERR_PTR(-ENOMEM);
7290 em->orig_start = orig_start;
7292 em->block_len = block_len;
7293 em->block_start = block_start;
7294 em->orig_block_len = orig_block_len;
7295 em->ram_bytes = ram_bytes;
7296 em->generation = -1;
7297 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7298 if (type == BTRFS_ORDERED_PREALLOC) {
7299 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7300 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7301 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7302 em->compress_type = compress_type;
7305 ret = btrfs_replace_extent_map_range(inode, em, true);
7307 free_extent_map(em);
7308 return ERR_PTR(ret);
7311 /* em got 2 refs now, callers needs to do free_extent_map once. */
7316 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7317 struct inode *inode,
7318 struct btrfs_dio_data *dio_data,
7320 unsigned int iomap_flags)
7322 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7323 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7324 struct extent_map *em = *map;
7326 u64 block_start, orig_start, orig_block_len, ram_bytes;
7327 struct btrfs_block_group *bg;
7328 bool can_nocow = false;
7329 bool space_reserved = false;
7334 * We don't allocate a new extent in the following cases
7336 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7338 * 2) The extent is marked as PREALLOC. We're good to go here and can
7339 * just use the extent.
7342 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7343 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7344 em->block_start != EXTENT_MAP_HOLE)) {
7345 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7346 type = BTRFS_ORDERED_PREALLOC;
7348 type = BTRFS_ORDERED_NOCOW;
7349 len = min(len, em->len - (start - em->start));
7350 block_start = em->block_start + (start - em->start);
7352 if (can_nocow_extent(inode, start, &len, &orig_start,
7353 &orig_block_len, &ram_bytes, false, false) == 1) {
7354 bg = btrfs_inc_nocow_writers(fs_info, block_start);
7362 struct extent_map *em2;
7364 /* We can NOCOW, so only need to reserve metadata space. */
7365 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7368 /* Our caller expects us to free the input extent map. */
7369 free_extent_map(em);
7371 btrfs_dec_nocow_writers(bg);
7372 if (nowait && (ret == -ENOSPC || ret == -EDQUOT))
7376 space_reserved = true;
7378 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7379 orig_start, block_start,
7380 len, orig_block_len,
7382 btrfs_dec_nocow_writers(bg);
7383 if (type == BTRFS_ORDERED_PREALLOC) {
7384 free_extent_map(em);
7394 dio_data->nocow_done = true;
7396 /* Our caller expects us to free the input extent map. */
7397 free_extent_map(em);
7404 * If we could not allocate data space before locking the file
7405 * range and we can't do a NOCOW write, then we have to fail.
7407 if (!dio_data->data_space_reserved)
7411 * We have to COW and we have already reserved data space before,
7412 * so now we reserve only metadata.
7414 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7418 space_reserved = true;
7420 em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7426 len = min(len, em->len - (start - em->start));
7428 btrfs_delalloc_release_metadata(BTRFS_I(inode),
7429 prev_len - len, true);
7433 * We have created our ordered extent, so we can now release our reservation
7434 * for an outstanding extent.
7436 btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
7439 * Need to update the i_size under the extent lock so buffered
7440 * readers will get the updated i_size when we unlock.
7442 if (start + len > i_size_read(inode))
7443 i_size_write(inode, start + len);
7445 if (ret && space_reserved) {
7446 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7447 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7452 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7453 loff_t length, unsigned int flags, struct iomap *iomap,
7454 struct iomap *srcmap)
7456 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7457 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7458 struct extent_map *em;
7459 struct extent_state *cached_state = NULL;
7460 struct btrfs_dio_data *dio_data = iter->private;
7461 u64 lockstart, lockend;
7462 const bool write = !!(flags & IOMAP_WRITE);
7465 const u64 data_alloc_len = length;
7466 bool unlock_extents = false;
7469 * We could potentially fault if we have a buffer > PAGE_SIZE, and if
7470 * we're NOWAIT we may submit a bio for a partial range and return
7471 * EIOCBQUEUED, which would result in an errant short read.
7473 * The best way to handle this would be to allow for partial completions
7474 * of iocb's, so we could submit the partial bio, return and fault in
7475 * the rest of the pages, and then submit the io for the rest of the
7476 * range. However we don't have that currently, so simply return
7477 * -EAGAIN at this point so that the normal path is used.
7479 if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE)
7483 * Cap the size of reads to that usually seen in buffered I/O as we need
7484 * to allocate a contiguous array for the checksums.
7487 len = min_t(u64, len, fs_info->sectorsize * BTRFS_MAX_BIO_SECTORS);
7490 lockend = start + len - 1;
7493 * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
7494 * enough if we've written compressed pages to this area, so we need to
7495 * flush the dirty pages again to make absolutely sure that any
7496 * outstanding dirty pages are on disk - the first flush only starts
7497 * compression on the data, while keeping the pages locked, so by the
7498 * time the second flush returns we know bios for the compressed pages
7499 * were submitted and finished, and the pages no longer under writeback.
7501 * If we have a NOWAIT request and we have any pages in the range that
7502 * are locked, likely due to compression still in progress, we don't want
7503 * to block on page locks. We also don't want to block on pages marked as
7504 * dirty or under writeback (same as for the non-compression case).
7505 * iomap_dio_rw() did the same check, but after that and before we got
7506 * here, mmap'ed writes may have happened or buffered reads started
7507 * (readpage() and readahead(), which lock pages), as we haven't locked
7508 * the file range yet.
7510 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7511 &BTRFS_I(inode)->runtime_flags)) {
7512 if (flags & IOMAP_NOWAIT) {
7513 if (filemap_range_needs_writeback(inode->i_mapping,
7514 lockstart, lockend))
7517 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7518 start + length - 1);
7524 memset(dio_data, 0, sizeof(*dio_data));
7527 * We always try to allocate data space and must do it before locking
7528 * the file range, to avoid deadlocks with concurrent writes to the same
7529 * range if the range has several extents and the writes don't expand the
7530 * current i_size (the inode lock is taken in shared mode). If we fail to
7531 * allocate data space here we continue and later, after locking the
7532 * file range, we fail with ENOSPC only if we figure out we can not do a
7535 if (write && !(flags & IOMAP_NOWAIT)) {
7536 ret = btrfs_check_data_free_space(BTRFS_I(inode),
7537 &dio_data->data_reserved,
7538 start, data_alloc_len, false);
7540 dio_data->data_space_reserved = true;
7541 else if (ret && !(BTRFS_I(inode)->flags &
7542 (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
7547 * If this errors out it's because we couldn't invalidate pagecache for
7548 * this range and we need to fallback to buffered IO, or we are doing a
7549 * NOWAIT read/write and we need to block.
7551 ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags);
7555 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7562 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7563 * io. INLINE is special, and we could probably kludge it in here, but
7564 * it's still buffered so for safety lets just fall back to the generic
7567 * For COMPRESSED we _have_ to read the entire extent in so we can
7568 * decompress it, so there will be buffering required no matter what we
7569 * do, so go ahead and fallback to buffered.
7571 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7572 * to buffered IO. Don't blame me, this is the price we pay for using
7575 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7576 em->block_start == EXTENT_MAP_INLINE) {
7577 free_extent_map(em);
7579 * If we are in a NOWAIT context, return -EAGAIN in order to
7580 * fallback to buffered IO. This is not only because we can
7581 * block with buffered IO (no support for NOWAIT semantics at
7582 * the moment) but also to avoid returning short reads to user
7583 * space - this happens if we were able to read some data from
7584 * previous non-compressed extents and then when we fallback to
7585 * buffered IO, at btrfs_file_read_iter() by calling
7586 * filemap_read(), we fail to fault in pages for the read buffer,
7587 * in which case filemap_read() returns a short read (the number
7588 * of bytes previously read is > 0, so it does not return -EFAULT).
7590 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
7594 len = min(len, em->len - (start - em->start));
7597 * If we have a NOWAIT request and the range contains multiple extents
7598 * (or a mix of extents and holes), then we return -EAGAIN to make the
7599 * caller fallback to a context where it can do a blocking (without
7600 * NOWAIT) request. This way we avoid doing partial IO and returning
7601 * success to the caller, which is not optimal for writes and for reads
7602 * it can result in unexpected behaviour for an application.
7604 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7605 * iomap_dio_rw(), we can end up returning less data then what the caller
7606 * asked for, resulting in an unexpected, and incorrect, short read.
7607 * That is, the caller asked to read N bytes and we return less than that,
7608 * which is wrong unless we are crossing EOF. This happens if we get a
7609 * page fault error when trying to fault in pages for the buffer that is
7610 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7611 * have previously submitted bios for other extents in the range, in
7612 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7613 * those bios have completed by the time we get the page fault error,
7614 * which we return back to our caller - we should only return EIOCBQUEUED
7615 * after we have submitted bios for all the extents in the range.
7617 if ((flags & IOMAP_NOWAIT) && len < length) {
7618 free_extent_map(em);
7624 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7628 unlock_extents = true;
7629 /* Recalc len in case the new em is smaller than requested */
7630 len = min(len, em->len - (start - em->start));
7631 if (dio_data->data_space_reserved) {
7633 u64 release_len = 0;
7635 if (dio_data->nocow_done) {
7636 release_offset = start;
7637 release_len = data_alloc_len;
7638 } else if (len < data_alloc_len) {
7639 release_offset = start + len;
7640 release_len = data_alloc_len - len;
7643 if (release_len > 0)
7644 btrfs_free_reserved_data_space(BTRFS_I(inode),
7645 dio_data->data_reserved,
7651 * We need to unlock only the end area that we aren't using.
7652 * The rest is going to be unlocked by the endio routine.
7654 lockstart = start + len;
7655 if (lockstart < lockend)
7656 unlock_extents = true;
7660 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7663 free_extent_state(cached_state);
7666 * Translate extent map information to iomap.
7667 * We trim the extents (and move the addr) even though iomap code does
7668 * that, since we have locked only the parts we are performing I/O in.
7670 if ((em->block_start == EXTENT_MAP_HOLE) ||
7671 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7672 iomap->addr = IOMAP_NULL_ADDR;
7673 iomap->type = IOMAP_HOLE;
7675 iomap->addr = em->block_start + (start - em->start);
7676 iomap->type = IOMAP_MAPPED;
7678 iomap->offset = start;
7679 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7680 iomap->length = len;
7681 free_extent_map(em);
7686 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7689 if (dio_data->data_space_reserved) {
7690 btrfs_free_reserved_data_space(BTRFS_I(inode),
7691 dio_data->data_reserved,
7692 start, data_alloc_len);
7693 extent_changeset_free(dio_data->data_reserved);
7699 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7700 ssize_t written, unsigned int flags, struct iomap *iomap)
7702 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7703 struct btrfs_dio_data *dio_data = iter->private;
7704 size_t submitted = dio_data->submitted;
7705 const bool write = !!(flags & IOMAP_WRITE);
7708 if (!write && (iomap->type == IOMAP_HOLE)) {
7709 /* If reading from a hole, unlock and return */
7710 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1,
7715 if (submitted < length) {
7717 length -= submitted;
7719 btrfs_mark_ordered_io_finished(BTRFS_I(inode), NULL,
7720 pos, length, false);
7722 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7723 pos + length - 1, NULL);
7728 extent_changeset_free(dio_data->data_reserved);
7732 static void btrfs_dio_end_io(struct btrfs_bio *bbio)
7734 struct btrfs_dio_private *dip =
7735 container_of(bbio, struct btrfs_dio_private, bbio);
7736 struct btrfs_inode *inode = bbio->inode;
7737 struct bio *bio = &bbio->bio;
7739 if (bio->bi_status) {
7740 btrfs_warn(inode->root->fs_info,
7741 "direct IO failed ino %llu op 0x%0x offset %#llx len %u err no %d",
7742 btrfs_ino(inode), bio->bi_opf,
7743 dip->file_offset, dip->bytes, bio->bi_status);
7746 if (btrfs_op(bio) == BTRFS_MAP_WRITE)
7747 btrfs_mark_ordered_io_finished(inode, NULL, dip->file_offset,
7748 dip->bytes, !bio->bi_status);
7750 unlock_extent(&inode->io_tree, dip->file_offset,
7751 dip->file_offset + dip->bytes - 1, NULL);
7753 bbio->bio.bi_private = bbio->private;
7754 iomap_dio_bio_end_io(bio);
7757 static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio,
7760 struct btrfs_bio *bbio = btrfs_bio(bio);
7761 struct btrfs_dio_private *dip =
7762 container_of(bbio, struct btrfs_dio_private, bbio);
7763 struct btrfs_dio_data *dio_data = iter->private;
7765 btrfs_bio_init(bbio, BTRFS_I(iter->inode), btrfs_dio_end_io, bio->bi_private);
7766 bbio->file_offset = file_offset;
7768 dip->file_offset = file_offset;
7769 dip->bytes = bio->bi_iter.bi_size;
7771 dio_data->submitted += bio->bi_iter.bi_size;
7772 btrfs_submit_bio(bio, 0);
7775 static const struct iomap_ops btrfs_dio_iomap_ops = {
7776 .iomap_begin = btrfs_dio_iomap_begin,
7777 .iomap_end = btrfs_dio_iomap_end,
7780 static const struct iomap_dio_ops btrfs_dio_ops = {
7781 .submit_io = btrfs_dio_submit_io,
7782 .bio_set = &btrfs_dio_bioset,
7785 ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, size_t done_before)
7787 struct btrfs_dio_data data;
7789 return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
7790 IOMAP_DIO_PARTIAL, &data, done_before);
7793 struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
7796 struct btrfs_dio_data data;
7798 return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
7799 IOMAP_DIO_PARTIAL, &data, done_before);
7802 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7807 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
7812 * fiemap_prep() called filemap_write_and_wait() for the whole possible
7813 * file range (0 to LLONG_MAX), but that is not enough if we have
7814 * compression enabled. The first filemap_fdatawrite_range() only kicks
7815 * in the compression of data (in an async thread) and will return
7816 * before the compression is done and writeback is started. A second
7817 * filemap_fdatawrite_range() is needed to wait for the compression to
7818 * complete and writeback to start. We also need to wait for ordered
7819 * extents to complete, because our fiemap implementation uses mainly
7820 * file extent items to list the extents, searching for extent maps
7821 * only for file ranges with holes or prealloc extents to figure out
7822 * if we have delalloc in those ranges.
7824 if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
7825 ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
7830 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
7833 static int btrfs_writepages(struct address_space *mapping,
7834 struct writeback_control *wbc)
7836 return extent_writepages(mapping, wbc);
7839 static void btrfs_readahead(struct readahead_control *rac)
7841 extent_readahead(rac);
7845 * For release_folio() and invalidate_folio() we have a race window where
7846 * folio_end_writeback() is called but the subpage spinlock is not yet released.
7847 * If we continue to release/invalidate the page, we could cause use-after-free
7848 * for subpage spinlock. So this function is to spin and wait for subpage
7851 static void wait_subpage_spinlock(struct page *page)
7853 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7854 struct btrfs_subpage *subpage;
7856 if (!btrfs_is_subpage(fs_info, page))
7859 ASSERT(PagePrivate(page) && page->private);
7860 subpage = (struct btrfs_subpage *)page->private;
7863 * This may look insane as we just acquire the spinlock and release it,
7864 * without doing anything. But we just want to make sure no one is
7865 * still holding the subpage spinlock.
7866 * And since the page is not dirty nor writeback, and we have page
7867 * locked, the only possible way to hold a spinlock is from the endio
7868 * function to clear page writeback.
7870 * Here we just acquire the spinlock so that all existing callers
7871 * should exit and we're safe to release/invalidate the page.
7873 spin_lock_irq(&subpage->lock);
7874 spin_unlock_irq(&subpage->lock);
7877 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7879 int ret = try_release_extent_mapping(&folio->page, gfp_flags);
7882 wait_subpage_spinlock(&folio->page);
7883 clear_page_extent_mapped(&folio->page);
7888 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7890 if (folio_test_writeback(folio) || folio_test_dirty(folio))
7892 return __btrfs_release_folio(folio, gfp_flags);
7895 #ifdef CONFIG_MIGRATION
7896 static int btrfs_migrate_folio(struct address_space *mapping,
7897 struct folio *dst, struct folio *src,
7898 enum migrate_mode mode)
7900 int ret = filemap_migrate_folio(mapping, dst, src, mode);
7902 if (ret != MIGRATEPAGE_SUCCESS)
7905 if (folio_test_ordered(src)) {
7906 folio_clear_ordered(src);
7907 folio_set_ordered(dst);
7910 return MIGRATEPAGE_SUCCESS;
7913 #define btrfs_migrate_folio NULL
7916 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
7919 struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
7920 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7921 struct extent_io_tree *tree = &inode->io_tree;
7922 struct extent_state *cached_state = NULL;
7923 u64 page_start = folio_pos(folio);
7924 u64 page_end = page_start + folio_size(folio) - 1;
7926 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
7929 * We have folio locked so no new ordered extent can be created on this
7930 * page, nor bio can be submitted for this folio.
7932 * But already submitted bio can still be finished on this folio.
7933 * Furthermore, endio function won't skip folio which has Ordered
7934 * (Private2) already cleared, so it's possible for endio and
7935 * invalidate_folio to do the same ordered extent accounting twice
7938 * So here we wait for any submitted bios to finish, so that we won't
7939 * do double ordered extent accounting on the same folio.
7941 folio_wait_writeback(folio);
7942 wait_subpage_spinlock(&folio->page);
7945 * For subpage case, we have call sites like
7946 * btrfs_punch_hole_lock_range() which passes range not aligned to
7948 * If the range doesn't cover the full folio, we don't need to and
7949 * shouldn't clear page extent mapped, as folio->private can still
7950 * record subpage dirty bits for other part of the range.
7952 * For cases that invalidate the full folio even the range doesn't
7953 * cover the full folio, like invalidating the last folio, we're
7954 * still safe to wait for ordered extent to finish.
7956 if (!(offset == 0 && length == folio_size(folio))) {
7957 btrfs_release_folio(folio, GFP_NOFS);
7961 if (!inode_evicting)
7962 lock_extent(tree, page_start, page_end, &cached_state);
7965 while (cur < page_end) {
7966 struct btrfs_ordered_extent *ordered;
7969 u32 extra_flags = 0;
7971 ordered = btrfs_lookup_first_ordered_range(inode, cur,
7972 page_end + 1 - cur);
7974 range_end = page_end;
7976 * No ordered extent covering this range, we are safe
7977 * to delete all extent states in the range.
7979 extra_flags = EXTENT_CLEAR_ALL_BITS;
7982 if (ordered->file_offset > cur) {
7984 * There is a range between [cur, oe->file_offset) not
7985 * covered by any ordered extent.
7986 * We are safe to delete all extent states, and handle
7987 * the ordered extent in the next iteration.
7989 range_end = ordered->file_offset - 1;
7990 extra_flags = EXTENT_CLEAR_ALL_BITS;
7994 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
7996 ASSERT(range_end + 1 - cur < U32_MAX);
7997 range_len = range_end + 1 - cur;
7998 if (!btrfs_page_test_ordered(fs_info, &folio->page, cur, range_len)) {
8000 * If Ordered (Private2) is cleared, it means endio has
8001 * already been executed for the range.
8002 * We can't delete the extent states as
8003 * btrfs_finish_ordered_io() may still use some of them.
8007 btrfs_page_clear_ordered(fs_info, &folio->page, cur, range_len);
8010 * IO on this page will never be started, so we need to account
8011 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8012 * here, must leave that up for the ordered extent completion.
8014 * This will also unlock the range for incoming
8015 * btrfs_finish_ordered_io().
8017 if (!inode_evicting)
8018 clear_extent_bit(tree, cur, range_end,
8020 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8021 EXTENT_DEFRAG, &cached_state);
8023 spin_lock_irq(&inode->ordered_tree.lock);
8024 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8025 ordered->truncated_len = min(ordered->truncated_len,
8026 cur - ordered->file_offset);
8027 spin_unlock_irq(&inode->ordered_tree.lock);
8030 * If the ordered extent has finished, we're safe to delete all
8031 * the extent states of the range, otherwise
8032 * btrfs_finish_ordered_io() will get executed by endio for
8033 * other pages, so we can't delete extent states.
8035 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8036 cur, range_end + 1 - cur)) {
8037 btrfs_finish_ordered_io(ordered);
8039 * The ordered extent has finished, now we're again
8040 * safe to delete all extent states of the range.
8042 extra_flags = EXTENT_CLEAR_ALL_BITS;
8046 btrfs_put_ordered_extent(ordered);
8048 * Qgroup reserved space handler
8049 * Sector(s) here will be either:
8051 * 1) Already written to disk or bio already finished
8052 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8053 * Qgroup will be handled by its qgroup_record then.
8054 * btrfs_qgroup_free_data() call will do nothing here.
8056 * 2) Not written to disk yet
8057 * Then btrfs_qgroup_free_data() call will clear the
8058 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8059 * reserved data space.
8060 * Since the IO will never happen for this page.
8062 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8063 if (!inode_evicting) {
8064 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8065 EXTENT_DELALLOC | EXTENT_UPTODATE |
8066 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
8067 extra_flags, &cached_state);
8069 cur = range_end + 1;
8072 * We have iterated through all ordered extents of the page, the page
8073 * should not have Ordered (Private2) anymore, or the above iteration
8074 * did something wrong.
8076 ASSERT(!folio_test_ordered(folio));
8077 btrfs_page_clear_checked(fs_info, &folio->page, folio_pos(folio), folio_size(folio));
8078 if (!inode_evicting)
8079 __btrfs_release_folio(folio, GFP_NOFS);
8080 clear_page_extent_mapped(&folio->page);
8084 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8085 * called from a page fault handler when a page is first dirtied. Hence we must
8086 * be careful to check for EOF conditions here. We set the page up correctly
8087 * for a written page which means we get ENOSPC checking when writing into
8088 * holes and correct delalloc and unwritten extent mapping on filesystems that
8089 * support these features.
8091 * We are not allowed to take the i_mutex here so we have to play games to
8092 * protect against truncate races as the page could now be beyond EOF. Because
8093 * truncate_setsize() writes the inode size before removing pages, once we have
8094 * the page lock we can determine safely if the page is beyond EOF. If it is not
8095 * beyond EOF, then the page is guaranteed safe against truncation until we
8098 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8100 struct page *page = vmf->page;
8101 struct inode *inode = file_inode(vmf->vma->vm_file);
8102 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8103 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8104 struct btrfs_ordered_extent *ordered;
8105 struct extent_state *cached_state = NULL;
8106 struct extent_changeset *data_reserved = NULL;
8107 unsigned long zero_start;
8117 reserved_space = PAGE_SIZE;
8119 sb_start_pagefault(inode->i_sb);
8120 page_start = page_offset(page);
8121 page_end = page_start + PAGE_SIZE - 1;
8125 * Reserving delalloc space after obtaining the page lock can lead to
8126 * deadlock. For example, if a dirty page is locked by this function
8127 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8128 * dirty page write out, then the btrfs_writepages() function could
8129 * end up waiting indefinitely to get a lock on the page currently
8130 * being processed by btrfs_page_mkwrite() function.
8132 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8133 page_start, reserved_space);
8135 ret2 = file_update_time(vmf->vma->vm_file);
8139 ret = vmf_error(ret2);
8145 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8147 down_read(&BTRFS_I(inode)->i_mmap_lock);
8149 size = i_size_read(inode);
8151 if ((page->mapping != inode->i_mapping) ||
8152 (page_start >= size)) {
8153 /* page got truncated out from underneath us */
8156 wait_on_page_writeback(page);
8158 lock_extent(io_tree, page_start, page_end, &cached_state);
8159 ret2 = set_page_extent_mapped(page);
8161 ret = vmf_error(ret2);
8162 unlock_extent(io_tree, page_start, page_end, &cached_state);
8167 * we can't set the delalloc bits if there are pending ordered
8168 * extents. Drop our locks and wait for them to finish
8170 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8173 unlock_extent(io_tree, page_start, page_end, &cached_state);
8175 up_read(&BTRFS_I(inode)->i_mmap_lock);
8176 btrfs_start_ordered_extent(ordered);
8177 btrfs_put_ordered_extent(ordered);
8181 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8182 reserved_space = round_up(size - page_start,
8183 fs_info->sectorsize);
8184 if (reserved_space < PAGE_SIZE) {
8185 end = page_start + reserved_space - 1;
8186 btrfs_delalloc_release_space(BTRFS_I(inode),
8187 data_reserved, page_start,
8188 PAGE_SIZE - reserved_space, true);
8193 * page_mkwrite gets called when the page is firstly dirtied after it's
8194 * faulted in, but write(2) could also dirty a page and set delalloc
8195 * bits, thus in this case for space account reason, we still need to
8196 * clear any delalloc bits within this page range since we have to
8197 * reserve data&meta space before lock_page() (see above comments).
8199 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8200 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8201 EXTENT_DEFRAG, &cached_state);
8203 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8206 unlock_extent(io_tree, page_start, page_end, &cached_state);
8207 ret = VM_FAULT_SIGBUS;
8211 /* page is wholly or partially inside EOF */
8212 if (page_start + PAGE_SIZE > size)
8213 zero_start = offset_in_page(size);
8215 zero_start = PAGE_SIZE;
8217 if (zero_start != PAGE_SIZE)
8218 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8220 btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
8221 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8222 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8224 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8226 unlock_extent(io_tree, page_start, page_end, &cached_state);
8227 up_read(&BTRFS_I(inode)->i_mmap_lock);
8229 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8230 sb_end_pagefault(inode->i_sb);
8231 extent_changeset_free(data_reserved);
8232 return VM_FAULT_LOCKED;
8236 up_read(&BTRFS_I(inode)->i_mmap_lock);
8238 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8239 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8240 reserved_space, (ret != 0));
8242 sb_end_pagefault(inode->i_sb);
8243 extent_changeset_free(data_reserved);
8247 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
8249 struct btrfs_truncate_control control = {
8251 .ino = btrfs_ino(inode),
8252 .min_type = BTRFS_EXTENT_DATA_KEY,
8253 .clear_extent_range = true,
8255 struct btrfs_root *root = inode->root;
8256 struct btrfs_fs_info *fs_info = root->fs_info;
8257 struct btrfs_block_rsv *rsv;
8259 struct btrfs_trans_handle *trans;
8260 u64 mask = fs_info->sectorsize - 1;
8261 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8263 if (!skip_writeback) {
8264 ret = btrfs_wait_ordered_range(&inode->vfs_inode,
8265 inode->vfs_inode.i_size & (~mask),
8272 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8273 * things going on here:
8275 * 1) We need to reserve space to update our inode.
8277 * 2) We need to have something to cache all the space that is going to
8278 * be free'd up by the truncate operation, but also have some slack
8279 * space reserved in case it uses space during the truncate (thank you
8280 * very much snapshotting).
8282 * And we need these to be separate. The fact is we can use a lot of
8283 * space doing the truncate, and we have no earthly idea how much space
8284 * we will use, so we need the truncate reservation to be separate so it
8285 * doesn't end up using space reserved for updating the inode. We also
8286 * need to be able to stop the transaction and start a new one, which
8287 * means we need to be able to update the inode several times, and we
8288 * have no idea of knowing how many times that will be, so we can't just
8289 * reserve 1 item for the entirety of the operation, so that has to be
8290 * done separately as well.
8292 * So that leaves us with
8294 * 1) rsv - for the truncate reservation, which we will steal from the
8295 * transaction reservation.
8296 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8297 * updating the inode.
8299 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8302 rsv->size = min_size;
8303 rsv->failfast = true;
8306 * 1 for the truncate slack space
8307 * 1 for updating the inode.
8309 trans = btrfs_start_transaction(root, 2);
8310 if (IS_ERR(trans)) {
8311 ret = PTR_ERR(trans);
8315 /* Migrate the slack space for the truncate to our reserve */
8316 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8320 trans->block_rsv = rsv;
8323 struct extent_state *cached_state = NULL;
8324 const u64 new_size = inode->vfs_inode.i_size;
8325 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8327 control.new_size = new_size;
8328 lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
8330 * We want to drop from the next block forward in case this new
8331 * size is not block aligned since we will be keeping the last
8332 * block of the extent just the way it is.
8334 btrfs_drop_extent_map_range(inode,
8335 ALIGN(new_size, fs_info->sectorsize),
8338 ret = btrfs_truncate_inode_items(trans, root, &control);
8340 inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
8341 btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
8343 unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
8345 trans->block_rsv = &fs_info->trans_block_rsv;
8346 if (ret != -ENOSPC && ret != -EAGAIN)
8349 ret = btrfs_update_inode(trans, root, inode);
8353 btrfs_end_transaction(trans);
8354 btrfs_btree_balance_dirty(fs_info);
8356 trans = btrfs_start_transaction(root, 2);
8357 if (IS_ERR(trans)) {
8358 ret = PTR_ERR(trans);
8363 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8364 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8365 rsv, min_size, false);
8366 BUG_ON(ret); /* shouldn't happen */
8367 trans->block_rsv = rsv;
8371 * We can't call btrfs_truncate_block inside a trans handle as we could
8372 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8373 * know we've truncated everything except the last little bit, and can
8374 * do btrfs_truncate_block and then update the disk_i_size.
8376 if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8377 btrfs_end_transaction(trans);
8378 btrfs_btree_balance_dirty(fs_info);
8380 ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size, 0, 0);
8383 trans = btrfs_start_transaction(root, 1);
8384 if (IS_ERR(trans)) {
8385 ret = PTR_ERR(trans);
8388 btrfs_inode_safe_disk_i_size_write(inode, 0);
8394 trans->block_rsv = &fs_info->trans_block_rsv;
8395 ret2 = btrfs_update_inode(trans, root, inode);
8399 ret2 = btrfs_end_transaction(trans);
8402 btrfs_btree_balance_dirty(fs_info);
8405 btrfs_free_block_rsv(fs_info, rsv);
8407 * So if we truncate and then write and fsync we normally would just
8408 * write the extents that changed, which is a problem if we need to
8409 * first truncate that entire inode. So set this flag so we write out
8410 * all of the extents in the inode to the sync log so we're completely
8413 * If no extents were dropped or trimmed we don't need to force the next
8414 * fsync to truncate all the inode's items from the log and re-log them
8415 * all. This means the truncate operation did not change the file size,
8416 * or changed it to a smaller size but there was only an implicit hole
8417 * between the old i_size and the new i_size, and there were no prealloc
8418 * extents beyond i_size to drop.
8420 if (control.extents_found > 0)
8421 btrfs_set_inode_full_sync(inode);
8426 struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
8429 struct inode *inode;
8431 inode = new_inode(dir->i_sb);
8434 * Subvolumes don't inherit the sgid bit or the parent's gid if
8435 * the parent's sgid bit is set. This is probably a bug.
8437 inode_init_owner(idmap, inode, NULL,
8438 S_IFDIR | (~current_umask() & S_IRWXUGO));
8439 inode->i_op = &btrfs_dir_inode_operations;
8440 inode->i_fop = &btrfs_dir_file_operations;
8445 struct inode *btrfs_alloc_inode(struct super_block *sb)
8447 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8448 struct btrfs_inode *ei;
8449 struct inode *inode;
8451 ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8458 ei->last_sub_trans = 0;
8459 ei->logged_trans = 0;
8460 ei->delalloc_bytes = 0;
8461 ei->new_delalloc_bytes = 0;
8462 ei->defrag_bytes = 0;
8463 ei->disk_i_size = 0;
8467 ei->index_cnt = (u64)-1;
8469 ei->last_unlink_trans = 0;
8470 ei->last_reflink_trans = 0;
8471 ei->last_log_commit = 0;
8473 spin_lock_init(&ei->lock);
8474 ei->outstanding_extents = 0;
8475 if (sb->s_magic != BTRFS_TEST_MAGIC)
8476 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8477 BTRFS_BLOCK_RSV_DELALLOC);
8478 ei->runtime_flags = 0;
8479 ei->prop_compress = BTRFS_COMPRESS_NONE;
8480 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8482 ei->delayed_node = NULL;
8484 ei->i_otime.tv_sec = 0;
8485 ei->i_otime.tv_nsec = 0;
8487 inode = &ei->vfs_inode;
8488 extent_map_tree_init(&ei->extent_tree);
8489 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
8490 ei->io_tree.inode = ei;
8491 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8492 IO_TREE_INODE_FILE_EXTENT);
8493 atomic_set(&ei->sync_writers, 0);
8494 mutex_init(&ei->log_mutex);
8495 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8496 INIT_LIST_HEAD(&ei->delalloc_inodes);
8497 INIT_LIST_HEAD(&ei->delayed_iput);
8498 RB_CLEAR_NODE(&ei->rb_node);
8499 init_rwsem(&ei->i_mmap_lock);
8504 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8505 void btrfs_test_destroy_inode(struct inode *inode)
8507 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8508 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8512 void btrfs_free_inode(struct inode *inode)
8514 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8517 void btrfs_destroy_inode(struct inode *vfs_inode)
8519 struct btrfs_ordered_extent *ordered;
8520 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8521 struct btrfs_root *root = inode->root;
8522 bool freespace_inode;
8524 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8525 WARN_ON(vfs_inode->i_data.nrpages);
8526 WARN_ON(inode->block_rsv.reserved);
8527 WARN_ON(inode->block_rsv.size);
8528 WARN_ON(inode->outstanding_extents);
8529 if (!S_ISDIR(vfs_inode->i_mode)) {
8530 WARN_ON(inode->delalloc_bytes);
8531 WARN_ON(inode->new_delalloc_bytes);
8533 WARN_ON(inode->csum_bytes);
8534 WARN_ON(inode->defrag_bytes);
8537 * This can happen where we create an inode, but somebody else also
8538 * created the same inode and we need to destroy the one we already
8545 * If this is a free space inode do not take the ordered extents lockdep
8548 freespace_inode = btrfs_is_free_space_inode(inode);
8551 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8555 btrfs_err(root->fs_info,
8556 "found ordered extent %llu %llu on inode cleanup",
8557 ordered->file_offset, ordered->num_bytes);
8559 if (!freespace_inode)
8560 btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
8562 btrfs_remove_ordered_extent(inode, ordered);
8563 btrfs_put_ordered_extent(ordered);
8564 btrfs_put_ordered_extent(ordered);
8567 btrfs_qgroup_check_reserved_leak(inode);
8568 inode_tree_del(inode);
8569 btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
8570 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8571 btrfs_put_root(inode->root);
8574 int btrfs_drop_inode(struct inode *inode)
8576 struct btrfs_root *root = BTRFS_I(inode)->root;
8581 /* the snap/subvol tree is on deleting */
8582 if (btrfs_root_refs(&root->root_item) == 0)
8585 return generic_drop_inode(inode);
8588 static void init_once(void *foo)
8590 struct btrfs_inode *ei = foo;
8592 inode_init_once(&ei->vfs_inode);
8595 void __cold btrfs_destroy_cachep(void)
8598 * Make sure all delayed rcu free inodes are flushed before we
8602 bioset_exit(&btrfs_dio_bioset);
8603 kmem_cache_destroy(btrfs_inode_cachep);
8606 int __init btrfs_init_cachep(void)
8608 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8609 sizeof(struct btrfs_inode), 0,
8610 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8612 if (!btrfs_inode_cachep)
8615 if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE,
8616 offsetof(struct btrfs_dio_private, bbio.bio),
8622 btrfs_destroy_cachep();
8626 static int btrfs_getattr(struct mnt_idmap *idmap,
8627 const struct path *path, struct kstat *stat,
8628 u32 request_mask, unsigned int flags)
8632 struct inode *inode = d_inode(path->dentry);
8633 u32 blocksize = inode->i_sb->s_blocksize;
8634 u32 bi_flags = BTRFS_I(inode)->flags;
8635 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8637 stat->result_mask |= STATX_BTIME;
8638 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8639 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8640 if (bi_flags & BTRFS_INODE_APPEND)
8641 stat->attributes |= STATX_ATTR_APPEND;
8642 if (bi_flags & BTRFS_INODE_COMPRESS)
8643 stat->attributes |= STATX_ATTR_COMPRESSED;
8644 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8645 stat->attributes |= STATX_ATTR_IMMUTABLE;
8646 if (bi_flags & BTRFS_INODE_NODUMP)
8647 stat->attributes |= STATX_ATTR_NODUMP;
8648 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8649 stat->attributes |= STATX_ATTR_VERITY;
8651 stat->attributes_mask |= (STATX_ATTR_APPEND |
8652 STATX_ATTR_COMPRESSED |
8653 STATX_ATTR_IMMUTABLE |
8656 generic_fillattr(idmap, inode, stat);
8657 stat->dev = BTRFS_I(inode)->root->anon_dev;
8659 spin_lock(&BTRFS_I(inode)->lock);
8660 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8661 inode_bytes = inode_get_bytes(inode);
8662 spin_unlock(&BTRFS_I(inode)->lock);
8663 stat->blocks = (ALIGN(inode_bytes, blocksize) +
8664 ALIGN(delalloc_bytes, blocksize)) >> 9;
8668 static int btrfs_rename_exchange(struct inode *old_dir,
8669 struct dentry *old_dentry,
8670 struct inode *new_dir,
8671 struct dentry *new_dentry)
8673 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8674 struct btrfs_trans_handle *trans;
8675 unsigned int trans_num_items;
8676 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8677 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8678 struct inode *new_inode = new_dentry->d_inode;
8679 struct inode *old_inode = old_dentry->d_inode;
8680 struct timespec64 ctime = current_time(old_inode);
8681 struct btrfs_rename_ctx old_rename_ctx;
8682 struct btrfs_rename_ctx new_rename_ctx;
8683 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8684 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8689 bool need_abort = false;
8690 struct fscrypt_name old_fname, new_fname;
8691 struct fscrypt_str *old_name, *new_name;
8694 * For non-subvolumes allow exchange only within one subvolume, in the
8695 * same inode namespace. Two subvolumes (represented as directory) can
8696 * be exchanged as they're a logical link and have a fixed inode number.
8699 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8700 new_ino != BTRFS_FIRST_FREE_OBJECTID))
8703 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8707 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8709 fscrypt_free_filename(&old_fname);
8713 old_name = &old_fname.disk_name;
8714 new_name = &new_fname.disk_name;
8716 /* close the race window with snapshot create/destroy ioctl */
8717 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8718 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8719 down_read(&fs_info->subvol_sem);
8723 * 1 to remove old dir item
8724 * 1 to remove old dir index
8725 * 1 to add new dir item
8726 * 1 to add new dir index
8727 * 1 to update parent inode
8729 * If the parents are the same, we only need to account for one
8731 trans_num_items = (old_dir == new_dir ? 9 : 10);
8732 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8734 * 1 to remove old root ref
8735 * 1 to remove old root backref
8736 * 1 to add new root ref
8737 * 1 to add new root backref
8739 trans_num_items += 4;
8742 * 1 to update inode item
8743 * 1 to remove old inode ref
8744 * 1 to add new inode ref
8746 trans_num_items += 3;
8748 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
8749 trans_num_items += 4;
8751 trans_num_items += 3;
8752 trans = btrfs_start_transaction(root, trans_num_items);
8753 if (IS_ERR(trans)) {
8754 ret = PTR_ERR(trans);
8759 ret = btrfs_record_root_in_trans(trans, dest);
8765 * We need to find a free sequence number both in the source and
8766 * in the destination directory for the exchange.
8768 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8771 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8775 BTRFS_I(old_inode)->dir_index = 0ULL;
8776 BTRFS_I(new_inode)->dir_index = 0ULL;
8778 /* Reference for the source. */
8779 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8780 /* force full log commit if subvolume involved. */
8781 btrfs_set_log_full_commit(trans);
8783 ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
8784 btrfs_ino(BTRFS_I(new_dir)),
8791 /* And now for the dest. */
8792 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8793 /* force full log commit if subvolume involved. */
8794 btrfs_set_log_full_commit(trans);
8796 ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
8797 btrfs_ino(BTRFS_I(old_dir)),
8801 btrfs_abort_transaction(trans, ret);
8806 /* Update inode version and ctime/mtime. */
8807 inode_inc_iversion(old_dir);
8808 inode_inc_iversion(new_dir);
8809 inode_inc_iversion(old_inode);
8810 inode_inc_iversion(new_inode);
8811 old_dir->i_mtime = ctime;
8812 old_dir->i_ctime = ctime;
8813 new_dir->i_mtime = ctime;
8814 new_dir->i_ctime = ctime;
8815 old_inode->i_ctime = ctime;
8816 new_inode->i_ctime = ctime;
8818 if (old_dentry->d_parent != new_dentry->d_parent) {
8819 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8820 BTRFS_I(old_inode), 1);
8821 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8822 BTRFS_I(new_inode), 1);
8825 /* src is a subvolume */
8826 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8827 ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8828 } else { /* src is an inode */
8829 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8830 BTRFS_I(old_dentry->d_inode),
8831 old_name, &old_rename_ctx);
8833 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
8836 btrfs_abort_transaction(trans, ret);
8840 /* dest is a subvolume */
8841 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8842 ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8843 } else { /* dest is an inode */
8844 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8845 BTRFS_I(new_dentry->d_inode),
8846 new_name, &new_rename_ctx);
8848 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
8851 btrfs_abort_transaction(trans, ret);
8855 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8856 new_name, 0, old_idx);
8858 btrfs_abort_transaction(trans, ret);
8862 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8863 old_name, 0, new_idx);
8865 btrfs_abort_transaction(trans, ret);
8869 if (old_inode->i_nlink == 1)
8870 BTRFS_I(old_inode)->dir_index = old_idx;
8871 if (new_inode->i_nlink == 1)
8872 BTRFS_I(new_inode)->dir_index = new_idx;
8875 * Now pin the logs of the roots. We do it to ensure that no other task
8876 * can sync the logs while we are in progress with the rename, because
8877 * that could result in an inconsistency in case any of the inodes that
8878 * are part of this rename operation were logged before.
8880 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8881 btrfs_pin_log_trans(root);
8882 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
8883 btrfs_pin_log_trans(dest);
8885 /* Do the log updates for all inodes. */
8886 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8887 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8888 old_rename_ctx.index, new_dentry->d_parent);
8889 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
8890 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
8891 new_rename_ctx.index, old_dentry->d_parent);
8893 /* Now unpin the logs. */
8894 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8895 btrfs_end_log_trans(root);
8896 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
8897 btrfs_end_log_trans(dest);
8899 ret2 = btrfs_end_transaction(trans);
8900 ret = ret ? ret : ret2;
8902 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8903 old_ino == BTRFS_FIRST_FREE_OBJECTID)
8904 up_read(&fs_info->subvol_sem);
8906 fscrypt_free_filename(&new_fname);
8907 fscrypt_free_filename(&old_fname);
8911 static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
8914 struct inode *inode;
8916 inode = new_inode(dir->i_sb);
8918 inode_init_owner(idmap, inode, dir,
8919 S_IFCHR | WHITEOUT_MODE);
8920 inode->i_op = &btrfs_special_inode_operations;
8921 init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
8926 static int btrfs_rename(struct mnt_idmap *idmap,
8927 struct inode *old_dir, struct dentry *old_dentry,
8928 struct inode *new_dir, struct dentry *new_dentry,
8931 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8932 struct btrfs_new_inode_args whiteout_args = {
8934 .dentry = old_dentry,
8936 struct btrfs_trans_handle *trans;
8937 unsigned int trans_num_items;
8938 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8939 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8940 struct inode *new_inode = d_inode(new_dentry);
8941 struct inode *old_inode = d_inode(old_dentry);
8942 struct btrfs_rename_ctx rename_ctx;
8946 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8947 struct fscrypt_name old_fname, new_fname;
8949 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8952 /* we only allow rename subvolume link between subvolumes */
8953 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8956 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8957 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
8960 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8961 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8964 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8968 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8970 fscrypt_free_filename(&old_fname);
8974 /* check for collisions, even if the name isn't there */
8975 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
8977 if (ret == -EEXIST) {
8979 * eexist without a new_inode */
8980 if (WARN_ON(!new_inode)) {
8981 goto out_fscrypt_names;
8984 /* maybe -EOVERFLOW */
8985 goto out_fscrypt_names;
8991 * we're using rename to replace one file with another. Start IO on it
8992 * now so we don't add too much work to the end of the transaction
8994 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8995 filemap_flush(old_inode->i_mapping);
8997 if (flags & RENAME_WHITEOUT) {
8998 whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
8999 if (!whiteout_args.inode) {
9001 goto out_fscrypt_names;
9003 ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
9005 goto out_whiteout_inode;
9007 /* 1 to update the old parent inode. */
9008 trans_num_items = 1;
9011 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9012 /* Close the race window with snapshot create/destroy ioctl */
9013 down_read(&fs_info->subvol_sem);
9015 * 1 to remove old root ref
9016 * 1 to remove old root backref
9017 * 1 to add new root ref
9018 * 1 to add new root backref
9020 trans_num_items += 4;
9024 * 1 to remove old inode ref
9025 * 1 to add new inode ref
9027 trans_num_items += 3;
9030 * 1 to remove old dir item
9031 * 1 to remove old dir index
9032 * 1 to add new dir item
9033 * 1 to add new dir index
9035 trans_num_items += 4;
9036 /* 1 to update new parent inode if it's not the same as the old parent */
9037 if (new_dir != old_dir)
9042 * 1 to remove inode ref
9043 * 1 to remove dir item
9044 * 1 to remove dir index
9045 * 1 to possibly add orphan item
9047 trans_num_items += 5;
9049 trans = btrfs_start_transaction(root, trans_num_items);
9050 if (IS_ERR(trans)) {
9051 ret = PTR_ERR(trans);
9056 ret = btrfs_record_root_in_trans(trans, dest);
9061 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9065 BTRFS_I(old_inode)->dir_index = 0ULL;
9066 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9067 /* force full log commit if subvolume involved. */
9068 btrfs_set_log_full_commit(trans);
9070 ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
9071 old_ino, btrfs_ino(BTRFS_I(new_dir)),
9077 inode_inc_iversion(old_dir);
9078 inode_inc_iversion(new_dir);
9079 inode_inc_iversion(old_inode);
9080 old_dir->i_mtime = current_time(old_dir);
9081 old_dir->i_ctime = old_dir->i_mtime;
9082 new_dir->i_mtime = old_dir->i_mtime;
9083 new_dir->i_ctime = old_dir->i_mtime;
9084 old_inode->i_ctime = old_dir->i_mtime;
9086 if (old_dentry->d_parent != new_dentry->d_parent)
9087 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9088 BTRFS_I(old_inode), 1);
9090 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9091 ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
9093 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9094 BTRFS_I(d_inode(old_dentry)),
9095 &old_fname.disk_name, &rename_ctx);
9097 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9100 btrfs_abort_transaction(trans, ret);
9105 inode_inc_iversion(new_inode);
9106 new_inode->i_ctime = current_time(new_inode);
9107 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9108 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9109 ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
9110 BUG_ON(new_inode->i_nlink == 0);
9112 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9113 BTRFS_I(d_inode(new_dentry)),
9114 &new_fname.disk_name);
9116 if (!ret && new_inode->i_nlink == 0)
9117 ret = btrfs_orphan_add(trans,
9118 BTRFS_I(d_inode(new_dentry)));
9120 btrfs_abort_transaction(trans, ret);
9125 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9126 &new_fname.disk_name, 0, index);
9128 btrfs_abort_transaction(trans, ret);
9132 if (old_inode->i_nlink == 1)
9133 BTRFS_I(old_inode)->dir_index = index;
9135 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9136 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9137 rename_ctx.index, new_dentry->d_parent);
9139 if (flags & RENAME_WHITEOUT) {
9140 ret = btrfs_create_new_inode(trans, &whiteout_args);
9142 btrfs_abort_transaction(trans, ret);
9145 unlock_new_inode(whiteout_args.inode);
9146 iput(whiteout_args.inode);
9147 whiteout_args.inode = NULL;
9151 ret2 = btrfs_end_transaction(trans);
9152 ret = ret ? ret : ret2;
9154 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9155 up_read(&fs_info->subvol_sem);
9156 if (flags & RENAME_WHITEOUT)
9157 btrfs_new_inode_args_destroy(&whiteout_args);
9159 if (flags & RENAME_WHITEOUT)
9160 iput(whiteout_args.inode);
9162 fscrypt_free_filename(&old_fname);
9163 fscrypt_free_filename(&new_fname);
9167 static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
9168 struct dentry *old_dentry, struct inode *new_dir,
9169 struct dentry *new_dentry, unsigned int flags)
9173 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9176 if (flags & RENAME_EXCHANGE)
9177 ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9180 ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
9183 btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
9188 struct btrfs_delalloc_work {
9189 struct inode *inode;
9190 struct completion completion;
9191 struct list_head list;
9192 struct btrfs_work work;
9195 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9197 struct btrfs_delalloc_work *delalloc_work;
9198 struct inode *inode;
9200 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9202 inode = delalloc_work->inode;
9203 filemap_flush(inode->i_mapping);
9204 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9205 &BTRFS_I(inode)->runtime_flags))
9206 filemap_flush(inode->i_mapping);
9209 complete(&delalloc_work->completion);
9212 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9214 struct btrfs_delalloc_work *work;
9216 work = kmalloc(sizeof(*work), GFP_NOFS);
9220 init_completion(&work->completion);
9221 INIT_LIST_HEAD(&work->list);
9222 work->inode = inode;
9223 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9229 * some fairly slow code that needs optimization. This walks the list
9230 * of all the inodes with pending delalloc and forces them to disk.
9232 static int start_delalloc_inodes(struct btrfs_root *root,
9233 struct writeback_control *wbc, bool snapshot,
9234 bool in_reclaim_context)
9236 struct btrfs_inode *binode;
9237 struct inode *inode;
9238 struct btrfs_delalloc_work *work, *next;
9239 struct list_head works;
9240 struct list_head splice;
9242 bool full_flush = wbc->nr_to_write == LONG_MAX;
9244 INIT_LIST_HEAD(&works);
9245 INIT_LIST_HEAD(&splice);
9247 mutex_lock(&root->delalloc_mutex);
9248 spin_lock(&root->delalloc_lock);
9249 list_splice_init(&root->delalloc_inodes, &splice);
9250 while (!list_empty(&splice)) {
9251 binode = list_entry(splice.next, struct btrfs_inode,
9254 list_move_tail(&binode->delalloc_inodes,
9255 &root->delalloc_inodes);
9257 if (in_reclaim_context &&
9258 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9261 inode = igrab(&binode->vfs_inode);
9263 cond_resched_lock(&root->delalloc_lock);
9266 spin_unlock(&root->delalloc_lock);
9269 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9270 &binode->runtime_flags);
9272 work = btrfs_alloc_delalloc_work(inode);
9278 list_add_tail(&work->list, &works);
9279 btrfs_queue_work(root->fs_info->flush_workers,
9282 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9283 btrfs_add_delayed_iput(BTRFS_I(inode));
9284 if (ret || wbc->nr_to_write <= 0)
9288 spin_lock(&root->delalloc_lock);
9290 spin_unlock(&root->delalloc_lock);
9293 list_for_each_entry_safe(work, next, &works, list) {
9294 list_del_init(&work->list);
9295 wait_for_completion(&work->completion);
9299 if (!list_empty(&splice)) {
9300 spin_lock(&root->delalloc_lock);
9301 list_splice_tail(&splice, &root->delalloc_inodes);
9302 spin_unlock(&root->delalloc_lock);
9304 mutex_unlock(&root->delalloc_mutex);
9308 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9310 struct writeback_control wbc = {
9311 .nr_to_write = LONG_MAX,
9312 .sync_mode = WB_SYNC_NONE,
9314 .range_end = LLONG_MAX,
9316 struct btrfs_fs_info *fs_info = root->fs_info;
9318 if (BTRFS_FS_ERROR(fs_info))
9321 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9324 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9325 bool in_reclaim_context)
9327 struct writeback_control wbc = {
9329 .sync_mode = WB_SYNC_NONE,
9331 .range_end = LLONG_MAX,
9333 struct btrfs_root *root;
9334 struct list_head splice;
9337 if (BTRFS_FS_ERROR(fs_info))
9340 INIT_LIST_HEAD(&splice);
9342 mutex_lock(&fs_info->delalloc_root_mutex);
9343 spin_lock(&fs_info->delalloc_root_lock);
9344 list_splice_init(&fs_info->delalloc_roots, &splice);
9345 while (!list_empty(&splice)) {
9347 * Reset nr_to_write here so we know that we're doing a full
9351 wbc.nr_to_write = LONG_MAX;
9353 root = list_first_entry(&splice, struct btrfs_root,
9355 root = btrfs_grab_root(root);
9357 list_move_tail(&root->delalloc_root,
9358 &fs_info->delalloc_roots);
9359 spin_unlock(&fs_info->delalloc_root_lock);
9361 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9362 btrfs_put_root(root);
9363 if (ret < 0 || wbc.nr_to_write <= 0)
9365 spin_lock(&fs_info->delalloc_root_lock);
9367 spin_unlock(&fs_info->delalloc_root_lock);
9371 if (!list_empty(&splice)) {
9372 spin_lock(&fs_info->delalloc_root_lock);
9373 list_splice_tail(&splice, &fs_info->delalloc_roots);
9374 spin_unlock(&fs_info->delalloc_root_lock);
9376 mutex_unlock(&fs_info->delalloc_root_mutex);
9380 static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
9381 struct dentry *dentry, const char *symname)
9383 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9384 struct btrfs_trans_handle *trans;
9385 struct btrfs_root *root = BTRFS_I(dir)->root;
9386 struct btrfs_path *path;
9387 struct btrfs_key key;
9388 struct inode *inode;
9389 struct btrfs_new_inode_args new_inode_args = {
9393 unsigned int trans_num_items;
9398 struct btrfs_file_extent_item *ei;
9399 struct extent_buffer *leaf;
9401 name_len = strlen(symname);
9402 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9403 return -ENAMETOOLONG;
9405 inode = new_inode(dir->i_sb);
9408 inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
9409 inode->i_op = &btrfs_symlink_inode_operations;
9410 inode_nohighmem(inode);
9411 inode->i_mapping->a_ops = &btrfs_aops;
9412 btrfs_i_size_write(BTRFS_I(inode), name_len);
9413 inode_set_bytes(inode, name_len);
9415 new_inode_args.inode = inode;
9416 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9419 /* 1 additional item for the inline extent */
9422 trans = btrfs_start_transaction(root, trans_num_items);
9423 if (IS_ERR(trans)) {
9424 err = PTR_ERR(trans);
9425 goto out_new_inode_args;
9428 err = btrfs_create_new_inode(trans, &new_inode_args);
9432 path = btrfs_alloc_path();
9435 btrfs_abort_transaction(trans, err);
9436 discard_new_inode(inode);
9440 key.objectid = btrfs_ino(BTRFS_I(inode));
9442 key.type = BTRFS_EXTENT_DATA_KEY;
9443 datasize = btrfs_file_extent_calc_inline_size(name_len);
9444 err = btrfs_insert_empty_item(trans, root, path, &key,
9447 btrfs_abort_transaction(trans, err);
9448 btrfs_free_path(path);
9449 discard_new_inode(inode);
9453 leaf = path->nodes[0];
9454 ei = btrfs_item_ptr(leaf, path->slots[0],
9455 struct btrfs_file_extent_item);
9456 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9457 btrfs_set_file_extent_type(leaf, ei,
9458 BTRFS_FILE_EXTENT_INLINE);
9459 btrfs_set_file_extent_encryption(leaf, ei, 0);
9460 btrfs_set_file_extent_compression(leaf, ei, 0);
9461 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9462 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9464 ptr = btrfs_file_extent_inline_start(ei);
9465 write_extent_buffer(leaf, symname, ptr, name_len);
9466 btrfs_mark_buffer_dirty(leaf);
9467 btrfs_free_path(path);
9469 d_instantiate_new(dentry, inode);
9472 btrfs_end_transaction(trans);
9473 btrfs_btree_balance_dirty(fs_info);
9475 btrfs_new_inode_args_destroy(&new_inode_args);
9482 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9483 struct btrfs_trans_handle *trans_in,
9484 struct btrfs_inode *inode,
9485 struct btrfs_key *ins,
9488 struct btrfs_file_extent_item stack_fi;
9489 struct btrfs_replace_extent_info extent_info;
9490 struct btrfs_trans_handle *trans = trans_in;
9491 struct btrfs_path *path;
9492 u64 start = ins->objectid;
9493 u64 len = ins->offset;
9494 int qgroup_released;
9497 memset(&stack_fi, 0, sizeof(stack_fi));
9499 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9500 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9501 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9502 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9503 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9504 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9505 /* Encryption and other encoding is reserved and all 0 */
9507 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9508 if (qgroup_released < 0)
9509 return ERR_PTR(qgroup_released);
9512 ret = insert_reserved_file_extent(trans, inode,
9513 file_offset, &stack_fi,
9514 true, qgroup_released);
9520 extent_info.disk_offset = start;
9521 extent_info.disk_len = len;
9522 extent_info.data_offset = 0;
9523 extent_info.data_len = len;
9524 extent_info.file_offset = file_offset;
9525 extent_info.extent_buf = (char *)&stack_fi;
9526 extent_info.is_new_extent = true;
9527 extent_info.update_times = true;
9528 extent_info.qgroup_reserved = qgroup_released;
9529 extent_info.insertions = 0;
9531 path = btrfs_alloc_path();
9537 ret = btrfs_replace_file_extents(inode, path, file_offset,
9538 file_offset + len - 1, &extent_info,
9540 btrfs_free_path(path);
9547 * We have released qgroup data range at the beginning of the function,
9548 * and normally qgroup_released bytes will be freed when committing
9550 * But if we error out early, we have to free what we have released
9551 * or we leak qgroup data reservation.
9553 btrfs_qgroup_free_refroot(inode->root->fs_info,
9554 inode->root->root_key.objectid, qgroup_released,
9555 BTRFS_QGROUP_RSV_DATA);
9556 return ERR_PTR(ret);
9559 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9560 u64 start, u64 num_bytes, u64 min_size,
9561 loff_t actual_len, u64 *alloc_hint,
9562 struct btrfs_trans_handle *trans)
9564 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9565 struct extent_map *em;
9566 struct btrfs_root *root = BTRFS_I(inode)->root;
9567 struct btrfs_key ins;
9568 u64 cur_offset = start;
9569 u64 clear_offset = start;
9572 u64 last_alloc = (u64)-1;
9574 bool own_trans = true;
9575 u64 end = start + num_bytes - 1;
9579 while (num_bytes > 0) {
9580 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9581 cur_bytes = max(cur_bytes, min_size);
9583 * If we are severely fragmented we could end up with really
9584 * small allocations, so if the allocator is returning small
9585 * chunks lets make its job easier by only searching for those
9588 cur_bytes = min(cur_bytes, last_alloc);
9589 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9590 min_size, 0, *alloc_hint, &ins, 1, 0);
9595 * We've reserved this space, and thus converted it from
9596 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9597 * from here on out we will only need to clear our reservation
9598 * for the remaining unreserved area, so advance our
9599 * clear_offset by our extent size.
9601 clear_offset += ins.offset;
9603 last_alloc = ins.offset;
9604 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9607 * Now that we inserted the prealloc extent we can finally
9608 * decrement the number of reservations in the block group.
9609 * If we did it before, we could race with relocation and have
9610 * relocation miss the reserved extent, making it fail later.
9612 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9613 if (IS_ERR(trans)) {
9614 ret = PTR_ERR(trans);
9615 btrfs_free_reserved_extent(fs_info, ins.objectid,
9620 em = alloc_extent_map();
9622 btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9623 cur_offset + ins.offset - 1, false);
9624 btrfs_set_inode_full_sync(BTRFS_I(inode));
9628 em->start = cur_offset;
9629 em->orig_start = cur_offset;
9630 em->len = ins.offset;
9631 em->block_start = ins.objectid;
9632 em->block_len = ins.offset;
9633 em->orig_block_len = ins.offset;
9634 em->ram_bytes = ins.offset;
9635 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9636 em->generation = trans->transid;
9638 ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9639 free_extent_map(em);
9641 num_bytes -= ins.offset;
9642 cur_offset += ins.offset;
9643 *alloc_hint = ins.objectid + ins.offset;
9645 inode_inc_iversion(inode);
9646 inode->i_ctime = current_time(inode);
9647 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9648 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9649 (actual_len > inode->i_size) &&
9650 (cur_offset > inode->i_size)) {
9651 if (cur_offset > actual_len)
9652 i_size = actual_len;
9654 i_size = cur_offset;
9655 i_size_write(inode, i_size);
9656 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9659 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9662 btrfs_abort_transaction(trans, ret);
9664 btrfs_end_transaction(trans);
9669 btrfs_end_transaction(trans);
9673 if (clear_offset < end)
9674 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9675 end - clear_offset + 1);
9679 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9680 u64 start, u64 num_bytes, u64 min_size,
9681 loff_t actual_len, u64 *alloc_hint)
9683 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9684 min_size, actual_len, alloc_hint,
9688 int btrfs_prealloc_file_range_trans(struct inode *inode,
9689 struct btrfs_trans_handle *trans, int mode,
9690 u64 start, u64 num_bytes, u64 min_size,
9691 loff_t actual_len, u64 *alloc_hint)
9693 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9694 min_size, actual_len, alloc_hint, trans);
9697 static int btrfs_permission(struct mnt_idmap *idmap,
9698 struct inode *inode, int mask)
9700 struct btrfs_root *root = BTRFS_I(inode)->root;
9701 umode_t mode = inode->i_mode;
9703 if (mask & MAY_WRITE &&
9704 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9705 if (btrfs_root_readonly(root))
9707 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9710 return generic_permission(idmap, inode, mask);
9713 static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
9714 struct file *file, umode_t mode)
9716 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9717 struct btrfs_trans_handle *trans;
9718 struct btrfs_root *root = BTRFS_I(dir)->root;
9719 struct inode *inode;
9720 struct btrfs_new_inode_args new_inode_args = {
9722 .dentry = file->f_path.dentry,
9725 unsigned int trans_num_items;
9728 inode = new_inode(dir->i_sb);
9731 inode_init_owner(idmap, inode, dir, mode);
9732 inode->i_fop = &btrfs_file_operations;
9733 inode->i_op = &btrfs_file_inode_operations;
9734 inode->i_mapping->a_ops = &btrfs_aops;
9736 new_inode_args.inode = inode;
9737 ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9741 trans = btrfs_start_transaction(root, trans_num_items);
9742 if (IS_ERR(trans)) {
9743 ret = PTR_ERR(trans);
9744 goto out_new_inode_args;
9747 ret = btrfs_create_new_inode(trans, &new_inode_args);
9750 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9751 * set it to 1 because d_tmpfile() will issue a warning if the count is
9754 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9756 set_nlink(inode, 1);
9759 d_tmpfile(file, inode);
9760 unlock_new_inode(inode);
9761 mark_inode_dirty(inode);
9764 btrfs_end_transaction(trans);
9765 btrfs_btree_balance_dirty(fs_info);
9767 btrfs_new_inode_args_destroy(&new_inode_args);
9771 return finish_open_simple(file, ret);
9774 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
9776 struct btrfs_fs_info *fs_info = inode->root->fs_info;
9777 unsigned long index = start >> PAGE_SHIFT;
9778 unsigned long end_index = end >> PAGE_SHIFT;
9782 ASSERT(end + 1 - start <= U32_MAX);
9783 len = end + 1 - start;
9784 while (index <= end_index) {
9785 page = find_get_page(inode->vfs_inode.i_mapping, index);
9786 ASSERT(page); /* Pages should be in the extent_io_tree */
9788 btrfs_page_set_writeback(fs_info, page, start, len);
9794 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
9797 switch (compress_type) {
9798 case BTRFS_COMPRESS_NONE:
9799 return BTRFS_ENCODED_IO_COMPRESSION_NONE;
9800 case BTRFS_COMPRESS_ZLIB:
9801 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
9802 case BTRFS_COMPRESS_LZO:
9804 * The LZO format depends on the sector size. 64K is the maximum
9805 * sector size that we support.
9807 if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
9809 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
9810 (fs_info->sectorsize_bits - 12);
9811 case BTRFS_COMPRESS_ZSTD:
9812 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
9818 static ssize_t btrfs_encoded_read_inline(
9820 struct iov_iter *iter, u64 start,
9822 struct extent_state **cached_state,
9823 u64 extent_start, size_t count,
9824 struct btrfs_ioctl_encoded_io_args *encoded,
9827 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9828 struct btrfs_root *root = inode->root;
9829 struct btrfs_fs_info *fs_info = root->fs_info;
9830 struct extent_io_tree *io_tree = &inode->io_tree;
9831 struct btrfs_path *path;
9832 struct extent_buffer *leaf;
9833 struct btrfs_file_extent_item *item;
9839 path = btrfs_alloc_path();
9844 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
9848 /* The extent item disappeared? */
9853 leaf = path->nodes[0];
9854 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
9856 ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
9857 ptr = btrfs_file_extent_inline_start(item);
9859 encoded->len = min_t(u64, extent_start + ram_bytes,
9860 inode->vfs_inode.i_size) - iocb->ki_pos;
9861 ret = btrfs_encoded_io_compression_from_extent(fs_info,
9862 btrfs_file_extent_compression(leaf, item));
9865 encoded->compression = ret;
9866 if (encoded->compression) {
9869 inline_size = btrfs_file_extent_inline_item_len(leaf,
9871 if (inline_size > count) {
9875 count = inline_size;
9876 encoded->unencoded_len = ram_bytes;
9877 encoded->unencoded_offset = iocb->ki_pos - extent_start;
9879 count = min_t(u64, count, encoded->len);
9880 encoded->len = count;
9881 encoded->unencoded_len = count;
9882 ptr += iocb->ki_pos - extent_start;
9885 tmp = kmalloc(count, GFP_NOFS);
9890 read_extent_buffer(leaf, tmp, ptr, count);
9891 btrfs_release_path(path);
9892 unlock_extent(io_tree, start, lockend, cached_state);
9893 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9896 ret = copy_to_iter(tmp, count, iter);
9901 btrfs_free_path(path);
9905 struct btrfs_encoded_read_private {
9906 struct btrfs_inode *inode;
9908 wait_queue_head_t wait;
9910 blk_status_t status;
9913 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
9915 struct btrfs_encoded_read_private *priv = bbio->private;
9917 if (bbio->bio.bi_status) {
9919 * The memory barrier implied by the atomic_dec_return() here
9920 * pairs with the memory barrier implied by the
9921 * atomic_dec_return() or io_wait_event() in
9922 * btrfs_encoded_read_regular_fill_pages() to ensure that this
9923 * write is observed before the load of status in
9924 * btrfs_encoded_read_regular_fill_pages().
9926 WRITE_ONCE(priv->status, bbio->bio.bi_status);
9928 if (!atomic_dec_return(&priv->pending))
9929 wake_up(&priv->wait);
9930 bio_put(&bbio->bio);
9933 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
9934 u64 file_offset, u64 disk_bytenr,
9935 u64 disk_io_size, struct page **pages)
9937 struct btrfs_encoded_read_private priv = {
9939 .file_offset = file_offset,
9940 .pending = ATOMIC_INIT(1),
9942 unsigned long i = 0;
9945 init_waitqueue_head(&priv.wait);
9946 /* Submit bios for the extent, splitting due to bio limits as necessary. */
9947 while (cur < disk_io_size) {
9948 struct bio *bio = NULL;
9949 u64 remaining = disk_io_size - cur;
9951 while (bio || remaining) {
9952 size_t bytes = min_t(u64, remaining, PAGE_SIZE);
9955 bio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ,
9957 btrfs_encoded_read_endio,
9959 bio->bi_iter.bi_sector =
9960 (disk_bytenr + cur) >> SECTOR_SHIFT;
9964 bio_add_page(bio, pages[i], bytes, 0) < bytes) {
9965 atomic_inc(&priv.pending);
9966 btrfs_submit_bio(bio, 0);
9977 if (atomic_dec_return(&priv.pending))
9978 io_wait_event(priv.wait, !atomic_read(&priv.pending));
9979 /* See btrfs_encoded_read_endio() for ordering. */
9980 return blk_status_to_errno(READ_ONCE(priv.status));
9983 static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
9984 struct iov_iter *iter,
9985 u64 start, u64 lockend,
9986 struct extent_state **cached_state,
9987 u64 disk_bytenr, u64 disk_io_size,
9988 size_t count, bool compressed,
9991 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9992 struct extent_io_tree *io_tree = &inode->io_tree;
9993 struct page **pages;
9994 unsigned long nr_pages, i;
9999 nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
10000 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
10003 ret = btrfs_alloc_page_array(nr_pages, pages);
10009 ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
10010 disk_io_size, pages);
10014 unlock_extent(io_tree, start, lockend, cached_state);
10015 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10022 i = (iocb->ki_pos - start) >> PAGE_SHIFT;
10023 page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
10026 while (cur < count) {
10027 size_t bytes = min_t(size_t, count - cur,
10028 PAGE_SIZE - page_offset);
10030 if (copy_page_to_iter(pages[i], page_offset, bytes,
10041 for (i = 0; i < nr_pages; i++) {
10043 __free_page(pages[i]);
10049 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
10050 struct btrfs_ioctl_encoded_io_args *encoded)
10052 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10053 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10054 struct extent_io_tree *io_tree = &inode->io_tree;
10056 size_t count = iov_iter_count(iter);
10057 u64 start, lockend, disk_bytenr, disk_io_size;
10058 struct extent_state *cached_state = NULL;
10059 struct extent_map *em;
10060 bool unlocked = false;
10062 file_accessed(iocb->ki_filp);
10064 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
10066 if (iocb->ki_pos >= inode->vfs_inode.i_size) {
10067 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10070 start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
10072 * We don't know how long the extent containing iocb->ki_pos is, but if
10073 * it's compressed we know that it won't be longer than this.
10075 lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
10078 struct btrfs_ordered_extent *ordered;
10080 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
10081 lockend - start + 1);
10083 goto out_unlock_inode;
10084 lock_extent(io_tree, start, lockend, &cached_state);
10085 ordered = btrfs_lookup_ordered_range(inode, start,
10086 lockend - start + 1);
10089 btrfs_put_ordered_extent(ordered);
10090 unlock_extent(io_tree, start, lockend, &cached_state);
10094 em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
10097 goto out_unlock_extent;
10100 if (em->block_start == EXTENT_MAP_INLINE) {
10101 u64 extent_start = em->start;
10104 * For inline extents we get everything we need out of the
10107 free_extent_map(em);
10109 ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
10110 &cached_state, extent_start,
10111 count, encoded, &unlocked);
10116 * We only want to return up to EOF even if the extent extends beyond
10119 encoded->len = min_t(u64, extent_map_end(em),
10120 inode->vfs_inode.i_size) - iocb->ki_pos;
10121 if (em->block_start == EXTENT_MAP_HOLE ||
10122 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
10123 disk_bytenr = EXTENT_MAP_HOLE;
10124 count = min_t(u64, count, encoded->len);
10125 encoded->len = count;
10126 encoded->unencoded_len = count;
10127 } else if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10128 disk_bytenr = em->block_start;
10130 * Bail if the buffer isn't large enough to return the whole
10131 * compressed extent.
10133 if (em->block_len > count) {
10137 disk_io_size = em->block_len;
10138 count = em->block_len;
10139 encoded->unencoded_len = em->ram_bytes;
10140 encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
10141 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10142 em->compress_type);
10145 encoded->compression = ret;
10147 disk_bytenr = em->block_start + (start - em->start);
10148 if (encoded->len > count)
10149 encoded->len = count;
10151 * Don't read beyond what we locked. This also limits the page
10152 * allocations that we'll do.
10154 disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
10155 count = start + disk_io_size - iocb->ki_pos;
10156 encoded->len = count;
10157 encoded->unencoded_len = count;
10158 disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
10160 free_extent_map(em);
10163 if (disk_bytenr == EXTENT_MAP_HOLE) {
10164 unlock_extent(io_tree, start, lockend, &cached_state);
10165 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10167 ret = iov_iter_zero(count, iter);
10171 ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
10172 &cached_state, disk_bytenr,
10173 disk_io_size, count,
10174 encoded->compression,
10180 iocb->ki_pos += encoded->len;
10182 free_extent_map(em);
10185 unlock_extent(io_tree, start, lockend, &cached_state);
10188 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10192 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
10193 const struct btrfs_ioctl_encoded_io_args *encoded)
10195 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10196 struct btrfs_root *root = inode->root;
10197 struct btrfs_fs_info *fs_info = root->fs_info;
10198 struct extent_io_tree *io_tree = &inode->io_tree;
10199 struct extent_changeset *data_reserved = NULL;
10200 struct extent_state *cached_state = NULL;
10204 u64 num_bytes, ram_bytes, disk_num_bytes;
10205 unsigned long nr_pages, i;
10206 struct page **pages;
10207 struct btrfs_key ins;
10208 bool extent_reserved = false;
10209 struct extent_map *em;
10212 switch (encoded->compression) {
10213 case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
10214 compression = BTRFS_COMPRESS_ZLIB;
10216 case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
10217 compression = BTRFS_COMPRESS_ZSTD;
10219 case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
10220 case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
10221 case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
10222 case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
10223 case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
10224 /* The sector size must match for LZO. */
10225 if (encoded->compression -
10226 BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
10227 fs_info->sectorsize_bits)
10229 compression = BTRFS_COMPRESS_LZO;
10234 if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
10237 orig_count = iov_iter_count(from);
10239 /* The extent size must be sane. */
10240 if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
10241 orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
10245 * The compressed data must be smaller than the decompressed data.
10247 * It's of course possible for data to compress to larger or the same
10248 * size, but the buffered I/O path falls back to no compression for such
10249 * data, and we don't want to break any assumptions by creating these
10252 * Note that this is less strict than the current check we have that the
10253 * compressed data must be at least one sector smaller than the
10254 * decompressed data. We only want to enforce the weaker requirement
10255 * from old kernels that it is at least one byte smaller.
10257 if (orig_count >= encoded->unencoded_len)
10260 /* The extent must start on a sector boundary. */
10261 start = iocb->ki_pos;
10262 if (!IS_ALIGNED(start, fs_info->sectorsize))
10266 * The extent must end on a sector boundary. However, we allow a write
10267 * which ends at or extends i_size to have an unaligned length; we round
10268 * up the extent size and set i_size to the unaligned end.
10270 if (start + encoded->len < inode->vfs_inode.i_size &&
10271 !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
10274 /* Finally, the offset in the unencoded data must be sector-aligned. */
10275 if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
10278 num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10279 ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10280 end = start + num_bytes - 1;
10283 * If the extent cannot be inline, the compressed data on disk must be
10284 * sector-aligned. For convenience, we extend it with zeroes if it
10287 disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10288 nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
10289 pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
10292 for (i = 0; i < nr_pages; i++) {
10293 size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
10296 pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
10301 kaddr = kmap_local_page(pages[i]);
10302 if (copy_from_iter(kaddr, bytes, from) != bytes) {
10303 kunmap_local(kaddr);
10307 if (bytes < PAGE_SIZE)
10308 memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
10309 kunmap_local(kaddr);
10313 struct btrfs_ordered_extent *ordered;
10315 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
10318 ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10319 start >> PAGE_SHIFT,
10320 end >> PAGE_SHIFT);
10323 lock_extent(io_tree, start, end, &cached_state);
10324 ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10326 !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10329 btrfs_put_ordered_extent(ordered);
10330 unlock_extent(io_tree, start, end, &cached_state);
10335 * We don't use the higher-level delalloc space functions because our
10336 * num_bytes and disk_num_bytes are different.
10338 ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10341 ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10343 goto out_free_data_space;
10344 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10347 goto out_qgroup_free_data;
10349 /* Try an inline extent first. */
10350 if (start == 0 && encoded->unencoded_len == encoded->len &&
10351 encoded->unencoded_offset == 0) {
10352 ret = cow_file_range_inline(inode, encoded->len, orig_count,
10353 compression, pages, true);
10357 goto out_delalloc_release;
10361 ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10362 disk_num_bytes, 0, 0, &ins, 1, 1);
10364 goto out_delalloc_release;
10365 extent_reserved = true;
10367 em = create_io_em(inode, start, num_bytes,
10368 start - encoded->unencoded_offset, ins.objectid,
10369 ins.offset, ins.offset, ram_bytes, compression,
10370 BTRFS_ORDERED_COMPRESSED);
10373 goto out_free_reserved;
10375 free_extent_map(em);
10377 ret = btrfs_add_ordered_extent(inode, start, num_bytes, ram_bytes,
10378 ins.objectid, ins.offset,
10379 encoded->unencoded_offset,
10380 (1 << BTRFS_ORDERED_ENCODED) |
10381 (1 << BTRFS_ORDERED_COMPRESSED),
10384 btrfs_drop_extent_map_range(inode, start, end, false);
10385 goto out_free_reserved;
10387 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10389 if (start + encoded->len > inode->vfs_inode.i_size)
10390 i_size_write(&inode->vfs_inode, start + encoded->len);
10392 unlock_extent(io_tree, start, end, &cached_state);
10394 btrfs_delalloc_release_extents(inode, num_bytes);
10396 if (btrfs_submit_compressed_write(inode, start, num_bytes, ins.objectid,
10397 ins.offset, pages, nr_pages, 0, NULL,
10399 btrfs_writepage_endio_finish_ordered(inode, pages[0], start, end, 0);
10407 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10408 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
10409 out_delalloc_release:
10410 btrfs_delalloc_release_extents(inode, num_bytes);
10411 btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10412 out_qgroup_free_data:
10414 btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes);
10415 out_free_data_space:
10417 * If btrfs_reserve_extent() succeeded, then we already decremented
10420 if (!extent_reserved)
10421 btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
10423 unlock_extent(io_tree, start, end, &cached_state);
10425 for (i = 0; i < nr_pages; i++) {
10427 __free_page(pages[i]);
10432 iocb->ki_pos += encoded->len;
10438 * Add an entry indicating a block group or device which is pinned by a
10439 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10440 * negative errno on failure.
10442 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10443 bool is_block_group)
10445 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10446 struct btrfs_swapfile_pin *sp, *entry;
10447 struct rb_node **p;
10448 struct rb_node *parent = NULL;
10450 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10455 sp->is_block_group = is_block_group;
10456 sp->bg_extent_count = 1;
10458 spin_lock(&fs_info->swapfile_pins_lock);
10459 p = &fs_info->swapfile_pins.rb_node;
10462 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10463 if (sp->ptr < entry->ptr ||
10464 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10465 p = &(*p)->rb_left;
10466 } else if (sp->ptr > entry->ptr ||
10467 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10468 p = &(*p)->rb_right;
10470 if (is_block_group)
10471 entry->bg_extent_count++;
10472 spin_unlock(&fs_info->swapfile_pins_lock);
10477 rb_link_node(&sp->node, parent, p);
10478 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10479 spin_unlock(&fs_info->swapfile_pins_lock);
10483 /* Free all of the entries pinned by this swapfile. */
10484 static void btrfs_free_swapfile_pins(struct inode *inode)
10486 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10487 struct btrfs_swapfile_pin *sp;
10488 struct rb_node *node, *next;
10490 spin_lock(&fs_info->swapfile_pins_lock);
10491 node = rb_first(&fs_info->swapfile_pins);
10493 next = rb_next(node);
10494 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10495 if (sp->inode == inode) {
10496 rb_erase(&sp->node, &fs_info->swapfile_pins);
10497 if (sp->is_block_group) {
10498 btrfs_dec_block_group_swap_extents(sp->ptr,
10499 sp->bg_extent_count);
10500 btrfs_put_block_group(sp->ptr);
10506 spin_unlock(&fs_info->swapfile_pins_lock);
10509 struct btrfs_swap_info {
10515 unsigned long nr_pages;
10519 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10520 struct btrfs_swap_info *bsi)
10522 unsigned long nr_pages;
10523 unsigned long max_pages;
10524 u64 first_ppage, first_ppage_reported, next_ppage;
10528 * Our swapfile may have had its size extended after the swap header was
10529 * written. In that case activating the swapfile should not go beyond
10530 * the max size set in the swap header.
10532 if (bsi->nr_pages >= sis->max)
10535 max_pages = sis->max - bsi->nr_pages;
10536 first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
10537 next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
10539 if (first_ppage >= next_ppage)
10541 nr_pages = next_ppage - first_ppage;
10542 nr_pages = min(nr_pages, max_pages);
10544 first_ppage_reported = first_ppage;
10545 if (bsi->start == 0)
10546 first_ppage_reported++;
10547 if (bsi->lowest_ppage > first_ppage_reported)
10548 bsi->lowest_ppage = first_ppage_reported;
10549 if (bsi->highest_ppage < (next_ppage - 1))
10550 bsi->highest_ppage = next_ppage - 1;
10552 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10555 bsi->nr_extents += ret;
10556 bsi->nr_pages += nr_pages;
10560 static void btrfs_swap_deactivate(struct file *file)
10562 struct inode *inode = file_inode(file);
10564 btrfs_free_swapfile_pins(inode);
10565 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10568 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10571 struct inode *inode = file_inode(file);
10572 struct btrfs_root *root = BTRFS_I(inode)->root;
10573 struct btrfs_fs_info *fs_info = root->fs_info;
10574 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10575 struct extent_state *cached_state = NULL;
10576 struct extent_map *em = NULL;
10577 struct btrfs_device *device = NULL;
10578 struct btrfs_swap_info bsi = {
10579 .lowest_ppage = (sector_t)-1ULL,
10586 * If the swap file was just created, make sure delalloc is done. If the
10587 * file changes again after this, the user is doing something stupid and
10588 * we don't really care.
10590 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10595 * The inode is locked, so these flags won't change after we check them.
10597 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10598 btrfs_warn(fs_info, "swapfile must not be compressed");
10601 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10602 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10605 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10606 btrfs_warn(fs_info, "swapfile must not be checksummed");
10611 * Balance or device remove/replace/resize can move stuff around from
10612 * under us. The exclop protection makes sure they aren't running/won't
10613 * run concurrently while we are mapping the swap extents, and
10614 * fs_info->swapfile_pins prevents them from running while the swap
10615 * file is active and moving the extents. Note that this also prevents
10616 * a concurrent device add which isn't actually necessary, but it's not
10617 * really worth the trouble to allow it.
10619 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10620 btrfs_warn(fs_info,
10621 "cannot activate swapfile while exclusive operation is running");
10626 * Prevent snapshot creation while we are activating the swap file.
10627 * We do not want to race with snapshot creation. If snapshot creation
10628 * already started before we bumped nr_swapfiles from 0 to 1 and
10629 * completes before the first write into the swap file after it is
10630 * activated, than that write would fallback to COW.
10632 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10633 btrfs_exclop_finish(fs_info);
10634 btrfs_warn(fs_info,
10635 "cannot activate swapfile because snapshot creation is in progress");
10639 * Snapshots can create extents which require COW even if NODATACOW is
10640 * set. We use this counter to prevent snapshots. We must increment it
10641 * before walking the extents because we don't want a concurrent
10642 * snapshot to run after we've already checked the extents.
10644 * It is possible that subvolume is marked for deletion but still not
10645 * removed yet. To prevent this race, we check the root status before
10646 * activating the swapfile.
10648 spin_lock(&root->root_item_lock);
10649 if (btrfs_root_dead(root)) {
10650 spin_unlock(&root->root_item_lock);
10652 btrfs_exclop_finish(fs_info);
10653 btrfs_warn(fs_info,
10654 "cannot activate swapfile because subvolume %llu is being deleted",
10655 root->root_key.objectid);
10658 atomic_inc(&root->nr_swapfiles);
10659 spin_unlock(&root->root_item_lock);
10661 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10663 lock_extent(io_tree, 0, isize - 1, &cached_state);
10665 while (start < isize) {
10666 u64 logical_block_start, physical_block_start;
10667 struct btrfs_block_group *bg;
10668 u64 len = isize - start;
10670 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10676 if (em->block_start == EXTENT_MAP_HOLE) {
10677 btrfs_warn(fs_info, "swapfile must not have holes");
10681 if (em->block_start == EXTENT_MAP_INLINE) {
10683 * It's unlikely we'll ever actually find ourselves
10684 * here, as a file small enough to fit inline won't be
10685 * big enough to store more than the swap header, but in
10686 * case something changes in the future, let's catch it
10687 * here rather than later.
10689 btrfs_warn(fs_info, "swapfile must not be inline");
10693 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10694 btrfs_warn(fs_info, "swapfile must not be compressed");
10699 logical_block_start = em->block_start + (start - em->start);
10700 len = min(len, em->len - (start - em->start));
10701 free_extent_map(em);
10704 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, false, true);
10710 btrfs_warn(fs_info,
10711 "swapfile must not be copy-on-write");
10716 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10722 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10723 btrfs_warn(fs_info,
10724 "swapfile must have single data profile");
10729 if (device == NULL) {
10730 device = em->map_lookup->stripes[0].dev;
10731 ret = btrfs_add_swapfile_pin(inode, device, false);
10736 } else if (device != em->map_lookup->stripes[0].dev) {
10737 btrfs_warn(fs_info, "swapfile must be on one device");
10742 physical_block_start = (em->map_lookup->stripes[0].physical +
10743 (logical_block_start - em->start));
10744 len = min(len, em->len - (logical_block_start - em->start));
10745 free_extent_map(em);
10748 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10750 btrfs_warn(fs_info,
10751 "could not find block group containing swapfile");
10756 if (!btrfs_inc_block_group_swap_extents(bg)) {
10757 btrfs_warn(fs_info,
10758 "block group for swapfile at %llu is read-only%s",
10760 atomic_read(&fs_info->scrubs_running) ?
10761 " (scrub running)" : "");
10762 btrfs_put_block_group(bg);
10767 ret = btrfs_add_swapfile_pin(inode, bg, true);
10769 btrfs_put_block_group(bg);
10776 if (bsi.block_len &&
10777 bsi.block_start + bsi.block_len == physical_block_start) {
10778 bsi.block_len += len;
10780 if (bsi.block_len) {
10781 ret = btrfs_add_swap_extent(sis, &bsi);
10786 bsi.block_start = physical_block_start;
10787 bsi.block_len = len;
10794 ret = btrfs_add_swap_extent(sis, &bsi);
10797 if (!IS_ERR_OR_NULL(em))
10798 free_extent_map(em);
10800 unlock_extent(io_tree, 0, isize - 1, &cached_state);
10803 btrfs_swap_deactivate(file);
10805 btrfs_drew_write_unlock(&root->snapshot_lock);
10807 btrfs_exclop_finish(fs_info);
10813 sis->bdev = device->bdev;
10814 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10815 sis->max = bsi.nr_pages;
10816 sis->pages = bsi.nr_pages - 1;
10817 sis->highest_bit = bsi.nr_pages - 1;
10818 return bsi.nr_extents;
10821 static void btrfs_swap_deactivate(struct file *file)
10825 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10828 return -EOPNOTSUPP;
10833 * Update the number of bytes used in the VFS' inode. When we replace extents in
10834 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10835 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10836 * always get a correct value.
10838 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10839 const u64 add_bytes,
10840 const u64 del_bytes)
10842 if (add_bytes == del_bytes)
10845 spin_lock(&inode->lock);
10847 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10849 inode_add_bytes(&inode->vfs_inode, add_bytes);
10850 spin_unlock(&inode->lock);
10854 * Verify that there are no ordered extents for a given file range.
10856 * @inode: The target inode.
10857 * @start: Start offset of the file range, should be sector size aligned.
10858 * @end: End offset (inclusive) of the file range, its value +1 should be
10859 * sector size aligned.
10861 * This should typically be used for cases where we locked an inode's VFS lock in
10862 * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
10863 * we have flushed all delalloc in the range, we have waited for all ordered
10864 * extents in the range to complete and finally we have locked the file range in
10865 * the inode's io_tree.
10867 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
10869 struct btrfs_root *root = inode->root;
10870 struct btrfs_ordered_extent *ordered;
10872 if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
10875 ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
10877 btrfs_err(root->fs_info,
10878 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
10879 start, end, btrfs_ino(inode), root->root_key.objectid,
10880 ordered->file_offset,
10881 ordered->file_offset + ordered->num_bytes - 1);
10882 btrfs_put_ordered_extent(ordered);
10885 ASSERT(ordered == NULL);
10888 static const struct inode_operations btrfs_dir_inode_operations = {
10889 .getattr = btrfs_getattr,
10890 .lookup = btrfs_lookup,
10891 .create = btrfs_create,
10892 .unlink = btrfs_unlink,
10893 .link = btrfs_link,
10894 .mkdir = btrfs_mkdir,
10895 .rmdir = btrfs_rmdir,
10896 .rename = btrfs_rename2,
10897 .symlink = btrfs_symlink,
10898 .setattr = btrfs_setattr,
10899 .mknod = btrfs_mknod,
10900 .listxattr = btrfs_listxattr,
10901 .permission = btrfs_permission,
10902 .get_inode_acl = btrfs_get_acl,
10903 .set_acl = btrfs_set_acl,
10904 .update_time = btrfs_update_time,
10905 .tmpfile = btrfs_tmpfile,
10906 .fileattr_get = btrfs_fileattr_get,
10907 .fileattr_set = btrfs_fileattr_set,
10910 static const struct file_operations btrfs_dir_file_operations = {
10911 .llseek = generic_file_llseek,
10912 .read = generic_read_dir,
10913 .iterate_shared = btrfs_real_readdir,
10914 .open = btrfs_opendir,
10915 .unlocked_ioctl = btrfs_ioctl,
10916 #ifdef CONFIG_COMPAT
10917 .compat_ioctl = btrfs_compat_ioctl,
10919 .release = btrfs_release_file,
10920 .fsync = btrfs_sync_file,
10924 * btrfs doesn't support the bmap operation because swapfiles
10925 * use bmap to make a mapping of extents in the file. They assume
10926 * these extents won't change over the life of the file and they
10927 * use the bmap result to do IO directly to the drive.
10929 * the btrfs bmap call would return logical addresses that aren't
10930 * suitable for IO and they also will change frequently as COW
10931 * operations happen. So, swapfile + btrfs == corruption.
10933 * For now we're avoiding this by dropping bmap.
10935 static const struct address_space_operations btrfs_aops = {
10936 .read_folio = btrfs_read_folio,
10937 .writepages = btrfs_writepages,
10938 .readahead = btrfs_readahead,
10939 .direct_IO = noop_direct_IO,
10940 .invalidate_folio = btrfs_invalidate_folio,
10941 .release_folio = btrfs_release_folio,
10942 .migrate_folio = btrfs_migrate_folio,
10943 .dirty_folio = filemap_dirty_folio,
10944 .error_remove_page = generic_error_remove_page,
10945 .swap_activate = btrfs_swap_activate,
10946 .swap_deactivate = btrfs_swap_deactivate,
10949 static const struct inode_operations btrfs_file_inode_operations = {
10950 .getattr = btrfs_getattr,
10951 .setattr = btrfs_setattr,
10952 .listxattr = btrfs_listxattr,
10953 .permission = btrfs_permission,
10954 .fiemap = btrfs_fiemap,
10955 .get_inode_acl = btrfs_get_acl,
10956 .set_acl = btrfs_set_acl,
10957 .update_time = btrfs_update_time,
10958 .fileattr_get = btrfs_fileattr_get,
10959 .fileattr_set = btrfs_fileattr_set,
10961 static const struct inode_operations btrfs_special_inode_operations = {
10962 .getattr = btrfs_getattr,
10963 .setattr = btrfs_setattr,
10964 .permission = btrfs_permission,
10965 .listxattr = btrfs_listxattr,
10966 .get_inode_acl = btrfs_get_acl,
10967 .set_acl = btrfs_set_acl,
10968 .update_time = btrfs_update_time,
10970 static const struct inode_operations btrfs_symlink_inode_operations = {
10971 .get_link = page_get_link,
10972 .getattr = btrfs_getattr,
10973 .setattr = btrfs_setattr,
10974 .permission = btrfs_permission,
10975 .listxattr = btrfs_listxattr,
10976 .update_time = btrfs_update_time,
10979 const struct dentry_operations btrfs_dentry_operations = {
10980 .d_delete = btrfs_dentry_delete,