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 * fscrypt_setup_filename() should never return a positive value, but
5428 * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
5432 /* This needs to handle no-key deletions later on */
5434 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
5435 &fname.disk_name, 0);
5436 if (IS_ERR_OR_NULL(di)) {
5437 ret = di ? PTR_ERR(di) : -ENOENT;
5441 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5442 if (location->type != BTRFS_INODE_ITEM_KEY &&
5443 location->type != BTRFS_ROOT_ITEM_KEY) {
5445 btrfs_warn(root->fs_info,
5446 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5447 __func__, fname.disk_name.name, btrfs_ino(dir),
5448 location->objectid, location->type, location->offset);
5451 *type = btrfs_dir_ftype(path->nodes[0], di);
5453 fscrypt_free_filename(&fname);
5454 btrfs_free_path(path);
5459 * when we hit a tree root in a directory, the btrfs part of the inode
5460 * needs to be changed to reflect the root directory of the tree root. This
5461 * is kind of like crossing a mount point.
5463 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5464 struct btrfs_inode *dir,
5465 struct dentry *dentry,
5466 struct btrfs_key *location,
5467 struct btrfs_root **sub_root)
5469 struct btrfs_path *path;
5470 struct btrfs_root *new_root;
5471 struct btrfs_root_ref *ref;
5472 struct extent_buffer *leaf;
5473 struct btrfs_key key;
5476 struct fscrypt_name fname;
5478 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
5482 path = btrfs_alloc_path();
5489 key.objectid = dir->root->root_key.objectid;
5490 key.type = BTRFS_ROOT_REF_KEY;
5491 key.offset = location->objectid;
5493 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5500 leaf = path->nodes[0];
5501 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5502 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5503 btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5506 ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5507 (unsigned long)(ref + 1), fname.disk_name.len);
5511 btrfs_release_path(path);
5513 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5514 if (IS_ERR(new_root)) {
5515 err = PTR_ERR(new_root);
5519 *sub_root = new_root;
5520 location->objectid = btrfs_root_dirid(&new_root->root_item);
5521 location->type = BTRFS_INODE_ITEM_KEY;
5522 location->offset = 0;
5525 btrfs_free_path(path);
5526 fscrypt_free_filename(&fname);
5530 static void inode_tree_add(struct btrfs_inode *inode)
5532 struct btrfs_root *root = inode->root;
5533 struct btrfs_inode *entry;
5535 struct rb_node *parent;
5536 struct rb_node *new = &inode->rb_node;
5537 u64 ino = btrfs_ino(inode);
5539 if (inode_unhashed(&inode->vfs_inode))
5542 spin_lock(&root->inode_lock);
5543 p = &root->inode_tree.rb_node;
5546 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5548 if (ino < btrfs_ino(entry))
5549 p = &parent->rb_left;
5550 else if (ino > btrfs_ino(entry))
5551 p = &parent->rb_right;
5553 WARN_ON(!(entry->vfs_inode.i_state &
5554 (I_WILL_FREE | I_FREEING)));
5555 rb_replace_node(parent, new, &root->inode_tree);
5556 RB_CLEAR_NODE(parent);
5557 spin_unlock(&root->inode_lock);
5561 rb_link_node(new, parent, p);
5562 rb_insert_color(new, &root->inode_tree);
5563 spin_unlock(&root->inode_lock);
5566 static void inode_tree_del(struct btrfs_inode *inode)
5568 struct btrfs_root *root = inode->root;
5571 spin_lock(&root->inode_lock);
5572 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5573 rb_erase(&inode->rb_node, &root->inode_tree);
5574 RB_CLEAR_NODE(&inode->rb_node);
5575 empty = RB_EMPTY_ROOT(&root->inode_tree);
5577 spin_unlock(&root->inode_lock);
5579 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5580 spin_lock(&root->inode_lock);
5581 empty = RB_EMPTY_ROOT(&root->inode_tree);
5582 spin_unlock(&root->inode_lock);
5584 btrfs_add_dead_root(root);
5589 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5591 struct btrfs_iget_args *args = p;
5593 inode->i_ino = args->ino;
5594 BTRFS_I(inode)->location.objectid = args->ino;
5595 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5596 BTRFS_I(inode)->location.offset = 0;
5597 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5598 BUG_ON(args->root && !BTRFS_I(inode)->root);
5600 if (args->root && args->root == args->root->fs_info->tree_root &&
5601 args->ino != BTRFS_BTREE_INODE_OBJECTID)
5602 set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5603 &BTRFS_I(inode)->runtime_flags);
5607 static int btrfs_find_actor(struct inode *inode, void *opaque)
5609 struct btrfs_iget_args *args = opaque;
5611 return args->ino == BTRFS_I(inode)->location.objectid &&
5612 args->root == BTRFS_I(inode)->root;
5615 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5616 struct btrfs_root *root)
5618 struct inode *inode;
5619 struct btrfs_iget_args args;
5620 unsigned long hashval = btrfs_inode_hash(ino, root);
5625 inode = iget5_locked(s, hashval, btrfs_find_actor,
5626 btrfs_init_locked_inode,
5632 * Get an inode object given its inode number and corresponding root.
5633 * Path can be preallocated to prevent recursing back to iget through
5634 * allocator. NULL is also valid but may require an additional allocation
5637 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5638 struct btrfs_root *root, struct btrfs_path *path)
5640 struct inode *inode;
5642 inode = btrfs_iget_locked(s, ino, root);
5644 return ERR_PTR(-ENOMEM);
5646 if (inode->i_state & I_NEW) {
5649 ret = btrfs_read_locked_inode(inode, path);
5651 inode_tree_add(BTRFS_I(inode));
5652 unlock_new_inode(inode);
5656 * ret > 0 can come from btrfs_search_slot called by
5657 * btrfs_read_locked_inode, this means the inode item
5662 inode = ERR_PTR(ret);
5669 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5671 return btrfs_iget_path(s, ino, root, NULL);
5674 static struct inode *new_simple_dir(struct super_block *s,
5675 struct btrfs_key *key,
5676 struct btrfs_root *root)
5678 struct inode *inode = new_inode(s);
5681 return ERR_PTR(-ENOMEM);
5683 BTRFS_I(inode)->root = btrfs_grab_root(root);
5684 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5685 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5687 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5689 * We only need lookup, the rest is read-only and there's no inode
5690 * associated with the dentry
5692 inode->i_op = &simple_dir_inode_operations;
5693 inode->i_opflags &= ~IOP_XATTR;
5694 inode->i_fop = &simple_dir_operations;
5695 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5696 inode->i_mtime = current_time(inode);
5697 inode->i_atime = inode->i_mtime;
5698 inode->i_ctime = inode->i_mtime;
5699 BTRFS_I(inode)->i_otime = inode->i_mtime;
5704 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5705 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5706 static_assert(BTRFS_FT_DIR == FT_DIR);
5707 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5708 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5709 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5710 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5711 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5713 static inline u8 btrfs_inode_type(struct inode *inode)
5715 return fs_umode_to_ftype(inode->i_mode);
5718 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5720 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5721 struct inode *inode;
5722 struct btrfs_root *root = BTRFS_I(dir)->root;
5723 struct btrfs_root *sub_root = root;
5724 struct btrfs_key location;
5728 if (dentry->d_name.len > BTRFS_NAME_LEN)
5729 return ERR_PTR(-ENAMETOOLONG);
5731 ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
5733 return ERR_PTR(ret);
5735 if (location.type == BTRFS_INODE_ITEM_KEY) {
5736 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5740 /* Do extra check against inode mode with di_type */
5741 if (btrfs_inode_type(inode) != di_type) {
5743 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5744 inode->i_mode, btrfs_inode_type(inode),
5747 return ERR_PTR(-EUCLEAN);
5752 ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
5753 &location, &sub_root);
5756 inode = ERR_PTR(ret);
5758 inode = new_simple_dir(dir->i_sb, &location, root);
5760 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5761 btrfs_put_root(sub_root);
5766 down_read(&fs_info->cleanup_work_sem);
5767 if (!sb_rdonly(inode->i_sb))
5768 ret = btrfs_orphan_cleanup(sub_root);
5769 up_read(&fs_info->cleanup_work_sem);
5772 inode = ERR_PTR(ret);
5779 static int btrfs_dentry_delete(const struct dentry *dentry)
5781 struct btrfs_root *root;
5782 struct inode *inode = d_inode(dentry);
5784 if (!inode && !IS_ROOT(dentry))
5785 inode = d_inode(dentry->d_parent);
5788 root = BTRFS_I(inode)->root;
5789 if (btrfs_root_refs(&root->root_item) == 0)
5792 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5798 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5801 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5803 if (inode == ERR_PTR(-ENOENT))
5805 return d_splice_alias(inode, dentry);
5809 * All this infrastructure exists because dir_emit can fault, and we are holding
5810 * the tree lock when doing readdir. For now just allocate a buffer and copy
5811 * our information into that, and then dir_emit from the buffer. This is
5812 * similar to what NFS does, only we don't keep the buffer around in pagecache
5813 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5814 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5817 static int btrfs_opendir(struct inode *inode, struct file *file)
5819 struct btrfs_file_private *private;
5821 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5824 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5825 if (!private->filldir_buf) {
5829 file->private_data = private;
5840 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5843 struct dir_entry *entry = addr;
5844 char *name = (char *)(entry + 1);
5846 ctx->pos = get_unaligned(&entry->offset);
5847 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5848 get_unaligned(&entry->ino),
5849 get_unaligned(&entry->type)))
5851 addr += sizeof(struct dir_entry) +
5852 get_unaligned(&entry->name_len);
5858 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5860 struct inode *inode = file_inode(file);
5861 struct btrfs_root *root = BTRFS_I(inode)->root;
5862 struct btrfs_file_private *private = file->private_data;
5863 struct btrfs_dir_item *di;
5864 struct btrfs_key key;
5865 struct btrfs_key found_key;
5866 struct btrfs_path *path;
5868 struct list_head ins_list;
5869 struct list_head del_list;
5876 struct btrfs_key location;
5878 if (!dir_emit_dots(file, ctx))
5881 path = btrfs_alloc_path();
5885 addr = private->filldir_buf;
5886 path->reada = READA_FORWARD;
5888 INIT_LIST_HEAD(&ins_list);
5889 INIT_LIST_HEAD(&del_list);
5890 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5893 key.type = BTRFS_DIR_INDEX_KEY;
5894 key.offset = ctx->pos;
5895 key.objectid = btrfs_ino(BTRFS_I(inode));
5897 btrfs_for_each_slot(root, &key, &found_key, path, ret) {
5898 struct dir_entry *entry;
5899 struct extent_buffer *leaf = path->nodes[0];
5902 if (found_key.objectid != key.objectid)
5904 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5906 if (found_key.offset < ctx->pos)
5908 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5910 di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
5911 name_len = btrfs_dir_name_len(leaf, di);
5912 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5914 btrfs_release_path(path);
5915 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5918 addr = private->filldir_buf;
5924 ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
5926 name_ptr = (char *)(entry + 1);
5927 read_extent_buffer(leaf, name_ptr,
5928 (unsigned long)(di + 1), name_len);
5929 put_unaligned(name_len, &entry->name_len);
5930 put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
5931 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5932 put_unaligned(location.objectid, &entry->ino);
5933 put_unaligned(found_key.offset, &entry->offset);
5935 addr += sizeof(struct dir_entry) + name_len;
5936 total_len += sizeof(struct dir_entry) + name_len;
5938 /* Catch error encountered during iteration */
5942 btrfs_release_path(path);
5944 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5948 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5953 * Stop new entries from being returned after we return the last
5956 * New directory entries are assigned a strictly increasing
5957 * offset. This means that new entries created during readdir
5958 * are *guaranteed* to be seen in the future by that readdir.
5959 * This has broken buggy programs which operate on names as
5960 * they're returned by readdir. Until we re-use freed offsets
5961 * we have this hack to stop new entries from being returned
5962 * under the assumption that they'll never reach this huge
5965 * This is being careful not to overflow 32bit loff_t unless the
5966 * last entry requires it because doing so has broken 32bit apps
5969 if (ctx->pos >= INT_MAX)
5970 ctx->pos = LLONG_MAX;
5977 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5978 btrfs_free_path(path);
5983 * This is somewhat expensive, updating the tree every time the
5984 * inode changes. But, it is most likely to find the inode in cache.
5985 * FIXME, needs more benchmarking...there are no reasons other than performance
5986 * to keep or drop this code.
5988 static int btrfs_dirty_inode(struct btrfs_inode *inode)
5990 struct btrfs_root *root = inode->root;
5991 struct btrfs_fs_info *fs_info = root->fs_info;
5992 struct btrfs_trans_handle *trans;
5995 if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
5998 trans = btrfs_join_transaction(root);
6000 return PTR_ERR(trans);
6002 ret = btrfs_update_inode(trans, root, inode);
6003 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6004 /* whoops, lets try again with the full transaction */
6005 btrfs_end_transaction(trans);
6006 trans = btrfs_start_transaction(root, 1);
6008 return PTR_ERR(trans);
6010 ret = btrfs_update_inode(trans, root, inode);
6012 btrfs_end_transaction(trans);
6013 if (inode->delayed_node)
6014 btrfs_balance_delayed_items(fs_info);
6020 * This is a copy of file_update_time. We need this so we can return error on
6021 * ENOSPC for updating the inode in the case of file write and mmap writes.
6023 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6026 struct btrfs_root *root = BTRFS_I(inode)->root;
6027 bool dirty = flags & ~S_VERSION;
6029 if (btrfs_root_readonly(root))
6032 if (flags & S_VERSION)
6033 dirty |= inode_maybe_inc_iversion(inode, dirty);
6034 if (flags & S_CTIME)
6035 inode->i_ctime = *now;
6036 if (flags & S_MTIME)
6037 inode->i_mtime = *now;
6038 if (flags & S_ATIME)
6039 inode->i_atime = *now;
6040 return dirty ? btrfs_dirty_inode(BTRFS_I(inode)) : 0;
6044 * find the highest existing sequence number in a directory
6045 * and then set the in-memory index_cnt variable to reflect
6046 * free sequence numbers
6048 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6050 struct btrfs_root *root = inode->root;
6051 struct btrfs_key key, found_key;
6052 struct btrfs_path *path;
6053 struct extent_buffer *leaf;
6056 key.objectid = btrfs_ino(inode);
6057 key.type = BTRFS_DIR_INDEX_KEY;
6058 key.offset = (u64)-1;
6060 path = btrfs_alloc_path();
6064 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6067 /* FIXME: we should be able to handle this */
6072 if (path->slots[0] == 0) {
6073 inode->index_cnt = BTRFS_DIR_START_INDEX;
6079 leaf = path->nodes[0];
6080 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6082 if (found_key.objectid != btrfs_ino(inode) ||
6083 found_key.type != BTRFS_DIR_INDEX_KEY) {
6084 inode->index_cnt = BTRFS_DIR_START_INDEX;
6088 inode->index_cnt = found_key.offset + 1;
6090 btrfs_free_path(path);
6095 * helper to find a free sequence number in a given directory. This current
6096 * code is very simple, later versions will do smarter things in the btree
6098 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6102 if (dir->index_cnt == (u64)-1) {
6103 ret = btrfs_inode_delayed_dir_index_count(dir);
6105 ret = btrfs_set_inode_index_count(dir);
6111 *index = dir->index_cnt;
6117 static int btrfs_insert_inode_locked(struct inode *inode)
6119 struct btrfs_iget_args args;
6121 args.ino = BTRFS_I(inode)->location.objectid;
6122 args.root = BTRFS_I(inode)->root;
6124 return insert_inode_locked4(inode,
6125 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6126 btrfs_find_actor, &args);
6129 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6130 unsigned int *trans_num_items)
6132 struct inode *dir = args->dir;
6133 struct inode *inode = args->inode;
6136 if (!args->orphan) {
6137 ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6143 ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6145 fscrypt_free_filename(&args->fname);
6149 /* 1 to add inode item */
6150 *trans_num_items = 1;
6151 /* 1 to add compression property */
6152 if (BTRFS_I(dir)->prop_compress)
6153 (*trans_num_items)++;
6154 /* 1 to add default ACL xattr */
6155 if (args->default_acl)
6156 (*trans_num_items)++;
6157 /* 1 to add access ACL xattr */
6159 (*trans_num_items)++;
6160 #ifdef CONFIG_SECURITY
6161 /* 1 to add LSM xattr */
6162 if (dir->i_security)
6163 (*trans_num_items)++;
6166 /* 1 to add orphan item */
6167 (*trans_num_items)++;
6171 * 1 to add dir index
6172 * 1 to update parent inode item
6174 * No need for 1 unit for the inode ref item because it is
6175 * inserted in a batch together with the inode item at
6176 * btrfs_create_new_inode().
6178 *trans_num_items += 3;
6183 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6185 posix_acl_release(args->acl);
6186 posix_acl_release(args->default_acl);
6187 fscrypt_free_filename(&args->fname);
6191 * Inherit flags from the parent inode.
6193 * Currently only the compression flags and the cow flags are inherited.
6195 static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
6201 if (flags & BTRFS_INODE_NOCOMPRESS) {
6202 inode->flags &= ~BTRFS_INODE_COMPRESS;
6203 inode->flags |= BTRFS_INODE_NOCOMPRESS;
6204 } else if (flags & BTRFS_INODE_COMPRESS) {
6205 inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
6206 inode->flags |= BTRFS_INODE_COMPRESS;
6209 if (flags & BTRFS_INODE_NODATACOW) {
6210 inode->flags |= BTRFS_INODE_NODATACOW;
6211 if (S_ISREG(inode->vfs_inode.i_mode))
6212 inode->flags |= BTRFS_INODE_NODATASUM;
6215 btrfs_sync_inode_flags_to_i_flags(&inode->vfs_inode);
6218 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6219 struct btrfs_new_inode_args *args)
6221 struct inode *dir = args->dir;
6222 struct inode *inode = args->inode;
6223 const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6224 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6225 struct btrfs_root *root;
6226 struct btrfs_inode_item *inode_item;
6227 struct btrfs_key *location;
6228 struct btrfs_path *path;
6230 struct btrfs_inode_ref *ref;
6231 struct btrfs_key key[2];
6233 struct btrfs_item_batch batch;
6237 path = btrfs_alloc_path();
6242 BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6243 root = BTRFS_I(inode)->root;
6245 ret = btrfs_get_free_objectid(root, &objectid);
6248 inode->i_ino = objectid;
6252 * O_TMPFILE, set link count to 0, so that after this point, we
6253 * fill in an inode item with the correct link count.
6255 set_nlink(inode, 0);
6257 trace_btrfs_inode_request(dir);
6259 ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6263 /* index_cnt is ignored for everything but a dir. */
6264 BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6265 BTRFS_I(inode)->generation = trans->transid;
6266 inode->i_generation = BTRFS_I(inode)->generation;
6269 * Subvolumes don't inherit flags from their parent directory.
6270 * Originally this was probably by accident, but we probably can't
6271 * change it now without compatibility issues.
6274 btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
6276 if (S_ISREG(inode->i_mode)) {
6277 if (btrfs_test_opt(fs_info, NODATASUM))
6278 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6279 if (btrfs_test_opt(fs_info, NODATACOW))
6280 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6281 BTRFS_INODE_NODATASUM;
6284 location = &BTRFS_I(inode)->location;
6285 location->objectid = objectid;
6286 location->offset = 0;
6287 location->type = BTRFS_INODE_ITEM_KEY;
6289 ret = btrfs_insert_inode_locked(inode);
6292 BTRFS_I(dir)->index_cnt--;
6297 * We could have gotten an inode number from somebody who was fsynced
6298 * and then removed in this same transaction, so let's just set full
6299 * sync since it will be a full sync anyway and this will blow away the
6300 * old info in the log.
6302 btrfs_set_inode_full_sync(BTRFS_I(inode));
6304 key[0].objectid = objectid;
6305 key[0].type = BTRFS_INODE_ITEM_KEY;
6308 sizes[0] = sizeof(struct btrfs_inode_item);
6310 if (!args->orphan) {
6312 * Start new inodes with an inode_ref. This is slightly more
6313 * efficient for small numbers of hard links since they will
6314 * be packed into one item. Extended refs will kick in if we
6315 * add more hard links than can fit in the ref item.
6317 key[1].objectid = objectid;
6318 key[1].type = BTRFS_INODE_REF_KEY;
6320 key[1].offset = objectid;
6321 sizes[1] = 2 + sizeof(*ref);
6323 key[1].offset = btrfs_ino(BTRFS_I(dir));
6324 sizes[1] = name->len + sizeof(*ref);
6328 batch.keys = &key[0];
6329 batch.data_sizes = &sizes[0];
6330 batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6331 batch.nr = args->orphan ? 1 : 2;
6332 ret = btrfs_insert_empty_items(trans, root, path, &batch);
6334 btrfs_abort_transaction(trans, ret);
6338 inode->i_mtime = current_time(inode);
6339 inode->i_atime = inode->i_mtime;
6340 inode->i_ctime = inode->i_mtime;
6341 BTRFS_I(inode)->i_otime = inode->i_mtime;
6344 * We're going to fill the inode item now, so at this point the inode
6345 * must be fully initialized.
6348 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6349 struct btrfs_inode_item);
6350 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6351 sizeof(*inode_item));
6352 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6354 if (!args->orphan) {
6355 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6356 struct btrfs_inode_ref);
6357 ptr = (unsigned long)(ref + 1);
6359 btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6360 btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6361 write_extent_buffer(path->nodes[0], "..", ptr, 2);
6363 btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6365 btrfs_set_inode_ref_index(path->nodes[0], ref,
6366 BTRFS_I(inode)->dir_index);
6367 write_extent_buffer(path->nodes[0], name->name, ptr,
6372 btrfs_mark_buffer_dirty(path->nodes[0]);
6374 * We don't need the path anymore, plus inheriting properties, adding
6375 * ACLs, security xattrs, orphan item or adding the link, will result in
6376 * allocating yet another path. So just free our path.
6378 btrfs_free_path(path);
6382 struct inode *parent;
6385 * Subvolumes inherit properties from their parent subvolume,
6386 * not the directory they were created in.
6388 parent = btrfs_iget(fs_info->sb, BTRFS_FIRST_FREE_OBJECTID,
6389 BTRFS_I(dir)->root);
6390 if (IS_ERR(parent)) {
6391 ret = PTR_ERR(parent);
6393 ret = btrfs_inode_inherit_props(trans, inode, parent);
6397 ret = btrfs_inode_inherit_props(trans, inode, dir);
6401 "error inheriting props for ino %llu (root %llu): %d",
6402 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid,
6407 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6410 if (!args->subvol) {
6411 ret = btrfs_init_inode_security(trans, args);
6413 btrfs_abort_transaction(trans, ret);
6418 inode_tree_add(BTRFS_I(inode));
6420 trace_btrfs_inode_new(inode);
6421 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6423 btrfs_update_root_times(trans, root);
6426 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6428 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6429 0, BTRFS_I(inode)->dir_index);
6432 btrfs_abort_transaction(trans, ret);
6440 * discard_new_inode() calls iput(), but the caller owns the reference
6444 discard_new_inode(inode);
6446 btrfs_free_path(path);
6451 * utility function to add 'inode' into 'parent_inode' with
6452 * a give name and a given sequence number.
6453 * if 'add_backref' is true, also insert a backref from the
6454 * inode to the parent directory.
6456 int btrfs_add_link(struct btrfs_trans_handle *trans,
6457 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6458 const struct fscrypt_str *name, int add_backref, u64 index)
6461 struct btrfs_key key;
6462 struct btrfs_root *root = parent_inode->root;
6463 u64 ino = btrfs_ino(inode);
6464 u64 parent_ino = btrfs_ino(parent_inode);
6466 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6467 memcpy(&key, &inode->root->root_key, sizeof(key));
6470 key.type = BTRFS_INODE_ITEM_KEY;
6474 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6475 ret = btrfs_add_root_ref(trans, key.objectid,
6476 root->root_key.objectid, parent_ino,
6478 } else if (add_backref) {
6479 ret = btrfs_insert_inode_ref(trans, root, name,
6480 ino, parent_ino, index);
6483 /* Nothing to clean up yet */
6487 ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6488 btrfs_inode_type(&inode->vfs_inode), index);
6489 if (ret == -EEXIST || ret == -EOVERFLOW)
6492 btrfs_abort_transaction(trans, ret);
6496 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6498 inode_inc_iversion(&parent_inode->vfs_inode);
6500 * If we are replaying a log tree, we do not want to update the mtime
6501 * and ctime of the parent directory with the current time, since the
6502 * log replay procedure is responsible for setting them to their correct
6503 * values (the ones it had when the fsync was done).
6505 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6506 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6508 parent_inode->vfs_inode.i_mtime = now;
6509 parent_inode->vfs_inode.i_ctime = now;
6511 ret = btrfs_update_inode(trans, root, parent_inode);
6513 btrfs_abort_transaction(trans, ret);
6517 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6520 err = btrfs_del_root_ref(trans, key.objectid,
6521 root->root_key.objectid, parent_ino,
6522 &local_index, name);
6524 btrfs_abort_transaction(trans, err);
6525 } else if (add_backref) {
6529 err = btrfs_del_inode_ref(trans, root, name, ino, parent_ino,
6532 btrfs_abort_transaction(trans, err);
6535 /* Return the original error code */
6539 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6540 struct inode *inode)
6542 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6543 struct btrfs_root *root = BTRFS_I(dir)->root;
6544 struct btrfs_new_inode_args new_inode_args = {
6549 unsigned int trans_num_items;
6550 struct btrfs_trans_handle *trans;
6553 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6557 trans = btrfs_start_transaction(root, trans_num_items);
6558 if (IS_ERR(trans)) {
6559 err = PTR_ERR(trans);
6560 goto out_new_inode_args;
6563 err = btrfs_create_new_inode(trans, &new_inode_args);
6565 d_instantiate_new(dentry, inode);
6567 btrfs_end_transaction(trans);
6568 btrfs_btree_balance_dirty(fs_info);
6570 btrfs_new_inode_args_destroy(&new_inode_args);
6577 static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
6578 struct dentry *dentry, umode_t mode, dev_t rdev)
6580 struct inode *inode;
6582 inode = new_inode(dir->i_sb);
6585 inode_init_owner(idmap, inode, dir, mode);
6586 inode->i_op = &btrfs_special_inode_operations;
6587 init_special_inode(inode, inode->i_mode, rdev);
6588 return btrfs_create_common(dir, dentry, inode);
6591 static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
6592 struct dentry *dentry, umode_t mode, bool excl)
6594 struct inode *inode;
6596 inode = new_inode(dir->i_sb);
6599 inode_init_owner(idmap, inode, dir, mode);
6600 inode->i_fop = &btrfs_file_operations;
6601 inode->i_op = &btrfs_file_inode_operations;
6602 inode->i_mapping->a_ops = &btrfs_aops;
6603 return btrfs_create_common(dir, dentry, inode);
6606 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6607 struct dentry *dentry)
6609 struct btrfs_trans_handle *trans = NULL;
6610 struct btrfs_root *root = BTRFS_I(dir)->root;
6611 struct inode *inode = d_inode(old_dentry);
6612 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6613 struct fscrypt_name fname;
6618 /* do not allow sys_link's with other subvols of the same device */
6619 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6622 if (inode->i_nlink >= BTRFS_LINK_MAX)
6625 err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
6629 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6634 * 2 items for inode and inode ref
6635 * 2 items for dir items
6636 * 1 item for parent inode
6637 * 1 item for orphan item deletion if O_TMPFILE
6639 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6640 if (IS_ERR(trans)) {
6641 err = PTR_ERR(trans);
6646 /* There are several dir indexes for this inode, clear the cache. */
6647 BTRFS_I(inode)->dir_index = 0ULL;
6649 inode_inc_iversion(inode);
6650 inode->i_ctime = current_time(inode);
6652 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6654 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6655 &fname.disk_name, 1, index);
6660 struct dentry *parent = dentry->d_parent;
6662 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6665 if (inode->i_nlink == 1) {
6667 * If new hard link count is 1, it's a file created
6668 * with open(2) O_TMPFILE flag.
6670 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6674 d_instantiate(dentry, inode);
6675 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6679 fscrypt_free_filename(&fname);
6681 btrfs_end_transaction(trans);
6683 inode_dec_link_count(inode);
6686 btrfs_btree_balance_dirty(fs_info);
6690 static int btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
6691 struct dentry *dentry, umode_t mode)
6693 struct inode *inode;
6695 inode = new_inode(dir->i_sb);
6698 inode_init_owner(idmap, inode, dir, S_IFDIR | mode);
6699 inode->i_op = &btrfs_dir_inode_operations;
6700 inode->i_fop = &btrfs_dir_file_operations;
6701 return btrfs_create_common(dir, dentry, inode);
6704 static noinline int uncompress_inline(struct btrfs_path *path,
6706 struct btrfs_file_extent_item *item)
6709 struct extent_buffer *leaf = path->nodes[0];
6712 unsigned long inline_size;
6716 compress_type = btrfs_file_extent_compression(leaf, item);
6717 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6718 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6719 tmp = kmalloc(inline_size, GFP_NOFS);
6722 ptr = btrfs_file_extent_inline_start(item);
6724 read_extent_buffer(leaf, tmp, ptr, inline_size);
6726 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6727 ret = btrfs_decompress(compress_type, tmp, page, 0, inline_size, max_size);
6730 * decompression code contains a memset to fill in any space between the end
6731 * of the uncompressed data and the end of max_size in case the decompressed
6732 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6733 * the end of an inline extent and the beginning of the next block, so we
6734 * cover that region here.
6737 if (max_size < PAGE_SIZE)
6738 memzero_page(page, max_size, PAGE_SIZE - max_size);
6743 static int read_inline_extent(struct btrfs_inode *inode, struct btrfs_path *path,
6746 struct btrfs_file_extent_item *fi;
6750 if (!page || PageUptodate(page))
6753 ASSERT(page_offset(page) == 0);
6755 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6756 struct btrfs_file_extent_item);
6757 if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
6758 return uncompress_inline(path, page, fi);
6760 copy_size = min_t(u64, PAGE_SIZE,
6761 btrfs_file_extent_ram_bytes(path->nodes[0], fi));
6762 kaddr = kmap_local_page(page);
6763 read_extent_buffer(path->nodes[0], kaddr,
6764 btrfs_file_extent_inline_start(fi), copy_size);
6765 kunmap_local(kaddr);
6766 if (copy_size < PAGE_SIZE)
6767 memzero_page(page, copy_size, PAGE_SIZE - copy_size);
6772 * Lookup the first extent overlapping a range in a file.
6774 * @inode: file to search in
6775 * @page: page to read extent data into if the extent is inline
6776 * @pg_offset: offset into @page to copy to
6777 * @start: file offset
6778 * @len: length of range starting at @start
6780 * Return the first &struct extent_map which overlaps the given range, reading
6781 * it from the B-tree and caching it if necessary. Note that there may be more
6782 * extents which overlap the given range after the returned extent_map.
6784 * If @page is not NULL and the extent is inline, this also reads the extent
6785 * data directly into the page and marks the extent up to date in the io_tree.
6787 * Return: ERR_PTR on error, non-NULL extent_map on success.
6789 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6790 struct page *page, size_t pg_offset,
6793 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6795 u64 extent_start = 0;
6797 u64 objectid = btrfs_ino(inode);
6798 int extent_type = -1;
6799 struct btrfs_path *path = NULL;
6800 struct btrfs_root *root = inode->root;
6801 struct btrfs_file_extent_item *item;
6802 struct extent_buffer *leaf;
6803 struct btrfs_key found_key;
6804 struct extent_map *em = NULL;
6805 struct extent_map_tree *em_tree = &inode->extent_tree;
6807 read_lock(&em_tree->lock);
6808 em = lookup_extent_mapping(em_tree, start, len);
6809 read_unlock(&em_tree->lock);
6812 if (em->start > start || em->start + em->len <= start)
6813 free_extent_map(em);
6814 else if (em->block_start == EXTENT_MAP_INLINE && page)
6815 free_extent_map(em);
6819 em = alloc_extent_map();
6824 em->start = EXTENT_MAP_HOLE;
6825 em->orig_start = EXTENT_MAP_HOLE;
6827 em->block_len = (u64)-1;
6829 path = btrfs_alloc_path();
6835 /* Chances are we'll be called again, so go ahead and do readahead */
6836 path->reada = READA_FORWARD;
6839 * The same explanation in load_free_space_cache applies here as well,
6840 * we only read when we're loading the free space cache, and at that
6841 * point the commit_root has everything we need.
6843 if (btrfs_is_free_space_inode(inode)) {
6844 path->search_commit_root = 1;
6845 path->skip_locking = 1;
6848 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6851 } else if (ret > 0) {
6852 if (path->slots[0] == 0)
6858 leaf = path->nodes[0];
6859 item = btrfs_item_ptr(leaf, path->slots[0],
6860 struct btrfs_file_extent_item);
6861 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6862 if (found_key.objectid != objectid ||
6863 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6865 * If we backup past the first extent we want to move forward
6866 * and see if there is an extent in front of us, otherwise we'll
6867 * say there is a hole for our whole search range which can
6874 extent_type = btrfs_file_extent_type(leaf, item);
6875 extent_start = found_key.offset;
6876 extent_end = btrfs_file_extent_end(path);
6877 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6878 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6879 /* Only regular file could have regular/prealloc extent */
6880 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6883 "regular/prealloc extent found for non-regular inode %llu",
6887 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6889 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6890 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6895 if (start >= extent_end) {
6897 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6898 ret = btrfs_next_leaf(root, path);
6904 leaf = path->nodes[0];
6906 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6907 if (found_key.objectid != objectid ||
6908 found_key.type != BTRFS_EXTENT_DATA_KEY)
6910 if (start + len <= found_key.offset)
6912 if (start > found_key.offset)
6915 /* New extent overlaps with existing one */
6917 em->orig_start = start;
6918 em->len = found_key.offset - start;
6919 em->block_start = EXTENT_MAP_HOLE;
6923 btrfs_extent_item_to_extent_map(inode, path, item, em);
6925 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6926 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6928 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6930 * Inline extent can only exist at file offset 0. This is
6931 * ensured by tree-checker and inline extent creation path.
6932 * Thus all members representing file offsets should be zero.
6934 ASSERT(pg_offset == 0);
6935 ASSERT(extent_start == 0);
6936 ASSERT(em->start == 0);
6939 * btrfs_extent_item_to_extent_map() should have properly
6940 * initialized em members already.
6942 * Other members are not utilized for inline extents.
6944 ASSERT(em->block_start == EXTENT_MAP_INLINE);
6945 ASSERT(em->len == fs_info->sectorsize);
6947 ret = read_inline_extent(inode, path, page);
6954 em->orig_start = start;
6956 em->block_start = EXTENT_MAP_HOLE;
6959 btrfs_release_path(path);
6960 if (em->start > start || extent_map_end(em) <= start) {
6962 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6963 em->start, em->len, start, len);
6968 write_lock(&em_tree->lock);
6969 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6970 write_unlock(&em_tree->lock);
6972 btrfs_free_path(path);
6974 trace_btrfs_get_extent(root, inode, em);
6977 free_extent_map(em);
6978 return ERR_PTR(ret);
6983 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
6986 const u64 orig_start,
6987 const u64 block_start,
6988 const u64 block_len,
6989 const u64 orig_block_len,
6990 const u64 ram_bytes,
6993 struct extent_map *em = NULL;
6996 if (type != BTRFS_ORDERED_NOCOW) {
6997 em = create_io_em(inode, start, len, orig_start, block_start,
6998 block_len, orig_block_len, ram_bytes,
6999 BTRFS_COMPRESS_NONE, /* compress_type */
7004 ret = btrfs_add_ordered_extent(inode, start, len, len, block_start,
7007 (1 << BTRFS_ORDERED_DIRECT),
7008 BTRFS_COMPRESS_NONE);
7011 free_extent_map(em);
7012 btrfs_drop_extent_map_range(inode, start,
7013 start + len - 1, false);
7022 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7025 struct btrfs_root *root = inode->root;
7026 struct btrfs_fs_info *fs_info = root->fs_info;
7027 struct extent_map *em;
7028 struct btrfs_key ins;
7032 alloc_hint = get_extent_allocation_hint(inode, start, len);
7033 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7034 0, alloc_hint, &ins, 1, 1);
7036 return ERR_PTR(ret);
7038 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7039 ins.objectid, ins.offset, ins.offset,
7040 ins.offset, BTRFS_ORDERED_REGULAR);
7041 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7043 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7049 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7051 struct btrfs_block_group *block_group;
7052 bool readonly = false;
7054 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7055 if (!block_group || block_group->ro)
7058 btrfs_put_block_group(block_group);
7063 * Check if we can do nocow write into the range [@offset, @offset + @len)
7065 * @offset: File offset
7066 * @len: The length to write, will be updated to the nocow writeable
7068 * @orig_start: (optional) Return the original file offset of the file extent
7069 * @orig_len: (optional) Return the original on-disk length of the file extent
7070 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7071 * @strict: if true, omit optimizations that might force us into unnecessary
7072 * cow. e.g., don't trust generation number.
7075 * >0 and update @len if we can do nocow write
7076 * 0 if we can't do nocow write
7077 * <0 if error happened
7079 * NOTE: This only checks the file extents, caller is responsible to wait for
7080 * any ordered extents.
7082 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7083 u64 *orig_start, u64 *orig_block_len,
7084 u64 *ram_bytes, bool nowait, bool strict)
7086 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7087 struct can_nocow_file_extent_args nocow_args = { 0 };
7088 struct btrfs_path *path;
7090 struct extent_buffer *leaf;
7091 struct btrfs_root *root = BTRFS_I(inode)->root;
7092 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7093 struct btrfs_file_extent_item *fi;
7094 struct btrfs_key key;
7097 path = btrfs_alloc_path();
7100 path->nowait = nowait;
7102 ret = btrfs_lookup_file_extent(NULL, root, path,
7103 btrfs_ino(BTRFS_I(inode)), offset, 0);
7108 if (path->slots[0] == 0) {
7109 /* can't find the item, must cow */
7116 leaf = path->nodes[0];
7117 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7118 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7119 key.type != BTRFS_EXTENT_DATA_KEY) {
7120 /* not our file or wrong item type, must cow */
7124 if (key.offset > offset) {
7125 /* Wrong offset, must cow */
7129 if (btrfs_file_extent_end(path) <= offset)
7132 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7133 found_type = btrfs_file_extent_type(leaf, fi);
7135 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7137 nocow_args.start = offset;
7138 nocow_args.end = offset + *len - 1;
7139 nocow_args.strict = strict;
7140 nocow_args.free_path = true;
7142 ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
7143 /* can_nocow_file_extent() has freed the path. */
7147 /* Treat errors as not being able to NOCOW. */
7153 if (btrfs_extent_readonly(fs_info, nocow_args.disk_bytenr))
7156 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7157 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7160 range_end = round_up(offset + nocow_args.num_bytes,
7161 root->fs_info->sectorsize) - 1;
7162 ret = test_range_bit(io_tree, offset, range_end,
7163 EXTENT_DELALLOC, 0, NULL);
7171 *orig_start = key.offset - nocow_args.extent_offset;
7173 *orig_block_len = nocow_args.disk_num_bytes;
7175 *len = nocow_args.num_bytes;
7178 btrfs_free_path(path);
7182 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7183 struct extent_state **cached_state,
7184 unsigned int iomap_flags)
7186 const bool writing = (iomap_flags & IOMAP_WRITE);
7187 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7188 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7189 struct btrfs_ordered_extent *ordered;
7194 if (!try_lock_extent(io_tree, lockstart, lockend,
7198 lock_extent(io_tree, lockstart, lockend, cached_state);
7201 * We're concerned with the entire range that we're going to be
7202 * doing DIO to, so we need to make sure there's no ordered
7203 * extents in this range.
7205 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7206 lockend - lockstart + 1);
7209 * We need to make sure there are no buffered pages in this
7210 * range either, we could have raced between the invalidate in
7211 * generic_file_direct_write and locking the extent. The
7212 * invalidate needs to happen so that reads after a write do not
7216 (!writing || !filemap_range_has_page(inode->i_mapping,
7217 lockstart, lockend)))
7220 unlock_extent(io_tree, lockstart, lockend, cached_state);
7224 btrfs_put_ordered_extent(ordered);
7229 * If we are doing a DIO read and the ordered extent we
7230 * found is for a buffered write, we can not wait for it
7231 * to complete and retry, because if we do so we can
7232 * deadlock with concurrent buffered writes on page
7233 * locks. This happens only if our DIO read covers more
7234 * than one extent map, if at this point has already
7235 * created an ordered extent for a previous extent map
7236 * and locked its range in the inode's io tree, and a
7237 * concurrent write against that previous extent map's
7238 * range and this range started (we unlock the ranges
7239 * in the io tree only when the bios complete and
7240 * buffered writes always lock pages before attempting
7241 * to lock range in the io tree).
7244 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7245 btrfs_start_ordered_extent(ordered);
7247 ret = nowait ? -EAGAIN : -ENOTBLK;
7248 btrfs_put_ordered_extent(ordered);
7251 * We could trigger writeback for this range (and wait
7252 * for it to complete) and then invalidate the pages for
7253 * this range (through invalidate_inode_pages2_range()),
7254 * but that can lead us to a deadlock with a concurrent
7255 * call to readahead (a buffered read or a defrag call
7256 * triggered a readahead) on a page lock due to an
7257 * ordered dio extent we created before but did not have
7258 * yet a corresponding bio submitted (whence it can not
7259 * complete), which makes readahead wait for that
7260 * ordered extent to complete while holding a lock on
7263 ret = nowait ? -EAGAIN : -ENOTBLK;
7275 /* The callers of this must take lock_extent() */
7276 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7277 u64 len, u64 orig_start, u64 block_start,
7278 u64 block_len, u64 orig_block_len,
7279 u64 ram_bytes, int compress_type,
7282 struct extent_map *em;
7285 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7286 type == BTRFS_ORDERED_COMPRESSED ||
7287 type == BTRFS_ORDERED_NOCOW ||
7288 type == BTRFS_ORDERED_REGULAR);
7290 em = alloc_extent_map();
7292 return ERR_PTR(-ENOMEM);
7295 em->orig_start = orig_start;
7297 em->block_len = block_len;
7298 em->block_start = block_start;
7299 em->orig_block_len = orig_block_len;
7300 em->ram_bytes = ram_bytes;
7301 em->generation = -1;
7302 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7303 if (type == BTRFS_ORDERED_PREALLOC) {
7304 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7305 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7306 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7307 em->compress_type = compress_type;
7310 ret = btrfs_replace_extent_map_range(inode, em, true);
7312 free_extent_map(em);
7313 return ERR_PTR(ret);
7316 /* em got 2 refs now, callers needs to do free_extent_map once. */
7321 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7322 struct inode *inode,
7323 struct btrfs_dio_data *dio_data,
7325 unsigned int iomap_flags)
7327 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7328 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7329 struct extent_map *em = *map;
7331 u64 block_start, orig_start, orig_block_len, ram_bytes;
7332 struct btrfs_block_group *bg;
7333 bool can_nocow = false;
7334 bool space_reserved = false;
7339 * We don't allocate a new extent in the following cases
7341 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7343 * 2) The extent is marked as PREALLOC. We're good to go here and can
7344 * just use the extent.
7347 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7348 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7349 em->block_start != EXTENT_MAP_HOLE)) {
7350 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7351 type = BTRFS_ORDERED_PREALLOC;
7353 type = BTRFS_ORDERED_NOCOW;
7354 len = min(len, em->len - (start - em->start));
7355 block_start = em->block_start + (start - em->start);
7357 if (can_nocow_extent(inode, start, &len, &orig_start,
7358 &orig_block_len, &ram_bytes, false, false) == 1) {
7359 bg = btrfs_inc_nocow_writers(fs_info, block_start);
7367 struct extent_map *em2;
7369 /* We can NOCOW, so only need to reserve metadata space. */
7370 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7373 /* Our caller expects us to free the input extent map. */
7374 free_extent_map(em);
7376 btrfs_dec_nocow_writers(bg);
7377 if (nowait && (ret == -ENOSPC || ret == -EDQUOT))
7381 space_reserved = true;
7383 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7384 orig_start, block_start,
7385 len, orig_block_len,
7387 btrfs_dec_nocow_writers(bg);
7388 if (type == BTRFS_ORDERED_PREALLOC) {
7389 free_extent_map(em);
7399 dio_data->nocow_done = true;
7401 /* Our caller expects us to free the input extent map. */
7402 free_extent_map(em);
7409 * If we could not allocate data space before locking the file
7410 * range and we can't do a NOCOW write, then we have to fail.
7412 if (!dio_data->data_space_reserved)
7416 * We have to COW and we have already reserved data space before,
7417 * so now we reserve only metadata.
7419 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7423 space_reserved = true;
7425 em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7431 len = min(len, em->len - (start - em->start));
7433 btrfs_delalloc_release_metadata(BTRFS_I(inode),
7434 prev_len - len, true);
7438 * We have created our ordered extent, so we can now release our reservation
7439 * for an outstanding extent.
7441 btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
7444 * Need to update the i_size under the extent lock so buffered
7445 * readers will get the updated i_size when we unlock.
7447 if (start + len > i_size_read(inode))
7448 i_size_write(inode, start + len);
7450 if (ret && space_reserved) {
7451 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7452 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7457 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7458 loff_t length, unsigned int flags, struct iomap *iomap,
7459 struct iomap *srcmap)
7461 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7462 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7463 struct extent_map *em;
7464 struct extent_state *cached_state = NULL;
7465 struct btrfs_dio_data *dio_data = iter->private;
7466 u64 lockstart, lockend;
7467 const bool write = !!(flags & IOMAP_WRITE);
7470 const u64 data_alloc_len = length;
7471 bool unlock_extents = false;
7474 * We could potentially fault if we have a buffer > PAGE_SIZE, and if
7475 * we're NOWAIT we may submit a bio for a partial range and return
7476 * EIOCBQUEUED, which would result in an errant short read.
7478 * The best way to handle this would be to allow for partial completions
7479 * of iocb's, so we could submit the partial bio, return and fault in
7480 * the rest of the pages, and then submit the io for the rest of the
7481 * range. However we don't have that currently, so simply return
7482 * -EAGAIN at this point so that the normal path is used.
7484 if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE)
7488 * Cap the size of reads to that usually seen in buffered I/O as we need
7489 * to allocate a contiguous array for the checksums.
7492 len = min_t(u64, len, fs_info->sectorsize * BTRFS_MAX_BIO_SECTORS);
7495 lockend = start + len - 1;
7498 * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
7499 * enough if we've written compressed pages to this area, so we need to
7500 * flush the dirty pages again to make absolutely sure that any
7501 * outstanding dirty pages are on disk - the first flush only starts
7502 * compression on the data, while keeping the pages locked, so by the
7503 * time the second flush returns we know bios for the compressed pages
7504 * were submitted and finished, and the pages no longer under writeback.
7506 * If we have a NOWAIT request and we have any pages in the range that
7507 * are locked, likely due to compression still in progress, we don't want
7508 * to block on page locks. We also don't want to block on pages marked as
7509 * dirty or under writeback (same as for the non-compression case).
7510 * iomap_dio_rw() did the same check, but after that and before we got
7511 * here, mmap'ed writes may have happened or buffered reads started
7512 * (readpage() and readahead(), which lock pages), as we haven't locked
7513 * the file range yet.
7515 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7516 &BTRFS_I(inode)->runtime_flags)) {
7517 if (flags & IOMAP_NOWAIT) {
7518 if (filemap_range_needs_writeback(inode->i_mapping,
7519 lockstart, lockend))
7522 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7523 start + length - 1);
7529 memset(dio_data, 0, sizeof(*dio_data));
7532 * We always try to allocate data space and must do it before locking
7533 * the file range, to avoid deadlocks with concurrent writes to the same
7534 * range if the range has several extents and the writes don't expand the
7535 * current i_size (the inode lock is taken in shared mode). If we fail to
7536 * allocate data space here we continue and later, after locking the
7537 * file range, we fail with ENOSPC only if we figure out we can not do a
7540 if (write && !(flags & IOMAP_NOWAIT)) {
7541 ret = btrfs_check_data_free_space(BTRFS_I(inode),
7542 &dio_data->data_reserved,
7543 start, data_alloc_len, false);
7545 dio_data->data_space_reserved = true;
7546 else if (ret && !(BTRFS_I(inode)->flags &
7547 (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
7552 * If this errors out it's because we couldn't invalidate pagecache for
7553 * this range and we need to fallback to buffered IO, or we are doing a
7554 * NOWAIT read/write and we need to block.
7556 ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags);
7560 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7567 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7568 * io. INLINE is special, and we could probably kludge it in here, but
7569 * it's still buffered so for safety lets just fall back to the generic
7572 * For COMPRESSED we _have_ to read the entire extent in so we can
7573 * decompress it, so there will be buffering required no matter what we
7574 * do, so go ahead and fallback to buffered.
7576 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7577 * to buffered IO. Don't blame me, this is the price we pay for using
7580 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7581 em->block_start == EXTENT_MAP_INLINE) {
7582 free_extent_map(em);
7584 * If we are in a NOWAIT context, return -EAGAIN in order to
7585 * fallback to buffered IO. This is not only because we can
7586 * block with buffered IO (no support for NOWAIT semantics at
7587 * the moment) but also to avoid returning short reads to user
7588 * space - this happens if we were able to read some data from
7589 * previous non-compressed extents and then when we fallback to
7590 * buffered IO, at btrfs_file_read_iter() by calling
7591 * filemap_read(), we fail to fault in pages for the read buffer,
7592 * in which case filemap_read() returns a short read (the number
7593 * of bytes previously read is > 0, so it does not return -EFAULT).
7595 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
7599 len = min(len, em->len - (start - em->start));
7602 * If we have a NOWAIT request and the range contains multiple extents
7603 * (or a mix of extents and holes), then we return -EAGAIN to make the
7604 * caller fallback to a context where it can do a blocking (without
7605 * NOWAIT) request. This way we avoid doing partial IO and returning
7606 * success to the caller, which is not optimal for writes and for reads
7607 * it can result in unexpected behaviour for an application.
7609 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7610 * iomap_dio_rw(), we can end up returning less data then what the caller
7611 * asked for, resulting in an unexpected, and incorrect, short read.
7612 * That is, the caller asked to read N bytes and we return less than that,
7613 * which is wrong unless we are crossing EOF. This happens if we get a
7614 * page fault error when trying to fault in pages for the buffer that is
7615 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7616 * have previously submitted bios for other extents in the range, in
7617 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7618 * those bios have completed by the time we get the page fault error,
7619 * which we return back to our caller - we should only return EIOCBQUEUED
7620 * after we have submitted bios for all the extents in the range.
7622 if ((flags & IOMAP_NOWAIT) && len < length) {
7623 free_extent_map(em);
7629 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7633 unlock_extents = true;
7634 /* Recalc len in case the new em is smaller than requested */
7635 len = min(len, em->len - (start - em->start));
7636 if (dio_data->data_space_reserved) {
7638 u64 release_len = 0;
7640 if (dio_data->nocow_done) {
7641 release_offset = start;
7642 release_len = data_alloc_len;
7643 } else if (len < data_alloc_len) {
7644 release_offset = start + len;
7645 release_len = data_alloc_len - len;
7648 if (release_len > 0)
7649 btrfs_free_reserved_data_space(BTRFS_I(inode),
7650 dio_data->data_reserved,
7656 * We need to unlock only the end area that we aren't using.
7657 * The rest is going to be unlocked by the endio routine.
7659 lockstart = start + len;
7660 if (lockstart < lockend)
7661 unlock_extents = true;
7665 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7668 free_extent_state(cached_state);
7671 * Translate extent map information to iomap.
7672 * We trim the extents (and move the addr) even though iomap code does
7673 * that, since we have locked only the parts we are performing I/O in.
7675 if ((em->block_start == EXTENT_MAP_HOLE) ||
7676 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7677 iomap->addr = IOMAP_NULL_ADDR;
7678 iomap->type = IOMAP_HOLE;
7680 iomap->addr = em->block_start + (start - em->start);
7681 iomap->type = IOMAP_MAPPED;
7683 iomap->offset = start;
7684 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7685 iomap->length = len;
7686 free_extent_map(em);
7691 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7694 if (dio_data->data_space_reserved) {
7695 btrfs_free_reserved_data_space(BTRFS_I(inode),
7696 dio_data->data_reserved,
7697 start, data_alloc_len);
7698 extent_changeset_free(dio_data->data_reserved);
7704 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7705 ssize_t written, unsigned int flags, struct iomap *iomap)
7707 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7708 struct btrfs_dio_data *dio_data = iter->private;
7709 size_t submitted = dio_data->submitted;
7710 const bool write = !!(flags & IOMAP_WRITE);
7713 if (!write && (iomap->type == IOMAP_HOLE)) {
7714 /* If reading from a hole, unlock and return */
7715 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1,
7720 if (submitted < length) {
7722 length -= submitted;
7724 btrfs_mark_ordered_io_finished(BTRFS_I(inode), NULL,
7725 pos, length, false);
7727 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7728 pos + length - 1, NULL);
7733 extent_changeset_free(dio_data->data_reserved);
7737 static void btrfs_dio_end_io(struct btrfs_bio *bbio)
7739 struct btrfs_dio_private *dip =
7740 container_of(bbio, struct btrfs_dio_private, bbio);
7741 struct btrfs_inode *inode = bbio->inode;
7742 struct bio *bio = &bbio->bio;
7744 if (bio->bi_status) {
7745 btrfs_warn(inode->root->fs_info,
7746 "direct IO failed ino %llu op 0x%0x offset %#llx len %u err no %d",
7747 btrfs_ino(inode), bio->bi_opf,
7748 dip->file_offset, dip->bytes, bio->bi_status);
7751 if (btrfs_op(bio) == BTRFS_MAP_WRITE)
7752 btrfs_mark_ordered_io_finished(inode, NULL, dip->file_offset,
7753 dip->bytes, !bio->bi_status);
7755 unlock_extent(&inode->io_tree, dip->file_offset,
7756 dip->file_offset + dip->bytes - 1, NULL);
7758 bbio->bio.bi_private = bbio->private;
7759 iomap_dio_bio_end_io(bio);
7762 static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio,
7765 struct btrfs_bio *bbio = btrfs_bio(bio);
7766 struct btrfs_dio_private *dip =
7767 container_of(bbio, struct btrfs_dio_private, bbio);
7768 struct btrfs_dio_data *dio_data = iter->private;
7770 btrfs_bio_init(bbio, BTRFS_I(iter->inode), btrfs_dio_end_io, bio->bi_private);
7771 bbio->file_offset = file_offset;
7773 dip->file_offset = file_offset;
7774 dip->bytes = bio->bi_iter.bi_size;
7776 dio_data->submitted += bio->bi_iter.bi_size;
7777 btrfs_submit_bio(bio, 0);
7780 static const struct iomap_ops btrfs_dio_iomap_ops = {
7781 .iomap_begin = btrfs_dio_iomap_begin,
7782 .iomap_end = btrfs_dio_iomap_end,
7785 static const struct iomap_dio_ops btrfs_dio_ops = {
7786 .submit_io = btrfs_dio_submit_io,
7787 .bio_set = &btrfs_dio_bioset,
7790 ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, size_t done_before)
7792 struct btrfs_dio_data data;
7794 return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
7795 IOMAP_DIO_PARTIAL, &data, done_before);
7798 struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
7801 struct btrfs_dio_data data;
7803 return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
7804 IOMAP_DIO_PARTIAL, &data, done_before);
7807 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7812 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
7817 * fiemap_prep() called filemap_write_and_wait() for the whole possible
7818 * file range (0 to LLONG_MAX), but that is not enough if we have
7819 * compression enabled. The first filemap_fdatawrite_range() only kicks
7820 * in the compression of data (in an async thread) and will return
7821 * before the compression is done and writeback is started. A second
7822 * filemap_fdatawrite_range() is needed to wait for the compression to
7823 * complete and writeback to start. We also need to wait for ordered
7824 * extents to complete, because our fiemap implementation uses mainly
7825 * file extent items to list the extents, searching for extent maps
7826 * only for file ranges with holes or prealloc extents to figure out
7827 * if we have delalloc in those ranges.
7829 if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
7830 ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
7835 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
7838 static int btrfs_writepages(struct address_space *mapping,
7839 struct writeback_control *wbc)
7841 return extent_writepages(mapping, wbc);
7844 static void btrfs_readahead(struct readahead_control *rac)
7846 extent_readahead(rac);
7850 * For release_folio() and invalidate_folio() we have a race window where
7851 * folio_end_writeback() is called but the subpage spinlock is not yet released.
7852 * If we continue to release/invalidate the page, we could cause use-after-free
7853 * for subpage spinlock. So this function is to spin and wait for subpage
7856 static void wait_subpage_spinlock(struct page *page)
7858 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7859 struct btrfs_subpage *subpage;
7861 if (!btrfs_is_subpage(fs_info, page))
7864 ASSERT(PagePrivate(page) && page->private);
7865 subpage = (struct btrfs_subpage *)page->private;
7868 * This may look insane as we just acquire the spinlock and release it,
7869 * without doing anything. But we just want to make sure no one is
7870 * still holding the subpage spinlock.
7871 * And since the page is not dirty nor writeback, and we have page
7872 * locked, the only possible way to hold a spinlock is from the endio
7873 * function to clear page writeback.
7875 * Here we just acquire the spinlock so that all existing callers
7876 * should exit and we're safe to release/invalidate the page.
7878 spin_lock_irq(&subpage->lock);
7879 spin_unlock_irq(&subpage->lock);
7882 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7884 int ret = try_release_extent_mapping(&folio->page, gfp_flags);
7887 wait_subpage_spinlock(&folio->page);
7888 clear_page_extent_mapped(&folio->page);
7893 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7895 if (folio_test_writeback(folio) || folio_test_dirty(folio))
7897 return __btrfs_release_folio(folio, gfp_flags);
7900 #ifdef CONFIG_MIGRATION
7901 static int btrfs_migrate_folio(struct address_space *mapping,
7902 struct folio *dst, struct folio *src,
7903 enum migrate_mode mode)
7905 int ret = filemap_migrate_folio(mapping, dst, src, mode);
7907 if (ret != MIGRATEPAGE_SUCCESS)
7910 if (folio_test_ordered(src)) {
7911 folio_clear_ordered(src);
7912 folio_set_ordered(dst);
7915 return MIGRATEPAGE_SUCCESS;
7918 #define btrfs_migrate_folio NULL
7921 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
7924 struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
7925 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7926 struct extent_io_tree *tree = &inode->io_tree;
7927 struct extent_state *cached_state = NULL;
7928 u64 page_start = folio_pos(folio);
7929 u64 page_end = page_start + folio_size(folio) - 1;
7931 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
7934 * We have folio locked so no new ordered extent can be created on this
7935 * page, nor bio can be submitted for this folio.
7937 * But already submitted bio can still be finished on this folio.
7938 * Furthermore, endio function won't skip folio which has Ordered
7939 * (Private2) already cleared, so it's possible for endio and
7940 * invalidate_folio to do the same ordered extent accounting twice
7943 * So here we wait for any submitted bios to finish, so that we won't
7944 * do double ordered extent accounting on the same folio.
7946 folio_wait_writeback(folio);
7947 wait_subpage_spinlock(&folio->page);
7950 * For subpage case, we have call sites like
7951 * btrfs_punch_hole_lock_range() which passes range not aligned to
7953 * If the range doesn't cover the full folio, we don't need to and
7954 * shouldn't clear page extent mapped, as folio->private can still
7955 * record subpage dirty bits for other part of the range.
7957 * For cases that invalidate the full folio even the range doesn't
7958 * cover the full folio, like invalidating the last folio, we're
7959 * still safe to wait for ordered extent to finish.
7961 if (!(offset == 0 && length == folio_size(folio))) {
7962 btrfs_release_folio(folio, GFP_NOFS);
7966 if (!inode_evicting)
7967 lock_extent(tree, page_start, page_end, &cached_state);
7970 while (cur < page_end) {
7971 struct btrfs_ordered_extent *ordered;
7974 u32 extra_flags = 0;
7976 ordered = btrfs_lookup_first_ordered_range(inode, cur,
7977 page_end + 1 - cur);
7979 range_end = page_end;
7981 * No ordered extent covering this range, we are safe
7982 * to delete all extent states in the range.
7984 extra_flags = EXTENT_CLEAR_ALL_BITS;
7987 if (ordered->file_offset > cur) {
7989 * There is a range between [cur, oe->file_offset) not
7990 * covered by any ordered extent.
7991 * We are safe to delete all extent states, and handle
7992 * the ordered extent in the next iteration.
7994 range_end = ordered->file_offset - 1;
7995 extra_flags = EXTENT_CLEAR_ALL_BITS;
7999 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8001 ASSERT(range_end + 1 - cur < U32_MAX);
8002 range_len = range_end + 1 - cur;
8003 if (!btrfs_page_test_ordered(fs_info, &folio->page, cur, range_len)) {
8005 * If Ordered (Private2) is cleared, it means endio has
8006 * already been executed for the range.
8007 * We can't delete the extent states as
8008 * btrfs_finish_ordered_io() may still use some of them.
8012 btrfs_page_clear_ordered(fs_info, &folio->page, cur, range_len);
8015 * IO on this page will never be started, so we need to account
8016 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8017 * here, must leave that up for the ordered extent completion.
8019 * This will also unlock the range for incoming
8020 * btrfs_finish_ordered_io().
8022 if (!inode_evicting)
8023 clear_extent_bit(tree, cur, range_end,
8025 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8026 EXTENT_DEFRAG, &cached_state);
8028 spin_lock_irq(&inode->ordered_tree.lock);
8029 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8030 ordered->truncated_len = min(ordered->truncated_len,
8031 cur - ordered->file_offset);
8032 spin_unlock_irq(&inode->ordered_tree.lock);
8035 * If the ordered extent has finished, we're safe to delete all
8036 * the extent states of the range, otherwise
8037 * btrfs_finish_ordered_io() will get executed by endio for
8038 * other pages, so we can't delete extent states.
8040 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8041 cur, range_end + 1 - cur)) {
8042 btrfs_finish_ordered_io(ordered);
8044 * The ordered extent has finished, now we're again
8045 * safe to delete all extent states of the range.
8047 extra_flags = EXTENT_CLEAR_ALL_BITS;
8051 btrfs_put_ordered_extent(ordered);
8053 * Qgroup reserved space handler
8054 * Sector(s) here will be either:
8056 * 1) Already written to disk or bio already finished
8057 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8058 * Qgroup will be handled by its qgroup_record then.
8059 * btrfs_qgroup_free_data() call will do nothing here.
8061 * 2) Not written to disk yet
8062 * Then btrfs_qgroup_free_data() call will clear the
8063 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8064 * reserved data space.
8065 * Since the IO will never happen for this page.
8067 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8068 if (!inode_evicting) {
8069 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8070 EXTENT_DELALLOC | EXTENT_UPTODATE |
8071 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
8072 extra_flags, &cached_state);
8074 cur = range_end + 1;
8077 * We have iterated through all ordered extents of the page, the page
8078 * should not have Ordered (Private2) anymore, or the above iteration
8079 * did something wrong.
8081 ASSERT(!folio_test_ordered(folio));
8082 btrfs_page_clear_checked(fs_info, &folio->page, folio_pos(folio), folio_size(folio));
8083 if (!inode_evicting)
8084 __btrfs_release_folio(folio, GFP_NOFS);
8085 clear_page_extent_mapped(&folio->page);
8089 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8090 * called from a page fault handler when a page is first dirtied. Hence we must
8091 * be careful to check for EOF conditions here. We set the page up correctly
8092 * for a written page which means we get ENOSPC checking when writing into
8093 * holes and correct delalloc and unwritten extent mapping on filesystems that
8094 * support these features.
8096 * We are not allowed to take the i_mutex here so we have to play games to
8097 * protect against truncate races as the page could now be beyond EOF. Because
8098 * truncate_setsize() writes the inode size before removing pages, once we have
8099 * the page lock we can determine safely if the page is beyond EOF. If it is not
8100 * beyond EOF, then the page is guaranteed safe against truncation until we
8103 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8105 struct page *page = vmf->page;
8106 struct inode *inode = file_inode(vmf->vma->vm_file);
8107 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8108 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8109 struct btrfs_ordered_extent *ordered;
8110 struct extent_state *cached_state = NULL;
8111 struct extent_changeset *data_reserved = NULL;
8112 unsigned long zero_start;
8122 reserved_space = PAGE_SIZE;
8124 sb_start_pagefault(inode->i_sb);
8125 page_start = page_offset(page);
8126 page_end = page_start + PAGE_SIZE - 1;
8130 * Reserving delalloc space after obtaining the page lock can lead to
8131 * deadlock. For example, if a dirty page is locked by this function
8132 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8133 * dirty page write out, then the btrfs_writepages() function could
8134 * end up waiting indefinitely to get a lock on the page currently
8135 * being processed by btrfs_page_mkwrite() function.
8137 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8138 page_start, reserved_space);
8140 ret2 = file_update_time(vmf->vma->vm_file);
8144 ret = vmf_error(ret2);
8150 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8152 down_read(&BTRFS_I(inode)->i_mmap_lock);
8154 size = i_size_read(inode);
8156 if ((page->mapping != inode->i_mapping) ||
8157 (page_start >= size)) {
8158 /* page got truncated out from underneath us */
8161 wait_on_page_writeback(page);
8163 lock_extent(io_tree, page_start, page_end, &cached_state);
8164 ret2 = set_page_extent_mapped(page);
8166 ret = vmf_error(ret2);
8167 unlock_extent(io_tree, page_start, page_end, &cached_state);
8172 * we can't set the delalloc bits if there are pending ordered
8173 * extents. Drop our locks and wait for them to finish
8175 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8178 unlock_extent(io_tree, page_start, page_end, &cached_state);
8180 up_read(&BTRFS_I(inode)->i_mmap_lock);
8181 btrfs_start_ordered_extent(ordered);
8182 btrfs_put_ordered_extent(ordered);
8186 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8187 reserved_space = round_up(size - page_start,
8188 fs_info->sectorsize);
8189 if (reserved_space < PAGE_SIZE) {
8190 end = page_start + reserved_space - 1;
8191 btrfs_delalloc_release_space(BTRFS_I(inode),
8192 data_reserved, page_start,
8193 PAGE_SIZE - reserved_space, true);
8198 * page_mkwrite gets called when the page is firstly dirtied after it's
8199 * faulted in, but write(2) could also dirty a page and set delalloc
8200 * bits, thus in this case for space account reason, we still need to
8201 * clear any delalloc bits within this page range since we have to
8202 * reserve data&meta space before lock_page() (see above comments).
8204 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8205 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8206 EXTENT_DEFRAG, &cached_state);
8208 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8211 unlock_extent(io_tree, page_start, page_end, &cached_state);
8212 ret = VM_FAULT_SIGBUS;
8216 /* page is wholly or partially inside EOF */
8217 if (page_start + PAGE_SIZE > size)
8218 zero_start = offset_in_page(size);
8220 zero_start = PAGE_SIZE;
8222 if (zero_start != PAGE_SIZE)
8223 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8225 btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
8226 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8227 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8229 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8231 unlock_extent(io_tree, page_start, page_end, &cached_state);
8232 up_read(&BTRFS_I(inode)->i_mmap_lock);
8234 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8235 sb_end_pagefault(inode->i_sb);
8236 extent_changeset_free(data_reserved);
8237 return VM_FAULT_LOCKED;
8241 up_read(&BTRFS_I(inode)->i_mmap_lock);
8243 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8244 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8245 reserved_space, (ret != 0));
8247 sb_end_pagefault(inode->i_sb);
8248 extent_changeset_free(data_reserved);
8252 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
8254 struct btrfs_truncate_control control = {
8256 .ino = btrfs_ino(inode),
8257 .min_type = BTRFS_EXTENT_DATA_KEY,
8258 .clear_extent_range = true,
8260 struct btrfs_root *root = inode->root;
8261 struct btrfs_fs_info *fs_info = root->fs_info;
8262 struct btrfs_block_rsv *rsv;
8264 struct btrfs_trans_handle *trans;
8265 u64 mask = fs_info->sectorsize - 1;
8266 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8268 if (!skip_writeback) {
8269 ret = btrfs_wait_ordered_range(&inode->vfs_inode,
8270 inode->vfs_inode.i_size & (~mask),
8277 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8278 * things going on here:
8280 * 1) We need to reserve space to update our inode.
8282 * 2) We need to have something to cache all the space that is going to
8283 * be free'd up by the truncate operation, but also have some slack
8284 * space reserved in case it uses space during the truncate (thank you
8285 * very much snapshotting).
8287 * And we need these to be separate. The fact is we can use a lot of
8288 * space doing the truncate, and we have no earthly idea how much space
8289 * we will use, so we need the truncate reservation to be separate so it
8290 * doesn't end up using space reserved for updating the inode. We also
8291 * need to be able to stop the transaction and start a new one, which
8292 * means we need to be able to update the inode several times, and we
8293 * have no idea of knowing how many times that will be, so we can't just
8294 * reserve 1 item for the entirety of the operation, so that has to be
8295 * done separately as well.
8297 * So that leaves us with
8299 * 1) rsv - for the truncate reservation, which we will steal from the
8300 * transaction reservation.
8301 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8302 * updating the inode.
8304 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8307 rsv->size = min_size;
8308 rsv->failfast = true;
8311 * 1 for the truncate slack space
8312 * 1 for updating the inode.
8314 trans = btrfs_start_transaction(root, 2);
8315 if (IS_ERR(trans)) {
8316 ret = PTR_ERR(trans);
8320 /* Migrate the slack space for the truncate to our reserve */
8321 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8325 trans->block_rsv = rsv;
8328 struct extent_state *cached_state = NULL;
8329 const u64 new_size = inode->vfs_inode.i_size;
8330 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8332 control.new_size = new_size;
8333 lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
8335 * We want to drop from the next block forward in case this new
8336 * size is not block aligned since we will be keeping the last
8337 * block of the extent just the way it is.
8339 btrfs_drop_extent_map_range(inode,
8340 ALIGN(new_size, fs_info->sectorsize),
8343 ret = btrfs_truncate_inode_items(trans, root, &control);
8345 inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
8346 btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
8348 unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
8350 trans->block_rsv = &fs_info->trans_block_rsv;
8351 if (ret != -ENOSPC && ret != -EAGAIN)
8354 ret = btrfs_update_inode(trans, root, inode);
8358 btrfs_end_transaction(trans);
8359 btrfs_btree_balance_dirty(fs_info);
8361 trans = btrfs_start_transaction(root, 2);
8362 if (IS_ERR(trans)) {
8363 ret = PTR_ERR(trans);
8368 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8369 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8370 rsv, min_size, false);
8371 BUG_ON(ret); /* shouldn't happen */
8372 trans->block_rsv = rsv;
8376 * We can't call btrfs_truncate_block inside a trans handle as we could
8377 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8378 * know we've truncated everything except the last little bit, and can
8379 * do btrfs_truncate_block and then update the disk_i_size.
8381 if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8382 btrfs_end_transaction(trans);
8383 btrfs_btree_balance_dirty(fs_info);
8385 ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size, 0, 0);
8388 trans = btrfs_start_transaction(root, 1);
8389 if (IS_ERR(trans)) {
8390 ret = PTR_ERR(trans);
8393 btrfs_inode_safe_disk_i_size_write(inode, 0);
8399 trans->block_rsv = &fs_info->trans_block_rsv;
8400 ret2 = btrfs_update_inode(trans, root, inode);
8404 ret2 = btrfs_end_transaction(trans);
8407 btrfs_btree_balance_dirty(fs_info);
8410 btrfs_free_block_rsv(fs_info, rsv);
8412 * So if we truncate and then write and fsync we normally would just
8413 * write the extents that changed, which is a problem if we need to
8414 * first truncate that entire inode. So set this flag so we write out
8415 * all of the extents in the inode to the sync log so we're completely
8418 * If no extents were dropped or trimmed we don't need to force the next
8419 * fsync to truncate all the inode's items from the log and re-log them
8420 * all. This means the truncate operation did not change the file size,
8421 * or changed it to a smaller size but there was only an implicit hole
8422 * between the old i_size and the new i_size, and there were no prealloc
8423 * extents beyond i_size to drop.
8425 if (control.extents_found > 0)
8426 btrfs_set_inode_full_sync(inode);
8431 struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
8434 struct inode *inode;
8436 inode = new_inode(dir->i_sb);
8439 * Subvolumes don't inherit the sgid bit or the parent's gid if
8440 * the parent's sgid bit is set. This is probably a bug.
8442 inode_init_owner(idmap, inode, NULL,
8443 S_IFDIR | (~current_umask() & S_IRWXUGO));
8444 inode->i_op = &btrfs_dir_inode_operations;
8445 inode->i_fop = &btrfs_dir_file_operations;
8450 struct inode *btrfs_alloc_inode(struct super_block *sb)
8452 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8453 struct btrfs_inode *ei;
8454 struct inode *inode;
8456 ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8463 ei->last_sub_trans = 0;
8464 ei->logged_trans = 0;
8465 ei->delalloc_bytes = 0;
8466 ei->new_delalloc_bytes = 0;
8467 ei->defrag_bytes = 0;
8468 ei->disk_i_size = 0;
8472 ei->index_cnt = (u64)-1;
8474 ei->last_unlink_trans = 0;
8475 ei->last_reflink_trans = 0;
8476 ei->last_log_commit = 0;
8478 spin_lock_init(&ei->lock);
8479 ei->outstanding_extents = 0;
8480 if (sb->s_magic != BTRFS_TEST_MAGIC)
8481 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8482 BTRFS_BLOCK_RSV_DELALLOC);
8483 ei->runtime_flags = 0;
8484 ei->prop_compress = BTRFS_COMPRESS_NONE;
8485 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8487 ei->delayed_node = NULL;
8489 ei->i_otime.tv_sec = 0;
8490 ei->i_otime.tv_nsec = 0;
8492 inode = &ei->vfs_inode;
8493 extent_map_tree_init(&ei->extent_tree);
8494 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
8495 ei->io_tree.inode = ei;
8496 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8497 IO_TREE_INODE_FILE_EXTENT);
8498 atomic_set(&ei->sync_writers, 0);
8499 mutex_init(&ei->log_mutex);
8500 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8501 INIT_LIST_HEAD(&ei->delalloc_inodes);
8502 INIT_LIST_HEAD(&ei->delayed_iput);
8503 RB_CLEAR_NODE(&ei->rb_node);
8504 init_rwsem(&ei->i_mmap_lock);
8509 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8510 void btrfs_test_destroy_inode(struct inode *inode)
8512 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8513 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8517 void btrfs_free_inode(struct inode *inode)
8519 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8522 void btrfs_destroy_inode(struct inode *vfs_inode)
8524 struct btrfs_ordered_extent *ordered;
8525 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8526 struct btrfs_root *root = inode->root;
8527 bool freespace_inode;
8529 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8530 WARN_ON(vfs_inode->i_data.nrpages);
8531 WARN_ON(inode->block_rsv.reserved);
8532 WARN_ON(inode->block_rsv.size);
8533 WARN_ON(inode->outstanding_extents);
8534 if (!S_ISDIR(vfs_inode->i_mode)) {
8535 WARN_ON(inode->delalloc_bytes);
8536 WARN_ON(inode->new_delalloc_bytes);
8538 WARN_ON(inode->csum_bytes);
8539 WARN_ON(inode->defrag_bytes);
8542 * This can happen where we create an inode, but somebody else also
8543 * created the same inode and we need to destroy the one we already
8550 * If this is a free space inode do not take the ordered extents lockdep
8553 freespace_inode = btrfs_is_free_space_inode(inode);
8556 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8560 btrfs_err(root->fs_info,
8561 "found ordered extent %llu %llu on inode cleanup",
8562 ordered->file_offset, ordered->num_bytes);
8564 if (!freespace_inode)
8565 btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
8567 btrfs_remove_ordered_extent(inode, ordered);
8568 btrfs_put_ordered_extent(ordered);
8569 btrfs_put_ordered_extent(ordered);
8572 btrfs_qgroup_check_reserved_leak(inode);
8573 inode_tree_del(inode);
8574 btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
8575 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8576 btrfs_put_root(inode->root);
8579 int btrfs_drop_inode(struct inode *inode)
8581 struct btrfs_root *root = BTRFS_I(inode)->root;
8586 /* the snap/subvol tree is on deleting */
8587 if (btrfs_root_refs(&root->root_item) == 0)
8590 return generic_drop_inode(inode);
8593 static void init_once(void *foo)
8595 struct btrfs_inode *ei = foo;
8597 inode_init_once(&ei->vfs_inode);
8600 void __cold btrfs_destroy_cachep(void)
8603 * Make sure all delayed rcu free inodes are flushed before we
8607 bioset_exit(&btrfs_dio_bioset);
8608 kmem_cache_destroy(btrfs_inode_cachep);
8611 int __init btrfs_init_cachep(void)
8613 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8614 sizeof(struct btrfs_inode), 0,
8615 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8617 if (!btrfs_inode_cachep)
8620 if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE,
8621 offsetof(struct btrfs_dio_private, bbio.bio),
8627 btrfs_destroy_cachep();
8631 static int btrfs_getattr(struct mnt_idmap *idmap,
8632 const struct path *path, struct kstat *stat,
8633 u32 request_mask, unsigned int flags)
8637 struct inode *inode = d_inode(path->dentry);
8638 u32 blocksize = inode->i_sb->s_blocksize;
8639 u32 bi_flags = BTRFS_I(inode)->flags;
8640 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8642 stat->result_mask |= STATX_BTIME;
8643 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8644 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8645 if (bi_flags & BTRFS_INODE_APPEND)
8646 stat->attributes |= STATX_ATTR_APPEND;
8647 if (bi_flags & BTRFS_INODE_COMPRESS)
8648 stat->attributes |= STATX_ATTR_COMPRESSED;
8649 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8650 stat->attributes |= STATX_ATTR_IMMUTABLE;
8651 if (bi_flags & BTRFS_INODE_NODUMP)
8652 stat->attributes |= STATX_ATTR_NODUMP;
8653 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8654 stat->attributes |= STATX_ATTR_VERITY;
8656 stat->attributes_mask |= (STATX_ATTR_APPEND |
8657 STATX_ATTR_COMPRESSED |
8658 STATX_ATTR_IMMUTABLE |
8661 generic_fillattr(idmap, inode, stat);
8662 stat->dev = BTRFS_I(inode)->root->anon_dev;
8664 spin_lock(&BTRFS_I(inode)->lock);
8665 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8666 inode_bytes = inode_get_bytes(inode);
8667 spin_unlock(&BTRFS_I(inode)->lock);
8668 stat->blocks = (ALIGN(inode_bytes, blocksize) +
8669 ALIGN(delalloc_bytes, blocksize)) >> 9;
8673 static int btrfs_rename_exchange(struct inode *old_dir,
8674 struct dentry *old_dentry,
8675 struct inode *new_dir,
8676 struct dentry *new_dentry)
8678 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8679 struct btrfs_trans_handle *trans;
8680 unsigned int trans_num_items;
8681 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8682 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8683 struct inode *new_inode = new_dentry->d_inode;
8684 struct inode *old_inode = old_dentry->d_inode;
8685 struct timespec64 ctime = current_time(old_inode);
8686 struct btrfs_rename_ctx old_rename_ctx;
8687 struct btrfs_rename_ctx new_rename_ctx;
8688 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8689 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8694 bool need_abort = false;
8695 struct fscrypt_name old_fname, new_fname;
8696 struct fscrypt_str *old_name, *new_name;
8699 * For non-subvolumes allow exchange only within one subvolume, in the
8700 * same inode namespace. Two subvolumes (represented as directory) can
8701 * be exchanged as they're a logical link and have a fixed inode number.
8704 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8705 new_ino != BTRFS_FIRST_FREE_OBJECTID))
8708 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8712 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8714 fscrypt_free_filename(&old_fname);
8718 old_name = &old_fname.disk_name;
8719 new_name = &new_fname.disk_name;
8721 /* close the race window with snapshot create/destroy ioctl */
8722 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8723 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8724 down_read(&fs_info->subvol_sem);
8728 * 1 to remove old dir item
8729 * 1 to remove old dir index
8730 * 1 to add new dir item
8731 * 1 to add new dir index
8732 * 1 to update parent inode
8734 * If the parents are the same, we only need to account for one
8736 trans_num_items = (old_dir == new_dir ? 9 : 10);
8737 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8739 * 1 to remove old root ref
8740 * 1 to remove old root backref
8741 * 1 to add new root ref
8742 * 1 to add new root backref
8744 trans_num_items += 4;
8747 * 1 to update inode item
8748 * 1 to remove old inode ref
8749 * 1 to add new inode ref
8751 trans_num_items += 3;
8753 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
8754 trans_num_items += 4;
8756 trans_num_items += 3;
8757 trans = btrfs_start_transaction(root, trans_num_items);
8758 if (IS_ERR(trans)) {
8759 ret = PTR_ERR(trans);
8764 ret = btrfs_record_root_in_trans(trans, dest);
8770 * We need to find a free sequence number both in the source and
8771 * in the destination directory for the exchange.
8773 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8776 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8780 BTRFS_I(old_inode)->dir_index = 0ULL;
8781 BTRFS_I(new_inode)->dir_index = 0ULL;
8783 /* Reference for the source. */
8784 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8785 /* force full log commit if subvolume involved. */
8786 btrfs_set_log_full_commit(trans);
8788 ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
8789 btrfs_ino(BTRFS_I(new_dir)),
8796 /* And now for the dest. */
8797 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8798 /* force full log commit if subvolume involved. */
8799 btrfs_set_log_full_commit(trans);
8801 ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
8802 btrfs_ino(BTRFS_I(old_dir)),
8806 btrfs_abort_transaction(trans, ret);
8811 /* Update inode version and ctime/mtime. */
8812 inode_inc_iversion(old_dir);
8813 inode_inc_iversion(new_dir);
8814 inode_inc_iversion(old_inode);
8815 inode_inc_iversion(new_inode);
8816 old_dir->i_mtime = ctime;
8817 old_dir->i_ctime = ctime;
8818 new_dir->i_mtime = ctime;
8819 new_dir->i_ctime = ctime;
8820 old_inode->i_ctime = ctime;
8821 new_inode->i_ctime = ctime;
8823 if (old_dentry->d_parent != new_dentry->d_parent) {
8824 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8825 BTRFS_I(old_inode), 1);
8826 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8827 BTRFS_I(new_inode), 1);
8830 /* src is a subvolume */
8831 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8832 ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8833 } else { /* src is an inode */
8834 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8835 BTRFS_I(old_dentry->d_inode),
8836 old_name, &old_rename_ctx);
8838 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
8841 btrfs_abort_transaction(trans, ret);
8845 /* dest is a subvolume */
8846 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8847 ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8848 } else { /* dest is an inode */
8849 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8850 BTRFS_I(new_dentry->d_inode),
8851 new_name, &new_rename_ctx);
8853 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
8856 btrfs_abort_transaction(trans, ret);
8860 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8861 new_name, 0, old_idx);
8863 btrfs_abort_transaction(trans, ret);
8867 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8868 old_name, 0, new_idx);
8870 btrfs_abort_transaction(trans, ret);
8874 if (old_inode->i_nlink == 1)
8875 BTRFS_I(old_inode)->dir_index = old_idx;
8876 if (new_inode->i_nlink == 1)
8877 BTRFS_I(new_inode)->dir_index = new_idx;
8880 * Now pin the logs of the roots. We do it to ensure that no other task
8881 * can sync the logs while we are in progress with the rename, because
8882 * that could result in an inconsistency in case any of the inodes that
8883 * are part of this rename operation were logged before.
8885 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8886 btrfs_pin_log_trans(root);
8887 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
8888 btrfs_pin_log_trans(dest);
8890 /* Do the log updates for all inodes. */
8891 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8892 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8893 old_rename_ctx.index, new_dentry->d_parent);
8894 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
8895 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
8896 new_rename_ctx.index, old_dentry->d_parent);
8898 /* Now unpin the logs. */
8899 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8900 btrfs_end_log_trans(root);
8901 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
8902 btrfs_end_log_trans(dest);
8904 ret2 = btrfs_end_transaction(trans);
8905 ret = ret ? ret : ret2;
8907 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8908 old_ino == BTRFS_FIRST_FREE_OBJECTID)
8909 up_read(&fs_info->subvol_sem);
8911 fscrypt_free_filename(&new_fname);
8912 fscrypt_free_filename(&old_fname);
8916 static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
8919 struct inode *inode;
8921 inode = new_inode(dir->i_sb);
8923 inode_init_owner(idmap, inode, dir,
8924 S_IFCHR | WHITEOUT_MODE);
8925 inode->i_op = &btrfs_special_inode_operations;
8926 init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
8931 static int btrfs_rename(struct mnt_idmap *idmap,
8932 struct inode *old_dir, struct dentry *old_dentry,
8933 struct inode *new_dir, struct dentry *new_dentry,
8936 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8937 struct btrfs_new_inode_args whiteout_args = {
8939 .dentry = old_dentry,
8941 struct btrfs_trans_handle *trans;
8942 unsigned int trans_num_items;
8943 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8944 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8945 struct inode *new_inode = d_inode(new_dentry);
8946 struct inode *old_inode = d_inode(old_dentry);
8947 struct btrfs_rename_ctx rename_ctx;
8951 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8952 struct fscrypt_name old_fname, new_fname;
8954 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8957 /* we only allow rename subvolume link between subvolumes */
8958 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8961 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8962 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
8965 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8966 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8969 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8973 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8975 fscrypt_free_filename(&old_fname);
8979 /* check for collisions, even if the name isn't there */
8980 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
8982 if (ret == -EEXIST) {
8984 * eexist without a new_inode */
8985 if (WARN_ON(!new_inode)) {
8986 goto out_fscrypt_names;
8989 /* maybe -EOVERFLOW */
8990 goto out_fscrypt_names;
8996 * we're using rename to replace one file with another. Start IO on it
8997 * now so we don't add too much work to the end of the transaction
8999 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9000 filemap_flush(old_inode->i_mapping);
9002 if (flags & RENAME_WHITEOUT) {
9003 whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
9004 if (!whiteout_args.inode) {
9006 goto out_fscrypt_names;
9008 ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
9010 goto out_whiteout_inode;
9012 /* 1 to update the old parent inode. */
9013 trans_num_items = 1;
9016 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9017 /* Close the race window with snapshot create/destroy ioctl */
9018 down_read(&fs_info->subvol_sem);
9020 * 1 to remove old root ref
9021 * 1 to remove old root backref
9022 * 1 to add new root ref
9023 * 1 to add new root backref
9025 trans_num_items += 4;
9029 * 1 to remove old inode ref
9030 * 1 to add new inode ref
9032 trans_num_items += 3;
9035 * 1 to remove old dir item
9036 * 1 to remove old dir index
9037 * 1 to add new dir item
9038 * 1 to add new dir index
9040 trans_num_items += 4;
9041 /* 1 to update new parent inode if it's not the same as the old parent */
9042 if (new_dir != old_dir)
9047 * 1 to remove inode ref
9048 * 1 to remove dir item
9049 * 1 to remove dir index
9050 * 1 to possibly add orphan item
9052 trans_num_items += 5;
9054 trans = btrfs_start_transaction(root, trans_num_items);
9055 if (IS_ERR(trans)) {
9056 ret = PTR_ERR(trans);
9061 ret = btrfs_record_root_in_trans(trans, dest);
9066 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9070 BTRFS_I(old_inode)->dir_index = 0ULL;
9071 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9072 /* force full log commit if subvolume involved. */
9073 btrfs_set_log_full_commit(trans);
9075 ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
9076 old_ino, btrfs_ino(BTRFS_I(new_dir)),
9082 inode_inc_iversion(old_dir);
9083 inode_inc_iversion(new_dir);
9084 inode_inc_iversion(old_inode);
9085 old_dir->i_mtime = current_time(old_dir);
9086 old_dir->i_ctime = old_dir->i_mtime;
9087 new_dir->i_mtime = old_dir->i_mtime;
9088 new_dir->i_ctime = old_dir->i_mtime;
9089 old_inode->i_ctime = old_dir->i_mtime;
9091 if (old_dentry->d_parent != new_dentry->d_parent)
9092 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9093 BTRFS_I(old_inode), 1);
9095 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9096 ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
9098 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9099 BTRFS_I(d_inode(old_dentry)),
9100 &old_fname.disk_name, &rename_ctx);
9102 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9105 btrfs_abort_transaction(trans, ret);
9110 inode_inc_iversion(new_inode);
9111 new_inode->i_ctime = current_time(new_inode);
9112 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9113 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9114 ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
9115 BUG_ON(new_inode->i_nlink == 0);
9117 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9118 BTRFS_I(d_inode(new_dentry)),
9119 &new_fname.disk_name);
9121 if (!ret && new_inode->i_nlink == 0)
9122 ret = btrfs_orphan_add(trans,
9123 BTRFS_I(d_inode(new_dentry)));
9125 btrfs_abort_transaction(trans, ret);
9130 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9131 &new_fname.disk_name, 0, index);
9133 btrfs_abort_transaction(trans, ret);
9137 if (old_inode->i_nlink == 1)
9138 BTRFS_I(old_inode)->dir_index = index;
9140 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9141 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9142 rename_ctx.index, new_dentry->d_parent);
9144 if (flags & RENAME_WHITEOUT) {
9145 ret = btrfs_create_new_inode(trans, &whiteout_args);
9147 btrfs_abort_transaction(trans, ret);
9150 unlock_new_inode(whiteout_args.inode);
9151 iput(whiteout_args.inode);
9152 whiteout_args.inode = NULL;
9156 ret2 = btrfs_end_transaction(trans);
9157 ret = ret ? ret : ret2;
9159 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9160 up_read(&fs_info->subvol_sem);
9161 if (flags & RENAME_WHITEOUT)
9162 btrfs_new_inode_args_destroy(&whiteout_args);
9164 if (flags & RENAME_WHITEOUT)
9165 iput(whiteout_args.inode);
9167 fscrypt_free_filename(&old_fname);
9168 fscrypt_free_filename(&new_fname);
9172 static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
9173 struct dentry *old_dentry, struct inode *new_dir,
9174 struct dentry *new_dentry, unsigned int flags)
9178 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9181 if (flags & RENAME_EXCHANGE)
9182 ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9185 ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
9188 btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
9193 struct btrfs_delalloc_work {
9194 struct inode *inode;
9195 struct completion completion;
9196 struct list_head list;
9197 struct btrfs_work work;
9200 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9202 struct btrfs_delalloc_work *delalloc_work;
9203 struct inode *inode;
9205 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9207 inode = delalloc_work->inode;
9208 filemap_flush(inode->i_mapping);
9209 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9210 &BTRFS_I(inode)->runtime_flags))
9211 filemap_flush(inode->i_mapping);
9214 complete(&delalloc_work->completion);
9217 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9219 struct btrfs_delalloc_work *work;
9221 work = kmalloc(sizeof(*work), GFP_NOFS);
9225 init_completion(&work->completion);
9226 INIT_LIST_HEAD(&work->list);
9227 work->inode = inode;
9228 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9234 * some fairly slow code that needs optimization. This walks the list
9235 * of all the inodes with pending delalloc and forces them to disk.
9237 static int start_delalloc_inodes(struct btrfs_root *root,
9238 struct writeback_control *wbc, bool snapshot,
9239 bool in_reclaim_context)
9241 struct btrfs_inode *binode;
9242 struct inode *inode;
9243 struct btrfs_delalloc_work *work, *next;
9244 struct list_head works;
9245 struct list_head splice;
9247 bool full_flush = wbc->nr_to_write == LONG_MAX;
9249 INIT_LIST_HEAD(&works);
9250 INIT_LIST_HEAD(&splice);
9252 mutex_lock(&root->delalloc_mutex);
9253 spin_lock(&root->delalloc_lock);
9254 list_splice_init(&root->delalloc_inodes, &splice);
9255 while (!list_empty(&splice)) {
9256 binode = list_entry(splice.next, struct btrfs_inode,
9259 list_move_tail(&binode->delalloc_inodes,
9260 &root->delalloc_inodes);
9262 if (in_reclaim_context &&
9263 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9266 inode = igrab(&binode->vfs_inode);
9268 cond_resched_lock(&root->delalloc_lock);
9271 spin_unlock(&root->delalloc_lock);
9274 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9275 &binode->runtime_flags);
9277 work = btrfs_alloc_delalloc_work(inode);
9283 list_add_tail(&work->list, &works);
9284 btrfs_queue_work(root->fs_info->flush_workers,
9287 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9288 btrfs_add_delayed_iput(BTRFS_I(inode));
9289 if (ret || wbc->nr_to_write <= 0)
9293 spin_lock(&root->delalloc_lock);
9295 spin_unlock(&root->delalloc_lock);
9298 list_for_each_entry_safe(work, next, &works, list) {
9299 list_del_init(&work->list);
9300 wait_for_completion(&work->completion);
9304 if (!list_empty(&splice)) {
9305 spin_lock(&root->delalloc_lock);
9306 list_splice_tail(&splice, &root->delalloc_inodes);
9307 spin_unlock(&root->delalloc_lock);
9309 mutex_unlock(&root->delalloc_mutex);
9313 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9315 struct writeback_control wbc = {
9316 .nr_to_write = LONG_MAX,
9317 .sync_mode = WB_SYNC_NONE,
9319 .range_end = LLONG_MAX,
9321 struct btrfs_fs_info *fs_info = root->fs_info;
9323 if (BTRFS_FS_ERROR(fs_info))
9326 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9329 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9330 bool in_reclaim_context)
9332 struct writeback_control wbc = {
9334 .sync_mode = WB_SYNC_NONE,
9336 .range_end = LLONG_MAX,
9338 struct btrfs_root *root;
9339 struct list_head splice;
9342 if (BTRFS_FS_ERROR(fs_info))
9345 INIT_LIST_HEAD(&splice);
9347 mutex_lock(&fs_info->delalloc_root_mutex);
9348 spin_lock(&fs_info->delalloc_root_lock);
9349 list_splice_init(&fs_info->delalloc_roots, &splice);
9350 while (!list_empty(&splice)) {
9352 * Reset nr_to_write here so we know that we're doing a full
9356 wbc.nr_to_write = LONG_MAX;
9358 root = list_first_entry(&splice, struct btrfs_root,
9360 root = btrfs_grab_root(root);
9362 list_move_tail(&root->delalloc_root,
9363 &fs_info->delalloc_roots);
9364 spin_unlock(&fs_info->delalloc_root_lock);
9366 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9367 btrfs_put_root(root);
9368 if (ret < 0 || wbc.nr_to_write <= 0)
9370 spin_lock(&fs_info->delalloc_root_lock);
9372 spin_unlock(&fs_info->delalloc_root_lock);
9376 if (!list_empty(&splice)) {
9377 spin_lock(&fs_info->delalloc_root_lock);
9378 list_splice_tail(&splice, &fs_info->delalloc_roots);
9379 spin_unlock(&fs_info->delalloc_root_lock);
9381 mutex_unlock(&fs_info->delalloc_root_mutex);
9385 static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
9386 struct dentry *dentry, const char *symname)
9388 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9389 struct btrfs_trans_handle *trans;
9390 struct btrfs_root *root = BTRFS_I(dir)->root;
9391 struct btrfs_path *path;
9392 struct btrfs_key key;
9393 struct inode *inode;
9394 struct btrfs_new_inode_args new_inode_args = {
9398 unsigned int trans_num_items;
9403 struct btrfs_file_extent_item *ei;
9404 struct extent_buffer *leaf;
9406 name_len = strlen(symname);
9407 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9408 return -ENAMETOOLONG;
9410 inode = new_inode(dir->i_sb);
9413 inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
9414 inode->i_op = &btrfs_symlink_inode_operations;
9415 inode_nohighmem(inode);
9416 inode->i_mapping->a_ops = &btrfs_aops;
9417 btrfs_i_size_write(BTRFS_I(inode), name_len);
9418 inode_set_bytes(inode, name_len);
9420 new_inode_args.inode = inode;
9421 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9424 /* 1 additional item for the inline extent */
9427 trans = btrfs_start_transaction(root, trans_num_items);
9428 if (IS_ERR(trans)) {
9429 err = PTR_ERR(trans);
9430 goto out_new_inode_args;
9433 err = btrfs_create_new_inode(trans, &new_inode_args);
9437 path = btrfs_alloc_path();
9440 btrfs_abort_transaction(trans, err);
9441 discard_new_inode(inode);
9445 key.objectid = btrfs_ino(BTRFS_I(inode));
9447 key.type = BTRFS_EXTENT_DATA_KEY;
9448 datasize = btrfs_file_extent_calc_inline_size(name_len);
9449 err = btrfs_insert_empty_item(trans, root, path, &key,
9452 btrfs_abort_transaction(trans, err);
9453 btrfs_free_path(path);
9454 discard_new_inode(inode);
9458 leaf = path->nodes[0];
9459 ei = btrfs_item_ptr(leaf, path->slots[0],
9460 struct btrfs_file_extent_item);
9461 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9462 btrfs_set_file_extent_type(leaf, ei,
9463 BTRFS_FILE_EXTENT_INLINE);
9464 btrfs_set_file_extent_encryption(leaf, ei, 0);
9465 btrfs_set_file_extent_compression(leaf, ei, 0);
9466 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9467 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9469 ptr = btrfs_file_extent_inline_start(ei);
9470 write_extent_buffer(leaf, symname, ptr, name_len);
9471 btrfs_mark_buffer_dirty(leaf);
9472 btrfs_free_path(path);
9474 d_instantiate_new(dentry, inode);
9477 btrfs_end_transaction(trans);
9478 btrfs_btree_balance_dirty(fs_info);
9480 btrfs_new_inode_args_destroy(&new_inode_args);
9487 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9488 struct btrfs_trans_handle *trans_in,
9489 struct btrfs_inode *inode,
9490 struct btrfs_key *ins,
9493 struct btrfs_file_extent_item stack_fi;
9494 struct btrfs_replace_extent_info extent_info;
9495 struct btrfs_trans_handle *trans = trans_in;
9496 struct btrfs_path *path;
9497 u64 start = ins->objectid;
9498 u64 len = ins->offset;
9499 int qgroup_released;
9502 memset(&stack_fi, 0, sizeof(stack_fi));
9504 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9505 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9506 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9507 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9508 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9509 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9510 /* Encryption and other encoding is reserved and all 0 */
9512 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9513 if (qgroup_released < 0)
9514 return ERR_PTR(qgroup_released);
9517 ret = insert_reserved_file_extent(trans, inode,
9518 file_offset, &stack_fi,
9519 true, qgroup_released);
9525 extent_info.disk_offset = start;
9526 extent_info.disk_len = len;
9527 extent_info.data_offset = 0;
9528 extent_info.data_len = len;
9529 extent_info.file_offset = file_offset;
9530 extent_info.extent_buf = (char *)&stack_fi;
9531 extent_info.is_new_extent = true;
9532 extent_info.update_times = true;
9533 extent_info.qgroup_reserved = qgroup_released;
9534 extent_info.insertions = 0;
9536 path = btrfs_alloc_path();
9542 ret = btrfs_replace_file_extents(inode, path, file_offset,
9543 file_offset + len - 1, &extent_info,
9545 btrfs_free_path(path);
9552 * We have released qgroup data range at the beginning of the function,
9553 * and normally qgroup_released bytes will be freed when committing
9555 * But if we error out early, we have to free what we have released
9556 * or we leak qgroup data reservation.
9558 btrfs_qgroup_free_refroot(inode->root->fs_info,
9559 inode->root->root_key.objectid, qgroup_released,
9560 BTRFS_QGROUP_RSV_DATA);
9561 return ERR_PTR(ret);
9564 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9565 u64 start, u64 num_bytes, u64 min_size,
9566 loff_t actual_len, u64 *alloc_hint,
9567 struct btrfs_trans_handle *trans)
9569 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9570 struct extent_map *em;
9571 struct btrfs_root *root = BTRFS_I(inode)->root;
9572 struct btrfs_key ins;
9573 u64 cur_offset = start;
9574 u64 clear_offset = start;
9577 u64 last_alloc = (u64)-1;
9579 bool own_trans = true;
9580 u64 end = start + num_bytes - 1;
9584 while (num_bytes > 0) {
9585 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9586 cur_bytes = max(cur_bytes, min_size);
9588 * If we are severely fragmented we could end up with really
9589 * small allocations, so if the allocator is returning small
9590 * chunks lets make its job easier by only searching for those
9593 cur_bytes = min(cur_bytes, last_alloc);
9594 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9595 min_size, 0, *alloc_hint, &ins, 1, 0);
9600 * We've reserved this space, and thus converted it from
9601 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9602 * from here on out we will only need to clear our reservation
9603 * for the remaining unreserved area, so advance our
9604 * clear_offset by our extent size.
9606 clear_offset += ins.offset;
9608 last_alloc = ins.offset;
9609 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9612 * Now that we inserted the prealloc extent we can finally
9613 * decrement the number of reservations in the block group.
9614 * If we did it before, we could race with relocation and have
9615 * relocation miss the reserved extent, making it fail later.
9617 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9618 if (IS_ERR(trans)) {
9619 ret = PTR_ERR(trans);
9620 btrfs_free_reserved_extent(fs_info, ins.objectid,
9625 em = alloc_extent_map();
9627 btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9628 cur_offset + ins.offset - 1, false);
9629 btrfs_set_inode_full_sync(BTRFS_I(inode));
9633 em->start = cur_offset;
9634 em->orig_start = cur_offset;
9635 em->len = ins.offset;
9636 em->block_start = ins.objectid;
9637 em->block_len = ins.offset;
9638 em->orig_block_len = ins.offset;
9639 em->ram_bytes = ins.offset;
9640 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9641 em->generation = trans->transid;
9643 ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9644 free_extent_map(em);
9646 num_bytes -= ins.offset;
9647 cur_offset += ins.offset;
9648 *alloc_hint = ins.objectid + ins.offset;
9650 inode_inc_iversion(inode);
9651 inode->i_ctime = current_time(inode);
9652 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9653 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9654 (actual_len > inode->i_size) &&
9655 (cur_offset > inode->i_size)) {
9656 if (cur_offset > actual_len)
9657 i_size = actual_len;
9659 i_size = cur_offset;
9660 i_size_write(inode, i_size);
9661 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9664 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9667 btrfs_abort_transaction(trans, ret);
9669 btrfs_end_transaction(trans);
9674 btrfs_end_transaction(trans);
9678 if (clear_offset < end)
9679 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9680 end - clear_offset + 1);
9684 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9685 u64 start, u64 num_bytes, u64 min_size,
9686 loff_t actual_len, u64 *alloc_hint)
9688 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9689 min_size, actual_len, alloc_hint,
9693 int btrfs_prealloc_file_range_trans(struct inode *inode,
9694 struct btrfs_trans_handle *trans, int mode,
9695 u64 start, u64 num_bytes, u64 min_size,
9696 loff_t actual_len, u64 *alloc_hint)
9698 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9699 min_size, actual_len, alloc_hint, trans);
9702 static int btrfs_permission(struct mnt_idmap *idmap,
9703 struct inode *inode, int mask)
9705 struct btrfs_root *root = BTRFS_I(inode)->root;
9706 umode_t mode = inode->i_mode;
9708 if (mask & MAY_WRITE &&
9709 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9710 if (btrfs_root_readonly(root))
9712 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9715 return generic_permission(idmap, inode, mask);
9718 static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
9719 struct file *file, umode_t mode)
9721 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9722 struct btrfs_trans_handle *trans;
9723 struct btrfs_root *root = BTRFS_I(dir)->root;
9724 struct inode *inode;
9725 struct btrfs_new_inode_args new_inode_args = {
9727 .dentry = file->f_path.dentry,
9730 unsigned int trans_num_items;
9733 inode = new_inode(dir->i_sb);
9736 inode_init_owner(idmap, inode, dir, mode);
9737 inode->i_fop = &btrfs_file_operations;
9738 inode->i_op = &btrfs_file_inode_operations;
9739 inode->i_mapping->a_ops = &btrfs_aops;
9741 new_inode_args.inode = inode;
9742 ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9746 trans = btrfs_start_transaction(root, trans_num_items);
9747 if (IS_ERR(trans)) {
9748 ret = PTR_ERR(trans);
9749 goto out_new_inode_args;
9752 ret = btrfs_create_new_inode(trans, &new_inode_args);
9755 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9756 * set it to 1 because d_tmpfile() will issue a warning if the count is
9759 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9761 set_nlink(inode, 1);
9764 d_tmpfile(file, inode);
9765 unlock_new_inode(inode);
9766 mark_inode_dirty(inode);
9769 btrfs_end_transaction(trans);
9770 btrfs_btree_balance_dirty(fs_info);
9772 btrfs_new_inode_args_destroy(&new_inode_args);
9776 return finish_open_simple(file, ret);
9779 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
9781 struct btrfs_fs_info *fs_info = inode->root->fs_info;
9782 unsigned long index = start >> PAGE_SHIFT;
9783 unsigned long end_index = end >> PAGE_SHIFT;
9787 ASSERT(end + 1 - start <= U32_MAX);
9788 len = end + 1 - start;
9789 while (index <= end_index) {
9790 page = find_get_page(inode->vfs_inode.i_mapping, index);
9791 ASSERT(page); /* Pages should be in the extent_io_tree */
9793 btrfs_page_set_writeback(fs_info, page, start, len);
9799 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
9802 switch (compress_type) {
9803 case BTRFS_COMPRESS_NONE:
9804 return BTRFS_ENCODED_IO_COMPRESSION_NONE;
9805 case BTRFS_COMPRESS_ZLIB:
9806 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
9807 case BTRFS_COMPRESS_LZO:
9809 * The LZO format depends on the sector size. 64K is the maximum
9810 * sector size that we support.
9812 if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
9814 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
9815 (fs_info->sectorsize_bits - 12);
9816 case BTRFS_COMPRESS_ZSTD:
9817 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
9823 static ssize_t btrfs_encoded_read_inline(
9825 struct iov_iter *iter, u64 start,
9827 struct extent_state **cached_state,
9828 u64 extent_start, size_t count,
9829 struct btrfs_ioctl_encoded_io_args *encoded,
9832 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9833 struct btrfs_root *root = inode->root;
9834 struct btrfs_fs_info *fs_info = root->fs_info;
9835 struct extent_io_tree *io_tree = &inode->io_tree;
9836 struct btrfs_path *path;
9837 struct extent_buffer *leaf;
9838 struct btrfs_file_extent_item *item;
9844 path = btrfs_alloc_path();
9849 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
9853 /* The extent item disappeared? */
9858 leaf = path->nodes[0];
9859 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
9861 ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
9862 ptr = btrfs_file_extent_inline_start(item);
9864 encoded->len = min_t(u64, extent_start + ram_bytes,
9865 inode->vfs_inode.i_size) - iocb->ki_pos;
9866 ret = btrfs_encoded_io_compression_from_extent(fs_info,
9867 btrfs_file_extent_compression(leaf, item));
9870 encoded->compression = ret;
9871 if (encoded->compression) {
9874 inline_size = btrfs_file_extent_inline_item_len(leaf,
9876 if (inline_size > count) {
9880 count = inline_size;
9881 encoded->unencoded_len = ram_bytes;
9882 encoded->unencoded_offset = iocb->ki_pos - extent_start;
9884 count = min_t(u64, count, encoded->len);
9885 encoded->len = count;
9886 encoded->unencoded_len = count;
9887 ptr += iocb->ki_pos - extent_start;
9890 tmp = kmalloc(count, GFP_NOFS);
9895 read_extent_buffer(leaf, tmp, ptr, count);
9896 btrfs_release_path(path);
9897 unlock_extent(io_tree, start, lockend, cached_state);
9898 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9901 ret = copy_to_iter(tmp, count, iter);
9906 btrfs_free_path(path);
9910 struct btrfs_encoded_read_private {
9911 struct btrfs_inode *inode;
9913 wait_queue_head_t wait;
9915 blk_status_t status;
9918 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
9920 struct btrfs_encoded_read_private *priv = bbio->private;
9922 if (bbio->bio.bi_status) {
9924 * The memory barrier implied by the atomic_dec_return() here
9925 * pairs with the memory barrier implied by the
9926 * atomic_dec_return() or io_wait_event() in
9927 * btrfs_encoded_read_regular_fill_pages() to ensure that this
9928 * write is observed before the load of status in
9929 * btrfs_encoded_read_regular_fill_pages().
9931 WRITE_ONCE(priv->status, bbio->bio.bi_status);
9933 if (!atomic_dec_return(&priv->pending))
9934 wake_up(&priv->wait);
9935 bio_put(&bbio->bio);
9938 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
9939 u64 file_offset, u64 disk_bytenr,
9940 u64 disk_io_size, struct page **pages)
9942 struct btrfs_encoded_read_private priv = {
9944 .file_offset = file_offset,
9945 .pending = ATOMIC_INIT(1),
9947 unsigned long i = 0;
9950 init_waitqueue_head(&priv.wait);
9951 /* Submit bios for the extent, splitting due to bio limits as necessary. */
9952 while (cur < disk_io_size) {
9953 struct bio *bio = NULL;
9954 u64 remaining = disk_io_size - cur;
9956 while (bio || remaining) {
9957 size_t bytes = min_t(u64, remaining, PAGE_SIZE);
9960 bio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ,
9962 btrfs_encoded_read_endio,
9964 bio->bi_iter.bi_sector =
9965 (disk_bytenr + cur) >> SECTOR_SHIFT;
9969 bio_add_page(bio, pages[i], bytes, 0) < bytes) {
9970 atomic_inc(&priv.pending);
9971 btrfs_submit_bio(bio, 0);
9982 if (atomic_dec_return(&priv.pending))
9983 io_wait_event(priv.wait, !atomic_read(&priv.pending));
9984 /* See btrfs_encoded_read_endio() for ordering. */
9985 return blk_status_to_errno(READ_ONCE(priv.status));
9988 static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
9989 struct iov_iter *iter,
9990 u64 start, u64 lockend,
9991 struct extent_state **cached_state,
9992 u64 disk_bytenr, u64 disk_io_size,
9993 size_t count, bool compressed,
9996 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9997 struct extent_io_tree *io_tree = &inode->io_tree;
9998 struct page **pages;
9999 unsigned long nr_pages, i;
10001 size_t page_offset;
10004 nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
10005 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
10008 ret = btrfs_alloc_page_array(nr_pages, pages);
10014 ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
10015 disk_io_size, pages);
10019 unlock_extent(io_tree, start, lockend, cached_state);
10020 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10027 i = (iocb->ki_pos - start) >> PAGE_SHIFT;
10028 page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
10031 while (cur < count) {
10032 size_t bytes = min_t(size_t, count - cur,
10033 PAGE_SIZE - page_offset);
10035 if (copy_page_to_iter(pages[i], page_offset, bytes,
10046 for (i = 0; i < nr_pages; i++) {
10048 __free_page(pages[i]);
10054 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
10055 struct btrfs_ioctl_encoded_io_args *encoded)
10057 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10058 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10059 struct extent_io_tree *io_tree = &inode->io_tree;
10061 size_t count = iov_iter_count(iter);
10062 u64 start, lockend, disk_bytenr, disk_io_size;
10063 struct extent_state *cached_state = NULL;
10064 struct extent_map *em;
10065 bool unlocked = false;
10067 file_accessed(iocb->ki_filp);
10069 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
10071 if (iocb->ki_pos >= inode->vfs_inode.i_size) {
10072 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10075 start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
10077 * We don't know how long the extent containing iocb->ki_pos is, but if
10078 * it's compressed we know that it won't be longer than this.
10080 lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
10083 struct btrfs_ordered_extent *ordered;
10085 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
10086 lockend - start + 1);
10088 goto out_unlock_inode;
10089 lock_extent(io_tree, start, lockend, &cached_state);
10090 ordered = btrfs_lookup_ordered_range(inode, start,
10091 lockend - start + 1);
10094 btrfs_put_ordered_extent(ordered);
10095 unlock_extent(io_tree, start, lockend, &cached_state);
10099 em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
10102 goto out_unlock_extent;
10105 if (em->block_start == EXTENT_MAP_INLINE) {
10106 u64 extent_start = em->start;
10109 * For inline extents we get everything we need out of the
10112 free_extent_map(em);
10114 ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
10115 &cached_state, extent_start,
10116 count, encoded, &unlocked);
10121 * We only want to return up to EOF even if the extent extends beyond
10124 encoded->len = min_t(u64, extent_map_end(em),
10125 inode->vfs_inode.i_size) - iocb->ki_pos;
10126 if (em->block_start == EXTENT_MAP_HOLE ||
10127 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
10128 disk_bytenr = EXTENT_MAP_HOLE;
10129 count = min_t(u64, count, encoded->len);
10130 encoded->len = count;
10131 encoded->unencoded_len = count;
10132 } else if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10133 disk_bytenr = em->block_start;
10135 * Bail if the buffer isn't large enough to return the whole
10136 * compressed extent.
10138 if (em->block_len > count) {
10142 disk_io_size = em->block_len;
10143 count = em->block_len;
10144 encoded->unencoded_len = em->ram_bytes;
10145 encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
10146 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10147 em->compress_type);
10150 encoded->compression = ret;
10152 disk_bytenr = em->block_start + (start - em->start);
10153 if (encoded->len > count)
10154 encoded->len = count;
10156 * Don't read beyond what we locked. This also limits the page
10157 * allocations that we'll do.
10159 disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
10160 count = start + disk_io_size - iocb->ki_pos;
10161 encoded->len = count;
10162 encoded->unencoded_len = count;
10163 disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
10165 free_extent_map(em);
10168 if (disk_bytenr == EXTENT_MAP_HOLE) {
10169 unlock_extent(io_tree, start, lockend, &cached_state);
10170 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10172 ret = iov_iter_zero(count, iter);
10176 ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
10177 &cached_state, disk_bytenr,
10178 disk_io_size, count,
10179 encoded->compression,
10185 iocb->ki_pos += encoded->len;
10187 free_extent_map(em);
10190 unlock_extent(io_tree, start, lockend, &cached_state);
10193 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10197 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
10198 const struct btrfs_ioctl_encoded_io_args *encoded)
10200 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10201 struct btrfs_root *root = inode->root;
10202 struct btrfs_fs_info *fs_info = root->fs_info;
10203 struct extent_io_tree *io_tree = &inode->io_tree;
10204 struct extent_changeset *data_reserved = NULL;
10205 struct extent_state *cached_state = NULL;
10209 u64 num_bytes, ram_bytes, disk_num_bytes;
10210 unsigned long nr_pages, i;
10211 struct page **pages;
10212 struct btrfs_key ins;
10213 bool extent_reserved = false;
10214 struct extent_map *em;
10217 switch (encoded->compression) {
10218 case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
10219 compression = BTRFS_COMPRESS_ZLIB;
10221 case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
10222 compression = BTRFS_COMPRESS_ZSTD;
10224 case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
10225 case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
10226 case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
10227 case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
10228 case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
10229 /* The sector size must match for LZO. */
10230 if (encoded->compression -
10231 BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
10232 fs_info->sectorsize_bits)
10234 compression = BTRFS_COMPRESS_LZO;
10239 if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
10242 orig_count = iov_iter_count(from);
10244 /* The extent size must be sane. */
10245 if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
10246 orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
10250 * The compressed data must be smaller than the decompressed data.
10252 * It's of course possible for data to compress to larger or the same
10253 * size, but the buffered I/O path falls back to no compression for such
10254 * data, and we don't want to break any assumptions by creating these
10257 * Note that this is less strict than the current check we have that the
10258 * compressed data must be at least one sector smaller than the
10259 * decompressed data. We only want to enforce the weaker requirement
10260 * from old kernels that it is at least one byte smaller.
10262 if (orig_count >= encoded->unencoded_len)
10265 /* The extent must start on a sector boundary. */
10266 start = iocb->ki_pos;
10267 if (!IS_ALIGNED(start, fs_info->sectorsize))
10271 * The extent must end on a sector boundary. However, we allow a write
10272 * which ends at or extends i_size to have an unaligned length; we round
10273 * up the extent size and set i_size to the unaligned end.
10275 if (start + encoded->len < inode->vfs_inode.i_size &&
10276 !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
10279 /* Finally, the offset in the unencoded data must be sector-aligned. */
10280 if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
10283 num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10284 ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10285 end = start + num_bytes - 1;
10288 * If the extent cannot be inline, the compressed data on disk must be
10289 * sector-aligned. For convenience, we extend it with zeroes if it
10292 disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10293 nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
10294 pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
10297 for (i = 0; i < nr_pages; i++) {
10298 size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
10301 pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
10306 kaddr = kmap_local_page(pages[i]);
10307 if (copy_from_iter(kaddr, bytes, from) != bytes) {
10308 kunmap_local(kaddr);
10312 if (bytes < PAGE_SIZE)
10313 memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
10314 kunmap_local(kaddr);
10318 struct btrfs_ordered_extent *ordered;
10320 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
10323 ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10324 start >> PAGE_SHIFT,
10325 end >> PAGE_SHIFT);
10328 lock_extent(io_tree, start, end, &cached_state);
10329 ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10331 !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10334 btrfs_put_ordered_extent(ordered);
10335 unlock_extent(io_tree, start, end, &cached_state);
10340 * We don't use the higher-level delalloc space functions because our
10341 * num_bytes and disk_num_bytes are different.
10343 ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10346 ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10348 goto out_free_data_space;
10349 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10352 goto out_qgroup_free_data;
10354 /* Try an inline extent first. */
10355 if (start == 0 && encoded->unencoded_len == encoded->len &&
10356 encoded->unencoded_offset == 0) {
10357 ret = cow_file_range_inline(inode, encoded->len, orig_count,
10358 compression, pages, true);
10362 goto out_delalloc_release;
10366 ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10367 disk_num_bytes, 0, 0, &ins, 1, 1);
10369 goto out_delalloc_release;
10370 extent_reserved = true;
10372 em = create_io_em(inode, start, num_bytes,
10373 start - encoded->unencoded_offset, ins.objectid,
10374 ins.offset, ins.offset, ram_bytes, compression,
10375 BTRFS_ORDERED_COMPRESSED);
10378 goto out_free_reserved;
10380 free_extent_map(em);
10382 ret = btrfs_add_ordered_extent(inode, start, num_bytes, ram_bytes,
10383 ins.objectid, ins.offset,
10384 encoded->unencoded_offset,
10385 (1 << BTRFS_ORDERED_ENCODED) |
10386 (1 << BTRFS_ORDERED_COMPRESSED),
10389 btrfs_drop_extent_map_range(inode, start, end, false);
10390 goto out_free_reserved;
10392 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10394 if (start + encoded->len > inode->vfs_inode.i_size)
10395 i_size_write(&inode->vfs_inode, start + encoded->len);
10397 unlock_extent(io_tree, start, end, &cached_state);
10399 btrfs_delalloc_release_extents(inode, num_bytes);
10401 if (btrfs_submit_compressed_write(inode, start, num_bytes, ins.objectid,
10402 ins.offset, pages, nr_pages, 0, NULL,
10404 btrfs_writepage_endio_finish_ordered(inode, pages[0], start, end, 0);
10412 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10413 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
10414 out_delalloc_release:
10415 btrfs_delalloc_release_extents(inode, num_bytes);
10416 btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10417 out_qgroup_free_data:
10419 btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes);
10420 out_free_data_space:
10422 * If btrfs_reserve_extent() succeeded, then we already decremented
10425 if (!extent_reserved)
10426 btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
10428 unlock_extent(io_tree, start, end, &cached_state);
10430 for (i = 0; i < nr_pages; i++) {
10432 __free_page(pages[i]);
10437 iocb->ki_pos += encoded->len;
10443 * Add an entry indicating a block group or device which is pinned by a
10444 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10445 * negative errno on failure.
10447 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10448 bool is_block_group)
10450 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10451 struct btrfs_swapfile_pin *sp, *entry;
10452 struct rb_node **p;
10453 struct rb_node *parent = NULL;
10455 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10460 sp->is_block_group = is_block_group;
10461 sp->bg_extent_count = 1;
10463 spin_lock(&fs_info->swapfile_pins_lock);
10464 p = &fs_info->swapfile_pins.rb_node;
10467 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10468 if (sp->ptr < entry->ptr ||
10469 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10470 p = &(*p)->rb_left;
10471 } else if (sp->ptr > entry->ptr ||
10472 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10473 p = &(*p)->rb_right;
10475 if (is_block_group)
10476 entry->bg_extent_count++;
10477 spin_unlock(&fs_info->swapfile_pins_lock);
10482 rb_link_node(&sp->node, parent, p);
10483 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10484 spin_unlock(&fs_info->swapfile_pins_lock);
10488 /* Free all of the entries pinned by this swapfile. */
10489 static void btrfs_free_swapfile_pins(struct inode *inode)
10491 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10492 struct btrfs_swapfile_pin *sp;
10493 struct rb_node *node, *next;
10495 spin_lock(&fs_info->swapfile_pins_lock);
10496 node = rb_first(&fs_info->swapfile_pins);
10498 next = rb_next(node);
10499 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10500 if (sp->inode == inode) {
10501 rb_erase(&sp->node, &fs_info->swapfile_pins);
10502 if (sp->is_block_group) {
10503 btrfs_dec_block_group_swap_extents(sp->ptr,
10504 sp->bg_extent_count);
10505 btrfs_put_block_group(sp->ptr);
10511 spin_unlock(&fs_info->swapfile_pins_lock);
10514 struct btrfs_swap_info {
10520 unsigned long nr_pages;
10524 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10525 struct btrfs_swap_info *bsi)
10527 unsigned long nr_pages;
10528 unsigned long max_pages;
10529 u64 first_ppage, first_ppage_reported, next_ppage;
10533 * Our swapfile may have had its size extended after the swap header was
10534 * written. In that case activating the swapfile should not go beyond
10535 * the max size set in the swap header.
10537 if (bsi->nr_pages >= sis->max)
10540 max_pages = sis->max - bsi->nr_pages;
10541 first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
10542 next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
10544 if (first_ppage >= next_ppage)
10546 nr_pages = next_ppage - first_ppage;
10547 nr_pages = min(nr_pages, max_pages);
10549 first_ppage_reported = first_ppage;
10550 if (bsi->start == 0)
10551 first_ppage_reported++;
10552 if (bsi->lowest_ppage > first_ppage_reported)
10553 bsi->lowest_ppage = first_ppage_reported;
10554 if (bsi->highest_ppage < (next_ppage - 1))
10555 bsi->highest_ppage = next_ppage - 1;
10557 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10560 bsi->nr_extents += ret;
10561 bsi->nr_pages += nr_pages;
10565 static void btrfs_swap_deactivate(struct file *file)
10567 struct inode *inode = file_inode(file);
10569 btrfs_free_swapfile_pins(inode);
10570 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10573 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10576 struct inode *inode = file_inode(file);
10577 struct btrfs_root *root = BTRFS_I(inode)->root;
10578 struct btrfs_fs_info *fs_info = root->fs_info;
10579 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10580 struct extent_state *cached_state = NULL;
10581 struct extent_map *em = NULL;
10582 struct btrfs_device *device = NULL;
10583 struct btrfs_swap_info bsi = {
10584 .lowest_ppage = (sector_t)-1ULL,
10591 * If the swap file was just created, make sure delalloc is done. If the
10592 * file changes again after this, the user is doing something stupid and
10593 * we don't really care.
10595 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10600 * The inode is locked, so these flags won't change after we check them.
10602 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10603 btrfs_warn(fs_info, "swapfile must not be compressed");
10606 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10607 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10610 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10611 btrfs_warn(fs_info, "swapfile must not be checksummed");
10616 * Balance or device remove/replace/resize can move stuff around from
10617 * under us. The exclop protection makes sure they aren't running/won't
10618 * run concurrently while we are mapping the swap extents, and
10619 * fs_info->swapfile_pins prevents them from running while the swap
10620 * file is active and moving the extents. Note that this also prevents
10621 * a concurrent device add which isn't actually necessary, but it's not
10622 * really worth the trouble to allow it.
10624 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10625 btrfs_warn(fs_info,
10626 "cannot activate swapfile while exclusive operation is running");
10631 * Prevent snapshot creation while we are activating the swap file.
10632 * We do not want to race with snapshot creation. If snapshot creation
10633 * already started before we bumped nr_swapfiles from 0 to 1 and
10634 * completes before the first write into the swap file after it is
10635 * activated, than that write would fallback to COW.
10637 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10638 btrfs_exclop_finish(fs_info);
10639 btrfs_warn(fs_info,
10640 "cannot activate swapfile because snapshot creation is in progress");
10644 * Snapshots can create extents which require COW even if NODATACOW is
10645 * set. We use this counter to prevent snapshots. We must increment it
10646 * before walking the extents because we don't want a concurrent
10647 * snapshot to run after we've already checked the extents.
10649 * It is possible that subvolume is marked for deletion but still not
10650 * removed yet. To prevent this race, we check the root status before
10651 * activating the swapfile.
10653 spin_lock(&root->root_item_lock);
10654 if (btrfs_root_dead(root)) {
10655 spin_unlock(&root->root_item_lock);
10657 btrfs_exclop_finish(fs_info);
10658 btrfs_warn(fs_info,
10659 "cannot activate swapfile because subvolume %llu is being deleted",
10660 root->root_key.objectid);
10663 atomic_inc(&root->nr_swapfiles);
10664 spin_unlock(&root->root_item_lock);
10666 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10668 lock_extent(io_tree, 0, isize - 1, &cached_state);
10670 while (start < isize) {
10671 u64 logical_block_start, physical_block_start;
10672 struct btrfs_block_group *bg;
10673 u64 len = isize - start;
10675 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10681 if (em->block_start == EXTENT_MAP_HOLE) {
10682 btrfs_warn(fs_info, "swapfile must not have holes");
10686 if (em->block_start == EXTENT_MAP_INLINE) {
10688 * It's unlikely we'll ever actually find ourselves
10689 * here, as a file small enough to fit inline won't be
10690 * big enough to store more than the swap header, but in
10691 * case something changes in the future, let's catch it
10692 * here rather than later.
10694 btrfs_warn(fs_info, "swapfile must not be inline");
10698 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10699 btrfs_warn(fs_info, "swapfile must not be compressed");
10704 logical_block_start = em->block_start + (start - em->start);
10705 len = min(len, em->len - (start - em->start));
10706 free_extent_map(em);
10709 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, false, true);
10715 btrfs_warn(fs_info,
10716 "swapfile must not be copy-on-write");
10721 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10727 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10728 btrfs_warn(fs_info,
10729 "swapfile must have single data profile");
10734 if (device == NULL) {
10735 device = em->map_lookup->stripes[0].dev;
10736 ret = btrfs_add_swapfile_pin(inode, device, false);
10741 } else if (device != em->map_lookup->stripes[0].dev) {
10742 btrfs_warn(fs_info, "swapfile must be on one device");
10747 physical_block_start = (em->map_lookup->stripes[0].physical +
10748 (logical_block_start - em->start));
10749 len = min(len, em->len - (logical_block_start - em->start));
10750 free_extent_map(em);
10753 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10755 btrfs_warn(fs_info,
10756 "could not find block group containing swapfile");
10761 if (!btrfs_inc_block_group_swap_extents(bg)) {
10762 btrfs_warn(fs_info,
10763 "block group for swapfile at %llu is read-only%s",
10765 atomic_read(&fs_info->scrubs_running) ?
10766 " (scrub running)" : "");
10767 btrfs_put_block_group(bg);
10772 ret = btrfs_add_swapfile_pin(inode, bg, true);
10774 btrfs_put_block_group(bg);
10781 if (bsi.block_len &&
10782 bsi.block_start + bsi.block_len == physical_block_start) {
10783 bsi.block_len += len;
10785 if (bsi.block_len) {
10786 ret = btrfs_add_swap_extent(sis, &bsi);
10791 bsi.block_start = physical_block_start;
10792 bsi.block_len = len;
10799 ret = btrfs_add_swap_extent(sis, &bsi);
10802 if (!IS_ERR_OR_NULL(em))
10803 free_extent_map(em);
10805 unlock_extent(io_tree, 0, isize - 1, &cached_state);
10808 btrfs_swap_deactivate(file);
10810 btrfs_drew_write_unlock(&root->snapshot_lock);
10812 btrfs_exclop_finish(fs_info);
10818 sis->bdev = device->bdev;
10819 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10820 sis->max = bsi.nr_pages;
10821 sis->pages = bsi.nr_pages - 1;
10822 sis->highest_bit = bsi.nr_pages - 1;
10823 return bsi.nr_extents;
10826 static void btrfs_swap_deactivate(struct file *file)
10830 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10833 return -EOPNOTSUPP;
10838 * Update the number of bytes used in the VFS' inode. When we replace extents in
10839 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10840 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10841 * always get a correct value.
10843 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10844 const u64 add_bytes,
10845 const u64 del_bytes)
10847 if (add_bytes == del_bytes)
10850 spin_lock(&inode->lock);
10852 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10854 inode_add_bytes(&inode->vfs_inode, add_bytes);
10855 spin_unlock(&inode->lock);
10859 * Verify that there are no ordered extents for a given file range.
10861 * @inode: The target inode.
10862 * @start: Start offset of the file range, should be sector size aligned.
10863 * @end: End offset (inclusive) of the file range, its value +1 should be
10864 * sector size aligned.
10866 * This should typically be used for cases where we locked an inode's VFS lock in
10867 * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
10868 * we have flushed all delalloc in the range, we have waited for all ordered
10869 * extents in the range to complete and finally we have locked the file range in
10870 * the inode's io_tree.
10872 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
10874 struct btrfs_root *root = inode->root;
10875 struct btrfs_ordered_extent *ordered;
10877 if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
10880 ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
10882 btrfs_err(root->fs_info,
10883 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
10884 start, end, btrfs_ino(inode), root->root_key.objectid,
10885 ordered->file_offset,
10886 ordered->file_offset + ordered->num_bytes - 1);
10887 btrfs_put_ordered_extent(ordered);
10890 ASSERT(ordered == NULL);
10893 static const struct inode_operations btrfs_dir_inode_operations = {
10894 .getattr = btrfs_getattr,
10895 .lookup = btrfs_lookup,
10896 .create = btrfs_create,
10897 .unlink = btrfs_unlink,
10898 .link = btrfs_link,
10899 .mkdir = btrfs_mkdir,
10900 .rmdir = btrfs_rmdir,
10901 .rename = btrfs_rename2,
10902 .symlink = btrfs_symlink,
10903 .setattr = btrfs_setattr,
10904 .mknod = btrfs_mknod,
10905 .listxattr = btrfs_listxattr,
10906 .permission = btrfs_permission,
10907 .get_inode_acl = btrfs_get_acl,
10908 .set_acl = btrfs_set_acl,
10909 .update_time = btrfs_update_time,
10910 .tmpfile = btrfs_tmpfile,
10911 .fileattr_get = btrfs_fileattr_get,
10912 .fileattr_set = btrfs_fileattr_set,
10915 static const struct file_operations btrfs_dir_file_operations = {
10916 .llseek = generic_file_llseek,
10917 .read = generic_read_dir,
10918 .iterate_shared = btrfs_real_readdir,
10919 .open = btrfs_opendir,
10920 .unlocked_ioctl = btrfs_ioctl,
10921 #ifdef CONFIG_COMPAT
10922 .compat_ioctl = btrfs_compat_ioctl,
10924 .release = btrfs_release_file,
10925 .fsync = btrfs_sync_file,
10929 * btrfs doesn't support the bmap operation because swapfiles
10930 * use bmap to make a mapping of extents in the file. They assume
10931 * these extents won't change over the life of the file and they
10932 * use the bmap result to do IO directly to the drive.
10934 * the btrfs bmap call would return logical addresses that aren't
10935 * suitable for IO and they also will change frequently as COW
10936 * operations happen. So, swapfile + btrfs == corruption.
10938 * For now we're avoiding this by dropping bmap.
10940 static const struct address_space_operations btrfs_aops = {
10941 .read_folio = btrfs_read_folio,
10942 .writepages = btrfs_writepages,
10943 .readahead = btrfs_readahead,
10944 .direct_IO = noop_direct_IO,
10945 .invalidate_folio = btrfs_invalidate_folio,
10946 .release_folio = btrfs_release_folio,
10947 .migrate_folio = btrfs_migrate_folio,
10948 .dirty_folio = filemap_dirty_folio,
10949 .error_remove_page = generic_error_remove_page,
10950 .swap_activate = btrfs_swap_activate,
10951 .swap_deactivate = btrfs_swap_deactivate,
10954 static const struct inode_operations btrfs_file_inode_operations = {
10955 .getattr = btrfs_getattr,
10956 .setattr = btrfs_setattr,
10957 .listxattr = btrfs_listxattr,
10958 .permission = btrfs_permission,
10959 .fiemap = btrfs_fiemap,
10960 .get_inode_acl = btrfs_get_acl,
10961 .set_acl = btrfs_set_acl,
10962 .update_time = btrfs_update_time,
10963 .fileattr_get = btrfs_fileattr_get,
10964 .fileattr_set = btrfs_fileattr_set,
10966 static const struct inode_operations btrfs_special_inode_operations = {
10967 .getattr = btrfs_getattr,
10968 .setattr = btrfs_setattr,
10969 .permission = btrfs_permission,
10970 .listxattr = btrfs_listxattr,
10971 .get_inode_acl = btrfs_get_acl,
10972 .set_acl = btrfs_set_acl,
10973 .update_time = btrfs_update_time,
10975 static const struct inode_operations btrfs_symlink_inode_operations = {
10976 .get_link = page_get_link,
10977 .getattr = btrfs_getattr,
10978 .setattr = btrfs_setattr,
10979 .permission = btrfs_permission,
10980 .listxattr = btrfs_listxattr,
10981 .update_time = btrfs_update_time,
10984 const struct dentry_operations btrfs_dentry_operations = {
10985 .d_delete = btrfs_dentry_delete,