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 struct btrfs_iget_args {
61 struct btrfs_root *root;
64 struct btrfs_dio_data {
66 struct extent_changeset *data_reserved;
67 bool data_space_reserved;
71 struct btrfs_dio_private {
75 * Since DIO can use anonymous page, we cannot use page_offset() to
76 * grab the file offset, thus need a dedicated member for file offset.
79 /* Used for bio::bi_size */
83 * References to this structure. There is one reference per in-flight
84 * bio plus one while we're still setting up.
88 /* Array of checksums */
91 /* This must be last */
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;
110 struct kmem_cache *btrfs_trans_handle_cachep;
111 struct kmem_cache *btrfs_path_cachep;
112 struct kmem_cache *btrfs_free_space_cachep;
113 struct kmem_cache *btrfs_free_space_bitmap_cachep;
115 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
116 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
117 static noinline int cow_file_range(struct btrfs_inode *inode,
118 struct page *locked_page,
119 u64 start, u64 end, int *page_started,
120 unsigned long *nr_written, int unlock,
122 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
123 u64 len, u64 orig_start, u64 block_start,
124 u64 block_len, u64 orig_block_len,
125 u64 ram_bytes, int compress_type,
129 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
131 * ilock_flags can have the following bit set:
133 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
134 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
136 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
138 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
140 if (ilock_flags & BTRFS_ILOCK_SHARED) {
141 if (ilock_flags & BTRFS_ILOCK_TRY) {
142 if (!inode_trylock_shared(inode))
147 inode_lock_shared(inode);
149 if (ilock_flags & BTRFS_ILOCK_TRY) {
150 if (!inode_trylock(inode))
157 if (ilock_flags & BTRFS_ILOCK_MMAP)
158 down_write(&BTRFS_I(inode)->i_mmap_lock);
163 * btrfs_inode_unlock - unock inode i_rwsem
165 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
166 * to decide whether the lock acquired is shared or exclusive.
168 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
170 if (ilock_flags & BTRFS_ILOCK_MMAP)
171 up_write(&BTRFS_I(inode)->i_mmap_lock);
172 if (ilock_flags & BTRFS_ILOCK_SHARED)
173 inode_unlock_shared(inode);
179 * Cleanup all submitted ordered extents in specified range to handle errors
180 * from the btrfs_run_delalloc_range() callback.
182 * NOTE: caller must ensure that when an error happens, it can not call
183 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
184 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
185 * to be released, which we want to happen only when finishing the ordered
186 * extent (btrfs_finish_ordered_io()).
188 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
189 struct page *locked_page,
190 u64 offset, u64 bytes)
192 unsigned long index = offset >> PAGE_SHIFT;
193 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
194 u64 page_start, page_end;
198 page_start = page_offset(locked_page);
199 page_end = page_start + PAGE_SIZE - 1;
202 while (index <= end_index) {
204 * For locked page, we will call end_extent_writepage() on it
205 * in run_delalloc_range() for the error handling. That
206 * end_extent_writepage() function will call
207 * btrfs_mark_ordered_io_finished() to clear page Ordered and
208 * run the ordered extent accounting.
210 * Here we can't just clear the Ordered bit, or
211 * btrfs_mark_ordered_io_finished() would skip the accounting
212 * for the page range, and the ordered extent will never finish.
214 if (locked_page && index == (page_start >> PAGE_SHIFT)) {
218 page = find_get_page(inode->vfs_inode.i_mapping, index);
224 * Here we just clear all Ordered bits for every page in the
225 * range, then btrfs_mark_ordered_io_finished() will handle
226 * the ordered extent accounting for the range.
228 btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
234 /* The locked page covers the full range, nothing needs to be done */
235 if (bytes + offset <= page_start + PAGE_SIZE)
238 * In case this page belongs to the delalloc range being
239 * instantiated then skip it, since the first page of a range is
240 * going to be properly cleaned up by the caller of
243 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
244 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
245 offset = page_offset(locked_page) + PAGE_SIZE;
249 return btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes, false);
252 static int btrfs_dirty_inode(struct inode *inode);
254 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
255 struct btrfs_new_inode_args *args)
259 if (args->default_acl) {
260 err = __btrfs_set_acl(trans, args->inode, args->default_acl,
266 err = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
270 if (!args->default_acl && !args->acl)
271 cache_no_acl(args->inode);
272 return btrfs_xattr_security_init(trans, args->inode, args->dir,
273 &args->dentry->d_name);
277 * this does all the hard work for inserting an inline extent into
278 * the btree. The caller should have done a btrfs_drop_extents so that
279 * no overlapping inline items exist in the btree
281 static int insert_inline_extent(struct btrfs_trans_handle *trans,
282 struct btrfs_path *path,
283 struct btrfs_inode *inode, bool extent_inserted,
284 size_t size, size_t compressed_size,
286 struct page **compressed_pages,
289 struct btrfs_root *root = inode->root;
290 struct extent_buffer *leaf;
291 struct page *page = NULL;
294 struct btrfs_file_extent_item *ei;
296 size_t cur_size = size;
299 ASSERT((compressed_size > 0 && compressed_pages) ||
300 (compressed_size == 0 && !compressed_pages));
302 if (compressed_size && compressed_pages)
303 cur_size = compressed_size;
305 if (!extent_inserted) {
306 struct btrfs_key key;
309 key.objectid = btrfs_ino(inode);
311 key.type = BTRFS_EXTENT_DATA_KEY;
313 datasize = btrfs_file_extent_calc_inline_size(cur_size);
314 ret = btrfs_insert_empty_item(trans, root, path, &key,
319 leaf = path->nodes[0];
320 ei = btrfs_item_ptr(leaf, path->slots[0],
321 struct btrfs_file_extent_item);
322 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
323 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
324 btrfs_set_file_extent_encryption(leaf, ei, 0);
325 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
326 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
327 ptr = btrfs_file_extent_inline_start(ei);
329 if (compress_type != BTRFS_COMPRESS_NONE) {
332 while (compressed_size > 0) {
333 cpage = compressed_pages[i];
334 cur_size = min_t(unsigned long, compressed_size,
337 kaddr = kmap_local_page(cpage);
338 write_extent_buffer(leaf, kaddr, ptr, cur_size);
343 compressed_size -= cur_size;
345 btrfs_set_file_extent_compression(leaf, ei,
348 page = find_get_page(inode->vfs_inode.i_mapping, 0);
349 btrfs_set_file_extent_compression(leaf, ei, 0);
350 kaddr = kmap_local_page(page);
351 write_extent_buffer(leaf, kaddr, ptr, size);
355 btrfs_mark_buffer_dirty(leaf);
356 btrfs_release_path(path);
359 * We align size to sectorsize for inline extents just for simplicity
362 ret = btrfs_inode_set_file_extent_range(inode, 0,
363 ALIGN(size, root->fs_info->sectorsize));
368 * We're an inline extent, so nobody can extend the file past i_size
369 * without locking a page we already have locked.
371 * We must do any i_size and inode updates before we unlock the pages.
372 * Otherwise we could end up racing with unlink.
374 i_size = i_size_read(&inode->vfs_inode);
375 if (update_i_size && size > i_size) {
376 i_size_write(&inode->vfs_inode, size);
379 inode->disk_i_size = i_size;
387 * conditionally insert an inline extent into the file. This
388 * does the checks required to make sure the data is small enough
389 * to fit as an inline extent.
391 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 size,
392 size_t compressed_size,
394 struct page **compressed_pages,
397 struct btrfs_drop_extents_args drop_args = { 0 };
398 struct btrfs_root *root = inode->root;
399 struct btrfs_fs_info *fs_info = root->fs_info;
400 struct btrfs_trans_handle *trans;
401 u64 data_len = (compressed_size ?: size);
403 struct btrfs_path *path;
406 * We can create an inline extent if it ends at or beyond the current
407 * i_size, is no larger than a sector (decompressed), and the (possibly
408 * compressed) data fits in a leaf and the configured maximum inline
411 if (size < i_size_read(&inode->vfs_inode) ||
412 size > fs_info->sectorsize ||
413 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
414 data_len > fs_info->max_inline)
417 path = btrfs_alloc_path();
421 trans = btrfs_join_transaction(root);
423 btrfs_free_path(path);
424 return PTR_ERR(trans);
426 trans->block_rsv = &inode->block_rsv;
428 drop_args.path = path;
430 drop_args.end = fs_info->sectorsize;
431 drop_args.drop_cache = true;
432 drop_args.replace_extent = true;
433 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
434 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
436 btrfs_abort_transaction(trans, ret);
440 ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
441 size, compressed_size, compress_type,
442 compressed_pages, update_i_size);
443 if (ret && ret != -ENOSPC) {
444 btrfs_abort_transaction(trans, ret);
446 } else if (ret == -ENOSPC) {
451 btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
452 ret = btrfs_update_inode(trans, root, inode);
453 if (ret && ret != -ENOSPC) {
454 btrfs_abort_transaction(trans, ret);
456 } else if (ret == -ENOSPC) {
461 btrfs_set_inode_full_sync(inode);
464 * Don't forget to free the reserved space, as for inlined extent
465 * it won't count as data extent, free them directly here.
466 * And at reserve time, it's always aligned to page size, so
467 * just free one page here.
469 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
470 btrfs_free_path(path);
471 btrfs_end_transaction(trans);
475 struct async_extent {
480 unsigned long nr_pages;
482 struct list_head list;
487 struct page *locked_page;
490 blk_opf_t write_flags;
491 struct list_head extents;
492 struct cgroup_subsys_state *blkcg_css;
493 struct btrfs_work work;
494 struct async_cow *async_cow;
499 struct async_chunk chunks[];
502 static noinline int add_async_extent(struct async_chunk *cow,
503 u64 start, u64 ram_size,
506 unsigned long nr_pages,
509 struct async_extent *async_extent;
511 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
512 BUG_ON(!async_extent); /* -ENOMEM */
513 async_extent->start = start;
514 async_extent->ram_size = ram_size;
515 async_extent->compressed_size = compressed_size;
516 async_extent->pages = pages;
517 async_extent->nr_pages = nr_pages;
518 async_extent->compress_type = compress_type;
519 list_add_tail(&async_extent->list, &cow->extents);
524 * Check if the inode needs to be submitted to compression, based on mount
525 * options, defragmentation, properties or heuristics.
527 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
530 struct btrfs_fs_info *fs_info = inode->root->fs_info;
532 if (!btrfs_inode_can_compress(inode)) {
533 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
534 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
539 * Special check for subpage.
541 * We lock the full page then run each delalloc range in the page, thus
542 * for the following case, we will hit some subpage specific corner case:
545 * | |///////| |///////|
548 * In above case, both range A and range B will try to unlock the full
549 * page [0, 64K), causing the one finished later will have page
550 * unlocked already, triggering various page lock requirement BUG_ON()s.
552 * So here we add an artificial limit that subpage compression can only
553 * if the range is fully page aligned.
555 * In theory we only need to ensure the first page is fully covered, but
556 * the tailing partial page will be locked until the full compression
557 * finishes, delaying the write of other range.
559 * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
560 * first to prevent any submitted async extent to unlock the full page.
561 * By this, we can ensure for subpage case that only the last async_cow
562 * will unlock the full page.
564 if (fs_info->sectorsize < PAGE_SIZE) {
565 if (!PAGE_ALIGNED(start) ||
566 !PAGE_ALIGNED(end + 1))
571 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
574 if (inode->defrag_compress)
576 /* bad compression ratios */
577 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
579 if (btrfs_test_opt(fs_info, COMPRESS) ||
580 inode->flags & BTRFS_INODE_COMPRESS ||
581 inode->prop_compress)
582 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
586 static inline void inode_should_defrag(struct btrfs_inode *inode,
587 u64 start, u64 end, u64 num_bytes, u32 small_write)
589 /* If this is a small write inside eof, kick off a defrag */
590 if (num_bytes < small_write &&
591 (start > 0 || end + 1 < inode->disk_i_size))
592 btrfs_add_inode_defrag(NULL, inode, small_write);
596 * we create compressed extents in two phases. The first
597 * phase compresses a range of pages that have already been
598 * locked (both pages and state bits are locked).
600 * This is done inside an ordered work queue, and the compression
601 * is spread across many cpus. The actual IO submission is step
602 * two, and the ordered work queue takes care of making sure that
603 * happens in the same order things were put onto the queue by
604 * writepages and friends.
606 * If this code finds it can't get good compression, it puts an
607 * entry onto the work queue to write the uncompressed bytes. This
608 * makes sure that both compressed inodes and uncompressed inodes
609 * are written in the same order that the flusher thread sent them
612 static noinline int compress_file_range(struct async_chunk *async_chunk)
614 struct inode *inode = async_chunk->inode;
615 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
616 u64 blocksize = fs_info->sectorsize;
617 u64 start = async_chunk->start;
618 u64 end = async_chunk->end;
622 struct page **pages = NULL;
623 unsigned long nr_pages;
624 unsigned long total_compressed = 0;
625 unsigned long total_in = 0;
628 int compress_type = fs_info->compress_type;
629 int compressed_extents = 0;
632 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
636 * We need to save i_size before now because it could change in between
637 * us evaluating the size and assigning it. This is because we lock and
638 * unlock the page in truncate and fallocate, and then modify the i_size
641 * The barriers are to emulate READ_ONCE, remove that once i_size_read
645 i_size = i_size_read(inode);
647 actual_end = min_t(u64, i_size, end + 1);
650 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
651 nr_pages = min_t(unsigned long, nr_pages,
652 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
655 * we don't want to send crud past the end of i_size through
656 * compression, that's just a waste of CPU time. So, if the
657 * end of the file is before the start of our current
658 * requested range of bytes, we bail out to the uncompressed
659 * cleanup code that can deal with all of this.
661 * It isn't really the fastest way to fix things, but this is a
662 * very uncommon corner.
664 if (actual_end <= start)
665 goto cleanup_and_bail_uncompressed;
667 total_compressed = actual_end - start;
670 * Skip compression for a small file range(<=blocksize) that
671 * isn't an inline extent, since it doesn't save disk space at all.
673 if (total_compressed <= blocksize &&
674 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
675 goto cleanup_and_bail_uncompressed;
678 * For subpage case, we require full page alignment for the sector
680 * Thus we must also check against @actual_end, not just @end.
682 if (blocksize < PAGE_SIZE) {
683 if (!PAGE_ALIGNED(start) ||
684 !PAGE_ALIGNED(round_up(actual_end, blocksize)))
685 goto cleanup_and_bail_uncompressed;
688 total_compressed = min_t(unsigned long, total_compressed,
689 BTRFS_MAX_UNCOMPRESSED);
694 * we do compression for mount -o compress and when the
695 * inode has not been flagged as nocompress. This flag can
696 * change at any time if we discover bad compression ratios.
698 if (inode_need_compress(BTRFS_I(inode), start, end)) {
700 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
702 /* just bail out to the uncompressed code */
707 if (BTRFS_I(inode)->defrag_compress)
708 compress_type = BTRFS_I(inode)->defrag_compress;
709 else if (BTRFS_I(inode)->prop_compress)
710 compress_type = BTRFS_I(inode)->prop_compress;
713 * we need to call clear_page_dirty_for_io on each
714 * page in the range. Otherwise applications with the file
715 * mmap'd can wander in and change the page contents while
716 * we are compressing them.
718 * If the compression fails for any reason, we set the pages
719 * dirty again later on.
721 * Note that the remaining part is redirtied, the start pointer
722 * has moved, the end is the original one.
725 extent_range_clear_dirty_for_io(inode, start, end);
729 /* Compression level is applied here and only here */
730 ret = btrfs_compress_pages(
731 compress_type | (fs_info->compress_level << 4),
732 inode->i_mapping, start,
739 unsigned long offset = offset_in_page(total_compressed);
740 struct page *page = pages[nr_pages - 1];
742 /* zero the tail end of the last page, we might be
743 * sending it down to disk
746 memzero_page(page, offset, PAGE_SIZE - offset);
752 * Check cow_file_range() for why we don't even try to create inline
753 * extent for subpage case.
755 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
756 /* lets try to make an inline extent */
757 if (ret || total_in < actual_end) {
758 /* we didn't compress the entire range, try
759 * to make an uncompressed inline extent.
761 ret = cow_file_range_inline(BTRFS_I(inode), actual_end,
762 0, BTRFS_COMPRESS_NONE,
765 /* try making a compressed inline extent */
766 ret = cow_file_range_inline(BTRFS_I(inode), actual_end,
768 compress_type, pages,
772 unsigned long clear_flags = EXTENT_DELALLOC |
773 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
774 EXTENT_DO_ACCOUNTING;
775 unsigned long page_error_op;
777 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
780 * inline extent creation worked or returned error,
781 * we don't need to create any more async work items.
782 * Unlock and free up our temp pages.
784 * We use DO_ACCOUNTING here because we need the
785 * delalloc_release_metadata to be done _after_ we drop
786 * our outstanding extent for clearing delalloc for this
789 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
793 PAGE_START_WRITEBACK |
798 * Ensure we only free the compressed pages if we have
799 * them allocated, as we can still reach here with
800 * inode_need_compress() == false.
803 for (i = 0; i < nr_pages; i++) {
804 WARN_ON(pages[i]->mapping);
815 * we aren't doing an inline extent round the compressed size
816 * up to a block size boundary so the allocator does sane
819 total_compressed = ALIGN(total_compressed, blocksize);
822 * one last check to make sure the compression is really a
823 * win, compare the page count read with the blocks on disk,
824 * compression must free at least one sector size
826 total_in = round_up(total_in, fs_info->sectorsize);
827 if (total_compressed + blocksize <= total_in) {
828 compressed_extents++;
831 * The async work queues will take care of doing actual
832 * allocation on disk for these compressed pages, and
833 * will submit them to the elevator.
835 add_async_extent(async_chunk, start, total_in,
836 total_compressed, pages, nr_pages,
839 if (start + total_in < end) {
845 return compressed_extents;
850 * the compression code ran but failed to make things smaller,
851 * free any pages it allocated and our page pointer array
853 for (i = 0; i < nr_pages; i++) {
854 WARN_ON(pages[i]->mapping);
859 total_compressed = 0;
862 /* flag the file so we don't compress in the future */
863 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
864 !(BTRFS_I(inode)->prop_compress)) {
865 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
868 cleanup_and_bail_uncompressed:
870 * No compression, but we still need to write the pages in the file
871 * we've been given so far. redirty the locked page if it corresponds
872 * to our extent and set things up for the async work queue to run
873 * cow_file_range to do the normal delalloc dance.
875 if (async_chunk->locked_page &&
876 (page_offset(async_chunk->locked_page) >= start &&
877 page_offset(async_chunk->locked_page)) <= end) {
878 __set_page_dirty_nobuffers(async_chunk->locked_page);
879 /* unlocked later on in the async handlers */
883 extent_range_redirty_for_io(inode, start, end);
884 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
885 BTRFS_COMPRESS_NONE);
886 compressed_extents++;
888 return compressed_extents;
891 static void free_async_extent_pages(struct async_extent *async_extent)
895 if (!async_extent->pages)
898 for (i = 0; i < async_extent->nr_pages; i++) {
899 WARN_ON(async_extent->pages[i]->mapping);
900 put_page(async_extent->pages[i]);
902 kfree(async_extent->pages);
903 async_extent->nr_pages = 0;
904 async_extent->pages = NULL;
907 static int submit_uncompressed_range(struct btrfs_inode *inode,
908 struct async_extent *async_extent,
909 struct page *locked_page)
911 u64 start = async_extent->start;
912 u64 end = async_extent->start + async_extent->ram_size - 1;
913 unsigned long nr_written = 0;
914 int page_started = 0;
918 * Call cow_file_range() to run the delalloc range directly, since we
919 * won't go to NOCOW or async path again.
921 * Also we call cow_file_range() with @unlock_page == 0, so that we
922 * can directly submit them without interruption.
924 ret = cow_file_range(inode, locked_page, start, end, &page_started,
925 &nr_written, 0, NULL);
926 /* Inline extent inserted, page gets unlocked and everything is done */
932 btrfs_cleanup_ordered_extents(inode, locked_page, start, end - start + 1);
934 const u64 page_start = page_offset(locked_page);
935 const u64 page_end = page_start + PAGE_SIZE - 1;
937 btrfs_page_set_error(inode->root->fs_info, locked_page,
938 page_start, PAGE_SIZE);
939 set_page_writeback(locked_page);
940 end_page_writeback(locked_page);
941 end_extent_writepage(locked_page, ret, page_start, page_end);
942 unlock_page(locked_page);
947 ret = extent_write_locked_range(&inode->vfs_inode, start, end);
948 /* All pages will be unlocked, including @locked_page */
954 static int submit_one_async_extent(struct btrfs_inode *inode,
955 struct async_chunk *async_chunk,
956 struct async_extent *async_extent,
959 struct extent_io_tree *io_tree = &inode->io_tree;
960 struct btrfs_root *root = inode->root;
961 struct btrfs_fs_info *fs_info = root->fs_info;
962 struct btrfs_key ins;
963 struct page *locked_page = NULL;
964 struct extent_map *em;
966 u64 start = async_extent->start;
967 u64 end = async_extent->start + async_extent->ram_size - 1;
970 * If async_chunk->locked_page is in the async_extent range, we need to
973 if (async_chunk->locked_page) {
974 u64 locked_page_start = page_offset(async_chunk->locked_page);
975 u64 locked_page_end = locked_page_start + PAGE_SIZE - 1;
977 if (!(start >= locked_page_end || end <= locked_page_start))
978 locked_page = async_chunk->locked_page;
980 lock_extent(io_tree, start, end, NULL);
982 /* We have fall back to uncompressed write */
983 if (!async_extent->pages)
984 return submit_uncompressed_range(inode, async_extent, locked_page);
986 ret = btrfs_reserve_extent(root, async_extent->ram_size,
987 async_extent->compressed_size,
988 async_extent->compressed_size,
989 0, *alloc_hint, &ins, 1, 1);
991 free_async_extent_pages(async_extent);
993 * Here we used to try again by going back to non-compressed
994 * path for ENOSPC. But we can't reserve space even for
995 * compressed size, how could it work for uncompressed size
996 * which requires larger size? So here we directly go error
1002 /* Here we're doing allocation and writeback of the compressed pages */
1003 em = create_io_em(inode, start,
1004 async_extent->ram_size, /* len */
1005 start, /* orig_start */
1006 ins.objectid, /* block_start */
1007 ins.offset, /* block_len */
1008 ins.offset, /* orig_block_len */
1009 async_extent->ram_size, /* ram_bytes */
1010 async_extent->compress_type,
1011 BTRFS_ORDERED_COMPRESSED);
1014 goto out_free_reserve;
1016 free_extent_map(em);
1018 ret = btrfs_add_ordered_extent(inode, start, /* file_offset */
1019 async_extent->ram_size, /* num_bytes */
1020 async_extent->ram_size, /* ram_bytes */
1021 ins.objectid, /* disk_bytenr */
1022 ins.offset, /* disk_num_bytes */
1024 1 << BTRFS_ORDERED_COMPRESSED,
1025 async_extent->compress_type);
1027 btrfs_drop_extent_map_range(inode, start, end, false);
1028 goto out_free_reserve;
1030 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1032 /* Clear dirty, set writeback and unlock the pages. */
1033 extent_clear_unlock_delalloc(inode, start, end,
1034 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
1035 PAGE_UNLOCK | PAGE_START_WRITEBACK);
1036 if (btrfs_submit_compressed_write(inode, start, /* file_offset */
1037 async_extent->ram_size, /* num_bytes */
1038 ins.objectid, /* disk_bytenr */
1039 ins.offset, /* compressed_len */
1040 async_extent->pages, /* compressed_pages */
1041 async_extent->nr_pages,
1042 async_chunk->write_flags,
1043 async_chunk->blkcg_css, true)) {
1044 const u64 start = async_extent->start;
1045 const u64 end = start + async_extent->ram_size - 1;
1047 btrfs_writepage_endio_finish_ordered(inode, NULL, start, end, 0);
1049 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
1050 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1051 free_async_extent_pages(async_extent);
1053 *alloc_hint = ins.objectid + ins.offset;
1054 kfree(async_extent);
1058 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1059 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1061 extent_clear_unlock_delalloc(inode, start, end,
1062 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
1063 EXTENT_DELALLOC_NEW |
1064 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
1065 PAGE_UNLOCK | PAGE_START_WRITEBACK |
1066 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1067 free_async_extent_pages(async_extent);
1068 kfree(async_extent);
1073 * Phase two of compressed writeback. This is the ordered portion of the code,
1074 * which only gets called in the order the work was queued. We walk all the
1075 * async extents created by compress_file_range and send them down to the disk.
1077 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
1079 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
1080 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1081 struct async_extent *async_extent;
1085 while (!list_empty(&async_chunk->extents)) {
1089 async_extent = list_entry(async_chunk->extents.next,
1090 struct async_extent, list);
1091 list_del(&async_extent->list);
1092 extent_start = async_extent->start;
1093 ram_size = async_extent->ram_size;
1095 ret = submit_one_async_extent(inode, async_chunk, async_extent,
1097 btrfs_debug(fs_info,
1098 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1099 inode->root->root_key.objectid,
1100 btrfs_ino(inode), extent_start, ram_size, ret);
1104 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1107 struct extent_map_tree *em_tree = &inode->extent_tree;
1108 struct extent_map *em;
1111 read_lock(&em_tree->lock);
1112 em = search_extent_mapping(em_tree, start, num_bytes);
1115 * if block start isn't an actual block number then find the
1116 * first block in this inode and use that as a hint. If that
1117 * block is also bogus then just don't worry about it.
1119 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1120 free_extent_map(em);
1121 em = search_extent_mapping(em_tree, 0, 0);
1122 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1123 alloc_hint = em->block_start;
1125 free_extent_map(em);
1127 alloc_hint = em->block_start;
1128 free_extent_map(em);
1131 read_unlock(&em_tree->lock);
1137 * when extent_io.c finds a delayed allocation range in the file,
1138 * the call backs end up in this code. The basic idea is to
1139 * allocate extents on disk for the range, and create ordered data structs
1140 * in ram to track those extents.
1142 * locked_page is the page that writepage had locked already. We use
1143 * it to make sure we don't do extra locks or unlocks.
1145 * *page_started is set to one if we unlock locked_page and do everything
1146 * required to start IO on it. It may be clean and already done with
1147 * IO when we return.
1149 * When unlock == 1, we unlock the pages in successfully allocated regions.
1150 * When unlock == 0, we leave them locked for writing them out.
1152 * However, we unlock all the pages except @locked_page in case of failure.
1154 * In summary, page locking state will be as follow:
1156 * - page_started == 1 (return value)
1157 * - All the pages are unlocked. IO is started.
1158 * - Note that this can happen only on success
1160 * - All the pages except @locked_page are unlocked in any case
1162 * - On success, all the pages are locked for writing out them
1163 * - On failure, all the pages except @locked_page are unlocked
1165 * When a failure happens in the second or later iteration of the
1166 * while-loop, the ordered extents created in previous iterations are kept
1167 * intact. So, the caller must clean them up by calling
1168 * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
1171 static noinline int cow_file_range(struct btrfs_inode *inode,
1172 struct page *locked_page,
1173 u64 start, u64 end, int *page_started,
1174 unsigned long *nr_written, int unlock,
1177 struct btrfs_root *root = inode->root;
1178 struct btrfs_fs_info *fs_info = root->fs_info;
1180 u64 orig_start = start;
1182 unsigned long ram_size;
1183 u64 cur_alloc_size = 0;
1185 u64 blocksize = fs_info->sectorsize;
1186 struct btrfs_key ins;
1187 struct extent_map *em;
1188 unsigned clear_bits;
1189 unsigned long page_ops;
1190 bool extent_reserved = false;
1193 if (btrfs_is_free_space_inode(inode)) {
1198 num_bytes = ALIGN(end - start + 1, blocksize);
1199 num_bytes = max(blocksize, num_bytes);
1200 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1202 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1205 * Due to the page size limit, for subpage we can only trigger the
1206 * writeback for the dirty sectors of page, that means data writeback
1207 * is doing more writeback than what we want.
1209 * This is especially unexpected for some call sites like fallocate,
1210 * where we only increase i_size after everything is done.
1211 * This means we can trigger inline extent even if we didn't want to.
1212 * So here we skip inline extent creation completely.
1214 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
1215 u64 actual_end = min_t(u64, i_size_read(&inode->vfs_inode),
1218 /* lets try to make an inline extent */
1219 ret = cow_file_range_inline(inode, actual_end, 0,
1220 BTRFS_COMPRESS_NONE, NULL, false);
1223 * We use DO_ACCOUNTING here because we need the
1224 * delalloc_release_metadata to be run _after_ we drop
1225 * our outstanding extent for clearing delalloc for this
1228 extent_clear_unlock_delalloc(inode, start, end,
1230 EXTENT_LOCKED | EXTENT_DELALLOC |
1231 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1232 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1233 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1234 *nr_written = *nr_written +
1235 (end - start + PAGE_SIZE) / PAGE_SIZE;
1238 * locked_page is locked by the caller of
1239 * writepage_delalloc(), not locked by
1240 * __process_pages_contig().
1242 * We can't let __process_pages_contig() to unlock it,
1243 * as it doesn't have any subpage::writers recorded.
1245 * Here we manually unlock the page, since the caller
1246 * can't use page_started to determine if it's an
1247 * inline extent or a compressed extent.
1249 unlock_page(locked_page);
1251 } else if (ret < 0) {
1256 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1259 * Relocation relies on the relocated extents to have exactly the same
1260 * size as the original extents. Normally writeback for relocation data
1261 * extents follows a NOCOW path because relocation preallocates the
1262 * extents. However, due to an operation such as scrub turning a block
1263 * group to RO mode, it may fallback to COW mode, so we must make sure
1264 * an extent allocated during COW has exactly the requested size and can
1265 * not be split into smaller extents, otherwise relocation breaks and
1266 * fails during the stage where it updates the bytenr of file extent
1269 if (btrfs_is_data_reloc_root(root))
1270 min_alloc_size = num_bytes;
1272 min_alloc_size = fs_info->sectorsize;
1274 while (num_bytes > 0) {
1275 cur_alloc_size = num_bytes;
1276 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1277 min_alloc_size, 0, alloc_hint,
1281 cur_alloc_size = ins.offset;
1282 extent_reserved = true;
1284 ram_size = ins.offset;
1285 em = create_io_em(inode, start, ins.offset, /* len */
1286 start, /* orig_start */
1287 ins.objectid, /* block_start */
1288 ins.offset, /* block_len */
1289 ins.offset, /* orig_block_len */
1290 ram_size, /* ram_bytes */
1291 BTRFS_COMPRESS_NONE, /* compress_type */
1292 BTRFS_ORDERED_REGULAR /* type */);
1297 free_extent_map(em);
1299 ret = btrfs_add_ordered_extent(inode, start, ram_size, ram_size,
1300 ins.objectid, cur_alloc_size, 0,
1301 1 << BTRFS_ORDERED_REGULAR,
1302 BTRFS_COMPRESS_NONE);
1304 goto out_drop_extent_cache;
1306 if (btrfs_is_data_reloc_root(root)) {
1307 ret = btrfs_reloc_clone_csums(inode, start,
1310 * Only drop cache here, and process as normal.
1312 * We must not allow extent_clear_unlock_delalloc()
1313 * at out_unlock label to free meta of this ordered
1314 * extent, as its meta should be freed by
1315 * btrfs_finish_ordered_io().
1317 * So we must continue until @start is increased to
1318 * skip current ordered extent.
1321 btrfs_drop_extent_map_range(inode, start,
1322 start + ram_size - 1,
1326 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1329 * We're not doing compressed IO, don't unlock the first page
1330 * (which the caller expects to stay locked), don't clear any
1331 * dirty bits and don't set any writeback bits
1333 * Do set the Ordered (Private2) bit so we know this page was
1334 * properly setup for writepage.
1336 page_ops = unlock ? PAGE_UNLOCK : 0;
1337 page_ops |= PAGE_SET_ORDERED;
1339 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1341 EXTENT_LOCKED | EXTENT_DELALLOC,
1343 if (num_bytes < cur_alloc_size)
1346 num_bytes -= cur_alloc_size;
1347 alloc_hint = ins.objectid + ins.offset;
1348 start += cur_alloc_size;
1349 extent_reserved = false;
1352 * btrfs_reloc_clone_csums() error, since start is increased
1353 * extent_clear_unlock_delalloc() at out_unlock label won't
1354 * free metadata of current ordered extent, we're OK to exit.
1362 out_drop_extent_cache:
1363 btrfs_drop_extent_map_range(inode, start, start + ram_size - 1, false);
1365 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1366 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1369 * If done_offset is non-NULL and ret == -EAGAIN, we expect the
1370 * caller to write out the successfully allocated region and retry.
1372 if (done_offset && ret == -EAGAIN) {
1373 if (orig_start < start)
1374 *done_offset = start - 1;
1376 *done_offset = start;
1378 } else if (ret == -EAGAIN) {
1379 /* Convert to -ENOSPC since the caller cannot retry. */
1384 * Now, we have three regions to clean up:
1386 * |-------(1)----|---(2)---|-------------(3)----------|
1387 * `- orig_start `- start `- start + cur_alloc_size `- end
1389 * We process each region below.
1392 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1393 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1394 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1397 * For the range (1). We have already instantiated the ordered extents
1398 * for this region. They are cleaned up by
1399 * btrfs_cleanup_ordered_extents() in e.g,
1400 * btrfs_run_delalloc_range(). EXTENT_LOCKED | EXTENT_DELALLOC are
1401 * already cleared in the above loop. And, EXTENT_DELALLOC_NEW |
1402 * EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV are handled by the cleanup
1405 * However, in case of unlock == 0, we still need to unlock the pages
1406 * (except @locked_page) to ensure all the pages are unlocked.
1408 if (!unlock && orig_start < start) {
1410 mapping_set_error(inode->vfs_inode.i_mapping, ret);
1411 extent_clear_unlock_delalloc(inode, orig_start, start - 1,
1412 locked_page, 0, page_ops);
1416 * For the range (2). If we reserved an extent for our delalloc range
1417 * (or a subrange) and failed to create the respective ordered extent,
1418 * then it means that when we reserved the extent we decremented the
1419 * extent's size from the data space_info's bytes_may_use counter and
1420 * incremented the space_info's bytes_reserved counter by the same
1421 * amount. We must make sure extent_clear_unlock_delalloc() does not try
1422 * to decrement again the data space_info's bytes_may_use counter,
1423 * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
1425 if (extent_reserved) {
1426 extent_clear_unlock_delalloc(inode, start,
1427 start + cur_alloc_size - 1,
1431 start += cur_alloc_size;
1437 * For the range (3). We never touched the region. In addition to the
1438 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1439 * space_info's bytes_may_use counter, reserved in
1440 * btrfs_check_data_free_space().
1442 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1443 clear_bits | EXTENT_CLEAR_DATA_RESV,
1449 * work queue call back to started compression on a file and pages
1451 static noinline void async_cow_start(struct btrfs_work *work)
1453 struct async_chunk *async_chunk;
1454 int compressed_extents;
1456 async_chunk = container_of(work, struct async_chunk, work);
1458 compressed_extents = compress_file_range(async_chunk);
1459 if (compressed_extents == 0) {
1460 btrfs_add_delayed_iput(async_chunk->inode);
1461 async_chunk->inode = NULL;
1466 * work queue call back to submit previously compressed pages
1468 static noinline void async_cow_submit(struct btrfs_work *work)
1470 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1472 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1473 unsigned long nr_pages;
1475 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1479 * ->inode could be NULL if async_chunk_start has failed to compress,
1480 * in which case we don't have anything to submit, yet we need to
1481 * always adjust ->async_delalloc_pages as its paired with the init
1482 * happening in cow_file_range_async
1484 if (async_chunk->inode)
1485 submit_compressed_extents(async_chunk);
1487 /* atomic_sub_return implies a barrier */
1488 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1490 cond_wake_up_nomb(&fs_info->async_submit_wait);
1493 static noinline void async_cow_free(struct btrfs_work *work)
1495 struct async_chunk *async_chunk;
1496 struct async_cow *async_cow;
1498 async_chunk = container_of(work, struct async_chunk, work);
1499 if (async_chunk->inode)
1500 btrfs_add_delayed_iput(async_chunk->inode);
1501 if (async_chunk->blkcg_css)
1502 css_put(async_chunk->blkcg_css);
1504 async_cow = async_chunk->async_cow;
1505 if (atomic_dec_and_test(&async_cow->num_chunks))
1509 static int cow_file_range_async(struct btrfs_inode *inode,
1510 struct writeback_control *wbc,
1511 struct page *locked_page,
1512 u64 start, u64 end, int *page_started,
1513 unsigned long *nr_written)
1515 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1516 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1517 struct async_cow *ctx;
1518 struct async_chunk *async_chunk;
1519 unsigned long nr_pages;
1521 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1523 bool should_compress;
1525 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1527 unlock_extent(&inode->io_tree, start, end, NULL);
1529 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1530 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1532 should_compress = false;
1534 should_compress = true;
1537 nofs_flag = memalloc_nofs_save();
1538 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1539 memalloc_nofs_restore(nofs_flag);
1542 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1543 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1544 EXTENT_DO_ACCOUNTING;
1545 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1546 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1548 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1549 clear_bits, page_ops);
1553 async_chunk = ctx->chunks;
1554 atomic_set(&ctx->num_chunks, num_chunks);
1556 for (i = 0; i < num_chunks; i++) {
1557 if (should_compress)
1558 cur_end = min(end, start + SZ_512K - 1);
1563 * igrab is called higher up in the call chain, take only the
1564 * lightweight reference for the callback lifetime
1566 ihold(&inode->vfs_inode);
1567 async_chunk[i].async_cow = ctx;
1568 async_chunk[i].inode = &inode->vfs_inode;
1569 async_chunk[i].start = start;
1570 async_chunk[i].end = cur_end;
1571 async_chunk[i].write_flags = write_flags;
1572 INIT_LIST_HEAD(&async_chunk[i].extents);
1575 * The locked_page comes all the way from writepage and its
1576 * the original page we were actually given. As we spread
1577 * this large delalloc region across multiple async_chunk
1578 * structs, only the first struct needs a pointer to locked_page
1580 * This way we don't need racey decisions about who is supposed
1585 * Depending on the compressibility, the pages might or
1586 * might not go through async. We want all of them to
1587 * be accounted against wbc once. Let's do it here
1588 * before the paths diverge. wbc accounting is used
1589 * only for foreign writeback detection and doesn't
1590 * need full accuracy. Just account the whole thing
1591 * against the first page.
1593 wbc_account_cgroup_owner(wbc, locked_page,
1595 async_chunk[i].locked_page = locked_page;
1598 async_chunk[i].locked_page = NULL;
1601 if (blkcg_css != blkcg_root_css) {
1603 async_chunk[i].blkcg_css = blkcg_css;
1605 async_chunk[i].blkcg_css = NULL;
1608 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1609 async_cow_submit, async_cow_free);
1611 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1612 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1614 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1616 *nr_written += nr_pages;
1617 start = cur_end + 1;
1623 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1624 struct page *locked_page, u64 start,
1625 u64 end, int *page_started,
1626 unsigned long *nr_written)
1628 u64 done_offset = end;
1630 bool locked_page_done = false;
1632 while (start <= end) {
1633 ret = cow_file_range(inode, locked_page, start, end, page_started,
1634 nr_written, 0, &done_offset);
1635 if (ret && ret != -EAGAIN)
1638 if (*page_started) {
1646 if (done_offset == start) {
1647 wait_on_bit_io(&inode->root->fs_info->flags,
1648 BTRFS_FS_NEED_ZONE_FINISH,
1649 TASK_UNINTERRUPTIBLE);
1653 if (!locked_page_done) {
1654 __set_page_dirty_nobuffers(locked_page);
1655 account_page_redirty(locked_page);
1657 locked_page_done = true;
1658 extent_write_locked_range(&inode->vfs_inode, start, done_offset);
1660 start = done_offset + 1;
1668 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1669 u64 bytenr, u64 num_bytes, bool nowait)
1671 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bytenr);
1672 struct btrfs_ordered_sum *sums;
1676 ret = btrfs_lookup_csums_range(csum_root, bytenr,
1677 bytenr + num_bytes - 1, &list, 0,
1679 if (ret == 0 && list_empty(&list))
1682 while (!list_empty(&list)) {
1683 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1684 list_del(&sums->list);
1692 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1693 const u64 start, const u64 end,
1694 int *page_started, unsigned long *nr_written)
1696 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1697 const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1698 const u64 range_bytes = end + 1 - start;
1699 struct extent_io_tree *io_tree = &inode->io_tree;
1700 u64 range_start = start;
1704 * If EXTENT_NORESERVE is set it means that when the buffered write was
1705 * made we had not enough available data space and therefore we did not
1706 * reserve data space for it, since we though we could do NOCOW for the
1707 * respective file range (either there is prealloc extent or the inode
1708 * has the NOCOW bit set).
1710 * However when we need to fallback to COW mode (because for example the
1711 * block group for the corresponding extent was turned to RO mode by a
1712 * scrub or relocation) we need to do the following:
1714 * 1) We increment the bytes_may_use counter of the data space info.
1715 * If COW succeeds, it allocates a new data extent and after doing
1716 * that it decrements the space info's bytes_may_use counter and
1717 * increments its bytes_reserved counter by the same amount (we do
1718 * this at btrfs_add_reserved_bytes()). So we need to increment the
1719 * bytes_may_use counter to compensate (when space is reserved at
1720 * buffered write time, the bytes_may_use counter is incremented);
1722 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1723 * that if the COW path fails for any reason, it decrements (through
1724 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1725 * data space info, which we incremented in the step above.
1727 * If we need to fallback to cow and the inode corresponds to a free
1728 * space cache inode or an inode of the data relocation tree, we must
1729 * also increment bytes_may_use of the data space_info for the same
1730 * reason. Space caches and relocated data extents always get a prealloc
1731 * extent for them, however scrub or balance may have set the block
1732 * group that contains that extent to RO mode and therefore force COW
1733 * when starting writeback.
1735 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1736 EXTENT_NORESERVE, 0);
1737 if (count > 0 || is_space_ino || is_reloc_ino) {
1739 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1740 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1742 if (is_space_ino || is_reloc_ino)
1743 bytes = range_bytes;
1745 spin_lock(&sinfo->lock);
1746 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1747 spin_unlock(&sinfo->lock);
1750 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1754 return cow_file_range(inode, locked_page, start, end, page_started,
1755 nr_written, 1, NULL);
1758 struct can_nocow_file_extent_args {
1761 /* Start file offset of the range we want to NOCOW. */
1763 /* End file offset (inclusive) of the range we want to NOCOW. */
1765 bool writeback_path;
1768 * Free the path passed to can_nocow_file_extent() once it's not needed
1773 /* Output fields. Only set when can_nocow_file_extent() returns 1. */
1778 /* Number of bytes that can be written to in NOCOW mode. */
1783 * Check if we can NOCOW the file extent that the path points to.
1784 * This function may return with the path released, so the caller should check
1785 * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
1787 * Returns: < 0 on error
1788 * 0 if we can not NOCOW
1791 static int can_nocow_file_extent(struct btrfs_path *path,
1792 struct btrfs_key *key,
1793 struct btrfs_inode *inode,
1794 struct can_nocow_file_extent_args *args)
1796 const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
1797 struct extent_buffer *leaf = path->nodes[0];
1798 struct btrfs_root *root = inode->root;
1799 struct btrfs_file_extent_item *fi;
1804 bool nowait = path->nowait;
1806 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
1807 extent_type = btrfs_file_extent_type(leaf, fi);
1809 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1812 /* Can't access these fields unless we know it's not an inline extent. */
1813 args->disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1814 args->disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1815 args->extent_offset = btrfs_file_extent_offset(leaf, fi);
1817 if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1818 extent_type == BTRFS_FILE_EXTENT_REG)
1822 * If the extent was created before the generation where the last snapshot
1823 * for its subvolume was created, then this implies the extent is shared,
1824 * hence we must COW.
1826 if (!args->strict &&
1827 btrfs_file_extent_generation(leaf, fi) <=
1828 btrfs_root_last_snapshot(&root->root_item))
1831 /* An explicit hole, must COW. */
1832 if (args->disk_bytenr == 0)
1835 /* Compressed/encrypted/encoded extents must be COWed. */
1836 if (btrfs_file_extent_compression(leaf, fi) ||
1837 btrfs_file_extent_encryption(leaf, fi) ||
1838 btrfs_file_extent_other_encoding(leaf, fi))
1841 extent_end = btrfs_file_extent_end(path);
1844 * The following checks can be expensive, as they need to take other
1845 * locks and do btree or rbtree searches, so release the path to avoid
1846 * blocking other tasks for too long.
1848 btrfs_release_path(path);
1850 ret = btrfs_cross_ref_exist(root, btrfs_ino(inode),
1851 key->offset - args->extent_offset,
1852 args->disk_bytenr, false, path);
1853 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1857 if (args->free_path) {
1859 * We don't need the path anymore, plus through the
1860 * csum_exist_in_range() call below we will end up allocating
1861 * another path. So free the path to avoid unnecessary extra
1864 btrfs_free_path(path);
1868 /* If there are pending snapshots for this root, we must COW. */
1869 if (args->writeback_path && !is_freespace_inode &&
1870 atomic_read(&root->snapshot_force_cow))
1873 args->disk_bytenr += args->extent_offset;
1874 args->disk_bytenr += args->start - key->offset;
1875 args->num_bytes = min(args->end + 1, extent_end) - args->start;
1878 * Force COW if csums exist in the range. This ensures that csums for a
1879 * given extent are either valid or do not exist.
1881 ret = csum_exist_in_range(root->fs_info, args->disk_bytenr, args->num_bytes,
1883 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1889 if (args->free_path && path)
1890 btrfs_free_path(path);
1892 return ret < 0 ? ret : can_nocow;
1896 * when nowcow writeback call back. This checks for snapshots or COW copies
1897 * of the extents that exist in the file, and COWs the file as required.
1899 * If no cow copies or snapshots exist, we write directly to the existing
1902 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1903 struct page *locked_page,
1904 const u64 start, const u64 end,
1906 unsigned long *nr_written)
1908 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1909 struct btrfs_root *root = inode->root;
1910 struct btrfs_path *path;
1911 u64 cow_start = (u64)-1;
1912 u64 cur_offset = start;
1914 bool check_prev = true;
1915 u64 ino = btrfs_ino(inode);
1916 struct btrfs_block_group *bg;
1918 struct can_nocow_file_extent_args nocow_args = { 0 };
1920 path = btrfs_alloc_path();
1922 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1923 EXTENT_LOCKED | EXTENT_DELALLOC |
1924 EXTENT_DO_ACCOUNTING |
1925 EXTENT_DEFRAG, PAGE_UNLOCK |
1926 PAGE_START_WRITEBACK |
1927 PAGE_END_WRITEBACK);
1931 nocow_args.end = end;
1932 nocow_args.writeback_path = true;
1935 struct btrfs_key found_key;
1936 struct btrfs_file_extent_item *fi;
1937 struct extent_buffer *leaf;
1945 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1951 * If there is no extent for our range when doing the initial
1952 * search, then go back to the previous slot as it will be the
1953 * one containing the search offset
1955 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1956 leaf = path->nodes[0];
1957 btrfs_item_key_to_cpu(leaf, &found_key,
1958 path->slots[0] - 1);
1959 if (found_key.objectid == ino &&
1960 found_key.type == BTRFS_EXTENT_DATA_KEY)
1965 /* Go to next leaf if we have exhausted the current one */
1966 leaf = path->nodes[0];
1967 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1968 ret = btrfs_next_leaf(root, path);
1970 if (cow_start != (u64)-1)
1971 cur_offset = cow_start;
1976 leaf = path->nodes[0];
1979 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1981 /* Didn't find anything for our INO */
1982 if (found_key.objectid > ino)
1985 * Keep searching until we find an EXTENT_ITEM or there are no
1986 * more extents for this inode
1988 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1989 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1994 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1995 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1996 found_key.offset > end)
2000 * If the found extent starts after requested offset, then
2001 * adjust extent_end to be right before this extent begins
2003 if (found_key.offset > cur_offset) {
2004 extent_end = found_key.offset;
2010 * Found extent which begins before our range and potentially
2013 fi = btrfs_item_ptr(leaf, path->slots[0],
2014 struct btrfs_file_extent_item);
2015 extent_type = btrfs_file_extent_type(leaf, fi);
2016 /* If this is triggered then we have a memory corruption. */
2017 ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
2018 if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
2022 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
2023 extent_end = btrfs_file_extent_end(path);
2026 * If the extent we got ends before our current offset, skip to
2029 if (extent_end <= cur_offset) {
2034 nocow_args.start = cur_offset;
2035 ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
2037 if (cow_start != (u64)-1)
2038 cur_offset = cow_start;
2040 } else if (ret == 0) {
2045 bg = btrfs_inc_nocow_writers(fs_info, nocow_args.disk_bytenr);
2050 * If nocow is false then record the beginning of the range
2051 * that needs to be COWed
2054 if (cow_start == (u64)-1)
2055 cow_start = cur_offset;
2056 cur_offset = extent_end;
2057 if (cur_offset > end)
2059 if (!path->nodes[0])
2066 * COW range from cow_start to found_key.offset - 1. As the key
2067 * will contain the beginning of the first extent that can be
2068 * NOCOW, following one which needs to be COW'ed
2070 if (cow_start != (u64)-1) {
2071 ret = fallback_to_cow(inode, locked_page,
2072 cow_start, found_key.offset - 1,
2073 page_started, nr_written);
2076 cow_start = (u64)-1;
2079 nocow_end = cur_offset + nocow_args.num_bytes - 1;
2081 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
2082 u64 orig_start = found_key.offset - nocow_args.extent_offset;
2083 struct extent_map *em;
2085 em = create_io_em(inode, cur_offset, nocow_args.num_bytes,
2087 nocow_args.disk_bytenr, /* block_start */
2088 nocow_args.num_bytes, /* block_len */
2089 nocow_args.disk_num_bytes, /* orig_block_len */
2090 ram_bytes, BTRFS_COMPRESS_NONE,
2091 BTRFS_ORDERED_PREALLOC);
2096 free_extent_map(em);
2097 ret = btrfs_add_ordered_extent(inode,
2098 cur_offset, nocow_args.num_bytes,
2099 nocow_args.num_bytes,
2100 nocow_args.disk_bytenr,
2101 nocow_args.num_bytes, 0,
2102 1 << BTRFS_ORDERED_PREALLOC,
2103 BTRFS_COMPRESS_NONE);
2105 btrfs_drop_extent_map_range(inode, cur_offset,
2110 ret = btrfs_add_ordered_extent(inode, cur_offset,
2111 nocow_args.num_bytes,
2112 nocow_args.num_bytes,
2113 nocow_args.disk_bytenr,
2114 nocow_args.num_bytes,
2116 1 << BTRFS_ORDERED_NOCOW,
2117 BTRFS_COMPRESS_NONE);
2123 btrfs_dec_nocow_writers(bg);
2127 if (btrfs_is_data_reloc_root(root))
2129 * Error handled later, as we must prevent
2130 * extent_clear_unlock_delalloc() in error handler
2131 * from freeing metadata of created ordered extent.
2133 ret = btrfs_reloc_clone_csums(inode, cur_offset,
2134 nocow_args.num_bytes);
2136 extent_clear_unlock_delalloc(inode, cur_offset, nocow_end,
2137 locked_page, EXTENT_LOCKED |
2139 EXTENT_CLEAR_DATA_RESV,
2140 PAGE_UNLOCK | PAGE_SET_ORDERED);
2142 cur_offset = extent_end;
2145 * btrfs_reloc_clone_csums() error, now we're OK to call error
2146 * handler, as metadata for created ordered extent will only
2147 * be freed by btrfs_finish_ordered_io().
2151 if (cur_offset > end)
2154 btrfs_release_path(path);
2156 if (cur_offset <= end && cow_start == (u64)-1)
2157 cow_start = cur_offset;
2159 if (cow_start != (u64)-1) {
2161 ret = fallback_to_cow(inode, locked_page, cow_start, end,
2162 page_started, nr_written);
2169 btrfs_dec_nocow_writers(bg);
2171 if (ret && cur_offset < end)
2172 extent_clear_unlock_delalloc(inode, cur_offset, end,
2173 locked_page, EXTENT_LOCKED |
2174 EXTENT_DELALLOC | EXTENT_DEFRAG |
2175 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
2176 PAGE_START_WRITEBACK |
2177 PAGE_END_WRITEBACK);
2178 btrfs_free_path(path);
2182 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
2184 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
2185 if (inode->defrag_bytes &&
2186 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
2195 * Function to process delayed allocation (create CoW) for ranges which are
2196 * being touched for the first time.
2198 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
2199 u64 start, u64 end, int *page_started, unsigned long *nr_written,
2200 struct writeback_control *wbc)
2203 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2206 * The range must cover part of the @locked_page, or the returned
2207 * @page_started can confuse the caller.
2209 ASSERT(!(end <= page_offset(locked_page) ||
2210 start >= page_offset(locked_page) + PAGE_SIZE));
2212 if (should_nocow(inode, start, end)) {
2214 * Normally on a zoned device we're only doing COW writes, but
2215 * in case of relocation on a zoned filesystem we have taken
2216 * precaution, that we're only writing sequentially. It's safe
2217 * to use run_delalloc_nocow() here, like for regular
2218 * preallocated inodes.
2220 ASSERT(!zoned || btrfs_is_data_reloc_root(inode->root));
2221 ret = run_delalloc_nocow(inode, locked_page, start, end,
2222 page_started, nr_written);
2223 } else if (!btrfs_inode_can_compress(inode) ||
2224 !inode_need_compress(inode, start, end)) {
2226 ret = run_delalloc_zoned(inode, locked_page, start, end,
2227 page_started, nr_written);
2229 ret = cow_file_range(inode, locked_page, start, end,
2230 page_started, nr_written, 1, NULL);
2232 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
2233 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
2234 page_started, nr_written);
2238 btrfs_cleanup_ordered_extents(inode, locked_page, start,
2243 void btrfs_split_delalloc_extent(struct inode *inode,
2244 struct extent_state *orig, u64 split)
2246 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2249 /* not delalloc, ignore it */
2250 if (!(orig->state & EXTENT_DELALLOC))
2253 size = orig->end - orig->start + 1;
2254 if (size > fs_info->max_extent_size) {
2259 * See the explanation in btrfs_merge_delalloc_extent, the same
2260 * applies here, just in reverse.
2262 new_size = orig->end - split + 1;
2263 num_extents = count_max_extents(fs_info, new_size);
2264 new_size = split - orig->start;
2265 num_extents += count_max_extents(fs_info, new_size);
2266 if (count_max_extents(fs_info, size) >= num_extents)
2270 spin_lock(&BTRFS_I(inode)->lock);
2271 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
2272 spin_unlock(&BTRFS_I(inode)->lock);
2276 * Handle merged delayed allocation extents so we can keep track of new extents
2277 * that are just merged onto old extents, such as when we are doing sequential
2278 * writes, so we can properly account for the metadata space we'll need.
2280 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
2281 struct extent_state *other)
2283 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2284 u64 new_size, old_size;
2287 /* not delalloc, ignore it */
2288 if (!(other->state & EXTENT_DELALLOC))
2291 if (new->start > other->start)
2292 new_size = new->end - other->start + 1;
2294 new_size = other->end - new->start + 1;
2296 /* we're not bigger than the max, unreserve the space and go */
2297 if (new_size <= fs_info->max_extent_size) {
2298 spin_lock(&BTRFS_I(inode)->lock);
2299 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2300 spin_unlock(&BTRFS_I(inode)->lock);
2305 * We have to add up either side to figure out how many extents were
2306 * accounted for before we merged into one big extent. If the number of
2307 * extents we accounted for is <= the amount we need for the new range
2308 * then we can return, otherwise drop. Think of it like this
2312 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2313 * need 2 outstanding extents, on one side we have 1 and the other side
2314 * we have 1 so they are == and we can return. But in this case
2316 * [MAX_SIZE+4k][MAX_SIZE+4k]
2318 * Each range on their own accounts for 2 extents, but merged together
2319 * they are only 3 extents worth of accounting, so we need to drop in
2322 old_size = other->end - other->start + 1;
2323 num_extents = count_max_extents(fs_info, old_size);
2324 old_size = new->end - new->start + 1;
2325 num_extents += count_max_extents(fs_info, old_size);
2326 if (count_max_extents(fs_info, new_size) >= num_extents)
2329 spin_lock(&BTRFS_I(inode)->lock);
2330 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2331 spin_unlock(&BTRFS_I(inode)->lock);
2334 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2335 struct inode *inode)
2337 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2339 spin_lock(&root->delalloc_lock);
2340 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2341 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2342 &root->delalloc_inodes);
2343 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2344 &BTRFS_I(inode)->runtime_flags);
2345 root->nr_delalloc_inodes++;
2346 if (root->nr_delalloc_inodes == 1) {
2347 spin_lock(&fs_info->delalloc_root_lock);
2348 BUG_ON(!list_empty(&root->delalloc_root));
2349 list_add_tail(&root->delalloc_root,
2350 &fs_info->delalloc_roots);
2351 spin_unlock(&fs_info->delalloc_root_lock);
2354 spin_unlock(&root->delalloc_lock);
2358 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2359 struct btrfs_inode *inode)
2361 struct btrfs_fs_info *fs_info = root->fs_info;
2363 if (!list_empty(&inode->delalloc_inodes)) {
2364 list_del_init(&inode->delalloc_inodes);
2365 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2366 &inode->runtime_flags);
2367 root->nr_delalloc_inodes--;
2368 if (!root->nr_delalloc_inodes) {
2369 ASSERT(list_empty(&root->delalloc_inodes));
2370 spin_lock(&fs_info->delalloc_root_lock);
2371 BUG_ON(list_empty(&root->delalloc_root));
2372 list_del_init(&root->delalloc_root);
2373 spin_unlock(&fs_info->delalloc_root_lock);
2378 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2379 struct btrfs_inode *inode)
2381 spin_lock(&root->delalloc_lock);
2382 __btrfs_del_delalloc_inode(root, inode);
2383 spin_unlock(&root->delalloc_lock);
2387 * Properly track delayed allocation bytes in the inode and to maintain the
2388 * list of inodes that have pending delalloc work to be done.
2390 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2393 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2395 if ((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC))
2398 * set_bit and clear bit hooks normally require _irqsave/restore
2399 * but in this case, we are only testing for the DELALLOC
2400 * bit, which is only set or cleared with irqs on
2402 if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2403 struct btrfs_root *root = BTRFS_I(inode)->root;
2404 u64 len = state->end + 1 - state->start;
2405 u32 num_extents = count_max_extents(fs_info, len);
2406 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2408 spin_lock(&BTRFS_I(inode)->lock);
2409 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2410 spin_unlock(&BTRFS_I(inode)->lock);
2412 /* For sanity tests */
2413 if (btrfs_is_testing(fs_info))
2416 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2417 fs_info->delalloc_batch);
2418 spin_lock(&BTRFS_I(inode)->lock);
2419 BTRFS_I(inode)->delalloc_bytes += len;
2420 if (bits & EXTENT_DEFRAG)
2421 BTRFS_I(inode)->defrag_bytes += len;
2422 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2423 &BTRFS_I(inode)->runtime_flags))
2424 btrfs_add_delalloc_inodes(root, inode);
2425 spin_unlock(&BTRFS_I(inode)->lock);
2428 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2429 (bits & EXTENT_DELALLOC_NEW)) {
2430 spin_lock(&BTRFS_I(inode)->lock);
2431 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2433 spin_unlock(&BTRFS_I(inode)->lock);
2438 * Once a range is no longer delalloc this function ensures that proper
2439 * accounting happens.
2441 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2442 struct extent_state *state, u32 bits)
2444 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2445 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2446 u64 len = state->end + 1 - state->start;
2447 u32 num_extents = count_max_extents(fs_info, len);
2449 if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
2450 spin_lock(&inode->lock);
2451 inode->defrag_bytes -= len;
2452 spin_unlock(&inode->lock);
2456 * set_bit and clear bit hooks normally require _irqsave/restore
2457 * but in this case, we are only testing for the DELALLOC
2458 * bit, which is only set or cleared with irqs on
2460 if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2461 struct btrfs_root *root = inode->root;
2462 bool do_list = !btrfs_is_free_space_inode(inode);
2464 spin_lock(&inode->lock);
2465 btrfs_mod_outstanding_extents(inode, -num_extents);
2466 spin_unlock(&inode->lock);
2469 * We don't reserve metadata space for space cache inodes so we
2470 * don't need to call delalloc_release_metadata if there is an
2473 if (bits & EXTENT_CLEAR_META_RESV &&
2474 root != fs_info->tree_root)
2475 btrfs_delalloc_release_metadata(inode, len, false);
2477 /* For sanity tests. */
2478 if (btrfs_is_testing(fs_info))
2481 if (!btrfs_is_data_reloc_root(root) &&
2482 do_list && !(state->state & EXTENT_NORESERVE) &&
2483 (bits & EXTENT_CLEAR_DATA_RESV))
2484 btrfs_free_reserved_data_space_noquota(fs_info, len);
2486 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2487 fs_info->delalloc_batch);
2488 spin_lock(&inode->lock);
2489 inode->delalloc_bytes -= len;
2490 if (do_list && inode->delalloc_bytes == 0 &&
2491 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2492 &inode->runtime_flags))
2493 btrfs_del_delalloc_inode(root, inode);
2494 spin_unlock(&inode->lock);
2497 if ((state->state & EXTENT_DELALLOC_NEW) &&
2498 (bits & EXTENT_DELALLOC_NEW)) {
2499 spin_lock(&inode->lock);
2500 ASSERT(inode->new_delalloc_bytes >= len);
2501 inode->new_delalloc_bytes -= len;
2502 if (bits & EXTENT_ADD_INODE_BYTES)
2503 inode_add_bytes(&inode->vfs_inode, len);
2504 spin_unlock(&inode->lock);
2509 * in order to insert checksums into the metadata in large chunks,
2510 * we wait until bio submission time. All the pages in the bio are
2511 * checksummed and sums are attached onto the ordered extent record.
2513 * At IO completion time the cums attached on the ordered extent record
2514 * are inserted into the btree
2516 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2517 u64 dio_file_offset)
2519 return btrfs_csum_one_bio(BTRFS_I(inode), bio, (u64)-1, false);
2523 * Split an extent_map at [start, start + len]
2525 * This function is intended to be used only for extract_ordered_extent().
2527 static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
2530 struct extent_map_tree *em_tree = &inode->extent_tree;
2531 struct extent_map *em;
2532 struct extent_map *split_pre = NULL;
2533 struct extent_map *split_mid = NULL;
2534 struct extent_map *split_post = NULL;
2536 unsigned long flags;
2539 if (pre == 0 && post == 0)
2542 split_pre = alloc_extent_map();
2544 split_mid = alloc_extent_map();
2546 split_post = alloc_extent_map();
2547 if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
2552 ASSERT(pre + post < len);
2554 lock_extent(&inode->io_tree, start, start + len - 1, NULL);
2555 write_lock(&em_tree->lock);
2556 em = lookup_extent_mapping(em_tree, start, len);
2562 ASSERT(em->len == len);
2563 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2564 ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
2565 ASSERT(test_bit(EXTENT_FLAG_PINNED, &em->flags));
2566 ASSERT(!test_bit(EXTENT_FLAG_LOGGING, &em->flags));
2567 ASSERT(!list_empty(&em->list));
2570 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
2572 /* First, replace the em with a new extent_map starting from * em->start */
2573 split_pre->start = em->start;
2574 split_pre->len = (pre ? pre : em->len - post);
2575 split_pre->orig_start = split_pre->start;
2576 split_pre->block_start = em->block_start;
2577 split_pre->block_len = split_pre->len;
2578 split_pre->orig_block_len = split_pre->block_len;
2579 split_pre->ram_bytes = split_pre->len;
2580 split_pre->flags = flags;
2581 split_pre->compress_type = em->compress_type;
2582 split_pre->generation = em->generation;
2584 replace_extent_mapping(em_tree, em, split_pre, 1);
2587 * Now we only have an extent_map at:
2588 * [em->start, em->start + pre] if pre != 0
2589 * [em->start, em->start + em->len - post] if pre == 0
2593 /* Insert the middle extent_map */
2594 split_mid->start = em->start + pre;
2595 split_mid->len = em->len - pre - post;
2596 split_mid->orig_start = split_mid->start;
2597 split_mid->block_start = em->block_start + pre;
2598 split_mid->block_len = split_mid->len;
2599 split_mid->orig_block_len = split_mid->block_len;
2600 split_mid->ram_bytes = split_mid->len;
2601 split_mid->flags = flags;
2602 split_mid->compress_type = em->compress_type;
2603 split_mid->generation = em->generation;
2604 add_extent_mapping(em_tree, split_mid, 1);
2608 split_post->start = em->start + em->len - post;
2609 split_post->len = post;
2610 split_post->orig_start = split_post->start;
2611 split_post->block_start = em->block_start + em->len - post;
2612 split_post->block_len = split_post->len;
2613 split_post->orig_block_len = split_post->block_len;
2614 split_post->ram_bytes = split_post->len;
2615 split_post->flags = flags;
2616 split_post->compress_type = em->compress_type;
2617 split_post->generation = em->generation;
2618 add_extent_mapping(em_tree, split_post, 1);
2622 free_extent_map(em);
2623 /* Once for the tree */
2624 free_extent_map(em);
2627 write_unlock(&em_tree->lock);
2628 unlock_extent(&inode->io_tree, start, start + len - 1, NULL);
2630 free_extent_map(split_pre);
2631 free_extent_map(split_mid);
2632 free_extent_map(split_post);
2637 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2638 struct bio *bio, loff_t file_offset)
2640 struct btrfs_ordered_extent *ordered;
2641 u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2643 u64 len = bio->bi_iter.bi_size;
2644 u64 end = start + len;
2649 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2650 if (WARN_ON_ONCE(!ordered))
2651 return BLK_STS_IOERR;
2653 /* No need to split */
2654 if (ordered->disk_num_bytes == len)
2657 /* We cannot split once end_bio'd ordered extent */
2658 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2663 /* We cannot split a compressed ordered extent */
2664 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2669 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2670 /* bio must be in one ordered extent */
2671 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2676 /* Checksum list should be empty */
2677 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2682 file_len = ordered->num_bytes;
2683 pre = start - ordered->disk_bytenr;
2684 post = ordered_end - end;
2686 ret = btrfs_split_ordered_extent(ordered, pre, post);
2689 ret = split_zoned_em(inode, file_offset, file_len, pre, post);
2692 btrfs_put_ordered_extent(ordered);
2694 return errno_to_blk_status(ret);
2697 void btrfs_submit_data_write_bio(struct inode *inode, struct bio *bio, int mirror_num)
2699 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2700 struct btrfs_inode *bi = BTRFS_I(inode);
2703 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2704 ret = extract_ordered_extent(bi, bio,
2705 page_offset(bio_first_bvec_all(bio)->bv_page));
2707 btrfs_bio_end_io(btrfs_bio(bio), ret);
2713 * If we need to checksum, and the I/O is not issued by fsync and
2714 * friends, that is ->sync_writers != 0, defer the submission to a
2715 * workqueue to parallelize it.
2717 * Csum items for reloc roots have already been cloned at this point,
2718 * so they are handled as part of the no-checksum case.
2720 if (!(bi->flags & BTRFS_INODE_NODATASUM) &&
2721 !test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state) &&
2722 !btrfs_is_data_reloc_root(bi->root)) {
2723 if (!atomic_read(&bi->sync_writers) &&
2724 btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
2725 btrfs_submit_bio_start))
2728 ret = btrfs_csum_one_bio(bi, bio, (u64)-1, false);
2730 btrfs_bio_end_io(btrfs_bio(bio), ret);
2734 btrfs_submit_bio(fs_info, bio, mirror_num);
2737 void btrfs_submit_data_read_bio(struct inode *inode, struct bio *bio,
2738 int mirror_num, enum btrfs_compression_type compress_type)
2740 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2743 if (compress_type != BTRFS_COMPRESS_NONE) {
2745 * btrfs_submit_compressed_read will handle completing the bio
2746 * if there were any errors, so just return here.
2748 btrfs_submit_compressed_read(inode, bio, mirror_num);
2752 /* Save the original iter for read repair */
2753 btrfs_bio(bio)->iter = bio->bi_iter;
2756 * Lookup bio sums does extra checks around whether we need to csum or
2757 * not, which is why we ignore skip_sum here.
2759 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2761 btrfs_bio_end_io(btrfs_bio(bio), ret);
2765 btrfs_submit_bio(fs_info, bio, mirror_num);
2769 * given a list of ordered sums record them in the inode. This happens
2770 * at IO completion time based on sums calculated at bio submission time.
2772 static int add_pending_csums(struct btrfs_trans_handle *trans,
2773 struct list_head *list)
2775 struct btrfs_ordered_sum *sum;
2776 struct btrfs_root *csum_root = NULL;
2779 list_for_each_entry(sum, list, list) {
2780 trans->adding_csums = true;
2782 csum_root = btrfs_csum_root(trans->fs_info,
2784 ret = btrfs_csum_file_blocks(trans, csum_root, sum);
2785 trans->adding_csums = false;
2792 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2795 struct extent_state **cached_state)
2797 u64 search_start = start;
2798 const u64 end = start + len - 1;
2800 while (search_start < end) {
2801 const u64 search_len = end - search_start + 1;
2802 struct extent_map *em;
2806 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2810 if (em->block_start != EXTENT_MAP_HOLE)
2814 if (em->start < search_start)
2815 em_len -= search_start - em->start;
2816 if (em_len > search_len)
2817 em_len = search_len;
2819 ret = set_extent_bit(&inode->io_tree, search_start,
2820 search_start + em_len - 1,
2821 EXTENT_DELALLOC_NEW, cached_state,
2824 search_start = extent_map_end(em);
2825 free_extent_map(em);
2832 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2833 unsigned int extra_bits,
2834 struct extent_state **cached_state)
2836 WARN_ON(PAGE_ALIGNED(end));
2838 if (start >= i_size_read(&inode->vfs_inode) &&
2839 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2841 * There can't be any extents following eof in this case so just
2842 * set the delalloc new bit for the range directly.
2844 extra_bits |= EXTENT_DELALLOC_NEW;
2848 ret = btrfs_find_new_delalloc_bytes(inode, start,
2855 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2859 /* see btrfs_writepage_start_hook for details on why this is required */
2860 struct btrfs_writepage_fixup {
2862 struct inode *inode;
2863 struct btrfs_work work;
2866 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2868 struct btrfs_writepage_fixup *fixup;
2869 struct btrfs_ordered_extent *ordered;
2870 struct extent_state *cached_state = NULL;
2871 struct extent_changeset *data_reserved = NULL;
2873 struct btrfs_inode *inode;
2877 bool free_delalloc_space = true;
2879 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2881 inode = BTRFS_I(fixup->inode);
2882 page_start = page_offset(page);
2883 page_end = page_offset(page) + PAGE_SIZE - 1;
2886 * This is similar to page_mkwrite, we need to reserve the space before
2887 * we take the page lock.
2889 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2895 * Before we queued this fixup, we took a reference on the page.
2896 * page->mapping may go NULL, but it shouldn't be moved to a different
2899 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2901 * Unfortunately this is a little tricky, either
2903 * 1) We got here and our page had already been dealt with and
2904 * we reserved our space, thus ret == 0, so we need to just
2905 * drop our space reservation and bail. This can happen the
2906 * first time we come into the fixup worker, or could happen
2907 * while waiting for the ordered extent.
2908 * 2) Our page was already dealt with, but we happened to get an
2909 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2910 * this case we obviously don't have anything to release, but
2911 * because the page was already dealt with we don't want to
2912 * mark the page with an error, so make sure we're resetting
2913 * ret to 0. This is why we have this check _before_ the ret
2914 * check, because we do not want to have a surprise ENOSPC
2915 * when the page was already properly dealt with.
2918 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2919 btrfs_delalloc_release_space(inode, data_reserved,
2920 page_start, PAGE_SIZE,
2928 * We can't mess with the page state unless it is locked, so now that
2929 * it is locked bail if we failed to make our space reservation.
2934 lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2936 /* already ordered? We're done */
2937 if (PageOrdered(page))
2940 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2942 unlock_extent(&inode->io_tree, page_start, page_end,
2945 btrfs_start_ordered_extent(ordered, 1);
2946 btrfs_put_ordered_extent(ordered);
2950 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2956 * Everything went as planned, we're now the owner of a dirty page with
2957 * delayed allocation bits set and space reserved for our COW
2960 * The page was dirty when we started, nothing should have cleaned it.
2962 BUG_ON(!PageDirty(page));
2963 free_delalloc_space = false;
2965 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2966 if (free_delalloc_space)
2967 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2969 unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2973 * We hit ENOSPC or other errors. Update the mapping and page
2974 * to reflect the errors and clean the page.
2976 mapping_set_error(page->mapping, ret);
2977 end_extent_writepage(page, ret, page_start, page_end);
2978 clear_page_dirty_for_io(page);
2981 btrfs_page_clear_checked(inode->root->fs_info, page, page_start, PAGE_SIZE);
2985 extent_changeset_free(data_reserved);
2987 * As a precaution, do a delayed iput in case it would be the last iput
2988 * that could need flushing space. Recursing back to fixup worker would
2991 btrfs_add_delayed_iput(&inode->vfs_inode);
2995 * There are a few paths in the higher layers of the kernel that directly
2996 * set the page dirty bit without asking the filesystem if it is a
2997 * good idea. This causes problems because we want to make sure COW
2998 * properly happens and the data=ordered rules are followed.
3000 * In our case any range that doesn't have the ORDERED bit set
3001 * hasn't been properly setup for IO. We kick off an async process
3002 * to fix it up. The async helper will wait for ordered extents, set
3003 * the delalloc bit and make it safe to write the page.
3005 int btrfs_writepage_cow_fixup(struct page *page)
3007 struct inode *inode = page->mapping->host;
3008 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3009 struct btrfs_writepage_fixup *fixup;
3011 /* This page has ordered extent covering it already */
3012 if (PageOrdered(page))
3016 * PageChecked is set below when we create a fixup worker for this page,
3017 * don't try to create another one if we're already PageChecked()
3019 * The extent_io writepage code will redirty the page if we send back
3022 if (PageChecked(page))
3025 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
3030 * We are already holding a reference to this inode from
3031 * write_cache_pages. We need to hold it because the space reservation
3032 * takes place outside of the page lock, and we can't trust
3033 * page->mapping outside of the page lock.
3036 btrfs_page_set_checked(fs_info, page, page_offset(page), PAGE_SIZE);
3038 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
3040 fixup->inode = inode;
3041 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
3046 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
3047 struct btrfs_inode *inode, u64 file_pos,
3048 struct btrfs_file_extent_item *stack_fi,
3049 const bool update_inode_bytes,
3050 u64 qgroup_reserved)
3052 struct btrfs_root *root = inode->root;
3053 const u64 sectorsize = root->fs_info->sectorsize;
3054 struct btrfs_path *path;
3055 struct extent_buffer *leaf;
3056 struct btrfs_key ins;
3057 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
3058 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
3059 u64 offset = btrfs_stack_file_extent_offset(stack_fi);
3060 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
3061 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
3062 struct btrfs_drop_extents_args drop_args = { 0 };
3065 path = btrfs_alloc_path();
3070 * we may be replacing one extent in the tree with another.
3071 * The new extent is pinned in the extent map, and we don't want
3072 * to drop it from the cache until it is completely in the btree.
3074 * So, tell btrfs_drop_extents to leave this extent in the cache.
3075 * the caller is expected to unpin it and allow it to be merged
3078 drop_args.path = path;
3079 drop_args.start = file_pos;
3080 drop_args.end = file_pos + num_bytes;
3081 drop_args.replace_extent = true;
3082 drop_args.extent_item_size = sizeof(*stack_fi);
3083 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
3087 if (!drop_args.extent_inserted) {
3088 ins.objectid = btrfs_ino(inode);
3089 ins.offset = file_pos;
3090 ins.type = BTRFS_EXTENT_DATA_KEY;
3092 ret = btrfs_insert_empty_item(trans, root, path, &ins,
3097 leaf = path->nodes[0];
3098 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
3099 write_extent_buffer(leaf, stack_fi,
3100 btrfs_item_ptr_offset(leaf, path->slots[0]),
3101 sizeof(struct btrfs_file_extent_item));
3103 btrfs_mark_buffer_dirty(leaf);
3104 btrfs_release_path(path);
3107 * If we dropped an inline extent here, we know the range where it is
3108 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
3109 * number of bytes only for that range containing the inline extent.
3110 * The remaining of the range will be processed when clearning the
3111 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
3113 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
3114 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
3116 inline_size = drop_args.bytes_found - inline_size;
3117 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
3118 drop_args.bytes_found -= inline_size;
3119 num_bytes -= sectorsize;
3122 if (update_inode_bytes)
3123 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
3125 ins.objectid = disk_bytenr;
3126 ins.offset = disk_num_bytes;
3127 ins.type = BTRFS_EXTENT_ITEM_KEY;
3129 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
3133 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
3135 qgroup_reserved, &ins);
3137 btrfs_free_path(path);
3142 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
3145 struct btrfs_block_group *cache;
3147 cache = btrfs_lookup_block_group(fs_info, start);
3150 spin_lock(&cache->lock);
3151 cache->delalloc_bytes -= len;
3152 spin_unlock(&cache->lock);
3154 btrfs_put_block_group(cache);
3157 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
3158 struct btrfs_ordered_extent *oe)
3160 struct btrfs_file_extent_item stack_fi;
3161 bool update_inode_bytes;
3162 u64 num_bytes = oe->num_bytes;
3163 u64 ram_bytes = oe->ram_bytes;
3165 memset(&stack_fi, 0, sizeof(stack_fi));
3166 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
3167 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
3168 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
3169 oe->disk_num_bytes);
3170 btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
3171 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags)) {
3172 num_bytes = oe->truncated_len;
3173 ram_bytes = num_bytes;
3175 btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
3176 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
3177 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3178 /* Encryption and other encoding is reserved and all 0 */
3181 * For delalloc, when completing an ordered extent we update the inode's
3182 * bytes when clearing the range in the inode's io tree, so pass false
3183 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3184 * except if the ordered extent was truncated.
3186 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3187 test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
3188 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3190 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
3191 oe->file_offset, &stack_fi,
3192 update_inode_bytes, oe->qgroup_rsv);
3196 * As ordered data IO finishes, this gets called so we can finish
3197 * an ordered extent if the range of bytes in the file it covers are
3200 int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3202 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
3203 struct btrfs_root *root = inode->root;
3204 struct btrfs_fs_info *fs_info = root->fs_info;
3205 struct btrfs_trans_handle *trans = NULL;
3206 struct extent_io_tree *io_tree = &inode->io_tree;
3207 struct extent_state *cached_state = NULL;
3209 int compress_type = 0;
3211 u64 logical_len = ordered_extent->num_bytes;
3212 bool freespace_inode;
3213 bool truncated = false;
3214 bool clear_reserved_extent = true;
3215 unsigned int clear_bits = EXTENT_DEFRAG;
3217 start = ordered_extent->file_offset;
3218 end = start + ordered_extent->num_bytes - 1;
3220 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3221 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3222 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3223 !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3224 clear_bits |= EXTENT_DELALLOC_NEW;
3226 freespace_inode = btrfs_is_free_space_inode(inode);
3227 if (!freespace_inode)
3228 btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
3230 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3235 /* A valid bdev implies a write on a sequential zone */
3236 if (ordered_extent->bdev) {
3237 btrfs_rewrite_logical_zoned(ordered_extent);
3238 btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3239 ordered_extent->disk_num_bytes);
3240 } else if (btrfs_is_data_reloc_root(inode->root)) {
3241 btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3242 ordered_extent->disk_num_bytes);
3245 btrfs_free_io_failure_record(inode, start, end);
3247 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3249 logical_len = ordered_extent->truncated_len;
3250 /* Truncated the entire extent, don't bother adding */
3255 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3256 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3258 btrfs_inode_safe_disk_i_size_write(inode, 0);
3259 if (freespace_inode)
3260 trans = btrfs_join_transaction_spacecache(root);
3262 trans = btrfs_join_transaction(root);
3263 if (IS_ERR(trans)) {
3264 ret = PTR_ERR(trans);
3268 trans->block_rsv = &inode->block_rsv;
3269 ret = btrfs_update_inode_fallback(trans, root, inode);
3270 if (ret) /* -ENOMEM or corruption */
3271 btrfs_abort_transaction(trans, ret);
3275 clear_bits |= EXTENT_LOCKED;
3276 lock_extent(io_tree, start, end, &cached_state);
3278 if (freespace_inode)
3279 trans = btrfs_join_transaction_spacecache(root);
3281 trans = btrfs_join_transaction(root);
3282 if (IS_ERR(trans)) {
3283 ret = PTR_ERR(trans);
3288 trans->block_rsv = &inode->block_rsv;
3290 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3291 compress_type = ordered_extent->compress_type;
3292 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3293 BUG_ON(compress_type);
3294 ret = btrfs_mark_extent_written(trans, inode,
3295 ordered_extent->file_offset,
3296 ordered_extent->file_offset +
3298 btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3299 ordered_extent->disk_num_bytes);
3301 BUG_ON(root == fs_info->tree_root);
3302 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3304 clear_reserved_extent = false;
3305 btrfs_release_delalloc_bytes(fs_info,
3306 ordered_extent->disk_bytenr,
3307 ordered_extent->disk_num_bytes);
3310 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3311 ordered_extent->num_bytes, trans->transid);
3313 btrfs_abort_transaction(trans, ret);
3317 ret = add_pending_csums(trans, &ordered_extent->list);
3319 btrfs_abort_transaction(trans, ret);
3324 * If this is a new delalloc range, clear its new delalloc flag to
3325 * update the inode's number of bytes. This needs to be done first
3326 * before updating the inode item.
3328 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3329 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3330 clear_extent_bit(&inode->io_tree, start, end,
3331 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3334 btrfs_inode_safe_disk_i_size_write(inode, 0);
3335 ret = btrfs_update_inode_fallback(trans, root, inode);
3336 if (ret) { /* -ENOMEM or corruption */
3337 btrfs_abort_transaction(trans, ret);
3342 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3346 btrfs_end_transaction(trans);
3348 if (ret || truncated) {
3349 u64 unwritten_start = start;
3352 * If we failed to finish this ordered extent for any reason we
3353 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3354 * extent, and mark the inode with the error if it wasn't
3355 * already set. Any error during writeback would have already
3356 * set the mapping error, so we need to set it if we're the ones
3357 * marking this ordered extent as failed.
3359 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3360 &ordered_extent->flags))
3361 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3364 unwritten_start += logical_len;
3365 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3367 /* Drop extent maps for the part of the extent we didn't write. */
3368 btrfs_drop_extent_map_range(inode, unwritten_start, end, false);
3371 * If the ordered extent had an IOERR or something else went
3372 * wrong we need to return the space for this ordered extent
3373 * back to the allocator. We only free the extent in the
3374 * truncated case if we didn't write out the extent at all.
3376 * If we made it past insert_reserved_file_extent before we
3377 * errored out then we don't need to do this as the accounting
3378 * has already been done.
3380 if ((ret || !logical_len) &&
3381 clear_reserved_extent &&
3382 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3383 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3385 * Discard the range before returning it back to the
3388 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3389 btrfs_discard_extent(fs_info,
3390 ordered_extent->disk_bytenr,
3391 ordered_extent->disk_num_bytes,
3393 btrfs_free_reserved_extent(fs_info,
3394 ordered_extent->disk_bytenr,
3395 ordered_extent->disk_num_bytes, 1);
3400 * This needs to be done to make sure anybody waiting knows we are done
3401 * updating everything for this ordered extent.
3403 btrfs_remove_ordered_extent(inode, ordered_extent);
3406 btrfs_put_ordered_extent(ordered_extent);
3407 /* once for the tree */
3408 btrfs_put_ordered_extent(ordered_extent);
3413 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3414 struct page *page, u64 start,
3415 u64 end, bool uptodate)
3417 trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3419 btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start, uptodate);
3423 * Verify the checksum for a single sector without any extra action that depend
3424 * on the type of I/O.
3426 int btrfs_check_sector_csum(struct btrfs_fs_info *fs_info, struct page *page,
3427 u32 pgoff, u8 *csum, const u8 * const csum_expected)
3429 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3432 ASSERT(pgoff + fs_info->sectorsize <= PAGE_SIZE);
3434 shash->tfm = fs_info->csum_shash;
3436 kaddr = kmap_local_page(page) + pgoff;
3437 crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
3438 kunmap_local(kaddr);
3440 if (memcmp(csum, csum_expected, fs_info->csum_size))
3445 static u8 *btrfs_csum_ptr(const struct btrfs_fs_info *fs_info, u8 *csums, u64 offset)
3447 u64 offset_in_sectors = offset >> fs_info->sectorsize_bits;
3449 return csums + offset_in_sectors * fs_info->csum_size;
3453 * check_data_csum - verify checksum of one sector of uncompressed data
3455 * @bbio: btrfs_bio which contains the csum
3456 * @bio_offset: offset to the beginning of the bio (in bytes)
3457 * @page: page where is the data to be verified
3458 * @pgoff: offset inside the page
3460 * The length of such check is always one sector size.
3462 * When csum mismatch is detected, we will also report the error and fill the
3463 * corrupted range with zero. (Thus it needs the extra parameters)
3465 int btrfs_check_data_csum(struct inode *inode, struct btrfs_bio *bbio,
3466 u32 bio_offset, struct page *page, u32 pgoff)
3468 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3469 u32 len = fs_info->sectorsize;
3471 u8 csum[BTRFS_CSUM_SIZE];
3473 ASSERT(pgoff + len <= PAGE_SIZE);
3475 csum_expected = btrfs_csum_ptr(fs_info, bbio->csum, bio_offset);
3477 if (btrfs_check_sector_csum(fs_info, page, pgoff, csum, csum_expected))
3482 btrfs_print_data_csum_error(BTRFS_I(inode),
3483 bbio->file_offset + bio_offset,
3484 csum, csum_expected, bbio->mirror_num);
3486 btrfs_dev_stat_inc_and_print(bbio->device,
3487 BTRFS_DEV_STAT_CORRUPTION_ERRS);
3488 memzero_page(page, pgoff, len);
3493 * When reads are done, we need to check csums to verify the data is correct.
3494 * if there's a match, we allow the bio to finish. If not, the code in
3495 * extent_io.c will try to find good copies for us.
3497 * @bio_offset: offset to the beginning of the bio (in bytes)
3498 * @start: file offset of the range start
3499 * @end: file offset of the range end (inclusive)
3501 * Return a bitmap where bit set means a csum mismatch, and bit not set means
3504 unsigned int btrfs_verify_data_csum(struct btrfs_bio *bbio,
3505 u32 bio_offset, struct page *page,
3508 struct inode *inode = page->mapping->host;
3509 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3510 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3511 struct btrfs_root *root = BTRFS_I(inode)->root;
3512 const u32 sectorsize = root->fs_info->sectorsize;
3514 unsigned int result = 0;
3517 * This only happens for NODATASUM or compressed read.
3518 * Normally this should be covered by above check for compressed read
3519 * or the next check for NODATASUM. Just do a quicker exit here.
3521 if (bbio->csum == NULL)
3524 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3527 if (unlikely(test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state)))
3530 ASSERT(page_offset(page) <= start &&
3531 end <= page_offset(page) + PAGE_SIZE - 1);
3532 for (pg_off = offset_in_page(start);
3533 pg_off < offset_in_page(end);
3534 pg_off += sectorsize, bio_offset += sectorsize) {
3535 u64 file_offset = pg_off + page_offset(page);
3538 if (btrfs_is_data_reloc_root(root) &&
3539 test_range_bit(io_tree, file_offset,
3540 file_offset + sectorsize - 1,
3541 EXTENT_NODATASUM, 1, NULL)) {
3542 /* Skip the range without csum for data reloc inode */
3543 clear_extent_bits(io_tree, file_offset,
3544 file_offset + sectorsize - 1,
3548 ret = btrfs_check_data_csum(inode, bbio, bio_offset, page, pg_off);
3550 const int nr_bit = (pg_off - offset_in_page(start)) >>
3551 root->fs_info->sectorsize_bits;
3553 result |= (1U << nr_bit);
3560 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3562 * @inode: The inode we want to perform iput on
3564 * This function uses the generic vfs_inode::i_count to track whether we should
3565 * just decrement it (in case it's > 1) or if this is the last iput then link
3566 * the inode to the delayed iput machinery. Delayed iputs are processed at
3567 * transaction commit time/superblock commit/cleaner kthread.
3569 void btrfs_add_delayed_iput(struct inode *inode)
3571 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3572 struct btrfs_inode *binode = BTRFS_I(inode);
3574 if (atomic_add_unless(&inode->i_count, -1, 1))
3577 atomic_inc(&fs_info->nr_delayed_iputs);
3578 spin_lock(&fs_info->delayed_iput_lock);
3579 ASSERT(list_empty(&binode->delayed_iput));
3580 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3581 spin_unlock(&fs_info->delayed_iput_lock);
3582 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3583 wake_up_process(fs_info->cleaner_kthread);
3586 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3587 struct btrfs_inode *inode)
3589 list_del_init(&inode->delayed_iput);
3590 spin_unlock(&fs_info->delayed_iput_lock);
3591 iput(&inode->vfs_inode);
3592 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3593 wake_up(&fs_info->delayed_iputs_wait);
3594 spin_lock(&fs_info->delayed_iput_lock);
3597 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3598 struct btrfs_inode *inode)
3600 if (!list_empty(&inode->delayed_iput)) {
3601 spin_lock(&fs_info->delayed_iput_lock);
3602 if (!list_empty(&inode->delayed_iput))
3603 run_delayed_iput_locked(fs_info, inode);
3604 spin_unlock(&fs_info->delayed_iput_lock);
3608 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3611 spin_lock(&fs_info->delayed_iput_lock);
3612 while (!list_empty(&fs_info->delayed_iputs)) {
3613 struct btrfs_inode *inode;
3615 inode = list_first_entry(&fs_info->delayed_iputs,
3616 struct btrfs_inode, delayed_iput);
3617 run_delayed_iput_locked(fs_info, inode);
3618 cond_resched_lock(&fs_info->delayed_iput_lock);
3620 spin_unlock(&fs_info->delayed_iput_lock);
3624 * Wait for flushing all delayed iputs
3626 * @fs_info: the filesystem
3628 * This will wait on any delayed iputs that are currently running with KILLABLE
3629 * set. Once they are all done running we will return, unless we are killed in
3630 * which case we return EINTR. This helps in user operations like fallocate etc
3631 * that might get blocked on the iputs.
3633 * Return EINTR if we were killed, 0 if nothing's pending
3635 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3637 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3638 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3645 * This creates an orphan entry for the given inode in case something goes wrong
3646 * in the middle of an unlink.
3648 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3649 struct btrfs_inode *inode)
3653 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3654 if (ret && ret != -EEXIST) {
3655 btrfs_abort_transaction(trans, ret);
3663 * We have done the delete so we can go ahead and remove the orphan item for
3664 * this particular inode.
3666 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3667 struct btrfs_inode *inode)
3669 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3673 * this cleans up any orphans that may be left on the list from the last use
3676 int btrfs_orphan_cleanup(struct btrfs_root *root)
3678 struct btrfs_fs_info *fs_info = root->fs_info;
3679 struct btrfs_path *path;
3680 struct extent_buffer *leaf;
3681 struct btrfs_key key, found_key;
3682 struct btrfs_trans_handle *trans;
3683 struct inode *inode;
3684 u64 last_objectid = 0;
3685 int ret = 0, nr_unlink = 0;
3687 if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3690 path = btrfs_alloc_path();
3695 path->reada = READA_BACK;
3697 key.objectid = BTRFS_ORPHAN_OBJECTID;
3698 key.type = BTRFS_ORPHAN_ITEM_KEY;
3699 key.offset = (u64)-1;
3702 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3707 * if ret == 0 means we found what we were searching for, which
3708 * is weird, but possible, so only screw with path if we didn't
3709 * find the key and see if we have stuff that matches
3713 if (path->slots[0] == 0)
3718 /* pull out the item */
3719 leaf = path->nodes[0];
3720 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3722 /* make sure the item matches what we want */
3723 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3725 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3728 /* release the path since we're done with it */
3729 btrfs_release_path(path);
3732 * this is where we are basically btrfs_lookup, without the
3733 * crossing root thing. we store the inode number in the
3734 * offset of the orphan item.
3737 if (found_key.offset == last_objectid) {
3739 "Error removing orphan entry, stopping orphan cleanup");
3744 last_objectid = found_key.offset;
3746 found_key.objectid = found_key.offset;
3747 found_key.type = BTRFS_INODE_ITEM_KEY;
3748 found_key.offset = 0;
3749 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3750 ret = PTR_ERR_OR_ZERO(inode);
3751 if (ret && ret != -ENOENT)
3754 if (ret == -ENOENT && root == fs_info->tree_root) {
3755 struct btrfs_root *dead_root;
3756 int is_dead_root = 0;
3759 * This is an orphan in the tree root. Currently these
3760 * could come from 2 sources:
3761 * a) a root (snapshot/subvolume) deletion in progress
3762 * b) a free space cache inode
3763 * We need to distinguish those two, as the orphan item
3764 * for a root must not get deleted before the deletion
3765 * of the snapshot/subvolume's tree completes.
3767 * btrfs_find_orphan_roots() ran before us, which has
3768 * found all deleted roots and loaded them into
3769 * fs_info->fs_roots_radix. So here we can find if an
3770 * orphan item corresponds to a deleted root by looking
3771 * up the root from that radix tree.
3774 spin_lock(&fs_info->fs_roots_radix_lock);
3775 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3776 (unsigned long)found_key.objectid);
3777 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3779 spin_unlock(&fs_info->fs_roots_radix_lock);
3782 /* prevent this orphan from being found again */
3783 key.offset = found_key.objectid - 1;
3790 * If we have an inode with links, there are a couple of
3793 * 1. We were halfway through creating fsverity metadata for the
3794 * file. In that case, the orphan item represents incomplete
3795 * fsverity metadata which must be cleaned up with
3796 * btrfs_drop_verity_items and deleting the orphan item.
3798 * 2. Old kernels (before v3.12) used to create an
3799 * orphan item for truncate indicating that there were possibly
3800 * extent items past i_size that needed to be deleted. In v3.12,
3801 * truncate was changed to update i_size in sync with the extent
3802 * items, but the (useless) orphan item was still created. Since
3803 * v4.18, we don't create the orphan item for truncate at all.
3805 * So, this item could mean that we need to do a truncate, but
3806 * only if this filesystem was last used on a pre-v3.12 kernel
3807 * and was not cleanly unmounted. The odds of that are quite
3808 * slim, and it's a pain to do the truncate now, so just delete
3811 * It's also possible that this orphan item was supposed to be
3812 * deleted but wasn't. The inode number may have been reused,
3813 * but either way, we can delete the orphan item.
3815 if (ret == -ENOENT || inode->i_nlink) {
3817 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3822 trans = btrfs_start_transaction(root, 1);
3823 if (IS_ERR(trans)) {
3824 ret = PTR_ERR(trans);
3827 btrfs_debug(fs_info, "auto deleting %Lu",
3828 found_key.objectid);
3829 ret = btrfs_del_orphan_item(trans, root,
3830 found_key.objectid);
3831 btrfs_end_transaction(trans);
3839 /* this will do delete_inode and everything for us */
3842 /* release the path since we're done with it */
3843 btrfs_release_path(path);
3845 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3846 trans = btrfs_join_transaction(root);
3848 btrfs_end_transaction(trans);
3852 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3856 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3857 btrfs_free_path(path);
3862 * very simple check to peek ahead in the leaf looking for xattrs. If we
3863 * don't find any xattrs, we know there can't be any acls.
3865 * slot is the slot the inode is in, objectid is the objectid of the inode
3867 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3868 int slot, u64 objectid,
3869 int *first_xattr_slot)
3871 u32 nritems = btrfs_header_nritems(leaf);
3872 struct btrfs_key found_key;
3873 static u64 xattr_access = 0;
3874 static u64 xattr_default = 0;
3877 if (!xattr_access) {
3878 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3879 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3880 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3881 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3885 *first_xattr_slot = -1;
3886 while (slot < nritems) {
3887 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3889 /* we found a different objectid, there must not be acls */
3890 if (found_key.objectid != objectid)
3893 /* we found an xattr, assume we've got an acl */
3894 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3895 if (*first_xattr_slot == -1)
3896 *first_xattr_slot = slot;
3897 if (found_key.offset == xattr_access ||
3898 found_key.offset == xattr_default)
3903 * we found a key greater than an xattr key, there can't
3904 * be any acls later on
3906 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3913 * it goes inode, inode backrefs, xattrs, extents,
3914 * so if there are a ton of hard links to an inode there can
3915 * be a lot of backrefs. Don't waste time searching too hard,
3916 * this is just an optimization
3921 /* we hit the end of the leaf before we found an xattr or
3922 * something larger than an xattr. We have to assume the inode
3925 if (*first_xattr_slot == -1)
3926 *first_xattr_slot = slot;
3931 * read an inode from the btree into the in-memory inode
3933 static int btrfs_read_locked_inode(struct inode *inode,
3934 struct btrfs_path *in_path)
3936 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3937 struct btrfs_path *path = in_path;
3938 struct extent_buffer *leaf;
3939 struct btrfs_inode_item *inode_item;
3940 struct btrfs_root *root = BTRFS_I(inode)->root;
3941 struct btrfs_key location;
3946 bool filled = false;
3947 int first_xattr_slot;
3949 ret = btrfs_fill_inode(inode, &rdev);
3954 path = btrfs_alloc_path();
3959 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3961 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3963 if (path != in_path)
3964 btrfs_free_path(path);
3968 leaf = path->nodes[0];
3973 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3974 struct btrfs_inode_item);
3975 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3976 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3977 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3978 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3979 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3980 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3981 round_up(i_size_read(inode), fs_info->sectorsize));
3983 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3984 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3986 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3987 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3989 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3990 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3992 BTRFS_I(inode)->i_otime.tv_sec =
3993 btrfs_timespec_sec(leaf, &inode_item->otime);
3994 BTRFS_I(inode)->i_otime.tv_nsec =
3995 btrfs_timespec_nsec(leaf, &inode_item->otime);
3997 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3998 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3999 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
4001 inode_set_iversion_queried(inode,
4002 btrfs_inode_sequence(leaf, inode_item));
4003 inode->i_generation = BTRFS_I(inode)->generation;
4005 rdev = btrfs_inode_rdev(leaf, inode_item);
4007 BTRFS_I(inode)->index_cnt = (u64)-1;
4008 btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
4009 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
4013 * If we were modified in the current generation and evicted from memory
4014 * and then re-read we need to do a full sync since we don't have any
4015 * idea about which extents were modified before we were evicted from
4018 * This is required for both inode re-read from disk and delayed inode
4019 * in delayed_nodes_tree.
4021 if (BTRFS_I(inode)->last_trans == fs_info->generation)
4022 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4023 &BTRFS_I(inode)->runtime_flags);
4026 * We don't persist the id of the transaction where an unlink operation
4027 * against the inode was last made. So here we assume the inode might
4028 * have been evicted, and therefore the exact value of last_unlink_trans
4029 * lost, and set it to last_trans to avoid metadata inconsistencies
4030 * between the inode and its parent if the inode is fsync'ed and the log
4031 * replayed. For example, in the scenario:
4034 * ln mydir/foo mydir/bar
4037 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
4038 * xfs_io -c fsync mydir/foo
4040 * mount fs, triggers fsync log replay
4042 * We must make sure that when we fsync our inode foo we also log its
4043 * parent inode, otherwise after log replay the parent still has the
4044 * dentry with the "bar" name but our inode foo has a link count of 1
4045 * and doesn't have an inode ref with the name "bar" anymore.
4047 * Setting last_unlink_trans to last_trans is a pessimistic approach,
4048 * but it guarantees correctness at the expense of occasional full
4049 * transaction commits on fsync if our inode is a directory, or if our
4050 * inode is not a directory, logging its parent unnecessarily.
4052 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
4055 * Same logic as for last_unlink_trans. We don't persist the generation
4056 * of the last transaction where this inode was used for a reflink
4057 * operation, so after eviction and reloading the inode we must be
4058 * pessimistic and assume the last transaction that modified the inode.
4060 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
4063 if (inode->i_nlink != 1 ||
4064 path->slots[0] >= btrfs_header_nritems(leaf))
4067 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4068 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
4071 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4072 if (location.type == BTRFS_INODE_REF_KEY) {
4073 struct btrfs_inode_ref *ref;
4075 ref = (struct btrfs_inode_ref *)ptr;
4076 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
4077 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
4078 struct btrfs_inode_extref *extref;
4080 extref = (struct btrfs_inode_extref *)ptr;
4081 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
4086 * try to precache a NULL acl entry for files that don't have
4087 * any xattrs or acls
4089 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
4090 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
4091 if (first_xattr_slot != -1) {
4092 path->slots[0] = first_xattr_slot;
4093 ret = btrfs_load_inode_props(inode, path);
4096 "error loading props for ino %llu (root %llu): %d",
4097 btrfs_ino(BTRFS_I(inode)),
4098 root->root_key.objectid, ret);
4100 if (path != in_path)
4101 btrfs_free_path(path);
4104 cache_no_acl(inode);
4106 switch (inode->i_mode & S_IFMT) {
4108 inode->i_mapping->a_ops = &btrfs_aops;
4109 inode->i_fop = &btrfs_file_operations;
4110 inode->i_op = &btrfs_file_inode_operations;
4113 inode->i_fop = &btrfs_dir_file_operations;
4114 inode->i_op = &btrfs_dir_inode_operations;
4117 inode->i_op = &btrfs_symlink_inode_operations;
4118 inode_nohighmem(inode);
4119 inode->i_mapping->a_ops = &btrfs_aops;
4122 inode->i_op = &btrfs_special_inode_operations;
4123 init_special_inode(inode, inode->i_mode, rdev);
4127 btrfs_sync_inode_flags_to_i_flags(inode);
4132 * given a leaf and an inode, copy the inode fields into the leaf
4134 static void fill_inode_item(struct btrfs_trans_handle *trans,
4135 struct extent_buffer *leaf,
4136 struct btrfs_inode_item *item,
4137 struct inode *inode)
4139 struct btrfs_map_token token;
4142 btrfs_init_map_token(&token, leaf);
4144 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4145 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4146 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
4147 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4148 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4150 btrfs_set_token_timespec_sec(&token, &item->atime,
4151 inode->i_atime.tv_sec);
4152 btrfs_set_token_timespec_nsec(&token, &item->atime,
4153 inode->i_atime.tv_nsec);
4155 btrfs_set_token_timespec_sec(&token, &item->mtime,
4156 inode->i_mtime.tv_sec);
4157 btrfs_set_token_timespec_nsec(&token, &item->mtime,
4158 inode->i_mtime.tv_nsec);
4160 btrfs_set_token_timespec_sec(&token, &item->ctime,
4161 inode->i_ctime.tv_sec);
4162 btrfs_set_token_timespec_nsec(&token, &item->ctime,
4163 inode->i_ctime.tv_nsec);
4165 btrfs_set_token_timespec_sec(&token, &item->otime,
4166 BTRFS_I(inode)->i_otime.tv_sec);
4167 btrfs_set_token_timespec_nsec(&token, &item->otime,
4168 BTRFS_I(inode)->i_otime.tv_nsec);
4170 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
4171 btrfs_set_token_inode_generation(&token, item,
4172 BTRFS_I(inode)->generation);
4173 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4174 btrfs_set_token_inode_transid(&token, item, trans->transid);
4175 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4176 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4177 BTRFS_I(inode)->ro_flags);
4178 btrfs_set_token_inode_flags(&token, item, flags);
4179 btrfs_set_token_inode_block_group(&token, item, 0);
4183 * copy everything in the in-memory inode into the btree.
4185 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4186 struct btrfs_root *root,
4187 struct btrfs_inode *inode)
4189 struct btrfs_inode_item *inode_item;
4190 struct btrfs_path *path;
4191 struct extent_buffer *leaf;
4194 path = btrfs_alloc_path();
4198 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
4205 leaf = path->nodes[0];
4206 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4207 struct btrfs_inode_item);
4209 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4210 btrfs_mark_buffer_dirty(leaf);
4211 btrfs_set_inode_last_trans(trans, inode);
4214 btrfs_free_path(path);
4219 * copy everything in the in-memory inode into the btree.
4221 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4222 struct btrfs_root *root,
4223 struct btrfs_inode *inode)
4225 struct btrfs_fs_info *fs_info = root->fs_info;
4229 * If the inode is a free space inode, we can deadlock during commit
4230 * if we put it into the delayed code.
4232 * The data relocation inode should also be directly updated
4235 if (!btrfs_is_free_space_inode(inode)
4236 && !btrfs_is_data_reloc_root(root)
4237 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4238 btrfs_update_root_times(trans, root);
4240 ret = btrfs_delayed_update_inode(trans, root, inode);
4242 btrfs_set_inode_last_trans(trans, inode);
4246 return btrfs_update_inode_item(trans, root, inode);
4249 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4250 struct btrfs_root *root, struct btrfs_inode *inode)
4254 ret = btrfs_update_inode(trans, root, inode);
4256 return btrfs_update_inode_item(trans, root, inode);
4261 * unlink helper that gets used here in inode.c and in the tree logging
4262 * recovery code. It remove a link in a directory with a given name, and
4263 * also drops the back refs in the inode to the directory
4265 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4266 struct btrfs_inode *dir,
4267 struct btrfs_inode *inode,
4268 const char *name, int name_len,
4269 struct btrfs_rename_ctx *rename_ctx)
4271 struct btrfs_root *root = dir->root;
4272 struct btrfs_fs_info *fs_info = root->fs_info;
4273 struct btrfs_path *path;
4275 struct btrfs_dir_item *di;
4277 u64 ino = btrfs_ino(inode);
4278 u64 dir_ino = btrfs_ino(dir);
4280 path = btrfs_alloc_path();
4286 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4287 name, name_len, -1);
4288 if (IS_ERR_OR_NULL(di)) {
4289 ret = di ? PTR_ERR(di) : -ENOENT;
4292 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4295 btrfs_release_path(path);
4298 * If we don't have dir index, we have to get it by looking up
4299 * the inode ref, since we get the inode ref, remove it directly,
4300 * it is unnecessary to do delayed deletion.
4302 * But if we have dir index, needn't search inode ref to get it.
4303 * Since the inode ref is close to the inode item, it is better
4304 * that we delay to delete it, and just do this deletion when
4305 * we update the inode item.
4307 if (inode->dir_index) {
4308 ret = btrfs_delayed_delete_inode_ref(inode);
4310 index = inode->dir_index;
4315 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4319 "failed to delete reference to %.*s, inode %llu parent %llu",
4320 name_len, name, ino, dir_ino);
4321 btrfs_abort_transaction(trans, ret);
4326 rename_ctx->index = index;
4328 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4330 btrfs_abort_transaction(trans, ret);
4335 * If we are in a rename context, we don't need to update anything in the
4336 * log. That will be done later during the rename by btrfs_log_new_name().
4337 * Besides that, doing it here would only cause extra unnecessary btree
4338 * operations on the log tree, increasing latency for applications.
4341 btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4343 btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4348 * If we have a pending delayed iput we could end up with the final iput
4349 * being run in btrfs-cleaner context. If we have enough of these built
4350 * up we can end up burning a lot of time in btrfs-cleaner without any
4351 * way to throttle the unlinks. Since we're currently holding a ref on
4352 * the inode we can run the delayed iput here without any issues as the
4353 * final iput won't be done until after we drop the ref we're currently
4356 btrfs_run_delayed_iput(fs_info, inode);
4358 btrfs_free_path(path);
4362 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4363 inode_inc_iversion(&inode->vfs_inode);
4364 inode_inc_iversion(&dir->vfs_inode);
4365 inode->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4366 dir->vfs_inode.i_mtime = inode->vfs_inode.i_ctime;
4367 dir->vfs_inode.i_ctime = inode->vfs_inode.i_ctime;
4368 ret = btrfs_update_inode(trans, root, dir);
4373 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4374 struct btrfs_inode *dir, struct btrfs_inode *inode,
4375 const char *name, int name_len)
4378 ret = __btrfs_unlink_inode(trans, dir, inode, name, name_len, NULL);
4380 drop_nlink(&inode->vfs_inode);
4381 ret = btrfs_update_inode(trans, inode->root, inode);
4387 * helper to start transaction for unlink and rmdir.
4389 * unlink and rmdir are special in btrfs, they do not always free space, so
4390 * if we cannot make our reservations the normal way try and see if there is
4391 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4392 * allow the unlink to occur.
4394 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4396 struct btrfs_root *root = BTRFS_I(dir)->root;
4399 * 1 for the possible orphan item
4400 * 1 for the dir item
4401 * 1 for the dir index
4402 * 1 for the inode ref
4404 * 1 for the parent inode
4406 return btrfs_start_transaction_fallback_global_rsv(root, 6);
4409 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4411 struct btrfs_trans_handle *trans;
4412 struct inode *inode = d_inode(dentry);
4415 trans = __unlink_start_trans(dir);
4417 return PTR_ERR(trans);
4419 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4422 ret = btrfs_unlink_inode(trans, BTRFS_I(dir),
4423 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4424 dentry->d_name.len);
4428 if (inode->i_nlink == 0) {
4429 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4435 btrfs_end_transaction(trans);
4436 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4440 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4441 struct inode *dir, struct dentry *dentry)
4443 struct btrfs_root *root = BTRFS_I(dir)->root;
4444 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4445 struct btrfs_path *path;
4446 struct extent_buffer *leaf;
4447 struct btrfs_dir_item *di;
4448 struct btrfs_key key;
4449 const char *name = dentry->d_name.name;
4450 int name_len = dentry->d_name.len;
4454 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4456 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4457 objectid = inode->root->root_key.objectid;
4458 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4459 objectid = inode->location.objectid;
4465 path = btrfs_alloc_path();
4469 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4470 name, name_len, -1);
4471 if (IS_ERR_OR_NULL(di)) {
4472 ret = di ? PTR_ERR(di) : -ENOENT;
4476 leaf = path->nodes[0];
4477 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4478 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4479 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4481 btrfs_abort_transaction(trans, ret);
4484 btrfs_release_path(path);
4487 * This is a placeholder inode for a subvolume we didn't have a
4488 * reference to at the time of the snapshot creation. In the meantime
4489 * we could have renamed the real subvol link into our snapshot, so
4490 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4491 * Instead simply lookup the dir_index_item for this entry so we can
4492 * remove it. Otherwise we know we have a ref to the root and we can
4493 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4495 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4496 di = btrfs_search_dir_index_item(root, path, dir_ino,
4498 if (IS_ERR_OR_NULL(di)) {
4503 btrfs_abort_transaction(trans, ret);
4507 leaf = path->nodes[0];
4508 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4510 btrfs_release_path(path);
4512 ret = btrfs_del_root_ref(trans, objectid,
4513 root->root_key.objectid, dir_ino,
4514 &index, name, name_len);
4516 btrfs_abort_transaction(trans, ret);
4521 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4523 btrfs_abort_transaction(trans, ret);
4527 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4528 inode_inc_iversion(dir);
4529 dir->i_mtime = current_time(dir);
4530 dir->i_ctime = dir->i_mtime;
4531 ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4533 btrfs_abort_transaction(trans, ret);
4535 btrfs_free_path(path);
4540 * Helper to check if the subvolume references other subvolumes or if it's
4543 static noinline int may_destroy_subvol(struct btrfs_root *root)
4545 struct btrfs_fs_info *fs_info = root->fs_info;
4546 struct btrfs_path *path;
4547 struct btrfs_dir_item *di;
4548 struct btrfs_key key;
4552 path = btrfs_alloc_path();
4556 /* Make sure this root isn't set as the default subvol */
4557 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4558 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4559 dir_id, "default", 7, 0);
4560 if (di && !IS_ERR(di)) {
4561 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4562 if (key.objectid == root->root_key.objectid) {
4565 "deleting default subvolume %llu is not allowed",
4569 btrfs_release_path(path);
4572 key.objectid = root->root_key.objectid;
4573 key.type = BTRFS_ROOT_REF_KEY;
4574 key.offset = (u64)-1;
4576 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4582 if (path->slots[0] > 0) {
4584 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4585 if (key.objectid == root->root_key.objectid &&
4586 key.type == BTRFS_ROOT_REF_KEY)
4590 btrfs_free_path(path);
4594 /* Delete all dentries for inodes belonging to the root */
4595 static void btrfs_prune_dentries(struct btrfs_root *root)
4597 struct btrfs_fs_info *fs_info = root->fs_info;
4598 struct rb_node *node;
4599 struct rb_node *prev;
4600 struct btrfs_inode *entry;
4601 struct inode *inode;
4604 if (!BTRFS_FS_ERROR(fs_info))
4605 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4607 spin_lock(&root->inode_lock);
4609 node = root->inode_tree.rb_node;
4613 entry = rb_entry(node, struct btrfs_inode, rb_node);
4615 if (objectid < btrfs_ino(entry))
4616 node = node->rb_left;
4617 else if (objectid > btrfs_ino(entry))
4618 node = node->rb_right;
4624 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4625 if (objectid <= btrfs_ino(entry)) {
4629 prev = rb_next(prev);
4633 entry = rb_entry(node, struct btrfs_inode, rb_node);
4634 objectid = btrfs_ino(entry) + 1;
4635 inode = igrab(&entry->vfs_inode);
4637 spin_unlock(&root->inode_lock);
4638 if (atomic_read(&inode->i_count) > 1)
4639 d_prune_aliases(inode);
4641 * btrfs_drop_inode will have it removed from the inode
4642 * cache when its usage count hits zero.
4646 spin_lock(&root->inode_lock);
4650 if (cond_resched_lock(&root->inode_lock))
4653 node = rb_next(node);
4655 spin_unlock(&root->inode_lock);
4658 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4660 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4661 struct btrfs_root *root = BTRFS_I(dir)->root;
4662 struct inode *inode = d_inode(dentry);
4663 struct btrfs_root *dest = BTRFS_I(inode)->root;
4664 struct btrfs_trans_handle *trans;
4665 struct btrfs_block_rsv block_rsv;
4670 * Don't allow to delete a subvolume with send in progress. This is
4671 * inside the inode lock so the error handling that has to drop the bit
4672 * again is not run concurrently.
4674 spin_lock(&dest->root_item_lock);
4675 if (dest->send_in_progress) {
4676 spin_unlock(&dest->root_item_lock);
4678 "attempt to delete subvolume %llu during send",
4679 dest->root_key.objectid);
4682 if (atomic_read(&dest->nr_swapfiles)) {
4683 spin_unlock(&dest->root_item_lock);
4685 "attempt to delete subvolume %llu with active swapfile",
4686 root->root_key.objectid);
4689 root_flags = btrfs_root_flags(&dest->root_item);
4690 btrfs_set_root_flags(&dest->root_item,
4691 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4692 spin_unlock(&dest->root_item_lock);
4694 down_write(&fs_info->subvol_sem);
4696 ret = may_destroy_subvol(dest);
4700 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4702 * One for dir inode,
4703 * two for dir entries,
4704 * two for root ref/backref.
4706 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4710 trans = btrfs_start_transaction(root, 0);
4711 if (IS_ERR(trans)) {
4712 ret = PTR_ERR(trans);
4715 trans->block_rsv = &block_rsv;
4716 trans->bytes_reserved = block_rsv.size;
4718 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4720 ret = btrfs_unlink_subvol(trans, dir, dentry);
4722 btrfs_abort_transaction(trans, ret);
4726 ret = btrfs_record_root_in_trans(trans, dest);
4728 btrfs_abort_transaction(trans, ret);
4732 memset(&dest->root_item.drop_progress, 0,
4733 sizeof(dest->root_item.drop_progress));
4734 btrfs_set_root_drop_level(&dest->root_item, 0);
4735 btrfs_set_root_refs(&dest->root_item, 0);
4737 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4738 ret = btrfs_insert_orphan_item(trans,
4740 dest->root_key.objectid);
4742 btrfs_abort_transaction(trans, ret);
4747 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4748 BTRFS_UUID_KEY_SUBVOL,
4749 dest->root_key.objectid);
4750 if (ret && ret != -ENOENT) {
4751 btrfs_abort_transaction(trans, ret);
4754 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4755 ret = btrfs_uuid_tree_remove(trans,
4756 dest->root_item.received_uuid,
4757 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4758 dest->root_key.objectid);
4759 if (ret && ret != -ENOENT) {
4760 btrfs_abort_transaction(trans, ret);
4765 free_anon_bdev(dest->anon_dev);
4768 trans->block_rsv = NULL;
4769 trans->bytes_reserved = 0;
4770 ret = btrfs_end_transaction(trans);
4771 inode->i_flags |= S_DEAD;
4773 btrfs_subvolume_release_metadata(root, &block_rsv);
4775 up_write(&fs_info->subvol_sem);
4777 spin_lock(&dest->root_item_lock);
4778 root_flags = btrfs_root_flags(&dest->root_item);
4779 btrfs_set_root_flags(&dest->root_item,
4780 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4781 spin_unlock(&dest->root_item_lock);
4783 d_invalidate(dentry);
4784 btrfs_prune_dentries(dest);
4785 ASSERT(dest->send_in_progress == 0);
4791 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4793 struct inode *inode = d_inode(dentry);
4794 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
4796 struct btrfs_trans_handle *trans;
4797 u64 last_unlink_trans;
4799 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4801 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
4802 if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4804 "extent tree v2 doesn't support snapshot deletion yet");
4807 return btrfs_delete_subvolume(dir, dentry);
4810 trans = __unlink_start_trans(dir);
4812 return PTR_ERR(trans);
4814 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4815 err = btrfs_unlink_subvol(trans, dir, dentry);
4819 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4823 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4825 /* now the directory is empty */
4826 err = btrfs_unlink_inode(trans, BTRFS_I(dir),
4827 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4828 dentry->d_name.len);
4830 btrfs_i_size_write(BTRFS_I(inode), 0);
4832 * Propagate the last_unlink_trans value of the deleted dir to
4833 * its parent directory. This is to prevent an unrecoverable
4834 * log tree in the case we do something like this:
4836 * 2) create snapshot under dir foo
4837 * 3) delete the snapshot
4840 * 6) fsync foo or some file inside foo
4842 if (last_unlink_trans >= trans->transid)
4843 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4846 btrfs_end_transaction(trans);
4847 btrfs_btree_balance_dirty(fs_info);
4853 * btrfs_truncate_block - read, zero a chunk and write a block
4854 * @inode - inode that we're zeroing
4855 * @from - the offset to start zeroing
4856 * @len - the length to zero, 0 to zero the entire range respective to the
4858 * @front - zero up to the offset instead of from the offset on
4860 * This will find the block for the "from" offset and cow the block and zero the
4861 * part we want to zero. This is used with truncate and hole punching.
4863 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4866 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4867 struct address_space *mapping = inode->vfs_inode.i_mapping;
4868 struct extent_io_tree *io_tree = &inode->io_tree;
4869 struct btrfs_ordered_extent *ordered;
4870 struct extent_state *cached_state = NULL;
4871 struct extent_changeset *data_reserved = NULL;
4872 bool only_release_metadata = false;
4873 u32 blocksize = fs_info->sectorsize;
4874 pgoff_t index = from >> PAGE_SHIFT;
4875 unsigned offset = from & (blocksize - 1);
4877 gfp_t mask = btrfs_alloc_write_mask(mapping);
4878 size_t write_bytes = blocksize;
4883 if (IS_ALIGNED(offset, blocksize) &&
4884 (!len || IS_ALIGNED(len, blocksize)))
4887 block_start = round_down(from, blocksize);
4888 block_end = block_start + blocksize - 1;
4890 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4893 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
4894 /* For nocow case, no need to reserve data space */
4895 only_release_metadata = true;
4900 ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
4902 if (!only_release_metadata)
4903 btrfs_free_reserved_data_space(inode, data_reserved,
4904 block_start, blocksize);
4908 page = find_or_create_page(mapping, index, mask);
4910 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4912 btrfs_delalloc_release_extents(inode, blocksize);
4916 ret = set_page_extent_mapped(page);
4920 if (!PageUptodate(page)) {
4921 ret = btrfs_read_folio(NULL, page_folio(page));
4923 if (page->mapping != mapping) {
4928 if (!PageUptodate(page)) {
4933 wait_on_page_writeback(page);
4935 lock_extent(io_tree, block_start, block_end, &cached_state);
4937 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4939 unlock_extent(io_tree, block_start, block_end, &cached_state);
4942 btrfs_start_ordered_extent(ordered, 1);
4943 btrfs_put_ordered_extent(ordered);
4947 clear_extent_bit(&inode->io_tree, block_start, block_end,
4948 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4951 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4954 unlock_extent(io_tree, block_start, block_end, &cached_state);
4958 if (offset != blocksize) {
4960 len = blocksize - offset;
4962 memzero_page(page, (block_start - page_offset(page)),
4965 memzero_page(page, (block_start - page_offset(page)) + offset,
4968 btrfs_page_clear_checked(fs_info, page, block_start,
4969 block_end + 1 - block_start);
4970 btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
4971 unlock_extent(io_tree, block_start, block_end, &cached_state);
4973 if (only_release_metadata)
4974 set_extent_bit(&inode->io_tree, block_start, block_end,
4975 EXTENT_NORESERVE, NULL, GFP_NOFS);
4979 if (only_release_metadata)
4980 btrfs_delalloc_release_metadata(inode, blocksize, true);
4982 btrfs_delalloc_release_space(inode, data_reserved,
4983 block_start, blocksize, true);
4985 btrfs_delalloc_release_extents(inode, blocksize);
4989 if (only_release_metadata)
4990 btrfs_check_nocow_unlock(inode);
4991 extent_changeset_free(data_reserved);
4995 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4996 u64 offset, u64 len)
4998 struct btrfs_fs_info *fs_info = root->fs_info;
4999 struct btrfs_trans_handle *trans;
5000 struct btrfs_drop_extents_args drop_args = { 0 };
5004 * If NO_HOLES is enabled, we don't need to do anything.
5005 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5006 * or btrfs_update_inode() will be called, which guarantee that the next
5007 * fsync will know this inode was changed and needs to be logged.
5009 if (btrfs_fs_incompat(fs_info, NO_HOLES))
5013 * 1 - for the one we're dropping
5014 * 1 - for the one we're adding
5015 * 1 - for updating the inode.
5017 trans = btrfs_start_transaction(root, 3);
5019 return PTR_ERR(trans);
5021 drop_args.start = offset;
5022 drop_args.end = offset + len;
5023 drop_args.drop_cache = true;
5025 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5027 btrfs_abort_transaction(trans, ret);
5028 btrfs_end_transaction(trans);
5032 ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
5034 btrfs_abort_transaction(trans, ret);
5036 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5037 btrfs_update_inode(trans, root, inode);
5039 btrfs_end_transaction(trans);
5044 * This function puts in dummy file extents for the area we're creating a hole
5045 * for. So if we are truncating this file to a larger size we need to insert
5046 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5047 * the range between oldsize and size
5049 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5051 struct btrfs_root *root = inode->root;
5052 struct btrfs_fs_info *fs_info = root->fs_info;
5053 struct extent_io_tree *io_tree = &inode->io_tree;
5054 struct extent_map *em = NULL;
5055 struct extent_state *cached_state = NULL;
5056 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5057 u64 block_end = ALIGN(size, fs_info->sectorsize);
5064 * If our size started in the middle of a block we need to zero out the
5065 * rest of the block before we expand the i_size, otherwise we could
5066 * expose stale data.
5068 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5072 if (size <= hole_start)
5075 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5077 cur_offset = hole_start;
5079 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5080 block_end - cur_offset);
5086 last_byte = min(extent_map_end(em), block_end);
5087 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5088 hole_size = last_byte - cur_offset;
5090 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5091 struct extent_map *hole_em;
5093 err = maybe_insert_hole(root, inode, cur_offset,
5098 err = btrfs_inode_set_file_extent_range(inode,
5099 cur_offset, hole_size);
5103 hole_em = alloc_extent_map();
5105 btrfs_drop_extent_map_range(inode, cur_offset,
5106 cur_offset + hole_size - 1,
5108 btrfs_set_inode_full_sync(inode);
5111 hole_em->start = cur_offset;
5112 hole_em->len = hole_size;
5113 hole_em->orig_start = cur_offset;
5115 hole_em->block_start = EXTENT_MAP_HOLE;
5116 hole_em->block_len = 0;
5117 hole_em->orig_block_len = 0;
5118 hole_em->ram_bytes = hole_size;
5119 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5120 hole_em->generation = fs_info->generation;
5122 err = btrfs_replace_extent_map_range(inode, hole_em, true);
5123 free_extent_map(hole_em);
5125 err = btrfs_inode_set_file_extent_range(inode,
5126 cur_offset, hole_size);
5131 free_extent_map(em);
5133 cur_offset = last_byte;
5134 if (cur_offset >= block_end)
5137 free_extent_map(em);
5138 unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5142 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5144 struct btrfs_root *root = BTRFS_I(inode)->root;
5145 struct btrfs_trans_handle *trans;
5146 loff_t oldsize = i_size_read(inode);
5147 loff_t newsize = attr->ia_size;
5148 int mask = attr->ia_valid;
5152 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5153 * special case where we need to update the times despite not having
5154 * these flags set. For all other operations the VFS set these flags
5155 * explicitly if it wants a timestamp update.
5157 if (newsize != oldsize) {
5158 inode_inc_iversion(inode);
5159 if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5160 inode->i_mtime = current_time(inode);
5161 inode->i_ctime = inode->i_mtime;
5165 if (newsize > oldsize) {
5167 * Don't do an expanding truncate while snapshotting is ongoing.
5168 * This is to ensure the snapshot captures a fully consistent
5169 * state of this file - if the snapshot captures this expanding
5170 * truncation, it must capture all writes that happened before
5173 btrfs_drew_write_lock(&root->snapshot_lock);
5174 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5176 btrfs_drew_write_unlock(&root->snapshot_lock);
5180 trans = btrfs_start_transaction(root, 1);
5181 if (IS_ERR(trans)) {
5182 btrfs_drew_write_unlock(&root->snapshot_lock);
5183 return PTR_ERR(trans);
5186 i_size_write(inode, newsize);
5187 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5188 pagecache_isize_extended(inode, oldsize, newsize);
5189 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5190 btrfs_drew_write_unlock(&root->snapshot_lock);
5191 btrfs_end_transaction(trans);
5193 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5195 if (btrfs_is_zoned(fs_info)) {
5196 ret = btrfs_wait_ordered_range(inode,
5197 ALIGN(newsize, fs_info->sectorsize),
5204 * We're truncating a file that used to have good data down to
5205 * zero. Make sure any new writes to the file get on disk
5209 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5210 &BTRFS_I(inode)->runtime_flags);
5212 truncate_setsize(inode, newsize);
5214 inode_dio_wait(inode);
5216 ret = btrfs_truncate(inode, newsize == oldsize);
5217 if (ret && inode->i_nlink) {
5221 * Truncate failed, so fix up the in-memory size. We
5222 * adjusted disk_i_size down as we removed extents, so
5223 * wait for disk_i_size to be stable and then update the
5224 * in-memory size to match.
5226 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5229 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5236 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5239 struct inode *inode = d_inode(dentry);
5240 struct btrfs_root *root = BTRFS_I(inode)->root;
5243 if (btrfs_root_readonly(root))
5246 err = setattr_prepare(mnt_userns, dentry, attr);
5250 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5251 err = btrfs_setsize(inode, attr);
5256 if (attr->ia_valid) {
5257 setattr_copy(mnt_userns, inode, attr);
5258 inode_inc_iversion(inode);
5259 err = btrfs_dirty_inode(inode);
5261 if (!err && attr->ia_valid & ATTR_MODE)
5262 err = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5269 * While truncating the inode pages during eviction, we get the VFS
5270 * calling btrfs_invalidate_folio() against each folio of the inode. This
5271 * is slow because the calls to btrfs_invalidate_folio() result in a
5272 * huge amount of calls to lock_extent() and clear_extent_bit(),
5273 * which keep merging and splitting extent_state structures over and over,
5274 * wasting lots of time.
5276 * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5277 * skip all those expensive operations on a per folio basis and do only
5278 * the ordered io finishing, while we release here the extent_map and
5279 * extent_state structures, without the excessive merging and splitting.
5281 static void evict_inode_truncate_pages(struct inode *inode)
5283 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5284 struct rb_node *node;
5286 ASSERT(inode->i_state & I_FREEING);
5287 truncate_inode_pages_final(&inode->i_data);
5289 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5292 * Keep looping until we have no more ranges in the io tree.
5293 * We can have ongoing bios started by readahead that have
5294 * their endio callback (extent_io.c:end_bio_extent_readpage)
5295 * still in progress (unlocked the pages in the bio but did not yet
5296 * unlocked the ranges in the io tree). Therefore this means some
5297 * ranges can still be locked and eviction started because before
5298 * submitting those bios, which are executed by a separate task (work
5299 * queue kthread), inode references (inode->i_count) were not taken
5300 * (which would be dropped in the end io callback of each bio).
5301 * Therefore here we effectively end up waiting for those bios and
5302 * anyone else holding locked ranges without having bumped the inode's
5303 * reference count - if we don't do it, when they access the inode's
5304 * io_tree to unlock a range it may be too late, leading to an
5305 * use-after-free issue.
5307 spin_lock(&io_tree->lock);
5308 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5309 struct extent_state *state;
5310 struct extent_state *cached_state = NULL;
5313 unsigned state_flags;
5315 node = rb_first(&io_tree->state);
5316 state = rb_entry(node, struct extent_state, rb_node);
5317 start = state->start;
5319 state_flags = state->state;
5320 spin_unlock(&io_tree->lock);
5322 lock_extent(io_tree, start, end, &cached_state);
5325 * If still has DELALLOC flag, the extent didn't reach disk,
5326 * and its reserved space won't be freed by delayed_ref.
5327 * So we need to free its reserved space here.
5328 * (Refer to comment in btrfs_invalidate_folio, case 2)
5330 * Note, end is the bytenr of last byte, so we need + 1 here.
5332 if (state_flags & EXTENT_DELALLOC)
5333 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5336 clear_extent_bit(io_tree, start, end,
5337 EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5341 spin_lock(&io_tree->lock);
5343 spin_unlock(&io_tree->lock);
5346 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5347 struct btrfs_block_rsv *rsv)
5349 struct btrfs_fs_info *fs_info = root->fs_info;
5350 struct btrfs_trans_handle *trans;
5351 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5355 * Eviction should be taking place at some place safe because of our
5356 * delayed iputs. However the normal flushing code will run delayed
5357 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5359 * We reserve the delayed_refs_extra here again because we can't use
5360 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5361 * above. We reserve our extra bit here because we generate a ton of
5362 * delayed refs activity by truncating.
5364 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5365 * if we fail to make this reservation we can re-try without the
5366 * delayed_refs_extra so we can make some forward progress.
5368 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5369 BTRFS_RESERVE_FLUSH_EVICT);
5371 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5372 BTRFS_RESERVE_FLUSH_EVICT);
5375 "could not allocate space for delete; will truncate on mount");
5376 return ERR_PTR(-ENOSPC);
5378 delayed_refs_extra = 0;
5381 trans = btrfs_join_transaction(root);
5385 if (delayed_refs_extra) {
5386 trans->block_rsv = &fs_info->trans_block_rsv;
5387 trans->bytes_reserved = delayed_refs_extra;
5388 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5389 delayed_refs_extra, 1);
5394 void btrfs_evict_inode(struct inode *inode)
5396 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5397 struct btrfs_trans_handle *trans;
5398 struct btrfs_root *root = BTRFS_I(inode)->root;
5399 struct btrfs_block_rsv *rsv;
5402 trace_btrfs_inode_evict(inode);
5405 fsverity_cleanup_inode(inode);
5410 evict_inode_truncate_pages(inode);
5412 if (inode->i_nlink &&
5413 ((btrfs_root_refs(&root->root_item) != 0 &&
5414 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5415 btrfs_is_free_space_inode(BTRFS_I(inode))))
5418 if (is_bad_inode(inode))
5421 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5423 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5426 if (inode->i_nlink > 0) {
5427 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5428 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5433 * This makes sure the inode item in tree is uptodate and the space for
5434 * the inode update is released.
5436 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5441 * This drops any pending insert or delete operations we have for this
5442 * inode. We could have a delayed dir index deletion queued up, but
5443 * we're removing the inode completely so that'll be taken care of in
5446 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5448 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5451 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5452 rsv->failfast = true;
5454 btrfs_i_size_write(BTRFS_I(inode), 0);
5457 struct btrfs_truncate_control control = {
5458 .inode = BTRFS_I(inode),
5459 .ino = btrfs_ino(BTRFS_I(inode)),
5464 trans = evict_refill_and_join(root, rsv);
5468 trans->block_rsv = rsv;
5470 ret = btrfs_truncate_inode_items(trans, root, &control);
5471 trans->block_rsv = &fs_info->trans_block_rsv;
5472 btrfs_end_transaction(trans);
5473 btrfs_btree_balance_dirty(fs_info);
5474 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5481 * Errors here aren't a big deal, it just means we leave orphan items in
5482 * the tree. They will be cleaned up on the next mount. If the inode
5483 * number gets reused, cleanup deletes the orphan item without doing
5484 * anything, and unlink reuses the existing orphan item.
5486 * If it turns out that we are dropping too many of these, we might want
5487 * to add a mechanism for retrying these after a commit.
5489 trans = evict_refill_and_join(root, rsv);
5490 if (!IS_ERR(trans)) {
5491 trans->block_rsv = rsv;
5492 btrfs_orphan_del(trans, BTRFS_I(inode));
5493 trans->block_rsv = &fs_info->trans_block_rsv;
5494 btrfs_end_transaction(trans);
5498 btrfs_free_block_rsv(fs_info, rsv);
5501 * If we didn't successfully delete, the orphan item will still be in
5502 * the tree and we'll retry on the next mount. Again, we might also want
5503 * to retry these periodically in the future.
5505 btrfs_remove_delayed_node(BTRFS_I(inode));
5506 fsverity_cleanup_inode(inode);
5511 * Return the key found in the dir entry in the location pointer, fill @type
5512 * with BTRFS_FT_*, and return 0.
5514 * If no dir entries were found, returns -ENOENT.
5515 * If found a corrupted location in dir entry, returns -EUCLEAN.
5517 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5518 struct btrfs_key *location, u8 *type)
5520 const char *name = dentry->d_name.name;
5521 int namelen = dentry->d_name.len;
5522 struct btrfs_dir_item *di;
5523 struct btrfs_path *path;
5524 struct btrfs_root *root = BTRFS_I(dir)->root;
5527 path = btrfs_alloc_path();
5531 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5533 if (IS_ERR_OR_NULL(di)) {
5534 ret = di ? PTR_ERR(di) : -ENOENT;
5538 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5539 if (location->type != BTRFS_INODE_ITEM_KEY &&
5540 location->type != BTRFS_ROOT_ITEM_KEY) {
5542 btrfs_warn(root->fs_info,
5543 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5544 __func__, name, btrfs_ino(BTRFS_I(dir)),
5545 location->objectid, location->type, location->offset);
5548 *type = btrfs_dir_type(path->nodes[0], di);
5550 btrfs_free_path(path);
5555 * when we hit a tree root in a directory, the btrfs part of the inode
5556 * needs to be changed to reflect the root directory of the tree root. This
5557 * is kind of like crossing a mount point.
5559 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5561 struct dentry *dentry,
5562 struct btrfs_key *location,
5563 struct btrfs_root **sub_root)
5565 struct btrfs_path *path;
5566 struct btrfs_root *new_root;
5567 struct btrfs_root_ref *ref;
5568 struct extent_buffer *leaf;
5569 struct btrfs_key key;
5573 path = btrfs_alloc_path();
5580 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5581 key.type = BTRFS_ROOT_REF_KEY;
5582 key.offset = location->objectid;
5584 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5591 leaf = path->nodes[0];
5592 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5593 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5594 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5597 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5598 (unsigned long)(ref + 1),
5599 dentry->d_name.len);
5603 btrfs_release_path(path);
5605 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5606 if (IS_ERR(new_root)) {
5607 err = PTR_ERR(new_root);
5611 *sub_root = new_root;
5612 location->objectid = btrfs_root_dirid(&new_root->root_item);
5613 location->type = BTRFS_INODE_ITEM_KEY;
5614 location->offset = 0;
5617 btrfs_free_path(path);
5621 static void inode_tree_add(struct inode *inode)
5623 struct btrfs_root *root = BTRFS_I(inode)->root;
5624 struct btrfs_inode *entry;
5626 struct rb_node *parent;
5627 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5628 u64 ino = btrfs_ino(BTRFS_I(inode));
5630 if (inode_unhashed(inode))
5633 spin_lock(&root->inode_lock);
5634 p = &root->inode_tree.rb_node;
5637 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5639 if (ino < btrfs_ino(entry))
5640 p = &parent->rb_left;
5641 else if (ino > btrfs_ino(entry))
5642 p = &parent->rb_right;
5644 WARN_ON(!(entry->vfs_inode.i_state &
5645 (I_WILL_FREE | I_FREEING)));
5646 rb_replace_node(parent, new, &root->inode_tree);
5647 RB_CLEAR_NODE(parent);
5648 spin_unlock(&root->inode_lock);
5652 rb_link_node(new, parent, p);
5653 rb_insert_color(new, &root->inode_tree);
5654 spin_unlock(&root->inode_lock);
5657 static void inode_tree_del(struct btrfs_inode *inode)
5659 struct btrfs_root *root = inode->root;
5662 spin_lock(&root->inode_lock);
5663 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5664 rb_erase(&inode->rb_node, &root->inode_tree);
5665 RB_CLEAR_NODE(&inode->rb_node);
5666 empty = RB_EMPTY_ROOT(&root->inode_tree);
5668 spin_unlock(&root->inode_lock);
5670 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5671 spin_lock(&root->inode_lock);
5672 empty = RB_EMPTY_ROOT(&root->inode_tree);
5673 spin_unlock(&root->inode_lock);
5675 btrfs_add_dead_root(root);
5680 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5682 struct btrfs_iget_args *args = p;
5684 inode->i_ino = args->ino;
5685 BTRFS_I(inode)->location.objectid = args->ino;
5686 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5687 BTRFS_I(inode)->location.offset = 0;
5688 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5689 BUG_ON(args->root && !BTRFS_I(inode)->root);
5691 if (args->root && args->root == args->root->fs_info->tree_root &&
5692 args->ino != BTRFS_BTREE_INODE_OBJECTID)
5693 set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5694 &BTRFS_I(inode)->runtime_flags);
5698 static int btrfs_find_actor(struct inode *inode, void *opaque)
5700 struct btrfs_iget_args *args = opaque;
5702 return args->ino == BTRFS_I(inode)->location.objectid &&
5703 args->root == BTRFS_I(inode)->root;
5706 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5707 struct btrfs_root *root)
5709 struct inode *inode;
5710 struct btrfs_iget_args args;
5711 unsigned long hashval = btrfs_inode_hash(ino, root);
5716 inode = iget5_locked(s, hashval, btrfs_find_actor,
5717 btrfs_init_locked_inode,
5723 * Get an inode object given its inode number and corresponding root.
5724 * Path can be preallocated to prevent recursing back to iget through
5725 * allocator. NULL is also valid but may require an additional allocation
5728 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5729 struct btrfs_root *root, struct btrfs_path *path)
5731 struct inode *inode;
5733 inode = btrfs_iget_locked(s, ino, root);
5735 return ERR_PTR(-ENOMEM);
5737 if (inode->i_state & I_NEW) {
5740 ret = btrfs_read_locked_inode(inode, path);
5742 inode_tree_add(inode);
5743 unlock_new_inode(inode);
5747 * ret > 0 can come from btrfs_search_slot called by
5748 * btrfs_read_locked_inode, this means the inode item
5753 inode = ERR_PTR(ret);
5760 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5762 return btrfs_iget_path(s, ino, root, NULL);
5765 static struct inode *new_simple_dir(struct super_block *s,
5766 struct btrfs_key *key,
5767 struct btrfs_root *root)
5769 struct inode *inode = new_inode(s);
5772 return ERR_PTR(-ENOMEM);
5774 BTRFS_I(inode)->root = btrfs_grab_root(root);
5775 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5776 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5778 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5780 * We only need lookup, the rest is read-only and there's no inode
5781 * associated with the dentry
5783 inode->i_op = &simple_dir_inode_operations;
5784 inode->i_opflags &= ~IOP_XATTR;
5785 inode->i_fop = &simple_dir_operations;
5786 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5787 inode->i_mtime = current_time(inode);
5788 inode->i_atime = inode->i_mtime;
5789 inode->i_ctime = inode->i_mtime;
5790 BTRFS_I(inode)->i_otime = inode->i_mtime;
5795 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5796 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5797 static_assert(BTRFS_FT_DIR == FT_DIR);
5798 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5799 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5800 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5801 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5802 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5804 static inline u8 btrfs_inode_type(struct inode *inode)
5806 return fs_umode_to_ftype(inode->i_mode);
5809 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5811 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5812 struct inode *inode;
5813 struct btrfs_root *root = BTRFS_I(dir)->root;
5814 struct btrfs_root *sub_root = root;
5815 struct btrfs_key location;
5819 if (dentry->d_name.len > BTRFS_NAME_LEN)
5820 return ERR_PTR(-ENAMETOOLONG);
5822 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5824 return ERR_PTR(ret);
5826 if (location.type == BTRFS_INODE_ITEM_KEY) {
5827 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5831 /* Do extra check against inode mode with di_type */
5832 if (btrfs_inode_type(inode) != di_type) {
5834 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5835 inode->i_mode, btrfs_inode_type(inode),
5838 return ERR_PTR(-EUCLEAN);
5843 ret = fixup_tree_root_location(fs_info, dir, dentry,
5844 &location, &sub_root);
5847 inode = ERR_PTR(ret);
5849 inode = new_simple_dir(dir->i_sb, &location, root);
5851 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5852 btrfs_put_root(sub_root);
5857 down_read(&fs_info->cleanup_work_sem);
5858 if (!sb_rdonly(inode->i_sb))
5859 ret = btrfs_orphan_cleanup(sub_root);
5860 up_read(&fs_info->cleanup_work_sem);
5863 inode = ERR_PTR(ret);
5870 static int btrfs_dentry_delete(const struct dentry *dentry)
5872 struct btrfs_root *root;
5873 struct inode *inode = d_inode(dentry);
5875 if (!inode && !IS_ROOT(dentry))
5876 inode = d_inode(dentry->d_parent);
5879 root = BTRFS_I(inode)->root;
5880 if (btrfs_root_refs(&root->root_item) == 0)
5883 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5889 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5892 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5894 if (inode == ERR_PTR(-ENOENT))
5896 return d_splice_alias(inode, dentry);
5900 * All this infrastructure exists because dir_emit can fault, and we are holding
5901 * the tree lock when doing readdir. For now just allocate a buffer and copy
5902 * our information into that, and then dir_emit from the buffer. This is
5903 * similar to what NFS does, only we don't keep the buffer around in pagecache
5904 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5905 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5908 static int btrfs_opendir(struct inode *inode, struct file *file)
5910 struct btrfs_file_private *private;
5912 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5915 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5916 if (!private->filldir_buf) {
5920 file->private_data = private;
5931 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5934 struct dir_entry *entry = addr;
5935 char *name = (char *)(entry + 1);
5937 ctx->pos = get_unaligned(&entry->offset);
5938 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5939 get_unaligned(&entry->ino),
5940 get_unaligned(&entry->type)))
5942 addr += sizeof(struct dir_entry) +
5943 get_unaligned(&entry->name_len);
5949 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5951 struct inode *inode = file_inode(file);
5952 struct btrfs_root *root = BTRFS_I(inode)->root;
5953 struct btrfs_file_private *private = file->private_data;
5954 struct btrfs_dir_item *di;
5955 struct btrfs_key key;
5956 struct btrfs_key found_key;
5957 struct btrfs_path *path;
5959 struct list_head ins_list;
5960 struct list_head del_list;
5967 struct btrfs_key location;
5969 if (!dir_emit_dots(file, ctx))
5972 path = btrfs_alloc_path();
5976 addr = private->filldir_buf;
5977 path->reada = READA_FORWARD;
5979 INIT_LIST_HEAD(&ins_list);
5980 INIT_LIST_HEAD(&del_list);
5981 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5984 key.type = BTRFS_DIR_INDEX_KEY;
5985 key.offset = ctx->pos;
5986 key.objectid = btrfs_ino(BTRFS_I(inode));
5988 btrfs_for_each_slot(root, &key, &found_key, path, ret) {
5989 struct dir_entry *entry;
5990 struct extent_buffer *leaf = path->nodes[0];
5992 if (found_key.objectid != key.objectid)
5994 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5996 if (found_key.offset < ctx->pos)
5998 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6000 di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
6001 name_len = btrfs_dir_name_len(leaf, di);
6002 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6004 btrfs_release_path(path);
6005 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6008 addr = private->filldir_buf;
6015 put_unaligned(name_len, &entry->name_len);
6016 name_ptr = (char *)(entry + 1);
6017 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6019 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6021 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6022 put_unaligned(location.objectid, &entry->ino);
6023 put_unaligned(found_key.offset, &entry->offset);
6025 addr += sizeof(struct dir_entry) + name_len;
6026 total_len += sizeof(struct dir_entry) + name_len;
6028 /* Catch error encountered during iteration */
6032 btrfs_release_path(path);
6034 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6038 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6043 * Stop new entries from being returned after we return the last
6046 * New directory entries are assigned a strictly increasing
6047 * offset. This means that new entries created during readdir
6048 * are *guaranteed* to be seen in the future by that readdir.
6049 * This has broken buggy programs which operate on names as
6050 * they're returned by readdir. Until we re-use freed offsets
6051 * we have this hack to stop new entries from being returned
6052 * under the assumption that they'll never reach this huge
6055 * This is being careful not to overflow 32bit loff_t unless the
6056 * last entry requires it because doing so has broken 32bit apps
6059 if (ctx->pos >= INT_MAX)
6060 ctx->pos = LLONG_MAX;
6067 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6068 btrfs_free_path(path);
6073 * This is somewhat expensive, updating the tree every time the
6074 * inode changes. But, it is most likely to find the inode in cache.
6075 * FIXME, needs more benchmarking...there are no reasons other than performance
6076 * to keep or drop this code.
6078 static int btrfs_dirty_inode(struct inode *inode)
6080 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6081 struct btrfs_root *root = BTRFS_I(inode)->root;
6082 struct btrfs_trans_handle *trans;
6085 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6088 trans = btrfs_join_transaction(root);
6090 return PTR_ERR(trans);
6092 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6093 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6094 /* whoops, lets try again with the full transaction */
6095 btrfs_end_transaction(trans);
6096 trans = btrfs_start_transaction(root, 1);
6098 return PTR_ERR(trans);
6100 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6102 btrfs_end_transaction(trans);
6103 if (BTRFS_I(inode)->delayed_node)
6104 btrfs_balance_delayed_items(fs_info);
6110 * This is a copy of file_update_time. We need this so we can return error on
6111 * ENOSPC for updating the inode in the case of file write and mmap writes.
6113 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6116 struct btrfs_root *root = BTRFS_I(inode)->root;
6117 bool dirty = flags & ~S_VERSION;
6119 if (btrfs_root_readonly(root))
6122 if (flags & S_VERSION)
6123 dirty |= inode_maybe_inc_iversion(inode, dirty);
6124 if (flags & S_CTIME)
6125 inode->i_ctime = *now;
6126 if (flags & S_MTIME)
6127 inode->i_mtime = *now;
6128 if (flags & S_ATIME)
6129 inode->i_atime = *now;
6130 return dirty ? btrfs_dirty_inode(inode) : 0;
6134 * find the highest existing sequence number in a directory
6135 * and then set the in-memory index_cnt variable to reflect
6136 * free sequence numbers
6138 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6140 struct btrfs_root *root = inode->root;
6141 struct btrfs_key key, found_key;
6142 struct btrfs_path *path;
6143 struct extent_buffer *leaf;
6146 key.objectid = btrfs_ino(inode);
6147 key.type = BTRFS_DIR_INDEX_KEY;
6148 key.offset = (u64)-1;
6150 path = btrfs_alloc_path();
6154 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6157 /* FIXME: we should be able to handle this */
6162 if (path->slots[0] == 0) {
6163 inode->index_cnt = BTRFS_DIR_START_INDEX;
6169 leaf = path->nodes[0];
6170 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6172 if (found_key.objectid != btrfs_ino(inode) ||
6173 found_key.type != BTRFS_DIR_INDEX_KEY) {
6174 inode->index_cnt = BTRFS_DIR_START_INDEX;
6178 inode->index_cnt = found_key.offset + 1;
6180 btrfs_free_path(path);
6185 * helper to find a free sequence number in a given directory. This current
6186 * code is very simple, later versions will do smarter things in the btree
6188 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6192 if (dir->index_cnt == (u64)-1) {
6193 ret = btrfs_inode_delayed_dir_index_count(dir);
6195 ret = btrfs_set_inode_index_count(dir);
6201 *index = dir->index_cnt;
6207 static int btrfs_insert_inode_locked(struct inode *inode)
6209 struct btrfs_iget_args args;
6211 args.ino = BTRFS_I(inode)->location.objectid;
6212 args.root = BTRFS_I(inode)->root;
6214 return insert_inode_locked4(inode,
6215 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6216 btrfs_find_actor, &args);
6219 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6220 unsigned int *trans_num_items)
6222 struct inode *dir = args->dir;
6223 struct inode *inode = args->inode;
6226 ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6230 /* 1 to add inode item */
6231 *trans_num_items = 1;
6232 /* 1 to add compression property */
6233 if (BTRFS_I(dir)->prop_compress)
6234 (*trans_num_items)++;
6235 /* 1 to add default ACL xattr */
6236 if (args->default_acl)
6237 (*trans_num_items)++;
6238 /* 1 to add access ACL xattr */
6240 (*trans_num_items)++;
6241 #ifdef CONFIG_SECURITY
6242 /* 1 to add LSM xattr */
6243 if (dir->i_security)
6244 (*trans_num_items)++;
6247 /* 1 to add orphan item */
6248 (*trans_num_items)++;
6252 * 1 to add dir index
6253 * 1 to update parent inode item
6255 * No need for 1 unit for the inode ref item because it is
6256 * inserted in a batch together with the inode item at
6257 * btrfs_create_new_inode().
6259 *trans_num_items += 3;
6264 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6266 posix_acl_release(args->acl);
6267 posix_acl_release(args->default_acl);
6271 * Inherit flags from the parent inode.
6273 * Currently only the compression flags and the cow flags are inherited.
6275 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6279 flags = BTRFS_I(dir)->flags;
6281 if (flags & BTRFS_INODE_NOCOMPRESS) {
6282 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6283 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6284 } else if (flags & BTRFS_INODE_COMPRESS) {
6285 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6286 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6289 if (flags & BTRFS_INODE_NODATACOW) {
6290 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6291 if (S_ISREG(inode->i_mode))
6292 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6295 btrfs_sync_inode_flags_to_i_flags(inode);
6298 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6299 struct btrfs_new_inode_args *args)
6301 struct inode *dir = args->dir;
6302 struct inode *inode = args->inode;
6303 const char *name = args->orphan ? NULL : args->dentry->d_name.name;
6304 int name_len = args->orphan ? 0 : args->dentry->d_name.len;
6305 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6306 struct btrfs_root *root;
6307 struct btrfs_inode_item *inode_item;
6308 struct btrfs_key *location;
6309 struct btrfs_path *path;
6311 struct btrfs_inode_ref *ref;
6312 struct btrfs_key key[2];
6314 struct btrfs_item_batch batch;
6318 path = btrfs_alloc_path();
6323 BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6324 root = BTRFS_I(inode)->root;
6326 ret = btrfs_get_free_objectid(root, &objectid);
6329 inode->i_ino = objectid;
6333 * O_TMPFILE, set link count to 0, so that after this point, we
6334 * fill in an inode item with the correct link count.
6336 set_nlink(inode, 0);
6338 trace_btrfs_inode_request(dir);
6340 ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6344 /* index_cnt is ignored for everything but a dir. */
6345 BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6346 BTRFS_I(inode)->generation = trans->transid;
6347 inode->i_generation = BTRFS_I(inode)->generation;
6350 * Subvolumes don't inherit flags from their parent directory.
6351 * Originally this was probably by accident, but we probably can't
6352 * change it now without compatibility issues.
6355 btrfs_inherit_iflags(inode, dir);
6357 if (S_ISREG(inode->i_mode)) {
6358 if (btrfs_test_opt(fs_info, NODATASUM))
6359 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6360 if (btrfs_test_opt(fs_info, NODATACOW))
6361 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6362 BTRFS_INODE_NODATASUM;
6365 location = &BTRFS_I(inode)->location;
6366 location->objectid = objectid;
6367 location->offset = 0;
6368 location->type = BTRFS_INODE_ITEM_KEY;
6370 ret = btrfs_insert_inode_locked(inode);
6373 BTRFS_I(dir)->index_cnt--;
6378 * We could have gotten an inode number from somebody who was fsynced
6379 * and then removed in this same transaction, so let's just set full
6380 * sync since it will be a full sync anyway and this will blow away the
6381 * old info in the log.
6383 btrfs_set_inode_full_sync(BTRFS_I(inode));
6385 key[0].objectid = objectid;
6386 key[0].type = BTRFS_INODE_ITEM_KEY;
6389 sizes[0] = sizeof(struct btrfs_inode_item);
6391 if (!args->orphan) {
6393 * Start new inodes with an inode_ref. This is slightly more
6394 * efficient for small numbers of hard links since they will
6395 * be packed into one item. Extended refs will kick in if we
6396 * add more hard links than can fit in the ref item.
6398 key[1].objectid = objectid;
6399 key[1].type = BTRFS_INODE_REF_KEY;
6401 key[1].offset = objectid;
6402 sizes[1] = 2 + sizeof(*ref);
6404 key[1].offset = btrfs_ino(BTRFS_I(dir));
6405 sizes[1] = name_len + sizeof(*ref);
6409 batch.keys = &key[0];
6410 batch.data_sizes = &sizes[0];
6411 batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6412 batch.nr = args->orphan ? 1 : 2;
6413 ret = btrfs_insert_empty_items(trans, root, path, &batch);
6415 btrfs_abort_transaction(trans, ret);
6419 inode->i_mtime = current_time(inode);
6420 inode->i_atime = inode->i_mtime;
6421 inode->i_ctime = inode->i_mtime;
6422 BTRFS_I(inode)->i_otime = inode->i_mtime;
6425 * We're going to fill the inode item now, so at this point the inode
6426 * must be fully initialized.
6429 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6430 struct btrfs_inode_item);
6431 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6432 sizeof(*inode_item));
6433 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6435 if (!args->orphan) {
6436 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6437 struct btrfs_inode_ref);
6438 ptr = (unsigned long)(ref + 1);
6440 btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6441 btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6442 write_extent_buffer(path->nodes[0], "..", ptr, 2);
6444 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6445 btrfs_set_inode_ref_index(path->nodes[0], ref,
6446 BTRFS_I(inode)->dir_index);
6447 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6451 btrfs_mark_buffer_dirty(path->nodes[0]);
6453 * We don't need the path anymore, plus inheriting properties, adding
6454 * ACLs, security xattrs, orphan item or adding the link, will result in
6455 * allocating yet another path. So just free our path.
6457 btrfs_free_path(path);
6461 struct inode *parent;
6464 * Subvolumes inherit properties from their parent subvolume,
6465 * not the directory they were created in.
6467 parent = btrfs_iget(fs_info->sb, BTRFS_FIRST_FREE_OBJECTID,
6468 BTRFS_I(dir)->root);
6469 if (IS_ERR(parent)) {
6470 ret = PTR_ERR(parent);
6472 ret = btrfs_inode_inherit_props(trans, inode, parent);
6476 ret = btrfs_inode_inherit_props(trans, inode, dir);
6480 "error inheriting props for ino %llu (root %llu): %d",
6481 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid,
6486 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6489 if (!args->subvol) {
6490 ret = btrfs_init_inode_security(trans, args);
6492 btrfs_abort_transaction(trans, ret);
6497 inode_tree_add(inode);
6499 trace_btrfs_inode_new(inode);
6500 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6502 btrfs_update_root_times(trans, root);
6505 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6507 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6508 name_len, 0, BTRFS_I(inode)->dir_index);
6511 btrfs_abort_transaction(trans, ret);
6519 * discard_new_inode() calls iput(), but the caller owns the reference
6523 discard_new_inode(inode);
6525 btrfs_free_path(path);
6530 * utility function to add 'inode' into 'parent_inode' with
6531 * a give name and a given sequence number.
6532 * if 'add_backref' is true, also insert a backref from the
6533 * inode to the parent directory.
6535 int btrfs_add_link(struct btrfs_trans_handle *trans,
6536 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6537 const char *name, int name_len, int add_backref, u64 index)
6540 struct btrfs_key key;
6541 struct btrfs_root *root = parent_inode->root;
6542 u64 ino = btrfs_ino(inode);
6543 u64 parent_ino = btrfs_ino(parent_inode);
6545 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6546 memcpy(&key, &inode->root->root_key, sizeof(key));
6549 key.type = BTRFS_INODE_ITEM_KEY;
6553 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6554 ret = btrfs_add_root_ref(trans, key.objectid,
6555 root->root_key.objectid, parent_ino,
6556 index, name, name_len);
6557 } else if (add_backref) {
6558 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6562 /* Nothing to clean up yet */
6566 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6567 btrfs_inode_type(&inode->vfs_inode), index);
6568 if (ret == -EEXIST || ret == -EOVERFLOW)
6571 btrfs_abort_transaction(trans, ret);
6575 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6577 inode_inc_iversion(&parent_inode->vfs_inode);
6579 * If we are replaying a log tree, we do not want to update the mtime
6580 * and ctime of the parent directory with the current time, since the
6581 * log replay procedure is responsible for setting them to their correct
6582 * values (the ones it had when the fsync was done).
6584 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6585 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6587 parent_inode->vfs_inode.i_mtime = now;
6588 parent_inode->vfs_inode.i_ctime = now;
6590 ret = btrfs_update_inode(trans, root, parent_inode);
6592 btrfs_abort_transaction(trans, ret);
6596 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6599 err = btrfs_del_root_ref(trans, key.objectid,
6600 root->root_key.objectid, parent_ino,
6601 &local_index, name, name_len);
6603 btrfs_abort_transaction(trans, err);
6604 } else if (add_backref) {
6608 err = btrfs_del_inode_ref(trans, root, name, name_len,
6609 ino, parent_ino, &local_index);
6611 btrfs_abort_transaction(trans, err);
6614 /* Return the original error code */
6618 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6619 struct inode *inode)
6621 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6622 struct btrfs_root *root = BTRFS_I(dir)->root;
6623 struct btrfs_new_inode_args new_inode_args = {
6628 unsigned int trans_num_items;
6629 struct btrfs_trans_handle *trans;
6632 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6636 trans = btrfs_start_transaction(root, trans_num_items);
6637 if (IS_ERR(trans)) {
6638 err = PTR_ERR(trans);
6639 goto out_new_inode_args;
6642 err = btrfs_create_new_inode(trans, &new_inode_args);
6644 d_instantiate_new(dentry, inode);
6646 btrfs_end_transaction(trans);
6647 btrfs_btree_balance_dirty(fs_info);
6649 btrfs_new_inode_args_destroy(&new_inode_args);
6656 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6657 struct dentry *dentry, umode_t mode, dev_t rdev)
6659 struct inode *inode;
6661 inode = new_inode(dir->i_sb);
6664 inode_init_owner(mnt_userns, inode, dir, mode);
6665 inode->i_op = &btrfs_special_inode_operations;
6666 init_special_inode(inode, inode->i_mode, rdev);
6667 return btrfs_create_common(dir, dentry, inode);
6670 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6671 struct dentry *dentry, umode_t mode, bool excl)
6673 struct inode *inode;
6675 inode = new_inode(dir->i_sb);
6678 inode_init_owner(mnt_userns, inode, dir, mode);
6679 inode->i_fop = &btrfs_file_operations;
6680 inode->i_op = &btrfs_file_inode_operations;
6681 inode->i_mapping->a_ops = &btrfs_aops;
6682 return btrfs_create_common(dir, dentry, inode);
6685 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6686 struct dentry *dentry)
6688 struct btrfs_trans_handle *trans = NULL;
6689 struct btrfs_root *root = BTRFS_I(dir)->root;
6690 struct inode *inode = d_inode(old_dentry);
6691 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6696 /* do not allow sys_link's with other subvols of the same device */
6697 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6700 if (inode->i_nlink >= BTRFS_LINK_MAX)
6703 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6708 * 2 items for inode and inode ref
6709 * 2 items for dir items
6710 * 1 item for parent inode
6711 * 1 item for orphan item deletion if O_TMPFILE
6713 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6714 if (IS_ERR(trans)) {
6715 err = PTR_ERR(trans);
6720 /* There are several dir indexes for this inode, clear the cache. */
6721 BTRFS_I(inode)->dir_index = 0ULL;
6723 inode_inc_iversion(inode);
6724 inode->i_ctime = current_time(inode);
6726 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6728 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6729 dentry->d_name.name, dentry->d_name.len, 1, index);
6734 struct dentry *parent = dentry->d_parent;
6736 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6739 if (inode->i_nlink == 1) {
6741 * If new hard link count is 1, it's a file created
6742 * with open(2) O_TMPFILE flag.
6744 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6748 d_instantiate(dentry, inode);
6749 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6754 btrfs_end_transaction(trans);
6756 inode_dec_link_count(inode);
6759 btrfs_btree_balance_dirty(fs_info);
6763 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6764 struct dentry *dentry, umode_t mode)
6766 struct inode *inode;
6768 inode = new_inode(dir->i_sb);
6771 inode_init_owner(mnt_userns, inode, dir, S_IFDIR | mode);
6772 inode->i_op = &btrfs_dir_inode_operations;
6773 inode->i_fop = &btrfs_dir_file_operations;
6774 return btrfs_create_common(dir, dentry, inode);
6777 static noinline int uncompress_inline(struct btrfs_path *path,
6779 size_t pg_offset, u64 extent_offset,
6780 struct btrfs_file_extent_item *item)
6783 struct extent_buffer *leaf = path->nodes[0];
6786 unsigned long inline_size;
6790 WARN_ON(pg_offset != 0);
6791 compress_type = btrfs_file_extent_compression(leaf, item);
6792 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6793 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6794 tmp = kmalloc(inline_size, GFP_NOFS);
6797 ptr = btrfs_file_extent_inline_start(item);
6799 read_extent_buffer(leaf, tmp, ptr, inline_size);
6801 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6802 ret = btrfs_decompress(compress_type, tmp, page,
6803 extent_offset, inline_size, max_size);
6806 * decompression code contains a memset to fill in any space between the end
6807 * of the uncompressed data and the end of max_size in case the decompressed
6808 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6809 * the end of an inline extent and the beginning of the next block, so we
6810 * cover that region here.
6813 if (max_size + pg_offset < PAGE_SIZE)
6814 memzero_page(page, pg_offset + max_size,
6815 PAGE_SIZE - max_size - pg_offset);
6821 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6822 * @inode: file to search in
6823 * @page: page to read extent data into if the extent is inline
6824 * @pg_offset: offset into @page to copy to
6825 * @start: file offset
6826 * @len: length of range starting at @start
6828 * This returns the first &struct extent_map which overlaps with the given
6829 * range, reading it from the B-tree and caching it if necessary. Note that
6830 * there may be more extents which overlap the given range after the returned
6833 * If @page is not NULL and the extent is inline, this also reads the extent
6834 * data directly into the page and marks the extent up to date in the io_tree.
6836 * Return: ERR_PTR on error, non-NULL extent_map on success.
6838 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6839 struct page *page, size_t pg_offset,
6842 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6844 u64 extent_start = 0;
6846 u64 objectid = btrfs_ino(inode);
6847 int extent_type = -1;
6848 struct btrfs_path *path = NULL;
6849 struct btrfs_root *root = inode->root;
6850 struct btrfs_file_extent_item *item;
6851 struct extent_buffer *leaf;
6852 struct btrfs_key found_key;
6853 struct extent_map *em = NULL;
6854 struct extent_map_tree *em_tree = &inode->extent_tree;
6856 read_lock(&em_tree->lock);
6857 em = lookup_extent_mapping(em_tree, start, len);
6858 read_unlock(&em_tree->lock);
6861 if (em->start > start || em->start + em->len <= start)
6862 free_extent_map(em);
6863 else if (em->block_start == EXTENT_MAP_INLINE && page)
6864 free_extent_map(em);
6868 em = alloc_extent_map();
6873 em->start = EXTENT_MAP_HOLE;
6874 em->orig_start = EXTENT_MAP_HOLE;
6876 em->block_len = (u64)-1;
6878 path = btrfs_alloc_path();
6884 /* Chances are we'll be called again, so go ahead and do readahead */
6885 path->reada = READA_FORWARD;
6888 * The same explanation in load_free_space_cache applies here as well,
6889 * we only read when we're loading the free space cache, and at that
6890 * point the commit_root has everything we need.
6892 if (btrfs_is_free_space_inode(inode)) {
6893 path->search_commit_root = 1;
6894 path->skip_locking = 1;
6897 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6900 } else if (ret > 0) {
6901 if (path->slots[0] == 0)
6907 leaf = path->nodes[0];
6908 item = btrfs_item_ptr(leaf, path->slots[0],
6909 struct btrfs_file_extent_item);
6910 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6911 if (found_key.objectid != objectid ||
6912 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6914 * If we backup past the first extent we want to move forward
6915 * and see if there is an extent in front of us, otherwise we'll
6916 * say there is a hole for our whole search range which can
6923 extent_type = btrfs_file_extent_type(leaf, item);
6924 extent_start = found_key.offset;
6925 extent_end = btrfs_file_extent_end(path);
6926 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6927 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6928 /* Only regular file could have regular/prealloc extent */
6929 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6932 "regular/prealloc extent found for non-regular inode %llu",
6936 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6938 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6939 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6944 if (start >= extent_end) {
6946 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6947 ret = btrfs_next_leaf(root, path);
6953 leaf = path->nodes[0];
6955 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6956 if (found_key.objectid != objectid ||
6957 found_key.type != BTRFS_EXTENT_DATA_KEY)
6959 if (start + len <= found_key.offset)
6961 if (start > found_key.offset)
6964 /* New extent overlaps with existing one */
6966 em->orig_start = start;
6967 em->len = found_key.offset - start;
6968 em->block_start = EXTENT_MAP_HOLE;
6972 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6974 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6975 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6977 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6981 size_t extent_offset;
6987 size = btrfs_file_extent_ram_bytes(leaf, item);
6988 extent_offset = page_offset(page) + pg_offset - extent_start;
6989 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6990 size - extent_offset);
6991 em->start = extent_start + extent_offset;
6992 em->len = ALIGN(copy_size, fs_info->sectorsize);
6993 em->orig_block_len = em->len;
6994 em->orig_start = em->start;
6995 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6997 if (!PageUptodate(page)) {
6998 if (btrfs_file_extent_compression(leaf, item) !=
6999 BTRFS_COMPRESS_NONE) {
7000 ret = uncompress_inline(path, page, pg_offset,
7001 extent_offset, item);
7005 map = kmap_local_page(page);
7006 read_extent_buffer(leaf, map + pg_offset, ptr,
7008 if (pg_offset + copy_size < PAGE_SIZE) {
7009 memset(map + pg_offset + copy_size, 0,
7010 PAGE_SIZE - pg_offset -
7015 flush_dcache_page(page);
7021 em->orig_start = start;
7023 em->block_start = EXTENT_MAP_HOLE;
7026 btrfs_release_path(path);
7027 if (em->start > start || extent_map_end(em) <= start) {
7029 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7030 em->start, em->len, start, len);
7035 write_lock(&em_tree->lock);
7036 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7037 write_unlock(&em_tree->lock);
7039 btrfs_free_path(path);
7041 trace_btrfs_get_extent(root, inode, em);
7044 free_extent_map(em);
7045 return ERR_PTR(ret);
7050 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7053 const u64 orig_start,
7054 const u64 block_start,
7055 const u64 block_len,
7056 const u64 orig_block_len,
7057 const u64 ram_bytes,
7060 struct extent_map *em = NULL;
7063 if (type != BTRFS_ORDERED_NOCOW) {
7064 em = create_io_em(inode, start, len, orig_start, block_start,
7065 block_len, orig_block_len, ram_bytes,
7066 BTRFS_COMPRESS_NONE, /* compress_type */
7071 ret = btrfs_add_ordered_extent(inode, start, len, len, block_start,
7074 (1 << BTRFS_ORDERED_DIRECT),
7075 BTRFS_COMPRESS_NONE);
7078 free_extent_map(em);
7079 btrfs_drop_extent_map_range(inode, start,
7080 start + len - 1, false);
7089 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7092 struct btrfs_root *root = inode->root;
7093 struct btrfs_fs_info *fs_info = root->fs_info;
7094 struct extent_map *em;
7095 struct btrfs_key ins;
7099 alloc_hint = get_extent_allocation_hint(inode, start, len);
7100 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7101 0, alloc_hint, &ins, 1, 1);
7103 return ERR_PTR(ret);
7105 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7106 ins.objectid, ins.offset, ins.offset,
7107 ins.offset, BTRFS_ORDERED_REGULAR);
7108 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7110 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7116 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7118 struct btrfs_block_group *block_group;
7119 bool readonly = false;
7121 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7122 if (!block_group || block_group->ro)
7125 btrfs_put_block_group(block_group);
7130 * Check if we can do nocow write into the range [@offset, @offset + @len)
7132 * @offset: File offset
7133 * @len: The length to write, will be updated to the nocow writeable
7135 * @orig_start: (optional) Return the original file offset of the file extent
7136 * @orig_len: (optional) Return the original on-disk length of the file extent
7137 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7138 * @strict: if true, omit optimizations that might force us into unnecessary
7139 * cow. e.g., don't trust generation number.
7142 * >0 and update @len if we can do nocow write
7143 * 0 if we can't do nocow write
7144 * <0 if error happened
7146 * NOTE: This only checks the file extents, caller is responsible to wait for
7147 * any ordered extents.
7149 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7150 u64 *orig_start, u64 *orig_block_len,
7151 u64 *ram_bytes, bool nowait, bool strict)
7153 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7154 struct can_nocow_file_extent_args nocow_args = { 0 };
7155 struct btrfs_path *path;
7157 struct extent_buffer *leaf;
7158 struct btrfs_root *root = BTRFS_I(inode)->root;
7159 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7160 struct btrfs_file_extent_item *fi;
7161 struct btrfs_key key;
7164 path = btrfs_alloc_path();
7167 path->nowait = nowait;
7169 ret = btrfs_lookup_file_extent(NULL, root, path,
7170 btrfs_ino(BTRFS_I(inode)), offset, 0);
7175 if (path->slots[0] == 0) {
7176 /* can't find the item, must cow */
7183 leaf = path->nodes[0];
7184 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7185 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7186 key.type != BTRFS_EXTENT_DATA_KEY) {
7187 /* not our file or wrong item type, must cow */
7191 if (key.offset > offset) {
7192 /* Wrong offset, must cow */
7196 if (btrfs_file_extent_end(path) <= offset)
7199 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7200 found_type = btrfs_file_extent_type(leaf, fi);
7202 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7204 nocow_args.start = offset;
7205 nocow_args.end = offset + *len - 1;
7206 nocow_args.strict = strict;
7207 nocow_args.free_path = true;
7209 ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
7210 /* can_nocow_file_extent() has freed the path. */
7214 /* Treat errors as not being able to NOCOW. */
7220 if (btrfs_extent_readonly(fs_info, nocow_args.disk_bytenr))
7223 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7224 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7227 range_end = round_up(offset + nocow_args.num_bytes,
7228 root->fs_info->sectorsize) - 1;
7229 ret = test_range_bit(io_tree, offset, range_end,
7230 EXTENT_DELALLOC, 0, NULL);
7238 *orig_start = key.offset - nocow_args.extent_offset;
7240 *orig_block_len = nocow_args.disk_num_bytes;
7242 *len = nocow_args.num_bytes;
7245 btrfs_free_path(path);
7249 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7250 struct extent_state **cached_state,
7251 unsigned int iomap_flags)
7253 const bool writing = (iomap_flags & IOMAP_WRITE);
7254 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7255 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7256 struct btrfs_ordered_extent *ordered;
7261 if (!try_lock_extent(io_tree, lockstart, lockend))
7264 lock_extent(io_tree, lockstart, lockend, cached_state);
7267 * We're concerned with the entire range that we're going to be
7268 * doing DIO to, so we need to make sure there's no ordered
7269 * extents in this range.
7271 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7272 lockend - lockstart + 1);
7275 * We need to make sure there are no buffered pages in this
7276 * range either, we could have raced between the invalidate in
7277 * generic_file_direct_write and locking the extent. The
7278 * invalidate needs to happen so that reads after a write do not
7282 (!writing || !filemap_range_has_page(inode->i_mapping,
7283 lockstart, lockend)))
7286 unlock_extent(io_tree, lockstart, lockend, cached_state);
7290 btrfs_put_ordered_extent(ordered);
7295 * If we are doing a DIO read and the ordered extent we
7296 * found is for a buffered write, we can not wait for it
7297 * to complete and retry, because if we do so we can
7298 * deadlock with concurrent buffered writes on page
7299 * locks. This happens only if our DIO read covers more
7300 * than one extent map, if at this point has already
7301 * created an ordered extent for a previous extent map
7302 * and locked its range in the inode's io tree, and a
7303 * concurrent write against that previous extent map's
7304 * range and this range started (we unlock the ranges
7305 * in the io tree only when the bios complete and
7306 * buffered writes always lock pages before attempting
7307 * to lock range in the io tree).
7310 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7311 btrfs_start_ordered_extent(ordered, 1);
7313 ret = nowait ? -EAGAIN : -ENOTBLK;
7314 btrfs_put_ordered_extent(ordered);
7317 * We could trigger writeback for this range (and wait
7318 * for it to complete) and then invalidate the pages for
7319 * this range (through invalidate_inode_pages2_range()),
7320 * but that can lead us to a deadlock with a concurrent
7321 * call to readahead (a buffered read or a defrag call
7322 * triggered a readahead) on a page lock due to an
7323 * ordered dio extent we created before but did not have
7324 * yet a corresponding bio submitted (whence it can not
7325 * complete), which makes readahead wait for that
7326 * ordered extent to complete while holding a lock on
7329 ret = nowait ? -EAGAIN : -ENOTBLK;
7341 /* The callers of this must take lock_extent() */
7342 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7343 u64 len, u64 orig_start, u64 block_start,
7344 u64 block_len, u64 orig_block_len,
7345 u64 ram_bytes, int compress_type,
7348 struct extent_map *em;
7351 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7352 type == BTRFS_ORDERED_COMPRESSED ||
7353 type == BTRFS_ORDERED_NOCOW ||
7354 type == BTRFS_ORDERED_REGULAR);
7356 em = alloc_extent_map();
7358 return ERR_PTR(-ENOMEM);
7361 em->orig_start = orig_start;
7363 em->block_len = block_len;
7364 em->block_start = block_start;
7365 em->orig_block_len = orig_block_len;
7366 em->ram_bytes = ram_bytes;
7367 em->generation = -1;
7368 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7369 if (type == BTRFS_ORDERED_PREALLOC) {
7370 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7371 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7372 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7373 em->compress_type = compress_type;
7376 ret = btrfs_replace_extent_map_range(inode, em, true);
7378 free_extent_map(em);
7379 return ERR_PTR(ret);
7382 /* em got 2 refs now, callers needs to do free_extent_map once. */
7387 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7388 struct inode *inode,
7389 struct btrfs_dio_data *dio_data,
7391 unsigned int iomap_flags)
7393 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7394 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7395 struct extent_map *em = *map;
7397 u64 block_start, orig_start, orig_block_len, ram_bytes;
7398 struct btrfs_block_group *bg;
7399 bool can_nocow = false;
7400 bool space_reserved = false;
7405 * We don't allocate a new extent in the following cases
7407 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7409 * 2) The extent is marked as PREALLOC. We're good to go here and can
7410 * just use the extent.
7413 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7414 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7415 em->block_start != EXTENT_MAP_HOLE)) {
7416 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7417 type = BTRFS_ORDERED_PREALLOC;
7419 type = BTRFS_ORDERED_NOCOW;
7420 len = min(len, em->len - (start - em->start));
7421 block_start = em->block_start + (start - em->start);
7423 if (can_nocow_extent(inode, start, &len, &orig_start,
7424 &orig_block_len, &ram_bytes, false, false) == 1) {
7425 bg = btrfs_inc_nocow_writers(fs_info, block_start);
7433 struct extent_map *em2;
7435 /* We can NOCOW, so only need to reserve metadata space. */
7436 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7439 /* Our caller expects us to free the input extent map. */
7440 free_extent_map(em);
7442 btrfs_dec_nocow_writers(bg);
7443 if (nowait && (ret == -ENOSPC || ret == -EDQUOT))
7447 space_reserved = true;
7449 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7450 orig_start, block_start,
7451 len, orig_block_len,
7453 btrfs_dec_nocow_writers(bg);
7454 if (type == BTRFS_ORDERED_PREALLOC) {
7455 free_extent_map(em);
7465 dio_data->nocow_done = true;
7467 /* Our caller expects us to free the input extent map. */
7468 free_extent_map(em);
7475 * If we could not allocate data space before locking the file
7476 * range and we can't do a NOCOW write, then we have to fail.
7478 if (!dio_data->data_space_reserved)
7482 * We have to COW and we have already reserved data space before,
7483 * so now we reserve only metadata.
7485 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7489 space_reserved = true;
7491 em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7497 len = min(len, em->len - (start - em->start));
7499 btrfs_delalloc_release_metadata(BTRFS_I(inode),
7500 prev_len - len, true);
7504 * We have created our ordered extent, so we can now release our reservation
7505 * for an outstanding extent.
7507 btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
7510 * Need to update the i_size under the extent lock so buffered
7511 * readers will get the updated i_size when we unlock.
7513 if (start + len > i_size_read(inode))
7514 i_size_write(inode, start + len);
7516 if (ret && space_reserved) {
7517 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7518 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7523 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7524 loff_t length, unsigned int flags, struct iomap *iomap,
7525 struct iomap *srcmap)
7527 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7528 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7529 struct extent_map *em;
7530 struct extent_state *cached_state = NULL;
7531 struct btrfs_dio_data *dio_data = iter->private;
7532 u64 lockstart, lockend;
7533 const bool write = !!(flags & IOMAP_WRITE);
7536 const u64 data_alloc_len = length;
7537 bool unlock_extents = false;
7540 * We could potentially fault if we have a buffer > PAGE_SIZE, and if
7541 * we're NOWAIT we may submit a bio for a partial range and return
7542 * EIOCBQUEUED, which would result in an errant short read.
7544 * The best way to handle this would be to allow for partial completions
7545 * of iocb's, so we could submit the partial bio, return and fault in
7546 * the rest of the pages, and then submit the io for the rest of the
7547 * range. However we don't have that currently, so simply return
7548 * -EAGAIN at this point so that the normal path is used.
7550 if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE)
7554 * Cap the size of reads to that usually seen in buffered I/O as we need
7555 * to allocate a contiguous array for the checksums.
7558 len = min_t(u64, len, fs_info->sectorsize * BTRFS_MAX_BIO_SECTORS);
7561 lockend = start + len - 1;
7564 * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
7565 * enough if we've written compressed pages to this area, so we need to
7566 * flush the dirty pages again to make absolutely sure that any
7567 * outstanding dirty pages are on disk - the first flush only starts
7568 * compression on the data, while keeping the pages locked, so by the
7569 * time the second flush returns we know bios for the compressed pages
7570 * were submitted and finished, and the pages no longer under writeback.
7572 * If we have a NOWAIT request and we have any pages in the range that
7573 * are locked, likely due to compression still in progress, we don't want
7574 * to block on page locks. We also don't want to block on pages marked as
7575 * dirty or under writeback (same as for the non-compression case).
7576 * iomap_dio_rw() did the same check, but after that and before we got
7577 * here, mmap'ed writes may have happened or buffered reads started
7578 * (readpage() and readahead(), which lock pages), as we haven't locked
7579 * the file range yet.
7581 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7582 &BTRFS_I(inode)->runtime_flags)) {
7583 if (flags & IOMAP_NOWAIT) {
7584 if (filemap_range_needs_writeback(inode->i_mapping,
7585 lockstart, lockend))
7588 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7589 start + length - 1);
7595 memset(dio_data, 0, sizeof(*dio_data));
7598 * We always try to allocate data space and must do it before locking
7599 * the file range, to avoid deadlocks with concurrent writes to the same
7600 * range if the range has several extents and the writes don't expand the
7601 * current i_size (the inode lock is taken in shared mode). If we fail to
7602 * allocate data space here we continue and later, after locking the
7603 * file range, we fail with ENOSPC only if we figure out we can not do a
7606 if (write && !(flags & IOMAP_NOWAIT)) {
7607 ret = btrfs_check_data_free_space(BTRFS_I(inode),
7608 &dio_data->data_reserved,
7609 start, data_alloc_len, false);
7611 dio_data->data_space_reserved = true;
7612 else if (ret && !(BTRFS_I(inode)->flags &
7613 (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
7618 * If this errors out it's because we couldn't invalidate pagecache for
7619 * this range and we need to fallback to buffered IO, or we are doing a
7620 * NOWAIT read/write and we need to block.
7622 ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags);
7626 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7633 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7634 * io. INLINE is special, and we could probably kludge it in here, but
7635 * it's still buffered so for safety lets just fall back to the generic
7638 * For COMPRESSED we _have_ to read the entire extent in so we can
7639 * decompress it, so there will be buffering required no matter what we
7640 * do, so go ahead and fallback to buffered.
7642 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7643 * to buffered IO. Don't blame me, this is the price we pay for using
7646 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7647 em->block_start == EXTENT_MAP_INLINE) {
7648 free_extent_map(em);
7650 * If we are in a NOWAIT context, return -EAGAIN in order to
7651 * fallback to buffered IO. This is not only because we can
7652 * block with buffered IO (no support for NOWAIT semantics at
7653 * the moment) but also to avoid returning short reads to user
7654 * space - this happens if we were able to read some data from
7655 * previous non-compressed extents and then when we fallback to
7656 * buffered IO, at btrfs_file_read_iter() by calling
7657 * filemap_read(), we fail to fault in pages for the read buffer,
7658 * in which case filemap_read() returns a short read (the number
7659 * of bytes previously read is > 0, so it does not return -EFAULT).
7661 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
7665 len = min(len, em->len - (start - em->start));
7668 * If we have a NOWAIT request and the range contains multiple extents
7669 * (or a mix of extents and holes), then we return -EAGAIN to make the
7670 * caller fallback to a context where it can do a blocking (without
7671 * NOWAIT) request. This way we avoid doing partial IO and returning
7672 * success to the caller, which is not optimal for writes and for reads
7673 * it can result in unexpected behaviour for an application.
7675 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7676 * iomap_dio_rw(), we can end up returning less data then what the caller
7677 * asked for, resulting in an unexpected, and incorrect, short read.
7678 * That is, the caller asked to read N bytes and we return less than that,
7679 * which is wrong unless we are crossing EOF. This happens if we get a
7680 * page fault error when trying to fault in pages for the buffer that is
7681 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7682 * have previously submitted bios for other extents in the range, in
7683 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7684 * those bios have completed by the time we get the page fault error,
7685 * which we return back to our caller - we should only return EIOCBQUEUED
7686 * after we have submitted bios for all the extents in the range.
7688 if ((flags & IOMAP_NOWAIT) && len < length) {
7689 free_extent_map(em);
7695 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7699 unlock_extents = true;
7700 /* Recalc len in case the new em is smaller than requested */
7701 len = min(len, em->len - (start - em->start));
7702 if (dio_data->data_space_reserved) {
7704 u64 release_len = 0;
7706 if (dio_data->nocow_done) {
7707 release_offset = start;
7708 release_len = data_alloc_len;
7709 } else if (len < data_alloc_len) {
7710 release_offset = start + len;
7711 release_len = data_alloc_len - len;
7714 if (release_len > 0)
7715 btrfs_free_reserved_data_space(BTRFS_I(inode),
7716 dio_data->data_reserved,
7722 * We need to unlock only the end area that we aren't using.
7723 * The rest is going to be unlocked by the endio routine.
7725 lockstart = start + len;
7726 if (lockstart < lockend)
7727 unlock_extents = true;
7731 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7734 free_extent_state(cached_state);
7737 * Translate extent map information to iomap.
7738 * We trim the extents (and move the addr) even though iomap code does
7739 * that, since we have locked only the parts we are performing I/O in.
7741 if ((em->block_start == EXTENT_MAP_HOLE) ||
7742 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7743 iomap->addr = IOMAP_NULL_ADDR;
7744 iomap->type = IOMAP_HOLE;
7746 iomap->addr = em->block_start + (start - em->start);
7747 iomap->type = IOMAP_MAPPED;
7749 iomap->offset = start;
7750 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7751 iomap->length = len;
7753 if (write && btrfs_use_zone_append(BTRFS_I(inode), em->block_start))
7754 iomap->flags |= IOMAP_F_ZONE_APPEND;
7756 free_extent_map(em);
7761 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7764 if (dio_data->data_space_reserved) {
7765 btrfs_free_reserved_data_space(BTRFS_I(inode),
7766 dio_data->data_reserved,
7767 start, data_alloc_len);
7768 extent_changeset_free(dio_data->data_reserved);
7774 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7775 ssize_t written, unsigned int flags, struct iomap *iomap)
7777 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7778 struct btrfs_dio_data *dio_data = iter->private;
7779 size_t submitted = dio_data->submitted;
7780 const bool write = !!(flags & IOMAP_WRITE);
7783 if (!write && (iomap->type == IOMAP_HOLE)) {
7784 /* If reading from a hole, unlock and return */
7785 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1,
7790 if (submitted < length) {
7792 length -= submitted;
7794 btrfs_mark_ordered_io_finished(BTRFS_I(inode), NULL,
7795 pos, length, false);
7797 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7798 pos + length - 1, NULL);
7803 extent_changeset_free(dio_data->data_reserved);
7807 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7810 * This implies a barrier so that stores to dio_bio->bi_status before
7811 * this and loads of dio_bio->bi_status after this are fully ordered.
7813 if (!refcount_dec_and_test(&dip->refs))
7816 if (btrfs_op(&dip->bio) == BTRFS_MAP_WRITE) {
7817 btrfs_mark_ordered_io_finished(BTRFS_I(dip->inode), NULL,
7818 dip->file_offset, dip->bytes,
7819 !dip->bio.bi_status);
7821 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7823 dip->file_offset + dip->bytes - 1, NULL);
7827 bio_endio(&dip->bio);
7830 static void submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7832 enum btrfs_compression_type compress_type)
7834 struct btrfs_dio_private *dip = btrfs_bio(bio)->private;
7835 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7837 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7839 refcount_inc(&dip->refs);
7840 btrfs_submit_bio(fs_info, bio, mirror_num);
7843 static blk_status_t btrfs_check_read_dio_bio(struct btrfs_dio_private *dip,
7844 struct btrfs_bio *bbio,
7845 const bool uptodate)
7847 struct inode *inode = dip->inode;
7848 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7849 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7850 blk_status_t err = BLK_STS_OK;
7851 struct bvec_iter iter;
7855 btrfs_bio_for_each_sector(fs_info, bv, bbio, iter, offset) {
7856 u64 start = bbio->file_offset + offset;
7859 (!csum || !btrfs_check_data_csum(inode, bbio, offset, bv.bv_page,
7861 btrfs_clean_io_failure(BTRFS_I(inode), start,
7862 bv.bv_page, bv.bv_offset);
7866 ret = btrfs_repair_one_sector(inode, bbio, offset,
7867 bv.bv_page, bv.bv_offset,
7868 submit_dio_repair_bio);
7870 err = errno_to_blk_status(ret);
7877 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7879 u64 dio_file_offset)
7881 return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, false);
7884 static void btrfs_end_dio_bio(struct btrfs_bio *bbio)
7886 struct btrfs_dio_private *dip = bbio->private;
7887 struct bio *bio = &bbio->bio;
7888 blk_status_t err = bio->bi_status;
7891 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7892 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7893 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7894 bio->bi_opf, bio->bi_iter.bi_sector,
7895 bio->bi_iter.bi_size, err);
7897 if (bio_op(bio) == REQ_OP_READ)
7898 err = btrfs_check_read_dio_bio(dip, bbio, !err);
7901 dip->bio.bi_status = err;
7903 btrfs_record_physical_zoned(dip->inode, bbio->file_offset, bio);
7906 btrfs_dio_private_put(dip);
7909 static void btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7910 u64 file_offset, int async_submit)
7912 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7913 struct btrfs_dio_private *dip = btrfs_bio(bio)->private;
7916 /* Save the original iter for read repair */
7917 if (btrfs_op(bio) == BTRFS_MAP_READ)
7918 btrfs_bio(bio)->iter = bio->bi_iter;
7920 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7923 if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
7924 /* Check btrfs_submit_data_write_bio() for async submit rules */
7925 if (async_submit && !atomic_read(&BTRFS_I(inode)->sync_writers) &&
7926 btrfs_wq_submit_bio(inode, bio, 0, file_offset,
7927 btrfs_submit_bio_start_direct_io))
7931 * If we aren't doing async submit, calculate the csum of the
7934 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, false);
7936 btrfs_bio_end_io(btrfs_bio(bio), ret);
7940 btrfs_bio(bio)->csum = btrfs_csum_ptr(fs_info, dip->csums,
7941 file_offset - dip->file_offset);
7944 btrfs_submit_bio(fs_info, bio, 0);
7947 static void btrfs_submit_direct(const struct iomap_iter *iter,
7948 struct bio *dio_bio, loff_t file_offset)
7950 struct btrfs_dio_private *dip =
7951 container_of(dio_bio, struct btrfs_dio_private, bio);
7952 struct inode *inode = iter->inode;
7953 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
7954 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7955 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7956 BTRFS_BLOCK_GROUP_RAID56_MASK);
7959 int async_submit = 0;
7961 u64 clone_offset = 0;
7965 blk_status_t status;
7966 struct btrfs_io_geometry geom;
7967 struct btrfs_dio_data *dio_data = iter->private;
7968 struct extent_map *em = NULL;
7971 dip->file_offset = file_offset;
7972 dip->bytes = dio_bio->bi_iter.bi_size;
7973 refcount_set(&dip->refs, 1);
7976 if (!write && !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
7977 unsigned int nr_sectors =
7978 (dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits);
7981 * Load the csums up front to reduce csum tree searches and
7982 * contention when submitting bios.
7984 status = BLK_STS_RESOURCE;
7985 dip->csums = kcalloc(nr_sectors, fs_info->csum_size, GFP_NOFS);
7989 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
7990 if (status != BLK_STS_OK)
7994 start_sector = dio_bio->bi_iter.bi_sector;
7995 submit_len = dio_bio->bi_iter.bi_size;
7998 logical = start_sector << 9;
7999 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8001 status = errno_to_blk_status(PTR_ERR(em));
8005 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8008 status = errno_to_blk_status(ret);
8012 clone_len = min(submit_len, geom.len);
8013 ASSERT(clone_len <= UINT_MAX);
8016 * This will never fail as it's passing GPF_NOFS and
8017 * the allocation is backed by btrfs_bioset.
8019 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len,
8020 btrfs_end_dio_bio, dip);
8021 btrfs_bio(bio)->file_offset = file_offset;
8023 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8024 status = extract_ordered_extent(BTRFS_I(inode), bio,
8032 ASSERT(submit_len >= clone_len);
8033 submit_len -= clone_len;
8036 * Increase the count before we submit the bio so we know
8037 * the end IO handler won't happen before we increase the
8038 * count. Otherwise, the dip might get freed before we're
8039 * done setting it up.
8041 * We transfer the initial reference to the last bio, so we
8042 * don't need to increment the reference count for the last one.
8044 if (submit_len > 0) {
8045 refcount_inc(&dip->refs);
8047 * If we are submitting more than one bio, submit them
8048 * all asynchronously. The exception is RAID 5 or 6, as
8049 * asynchronous checksums make it difficult to collect
8050 * full stripe writes.
8056 btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8058 dio_data->submitted += clone_len;
8059 clone_offset += clone_len;
8060 start_sector += clone_len >> 9;
8061 file_offset += clone_len;
8063 free_extent_map(em);
8064 } while (submit_len > 0);
8068 free_extent_map(em);
8070 dio_bio->bi_status = status;
8071 btrfs_dio_private_put(dip);
8074 static const struct iomap_ops btrfs_dio_iomap_ops = {
8075 .iomap_begin = btrfs_dio_iomap_begin,
8076 .iomap_end = btrfs_dio_iomap_end,
8079 static const struct iomap_dio_ops btrfs_dio_ops = {
8080 .submit_io = btrfs_submit_direct,
8081 .bio_set = &btrfs_dio_bioset,
8084 ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, size_t done_before)
8086 struct btrfs_dio_data data;
8088 return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
8089 IOMAP_DIO_PARTIAL, &data, done_before);
8092 struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
8095 struct btrfs_dio_data data;
8097 return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
8098 IOMAP_DIO_PARTIAL, &data, done_before);
8101 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8106 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8111 * fiemap_prep() called filemap_write_and_wait() for the whole possible
8112 * file range (0 to LLONG_MAX), but that is not enough if we have
8113 * compression enabled. The first filemap_fdatawrite_range() only kicks
8114 * in the compression of data (in an async thread) and will return
8115 * before the compression is done and writeback is started. A second
8116 * filemap_fdatawrite_range() is needed to wait for the compression to
8117 * complete and writeback to start. We also need to wait for ordered
8118 * extents to complete, because our fiemap implementation uses mainly
8119 * file extent items to list the extents, searching for extent maps
8120 * only for file ranges with holes or prealloc extents to figure out
8121 * if we have delalloc in those ranges.
8123 if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
8124 ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
8129 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8132 static int btrfs_writepages(struct address_space *mapping,
8133 struct writeback_control *wbc)
8135 return extent_writepages(mapping, wbc);
8138 static void btrfs_readahead(struct readahead_control *rac)
8140 extent_readahead(rac);
8144 * For release_folio() and invalidate_folio() we have a race window where
8145 * folio_end_writeback() is called but the subpage spinlock is not yet released.
8146 * If we continue to release/invalidate the page, we could cause use-after-free
8147 * for subpage spinlock. So this function is to spin and wait for subpage
8150 static void wait_subpage_spinlock(struct page *page)
8152 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
8153 struct btrfs_subpage *subpage;
8155 if (!btrfs_is_subpage(fs_info, page))
8158 ASSERT(PagePrivate(page) && page->private);
8159 subpage = (struct btrfs_subpage *)page->private;
8162 * This may look insane as we just acquire the spinlock and release it,
8163 * without doing anything. But we just want to make sure no one is
8164 * still holding the subpage spinlock.
8165 * And since the page is not dirty nor writeback, and we have page
8166 * locked, the only possible way to hold a spinlock is from the endio
8167 * function to clear page writeback.
8169 * Here we just acquire the spinlock so that all existing callers
8170 * should exit and we're safe to release/invalidate the page.
8172 spin_lock_irq(&subpage->lock);
8173 spin_unlock_irq(&subpage->lock);
8176 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
8178 int ret = try_release_extent_mapping(&folio->page, gfp_flags);
8181 wait_subpage_spinlock(&folio->page);
8182 clear_page_extent_mapped(&folio->page);
8187 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
8189 if (folio_test_writeback(folio) || folio_test_dirty(folio))
8191 return __btrfs_release_folio(folio, gfp_flags);
8194 #ifdef CONFIG_MIGRATION
8195 static int btrfs_migrate_folio(struct address_space *mapping,
8196 struct folio *dst, struct folio *src,
8197 enum migrate_mode mode)
8199 int ret = filemap_migrate_folio(mapping, dst, src, mode);
8201 if (ret != MIGRATEPAGE_SUCCESS)
8204 if (folio_test_ordered(src)) {
8205 folio_clear_ordered(src);
8206 folio_set_ordered(dst);
8209 return MIGRATEPAGE_SUCCESS;
8212 #define btrfs_migrate_folio NULL
8215 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
8218 struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
8219 struct btrfs_fs_info *fs_info = inode->root->fs_info;
8220 struct extent_io_tree *tree = &inode->io_tree;
8221 struct extent_state *cached_state = NULL;
8222 u64 page_start = folio_pos(folio);
8223 u64 page_end = page_start + folio_size(folio) - 1;
8225 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8228 * We have folio locked so no new ordered extent can be created on this
8229 * page, nor bio can be submitted for this folio.
8231 * But already submitted bio can still be finished on this folio.
8232 * Furthermore, endio function won't skip folio which has Ordered
8233 * (Private2) already cleared, so it's possible for endio and
8234 * invalidate_folio to do the same ordered extent accounting twice
8237 * So here we wait for any submitted bios to finish, so that we won't
8238 * do double ordered extent accounting on the same folio.
8240 folio_wait_writeback(folio);
8241 wait_subpage_spinlock(&folio->page);
8244 * For subpage case, we have call sites like
8245 * btrfs_punch_hole_lock_range() which passes range not aligned to
8247 * If the range doesn't cover the full folio, we don't need to and
8248 * shouldn't clear page extent mapped, as folio->private can still
8249 * record subpage dirty bits for other part of the range.
8251 * For cases that invalidate the full folio even the range doesn't
8252 * cover the full folio, like invalidating the last folio, we're
8253 * still safe to wait for ordered extent to finish.
8255 if (!(offset == 0 && length == folio_size(folio))) {
8256 btrfs_release_folio(folio, GFP_NOFS);
8260 if (!inode_evicting)
8261 lock_extent(tree, page_start, page_end, &cached_state);
8264 while (cur < page_end) {
8265 struct btrfs_ordered_extent *ordered;
8268 u32 extra_flags = 0;
8270 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8271 page_end + 1 - cur);
8273 range_end = page_end;
8275 * No ordered extent covering this range, we are safe
8276 * to delete all extent states in the range.
8278 extra_flags = EXTENT_CLEAR_ALL_BITS;
8281 if (ordered->file_offset > cur) {
8283 * There is a range between [cur, oe->file_offset) not
8284 * covered by any ordered extent.
8285 * We are safe to delete all extent states, and handle
8286 * the ordered extent in the next iteration.
8288 range_end = ordered->file_offset - 1;
8289 extra_flags = EXTENT_CLEAR_ALL_BITS;
8293 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8295 ASSERT(range_end + 1 - cur < U32_MAX);
8296 range_len = range_end + 1 - cur;
8297 if (!btrfs_page_test_ordered(fs_info, &folio->page, cur, range_len)) {
8299 * If Ordered (Private2) is cleared, it means endio has
8300 * already been executed for the range.
8301 * We can't delete the extent states as
8302 * btrfs_finish_ordered_io() may still use some of them.
8306 btrfs_page_clear_ordered(fs_info, &folio->page, cur, range_len);
8309 * IO on this page will never be started, so we need to account
8310 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8311 * here, must leave that up for the ordered extent completion.
8313 * This will also unlock the range for incoming
8314 * btrfs_finish_ordered_io().
8316 if (!inode_evicting)
8317 clear_extent_bit(tree, cur, range_end,
8319 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8320 EXTENT_DEFRAG, &cached_state);
8322 spin_lock_irq(&inode->ordered_tree.lock);
8323 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8324 ordered->truncated_len = min(ordered->truncated_len,
8325 cur - ordered->file_offset);
8326 spin_unlock_irq(&inode->ordered_tree.lock);
8329 * If the ordered extent has finished, we're safe to delete all
8330 * the extent states of the range, otherwise
8331 * btrfs_finish_ordered_io() will get executed by endio for
8332 * other pages, so we can't delete extent states.
8334 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8335 cur, range_end + 1 - cur)) {
8336 btrfs_finish_ordered_io(ordered);
8338 * The ordered extent has finished, now we're again
8339 * safe to delete all extent states of the range.
8341 extra_flags = EXTENT_CLEAR_ALL_BITS;
8345 btrfs_put_ordered_extent(ordered);
8347 * Qgroup reserved space handler
8348 * Sector(s) here will be either:
8350 * 1) Already written to disk or bio already finished
8351 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8352 * Qgroup will be handled by its qgroup_record then.
8353 * btrfs_qgroup_free_data() call will do nothing here.
8355 * 2) Not written to disk yet
8356 * Then btrfs_qgroup_free_data() call will clear the
8357 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8358 * reserved data space.
8359 * Since the IO will never happen for this page.
8361 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8362 if (!inode_evicting) {
8363 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8364 EXTENT_DELALLOC | EXTENT_UPTODATE |
8365 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
8366 extra_flags, &cached_state);
8368 cur = range_end + 1;
8371 * We have iterated through all ordered extents of the page, the page
8372 * should not have Ordered (Private2) anymore, or the above iteration
8373 * did something wrong.
8375 ASSERT(!folio_test_ordered(folio));
8376 btrfs_page_clear_checked(fs_info, &folio->page, folio_pos(folio), folio_size(folio));
8377 if (!inode_evicting)
8378 __btrfs_release_folio(folio, GFP_NOFS);
8379 clear_page_extent_mapped(&folio->page);
8383 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8384 * called from a page fault handler when a page is first dirtied. Hence we must
8385 * be careful to check for EOF conditions here. We set the page up correctly
8386 * for a written page which means we get ENOSPC checking when writing into
8387 * holes and correct delalloc and unwritten extent mapping on filesystems that
8388 * support these features.
8390 * We are not allowed to take the i_mutex here so we have to play games to
8391 * protect against truncate races as the page could now be beyond EOF. Because
8392 * truncate_setsize() writes the inode size before removing pages, once we have
8393 * the page lock we can determine safely if the page is beyond EOF. If it is not
8394 * beyond EOF, then the page is guaranteed safe against truncation until we
8397 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8399 struct page *page = vmf->page;
8400 struct inode *inode = file_inode(vmf->vma->vm_file);
8401 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8402 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8403 struct btrfs_ordered_extent *ordered;
8404 struct extent_state *cached_state = NULL;
8405 struct extent_changeset *data_reserved = NULL;
8406 unsigned long zero_start;
8416 reserved_space = PAGE_SIZE;
8418 sb_start_pagefault(inode->i_sb);
8419 page_start = page_offset(page);
8420 page_end = page_start + PAGE_SIZE - 1;
8424 * Reserving delalloc space after obtaining the page lock can lead to
8425 * deadlock. For example, if a dirty page is locked by this function
8426 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8427 * dirty page write out, then the btrfs_writepages() function could
8428 * end up waiting indefinitely to get a lock on the page currently
8429 * being processed by btrfs_page_mkwrite() function.
8431 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8432 page_start, reserved_space);
8434 ret2 = file_update_time(vmf->vma->vm_file);
8438 ret = vmf_error(ret2);
8444 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8446 down_read(&BTRFS_I(inode)->i_mmap_lock);
8448 size = i_size_read(inode);
8450 if ((page->mapping != inode->i_mapping) ||
8451 (page_start >= size)) {
8452 /* page got truncated out from underneath us */
8455 wait_on_page_writeback(page);
8457 lock_extent(io_tree, page_start, page_end, &cached_state);
8458 ret2 = set_page_extent_mapped(page);
8460 ret = vmf_error(ret2);
8461 unlock_extent(io_tree, page_start, page_end, &cached_state);
8466 * we can't set the delalloc bits if there are pending ordered
8467 * extents. Drop our locks and wait for them to finish
8469 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8472 unlock_extent(io_tree, page_start, page_end, &cached_state);
8474 up_read(&BTRFS_I(inode)->i_mmap_lock);
8475 btrfs_start_ordered_extent(ordered, 1);
8476 btrfs_put_ordered_extent(ordered);
8480 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8481 reserved_space = round_up(size - page_start,
8482 fs_info->sectorsize);
8483 if (reserved_space < PAGE_SIZE) {
8484 end = page_start + reserved_space - 1;
8485 btrfs_delalloc_release_space(BTRFS_I(inode),
8486 data_reserved, page_start,
8487 PAGE_SIZE - reserved_space, true);
8492 * page_mkwrite gets called when the page is firstly dirtied after it's
8493 * faulted in, but write(2) could also dirty a page and set delalloc
8494 * bits, thus in this case for space account reason, we still need to
8495 * clear any delalloc bits within this page range since we have to
8496 * reserve data&meta space before lock_page() (see above comments).
8498 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8499 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8500 EXTENT_DEFRAG, &cached_state);
8502 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8505 unlock_extent(io_tree, page_start, page_end, &cached_state);
8506 ret = VM_FAULT_SIGBUS;
8510 /* page is wholly or partially inside EOF */
8511 if (page_start + PAGE_SIZE > size)
8512 zero_start = offset_in_page(size);
8514 zero_start = PAGE_SIZE;
8516 if (zero_start != PAGE_SIZE)
8517 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8519 btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
8520 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8521 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8523 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8525 unlock_extent(io_tree, page_start, page_end, &cached_state);
8526 up_read(&BTRFS_I(inode)->i_mmap_lock);
8528 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8529 sb_end_pagefault(inode->i_sb);
8530 extent_changeset_free(data_reserved);
8531 return VM_FAULT_LOCKED;
8535 up_read(&BTRFS_I(inode)->i_mmap_lock);
8537 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8538 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8539 reserved_space, (ret != 0));
8541 sb_end_pagefault(inode->i_sb);
8542 extent_changeset_free(data_reserved);
8546 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8548 struct btrfs_truncate_control control = {
8549 .inode = BTRFS_I(inode),
8550 .ino = btrfs_ino(BTRFS_I(inode)),
8551 .min_type = BTRFS_EXTENT_DATA_KEY,
8552 .clear_extent_range = true,
8554 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8555 struct btrfs_root *root = BTRFS_I(inode)->root;
8556 struct btrfs_block_rsv *rsv;
8558 struct btrfs_trans_handle *trans;
8559 u64 mask = fs_info->sectorsize - 1;
8560 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8562 if (!skip_writeback) {
8563 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8570 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8571 * things going on here:
8573 * 1) We need to reserve space to update our inode.
8575 * 2) We need to have something to cache all the space that is going to
8576 * be free'd up by the truncate operation, but also have some slack
8577 * space reserved in case it uses space during the truncate (thank you
8578 * very much snapshotting).
8580 * And we need these to be separate. The fact is we can use a lot of
8581 * space doing the truncate, and we have no earthly idea how much space
8582 * we will use, so we need the truncate reservation to be separate so it
8583 * doesn't end up using space reserved for updating the inode. We also
8584 * need to be able to stop the transaction and start a new one, which
8585 * means we need to be able to update the inode several times, and we
8586 * have no idea of knowing how many times that will be, so we can't just
8587 * reserve 1 item for the entirety of the operation, so that has to be
8588 * done separately as well.
8590 * So that leaves us with
8592 * 1) rsv - for the truncate reservation, which we will steal from the
8593 * transaction reservation.
8594 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8595 * updating the inode.
8597 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8600 rsv->size = min_size;
8601 rsv->failfast = true;
8604 * 1 for the truncate slack space
8605 * 1 for updating the inode.
8607 trans = btrfs_start_transaction(root, 2);
8608 if (IS_ERR(trans)) {
8609 ret = PTR_ERR(trans);
8613 /* Migrate the slack space for the truncate to our reserve */
8614 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8618 trans->block_rsv = rsv;
8621 struct extent_state *cached_state = NULL;
8622 const u64 new_size = inode->i_size;
8623 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8625 control.new_size = new_size;
8626 lock_extent(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
8629 * We want to drop from the next block forward in case this new
8630 * size is not block aligned since we will be keeping the last
8631 * block of the extent just the way it is.
8633 btrfs_drop_extent_map_range(BTRFS_I(inode),
8634 ALIGN(new_size, fs_info->sectorsize),
8637 ret = btrfs_truncate_inode_items(trans, root, &control);
8639 inode_sub_bytes(inode, control.sub_bytes);
8640 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), control.last_size);
8642 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
8645 trans->block_rsv = &fs_info->trans_block_rsv;
8646 if (ret != -ENOSPC && ret != -EAGAIN)
8649 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8653 btrfs_end_transaction(trans);
8654 btrfs_btree_balance_dirty(fs_info);
8656 trans = btrfs_start_transaction(root, 2);
8657 if (IS_ERR(trans)) {
8658 ret = PTR_ERR(trans);
8663 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8664 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8665 rsv, min_size, false);
8666 BUG_ON(ret); /* shouldn't happen */
8667 trans->block_rsv = rsv;
8671 * We can't call btrfs_truncate_block inside a trans handle as we could
8672 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8673 * know we've truncated everything except the last little bit, and can
8674 * do btrfs_truncate_block and then update the disk_i_size.
8676 if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8677 btrfs_end_transaction(trans);
8678 btrfs_btree_balance_dirty(fs_info);
8680 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8683 trans = btrfs_start_transaction(root, 1);
8684 if (IS_ERR(trans)) {
8685 ret = PTR_ERR(trans);
8688 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8694 trans->block_rsv = &fs_info->trans_block_rsv;
8695 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8699 ret2 = btrfs_end_transaction(trans);
8702 btrfs_btree_balance_dirty(fs_info);
8705 btrfs_free_block_rsv(fs_info, rsv);
8707 * So if we truncate and then write and fsync we normally would just
8708 * write the extents that changed, which is a problem if we need to
8709 * first truncate that entire inode. So set this flag so we write out
8710 * all of the extents in the inode to the sync log so we're completely
8713 * If no extents were dropped or trimmed we don't need to force the next
8714 * fsync to truncate all the inode's items from the log and re-log them
8715 * all. This means the truncate operation did not change the file size,
8716 * or changed it to a smaller size but there was only an implicit hole
8717 * between the old i_size and the new i_size, and there were no prealloc
8718 * extents beyond i_size to drop.
8720 if (control.extents_found > 0)
8721 btrfs_set_inode_full_sync(BTRFS_I(inode));
8726 struct inode *btrfs_new_subvol_inode(struct user_namespace *mnt_userns,
8729 struct inode *inode;
8731 inode = new_inode(dir->i_sb);
8734 * Subvolumes don't inherit the sgid bit or the parent's gid if
8735 * the parent's sgid bit is set. This is probably a bug.
8737 inode_init_owner(mnt_userns, inode, NULL,
8738 S_IFDIR | (~current_umask() & S_IRWXUGO));
8739 inode->i_op = &btrfs_dir_inode_operations;
8740 inode->i_fop = &btrfs_dir_file_operations;
8745 struct inode *btrfs_alloc_inode(struct super_block *sb)
8747 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8748 struct btrfs_inode *ei;
8749 struct inode *inode;
8751 ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8758 ei->last_sub_trans = 0;
8759 ei->logged_trans = 0;
8760 ei->delalloc_bytes = 0;
8761 ei->new_delalloc_bytes = 0;
8762 ei->defrag_bytes = 0;
8763 ei->disk_i_size = 0;
8767 ei->index_cnt = (u64)-1;
8769 ei->last_unlink_trans = 0;
8770 ei->last_reflink_trans = 0;
8771 ei->last_log_commit = 0;
8773 spin_lock_init(&ei->lock);
8774 spin_lock_init(&ei->io_failure_lock);
8775 ei->outstanding_extents = 0;
8776 if (sb->s_magic != BTRFS_TEST_MAGIC)
8777 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8778 BTRFS_BLOCK_RSV_DELALLOC);
8779 ei->runtime_flags = 0;
8780 ei->prop_compress = BTRFS_COMPRESS_NONE;
8781 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8783 ei->delayed_node = NULL;
8785 ei->i_otime.tv_sec = 0;
8786 ei->i_otime.tv_nsec = 0;
8788 inode = &ei->vfs_inode;
8789 extent_map_tree_init(&ei->extent_tree);
8790 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8791 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8792 IO_TREE_INODE_FILE_EXTENT, NULL);
8793 ei->io_failure_tree = RB_ROOT;
8794 atomic_set(&ei->sync_writers, 0);
8795 mutex_init(&ei->log_mutex);
8796 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8797 INIT_LIST_HEAD(&ei->delalloc_inodes);
8798 INIT_LIST_HEAD(&ei->delayed_iput);
8799 RB_CLEAR_NODE(&ei->rb_node);
8800 init_rwsem(&ei->i_mmap_lock);
8805 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8806 void btrfs_test_destroy_inode(struct inode *inode)
8808 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8809 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8813 void btrfs_free_inode(struct inode *inode)
8815 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8818 void btrfs_destroy_inode(struct inode *vfs_inode)
8820 struct btrfs_ordered_extent *ordered;
8821 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8822 struct btrfs_root *root = inode->root;
8823 bool freespace_inode;
8825 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8826 WARN_ON(vfs_inode->i_data.nrpages);
8827 WARN_ON(inode->block_rsv.reserved);
8828 WARN_ON(inode->block_rsv.size);
8829 WARN_ON(inode->outstanding_extents);
8830 if (!S_ISDIR(vfs_inode->i_mode)) {
8831 WARN_ON(inode->delalloc_bytes);
8832 WARN_ON(inode->new_delalloc_bytes);
8834 WARN_ON(inode->csum_bytes);
8835 WARN_ON(inode->defrag_bytes);
8838 * This can happen where we create an inode, but somebody else also
8839 * created the same inode and we need to destroy the one we already
8846 * If this is a free space inode do not take the ordered extents lockdep
8849 freespace_inode = btrfs_is_free_space_inode(inode);
8852 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8856 btrfs_err(root->fs_info,
8857 "found ordered extent %llu %llu on inode cleanup",
8858 ordered->file_offset, ordered->num_bytes);
8860 if (!freespace_inode)
8861 btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
8863 btrfs_remove_ordered_extent(inode, ordered);
8864 btrfs_put_ordered_extent(ordered);
8865 btrfs_put_ordered_extent(ordered);
8868 btrfs_qgroup_check_reserved_leak(inode);
8869 inode_tree_del(inode);
8870 btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
8871 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8872 btrfs_put_root(inode->root);
8875 int btrfs_drop_inode(struct inode *inode)
8877 struct btrfs_root *root = BTRFS_I(inode)->root;
8882 /* the snap/subvol tree is on deleting */
8883 if (btrfs_root_refs(&root->root_item) == 0)
8886 return generic_drop_inode(inode);
8889 static void init_once(void *foo)
8891 struct btrfs_inode *ei = foo;
8893 inode_init_once(&ei->vfs_inode);
8896 void __cold btrfs_destroy_cachep(void)
8899 * Make sure all delayed rcu free inodes are flushed before we
8903 bioset_exit(&btrfs_dio_bioset);
8904 kmem_cache_destroy(btrfs_inode_cachep);
8905 kmem_cache_destroy(btrfs_trans_handle_cachep);
8906 kmem_cache_destroy(btrfs_path_cachep);
8907 kmem_cache_destroy(btrfs_free_space_cachep);
8908 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8911 int __init btrfs_init_cachep(void)
8913 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8914 sizeof(struct btrfs_inode), 0,
8915 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8917 if (!btrfs_inode_cachep)
8920 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8921 sizeof(struct btrfs_trans_handle), 0,
8922 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8923 if (!btrfs_trans_handle_cachep)
8926 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8927 sizeof(struct btrfs_path), 0,
8928 SLAB_MEM_SPREAD, NULL);
8929 if (!btrfs_path_cachep)
8932 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8933 sizeof(struct btrfs_free_space), 0,
8934 SLAB_MEM_SPREAD, NULL);
8935 if (!btrfs_free_space_cachep)
8938 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8939 PAGE_SIZE, PAGE_SIZE,
8940 SLAB_MEM_SPREAD, NULL);
8941 if (!btrfs_free_space_bitmap_cachep)
8944 if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE,
8945 offsetof(struct btrfs_dio_private, bio),
8951 btrfs_destroy_cachep();
8955 static int btrfs_getattr(struct user_namespace *mnt_userns,
8956 const struct path *path, struct kstat *stat,
8957 u32 request_mask, unsigned int flags)
8961 struct inode *inode = d_inode(path->dentry);
8962 u32 blocksize = inode->i_sb->s_blocksize;
8963 u32 bi_flags = BTRFS_I(inode)->flags;
8964 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8966 stat->result_mask |= STATX_BTIME;
8967 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8968 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8969 if (bi_flags & BTRFS_INODE_APPEND)
8970 stat->attributes |= STATX_ATTR_APPEND;
8971 if (bi_flags & BTRFS_INODE_COMPRESS)
8972 stat->attributes |= STATX_ATTR_COMPRESSED;
8973 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8974 stat->attributes |= STATX_ATTR_IMMUTABLE;
8975 if (bi_flags & BTRFS_INODE_NODUMP)
8976 stat->attributes |= STATX_ATTR_NODUMP;
8977 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8978 stat->attributes |= STATX_ATTR_VERITY;
8980 stat->attributes_mask |= (STATX_ATTR_APPEND |
8981 STATX_ATTR_COMPRESSED |
8982 STATX_ATTR_IMMUTABLE |
8985 generic_fillattr(mnt_userns, inode, stat);
8986 stat->dev = BTRFS_I(inode)->root->anon_dev;
8988 spin_lock(&BTRFS_I(inode)->lock);
8989 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8990 inode_bytes = inode_get_bytes(inode);
8991 spin_unlock(&BTRFS_I(inode)->lock);
8992 stat->blocks = (ALIGN(inode_bytes, blocksize) +
8993 ALIGN(delalloc_bytes, blocksize)) >> 9;
8997 static int btrfs_rename_exchange(struct inode *old_dir,
8998 struct dentry *old_dentry,
8999 struct inode *new_dir,
9000 struct dentry *new_dentry)
9002 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9003 struct btrfs_trans_handle *trans;
9004 unsigned int trans_num_items;
9005 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9006 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9007 struct inode *new_inode = new_dentry->d_inode;
9008 struct inode *old_inode = old_dentry->d_inode;
9009 struct timespec64 ctime = current_time(old_inode);
9010 struct btrfs_rename_ctx old_rename_ctx;
9011 struct btrfs_rename_ctx new_rename_ctx;
9012 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9013 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9018 bool need_abort = false;
9021 * For non-subvolumes allow exchange only within one subvolume, in the
9022 * same inode namespace. Two subvolumes (represented as directory) can
9023 * be exchanged as they're a logical link and have a fixed inode number.
9026 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
9027 new_ino != BTRFS_FIRST_FREE_OBJECTID))
9030 /* close the race window with snapshot create/destroy ioctl */
9031 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9032 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9033 down_read(&fs_info->subvol_sem);
9037 * 1 to remove old dir item
9038 * 1 to remove old dir index
9039 * 1 to add new dir item
9040 * 1 to add new dir index
9041 * 1 to update parent inode
9043 * If the parents are the same, we only need to account for one
9045 trans_num_items = (old_dir == new_dir ? 9 : 10);
9046 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9048 * 1 to remove old root ref
9049 * 1 to remove old root backref
9050 * 1 to add new root ref
9051 * 1 to add new root backref
9053 trans_num_items += 4;
9056 * 1 to update inode item
9057 * 1 to remove old inode ref
9058 * 1 to add new inode ref
9060 trans_num_items += 3;
9062 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9063 trans_num_items += 4;
9065 trans_num_items += 3;
9066 trans = btrfs_start_transaction(root, trans_num_items);
9067 if (IS_ERR(trans)) {
9068 ret = PTR_ERR(trans);
9073 ret = btrfs_record_root_in_trans(trans, dest);
9079 * We need to find a free sequence number both in the source and
9080 * in the destination directory for the exchange.
9082 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9085 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9089 BTRFS_I(old_inode)->dir_index = 0ULL;
9090 BTRFS_I(new_inode)->dir_index = 0ULL;
9092 /* Reference for the source. */
9093 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9094 /* force full log commit if subvolume involved. */
9095 btrfs_set_log_full_commit(trans);
9097 ret = btrfs_insert_inode_ref(trans, dest,
9098 new_dentry->d_name.name,
9099 new_dentry->d_name.len,
9101 btrfs_ino(BTRFS_I(new_dir)),
9108 /* And now for the dest. */
9109 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9110 /* force full log commit if subvolume involved. */
9111 btrfs_set_log_full_commit(trans);
9113 ret = btrfs_insert_inode_ref(trans, root,
9114 old_dentry->d_name.name,
9115 old_dentry->d_name.len,
9117 btrfs_ino(BTRFS_I(old_dir)),
9121 btrfs_abort_transaction(trans, ret);
9126 /* Update inode version and ctime/mtime. */
9127 inode_inc_iversion(old_dir);
9128 inode_inc_iversion(new_dir);
9129 inode_inc_iversion(old_inode);
9130 inode_inc_iversion(new_inode);
9131 old_dir->i_mtime = ctime;
9132 old_dir->i_ctime = ctime;
9133 new_dir->i_mtime = ctime;
9134 new_dir->i_ctime = ctime;
9135 old_inode->i_ctime = ctime;
9136 new_inode->i_ctime = ctime;
9138 if (old_dentry->d_parent != new_dentry->d_parent) {
9139 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9140 BTRFS_I(old_inode), 1);
9141 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9142 BTRFS_I(new_inode), 1);
9145 /* src is a subvolume */
9146 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9147 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9148 } else { /* src is an inode */
9149 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9150 BTRFS_I(old_dentry->d_inode),
9151 old_dentry->d_name.name,
9152 old_dentry->d_name.len,
9155 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9158 btrfs_abort_transaction(trans, ret);
9162 /* dest is a subvolume */
9163 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9164 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9165 } else { /* dest is an inode */
9166 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9167 BTRFS_I(new_dentry->d_inode),
9168 new_dentry->d_name.name,
9169 new_dentry->d_name.len,
9172 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9175 btrfs_abort_transaction(trans, ret);
9179 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9180 new_dentry->d_name.name,
9181 new_dentry->d_name.len, 0, old_idx);
9183 btrfs_abort_transaction(trans, ret);
9187 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9188 old_dentry->d_name.name,
9189 old_dentry->d_name.len, 0, new_idx);
9191 btrfs_abort_transaction(trans, ret);
9195 if (old_inode->i_nlink == 1)
9196 BTRFS_I(old_inode)->dir_index = old_idx;
9197 if (new_inode->i_nlink == 1)
9198 BTRFS_I(new_inode)->dir_index = new_idx;
9201 * Now pin the logs of the roots. We do it to ensure that no other task
9202 * can sync the logs while we are in progress with the rename, because
9203 * that could result in an inconsistency in case any of the inodes that
9204 * are part of this rename operation were logged before.
9206 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9207 btrfs_pin_log_trans(root);
9208 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9209 btrfs_pin_log_trans(dest);
9211 /* Do the log updates for all inodes. */
9212 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9213 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9214 old_rename_ctx.index, new_dentry->d_parent);
9215 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9216 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
9217 new_rename_ctx.index, old_dentry->d_parent);
9219 /* Now unpin the logs. */
9220 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9221 btrfs_end_log_trans(root);
9222 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9223 btrfs_end_log_trans(dest);
9225 ret2 = btrfs_end_transaction(trans);
9226 ret = ret ? ret : ret2;
9228 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9229 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9230 up_read(&fs_info->subvol_sem);
9235 static struct inode *new_whiteout_inode(struct user_namespace *mnt_userns,
9238 struct inode *inode;
9240 inode = new_inode(dir->i_sb);
9242 inode_init_owner(mnt_userns, inode, dir,
9243 S_IFCHR | WHITEOUT_MODE);
9244 inode->i_op = &btrfs_special_inode_operations;
9245 init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
9250 static int btrfs_rename(struct user_namespace *mnt_userns,
9251 struct inode *old_dir, struct dentry *old_dentry,
9252 struct inode *new_dir, struct dentry *new_dentry,
9255 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9256 struct btrfs_new_inode_args whiteout_args = {
9258 .dentry = old_dentry,
9260 struct btrfs_trans_handle *trans;
9261 unsigned int trans_num_items;
9262 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9263 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9264 struct inode *new_inode = d_inode(new_dentry);
9265 struct inode *old_inode = d_inode(old_dentry);
9266 struct btrfs_rename_ctx rename_ctx;
9270 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9272 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9275 /* we only allow rename subvolume link between subvolumes */
9276 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9279 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9280 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9283 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9284 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9288 /* check for collisions, even if the name isn't there */
9289 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9290 new_dentry->d_name.name,
9291 new_dentry->d_name.len);
9294 if (ret == -EEXIST) {
9296 * eexist without a new_inode */
9297 if (WARN_ON(!new_inode)) {
9301 /* maybe -EOVERFLOW */
9308 * we're using rename to replace one file with another. Start IO on it
9309 * now so we don't add too much work to the end of the transaction
9311 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9312 filemap_flush(old_inode->i_mapping);
9314 if (flags & RENAME_WHITEOUT) {
9315 whiteout_args.inode = new_whiteout_inode(mnt_userns, old_dir);
9316 if (!whiteout_args.inode)
9318 ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
9320 goto out_whiteout_inode;
9322 /* 1 to update the old parent inode. */
9323 trans_num_items = 1;
9326 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9327 /* Close the race window with snapshot create/destroy ioctl */
9328 down_read(&fs_info->subvol_sem);
9330 * 1 to remove old root ref
9331 * 1 to remove old root backref
9332 * 1 to add new root ref
9333 * 1 to add new root backref
9335 trans_num_items += 4;
9339 * 1 to remove old inode ref
9340 * 1 to add new inode ref
9342 trans_num_items += 3;
9345 * 1 to remove old dir item
9346 * 1 to remove old dir index
9347 * 1 to add new dir item
9348 * 1 to add new dir index
9350 trans_num_items += 4;
9351 /* 1 to update new parent inode if it's not the same as the old parent */
9352 if (new_dir != old_dir)
9357 * 1 to remove inode ref
9358 * 1 to remove dir item
9359 * 1 to remove dir index
9360 * 1 to possibly add orphan item
9362 trans_num_items += 5;
9364 trans = btrfs_start_transaction(root, trans_num_items);
9365 if (IS_ERR(trans)) {
9366 ret = PTR_ERR(trans);
9371 ret = btrfs_record_root_in_trans(trans, dest);
9376 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9380 BTRFS_I(old_inode)->dir_index = 0ULL;
9381 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9382 /* force full log commit if subvolume involved. */
9383 btrfs_set_log_full_commit(trans);
9385 ret = btrfs_insert_inode_ref(trans, dest,
9386 new_dentry->d_name.name,
9387 new_dentry->d_name.len,
9389 btrfs_ino(BTRFS_I(new_dir)), index);
9394 inode_inc_iversion(old_dir);
9395 inode_inc_iversion(new_dir);
9396 inode_inc_iversion(old_inode);
9397 old_dir->i_mtime = current_time(old_dir);
9398 old_dir->i_ctime = old_dir->i_mtime;
9399 new_dir->i_mtime = old_dir->i_mtime;
9400 new_dir->i_ctime = old_dir->i_mtime;
9401 old_inode->i_ctime = old_dir->i_mtime;
9403 if (old_dentry->d_parent != new_dentry->d_parent)
9404 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9405 BTRFS_I(old_inode), 1);
9407 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9408 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9410 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9411 BTRFS_I(d_inode(old_dentry)),
9412 old_dentry->d_name.name,
9413 old_dentry->d_name.len,
9416 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9419 btrfs_abort_transaction(trans, ret);
9424 inode_inc_iversion(new_inode);
9425 new_inode->i_ctime = current_time(new_inode);
9426 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9427 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9428 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9429 BUG_ON(new_inode->i_nlink == 0);
9431 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9432 BTRFS_I(d_inode(new_dentry)),
9433 new_dentry->d_name.name,
9434 new_dentry->d_name.len);
9436 if (!ret && new_inode->i_nlink == 0)
9437 ret = btrfs_orphan_add(trans,
9438 BTRFS_I(d_inode(new_dentry)));
9440 btrfs_abort_transaction(trans, ret);
9445 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9446 new_dentry->d_name.name,
9447 new_dentry->d_name.len, 0, index);
9449 btrfs_abort_transaction(trans, ret);
9453 if (old_inode->i_nlink == 1)
9454 BTRFS_I(old_inode)->dir_index = index;
9456 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9457 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9458 rename_ctx.index, new_dentry->d_parent);
9460 if (flags & RENAME_WHITEOUT) {
9461 ret = btrfs_create_new_inode(trans, &whiteout_args);
9463 btrfs_abort_transaction(trans, ret);
9466 unlock_new_inode(whiteout_args.inode);
9467 iput(whiteout_args.inode);
9468 whiteout_args.inode = NULL;
9472 ret2 = btrfs_end_transaction(trans);
9473 ret = ret ? ret : ret2;
9475 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9476 up_read(&fs_info->subvol_sem);
9477 if (flags & RENAME_WHITEOUT)
9478 btrfs_new_inode_args_destroy(&whiteout_args);
9480 if (flags & RENAME_WHITEOUT)
9481 iput(whiteout_args.inode);
9485 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9486 struct dentry *old_dentry, struct inode *new_dir,
9487 struct dentry *new_dentry, unsigned int flags)
9491 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9494 if (flags & RENAME_EXCHANGE)
9495 ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9498 ret = btrfs_rename(mnt_userns, old_dir, old_dentry, new_dir,
9501 btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
9506 struct btrfs_delalloc_work {
9507 struct inode *inode;
9508 struct completion completion;
9509 struct list_head list;
9510 struct btrfs_work work;
9513 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9515 struct btrfs_delalloc_work *delalloc_work;
9516 struct inode *inode;
9518 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9520 inode = delalloc_work->inode;
9521 filemap_flush(inode->i_mapping);
9522 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9523 &BTRFS_I(inode)->runtime_flags))
9524 filemap_flush(inode->i_mapping);
9527 complete(&delalloc_work->completion);
9530 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9532 struct btrfs_delalloc_work *work;
9534 work = kmalloc(sizeof(*work), GFP_NOFS);
9538 init_completion(&work->completion);
9539 INIT_LIST_HEAD(&work->list);
9540 work->inode = inode;
9541 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9547 * some fairly slow code that needs optimization. This walks the list
9548 * of all the inodes with pending delalloc and forces them to disk.
9550 static int start_delalloc_inodes(struct btrfs_root *root,
9551 struct writeback_control *wbc, bool snapshot,
9552 bool in_reclaim_context)
9554 struct btrfs_inode *binode;
9555 struct inode *inode;
9556 struct btrfs_delalloc_work *work, *next;
9557 struct list_head works;
9558 struct list_head splice;
9560 bool full_flush = wbc->nr_to_write == LONG_MAX;
9562 INIT_LIST_HEAD(&works);
9563 INIT_LIST_HEAD(&splice);
9565 mutex_lock(&root->delalloc_mutex);
9566 spin_lock(&root->delalloc_lock);
9567 list_splice_init(&root->delalloc_inodes, &splice);
9568 while (!list_empty(&splice)) {
9569 binode = list_entry(splice.next, struct btrfs_inode,
9572 list_move_tail(&binode->delalloc_inodes,
9573 &root->delalloc_inodes);
9575 if (in_reclaim_context &&
9576 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9579 inode = igrab(&binode->vfs_inode);
9581 cond_resched_lock(&root->delalloc_lock);
9584 spin_unlock(&root->delalloc_lock);
9587 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9588 &binode->runtime_flags);
9590 work = btrfs_alloc_delalloc_work(inode);
9596 list_add_tail(&work->list, &works);
9597 btrfs_queue_work(root->fs_info->flush_workers,
9600 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9601 btrfs_add_delayed_iput(inode);
9602 if (ret || wbc->nr_to_write <= 0)
9606 spin_lock(&root->delalloc_lock);
9608 spin_unlock(&root->delalloc_lock);
9611 list_for_each_entry_safe(work, next, &works, list) {
9612 list_del_init(&work->list);
9613 wait_for_completion(&work->completion);
9617 if (!list_empty(&splice)) {
9618 spin_lock(&root->delalloc_lock);
9619 list_splice_tail(&splice, &root->delalloc_inodes);
9620 spin_unlock(&root->delalloc_lock);
9622 mutex_unlock(&root->delalloc_mutex);
9626 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9628 struct writeback_control wbc = {
9629 .nr_to_write = LONG_MAX,
9630 .sync_mode = WB_SYNC_NONE,
9632 .range_end = LLONG_MAX,
9634 struct btrfs_fs_info *fs_info = root->fs_info;
9636 if (BTRFS_FS_ERROR(fs_info))
9639 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9642 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9643 bool in_reclaim_context)
9645 struct writeback_control wbc = {
9647 .sync_mode = WB_SYNC_NONE,
9649 .range_end = LLONG_MAX,
9651 struct btrfs_root *root;
9652 struct list_head splice;
9655 if (BTRFS_FS_ERROR(fs_info))
9658 INIT_LIST_HEAD(&splice);
9660 mutex_lock(&fs_info->delalloc_root_mutex);
9661 spin_lock(&fs_info->delalloc_root_lock);
9662 list_splice_init(&fs_info->delalloc_roots, &splice);
9663 while (!list_empty(&splice)) {
9665 * Reset nr_to_write here so we know that we're doing a full
9669 wbc.nr_to_write = LONG_MAX;
9671 root = list_first_entry(&splice, struct btrfs_root,
9673 root = btrfs_grab_root(root);
9675 list_move_tail(&root->delalloc_root,
9676 &fs_info->delalloc_roots);
9677 spin_unlock(&fs_info->delalloc_root_lock);
9679 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9680 btrfs_put_root(root);
9681 if (ret < 0 || wbc.nr_to_write <= 0)
9683 spin_lock(&fs_info->delalloc_root_lock);
9685 spin_unlock(&fs_info->delalloc_root_lock);
9689 if (!list_empty(&splice)) {
9690 spin_lock(&fs_info->delalloc_root_lock);
9691 list_splice_tail(&splice, &fs_info->delalloc_roots);
9692 spin_unlock(&fs_info->delalloc_root_lock);
9694 mutex_unlock(&fs_info->delalloc_root_mutex);
9698 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9699 struct dentry *dentry, const char *symname)
9701 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9702 struct btrfs_trans_handle *trans;
9703 struct btrfs_root *root = BTRFS_I(dir)->root;
9704 struct btrfs_path *path;
9705 struct btrfs_key key;
9706 struct inode *inode;
9707 struct btrfs_new_inode_args new_inode_args = {
9711 unsigned int trans_num_items;
9716 struct btrfs_file_extent_item *ei;
9717 struct extent_buffer *leaf;
9719 name_len = strlen(symname);
9720 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9721 return -ENAMETOOLONG;
9723 inode = new_inode(dir->i_sb);
9726 inode_init_owner(mnt_userns, inode, dir, S_IFLNK | S_IRWXUGO);
9727 inode->i_op = &btrfs_symlink_inode_operations;
9728 inode_nohighmem(inode);
9729 inode->i_mapping->a_ops = &btrfs_aops;
9730 btrfs_i_size_write(BTRFS_I(inode), name_len);
9731 inode_set_bytes(inode, name_len);
9733 new_inode_args.inode = inode;
9734 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9737 /* 1 additional item for the inline extent */
9740 trans = btrfs_start_transaction(root, trans_num_items);
9741 if (IS_ERR(trans)) {
9742 err = PTR_ERR(trans);
9743 goto out_new_inode_args;
9746 err = btrfs_create_new_inode(trans, &new_inode_args);
9750 path = btrfs_alloc_path();
9753 btrfs_abort_transaction(trans, err);
9754 discard_new_inode(inode);
9758 key.objectid = btrfs_ino(BTRFS_I(inode));
9760 key.type = BTRFS_EXTENT_DATA_KEY;
9761 datasize = btrfs_file_extent_calc_inline_size(name_len);
9762 err = btrfs_insert_empty_item(trans, root, path, &key,
9765 btrfs_abort_transaction(trans, err);
9766 btrfs_free_path(path);
9767 discard_new_inode(inode);
9771 leaf = path->nodes[0];
9772 ei = btrfs_item_ptr(leaf, path->slots[0],
9773 struct btrfs_file_extent_item);
9774 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9775 btrfs_set_file_extent_type(leaf, ei,
9776 BTRFS_FILE_EXTENT_INLINE);
9777 btrfs_set_file_extent_encryption(leaf, ei, 0);
9778 btrfs_set_file_extent_compression(leaf, ei, 0);
9779 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9780 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9782 ptr = btrfs_file_extent_inline_start(ei);
9783 write_extent_buffer(leaf, symname, ptr, name_len);
9784 btrfs_mark_buffer_dirty(leaf);
9785 btrfs_free_path(path);
9787 d_instantiate_new(dentry, inode);
9790 btrfs_end_transaction(trans);
9791 btrfs_btree_balance_dirty(fs_info);
9793 btrfs_new_inode_args_destroy(&new_inode_args);
9800 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9801 struct btrfs_trans_handle *trans_in,
9802 struct btrfs_inode *inode,
9803 struct btrfs_key *ins,
9806 struct btrfs_file_extent_item stack_fi;
9807 struct btrfs_replace_extent_info extent_info;
9808 struct btrfs_trans_handle *trans = trans_in;
9809 struct btrfs_path *path;
9810 u64 start = ins->objectid;
9811 u64 len = ins->offset;
9812 int qgroup_released;
9815 memset(&stack_fi, 0, sizeof(stack_fi));
9817 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9818 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9819 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9820 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9821 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9822 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9823 /* Encryption and other encoding is reserved and all 0 */
9825 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9826 if (qgroup_released < 0)
9827 return ERR_PTR(qgroup_released);
9830 ret = insert_reserved_file_extent(trans, inode,
9831 file_offset, &stack_fi,
9832 true, qgroup_released);
9838 extent_info.disk_offset = start;
9839 extent_info.disk_len = len;
9840 extent_info.data_offset = 0;
9841 extent_info.data_len = len;
9842 extent_info.file_offset = file_offset;
9843 extent_info.extent_buf = (char *)&stack_fi;
9844 extent_info.is_new_extent = true;
9845 extent_info.update_times = true;
9846 extent_info.qgroup_reserved = qgroup_released;
9847 extent_info.insertions = 0;
9849 path = btrfs_alloc_path();
9855 ret = btrfs_replace_file_extents(inode, path, file_offset,
9856 file_offset + len - 1, &extent_info,
9858 btrfs_free_path(path);
9865 * We have released qgroup data range at the beginning of the function,
9866 * and normally qgroup_released bytes will be freed when committing
9868 * But if we error out early, we have to free what we have released
9869 * or we leak qgroup data reservation.
9871 btrfs_qgroup_free_refroot(inode->root->fs_info,
9872 inode->root->root_key.objectid, qgroup_released,
9873 BTRFS_QGROUP_RSV_DATA);
9874 return ERR_PTR(ret);
9877 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9878 u64 start, u64 num_bytes, u64 min_size,
9879 loff_t actual_len, u64 *alloc_hint,
9880 struct btrfs_trans_handle *trans)
9882 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9883 struct extent_map *em;
9884 struct btrfs_root *root = BTRFS_I(inode)->root;
9885 struct btrfs_key ins;
9886 u64 cur_offset = start;
9887 u64 clear_offset = start;
9890 u64 last_alloc = (u64)-1;
9892 bool own_trans = true;
9893 u64 end = start + num_bytes - 1;
9897 while (num_bytes > 0) {
9898 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9899 cur_bytes = max(cur_bytes, min_size);
9901 * If we are severely fragmented we could end up with really
9902 * small allocations, so if the allocator is returning small
9903 * chunks lets make its job easier by only searching for those
9906 cur_bytes = min(cur_bytes, last_alloc);
9907 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9908 min_size, 0, *alloc_hint, &ins, 1, 0);
9913 * We've reserved this space, and thus converted it from
9914 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9915 * from here on out we will only need to clear our reservation
9916 * for the remaining unreserved area, so advance our
9917 * clear_offset by our extent size.
9919 clear_offset += ins.offset;
9921 last_alloc = ins.offset;
9922 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9925 * Now that we inserted the prealloc extent we can finally
9926 * decrement the number of reservations in the block group.
9927 * If we did it before, we could race with relocation and have
9928 * relocation miss the reserved extent, making it fail later.
9930 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9931 if (IS_ERR(trans)) {
9932 ret = PTR_ERR(trans);
9933 btrfs_free_reserved_extent(fs_info, ins.objectid,
9938 em = alloc_extent_map();
9940 btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9941 cur_offset + ins.offset - 1, false);
9942 btrfs_set_inode_full_sync(BTRFS_I(inode));
9946 em->start = cur_offset;
9947 em->orig_start = cur_offset;
9948 em->len = ins.offset;
9949 em->block_start = ins.objectid;
9950 em->block_len = ins.offset;
9951 em->orig_block_len = ins.offset;
9952 em->ram_bytes = ins.offset;
9953 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9954 em->generation = trans->transid;
9956 ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9957 free_extent_map(em);
9959 num_bytes -= ins.offset;
9960 cur_offset += ins.offset;
9961 *alloc_hint = ins.objectid + ins.offset;
9963 inode_inc_iversion(inode);
9964 inode->i_ctime = current_time(inode);
9965 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9966 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9967 (actual_len > inode->i_size) &&
9968 (cur_offset > inode->i_size)) {
9969 if (cur_offset > actual_len)
9970 i_size = actual_len;
9972 i_size = cur_offset;
9973 i_size_write(inode, i_size);
9974 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9977 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9980 btrfs_abort_transaction(trans, ret);
9982 btrfs_end_transaction(trans);
9987 btrfs_end_transaction(trans);
9991 if (clear_offset < end)
9992 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9993 end - clear_offset + 1);
9997 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9998 u64 start, u64 num_bytes, u64 min_size,
9999 loff_t actual_len, u64 *alloc_hint)
10001 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10002 min_size, actual_len, alloc_hint,
10006 int btrfs_prealloc_file_range_trans(struct inode *inode,
10007 struct btrfs_trans_handle *trans, int mode,
10008 u64 start, u64 num_bytes, u64 min_size,
10009 loff_t actual_len, u64 *alloc_hint)
10011 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10012 min_size, actual_len, alloc_hint, trans);
10015 static int btrfs_permission(struct user_namespace *mnt_userns,
10016 struct inode *inode, int mask)
10018 struct btrfs_root *root = BTRFS_I(inode)->root;
10019 umode_t mode = inode->i_mode;
10021 if (mask & MAY_WRITE &&
10022 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10023 if (btrfs_root_readonly(root))
10025 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10028 return generic_permission(mnt_userns, inode, mask);
10031 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10032 struct file *file, umode_t mode)
10034 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10035 struct btrfs_trans_handle *trans;
10036 struct btrfs_root *root = BTRFS_I(dir)->root;
10037 struct inode *inode;
10038 struct btrfs_new_inode_args new_inode_args = {
10040 .dentry = file->f_path.dentry,
10043 unsigned int trans_num_items;
10046 inode = new_inode(dir->i_sb);
10049 inode_init_owner(mnt_userns, inode, dir, mode);
10050 inode->i_fop = &btrfs_file_operations;
10051 inode->i_op = &btrfs_file_inode_operations;
10052 inode->i_mapping->a_ops = &btrfs_aops;
10054 new_inode_args.inode = inode;
10055 ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
10059 trans = btrfs_start_transaction(root, trans_num_items);
10060 if (IS_ERR(trans)) {
10061 ret = PTR_ERR(trans);
10062 goto out_new_inode_args;
10065 ret = btrfs_create_new_inode(trans, &new_inode_args);
10068 * We set number of links to 0 in btrfs_create_new_inode(), and here we
10069 * set it to 1 because d_tmpfile() will issue a warning if the count is
10072 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10074 set_nlink(inode, 1);
10077 d_tmpfile(file, inode);
10078 unlock_new_inode(inode);
10079 mark_inode_dirty(inode);
10082 btrfs_end_transaction(trans);
10083 btrfs_btree_balance_dirty(fs_info);
10084 out_new_inode_args:
10085 btrfs_new_inode_args_destroy(&new_inode_args);
10089 return finish_open_simple(file, ret);
10092 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
10094 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10095 unsigned long index = start >> PAGE_SHIFT;
10096 unsigned long end_index = end >> PAGE_SHIFT;
10100 ASSERT(end + 1 - start <= U32_MAX);
10101 len = end + 1 - start;
10102 while (index <= end_index) {
10103 page = find_get_page(inode->vfs_inode.i_mapping, index);
10104 ASSERT(page); /* Pages should be in the extent_io_tree */
10106 btrfs_page_set_writeback(fs_info, page, start, len);
10112 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
10115 switch (compress_type) {
10116 case BTRFS_COMPRESS_NONE:
10117 return BTRFS_ENCODED_IO_COMPRESSION_NONE;
10118 case BTRFS_COMPRESS_ZLIB:
10119 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
10120 case BTRFS_COMPRESS_LZO:
10122 * The LZO format depends on the sector size. 64K is the maximum
10123 * sector size that we support.
10125 if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
10127 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
10128 (fs_info->sectorsize_bits - 12);
10129 case BTRFS_COMPRESS_ZSTD:
10130 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
10136 static ssize_t btrfs_encoded_read_inline(
10137 struct kiocb *iocb,
10138 struct iov_iter *iter, u64 start,
10140 struct extent_state **cached_state,
10141 u64 extent_start, size_t count,
10142 struct btrfs_ioctl_encoded_io_args *encoded,
10145 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10146 struct btrfs_root *root = inode->root;
10147 struct btrfs_fs_info *fs_info = root->fs_info;
10148 struct extent_io_tree *io_tree = &inode->io_tree;
10149 struct btrfs_path *path;
10150 struct extent_buffer *leaf;
10151 struct btrfs_file_extent_item *item;
10157 path = btrfs_alloc_path();
10162 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
10166 /* The extent item disappeared? */
10171 leaf = path->nodes[0];
10172 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10174 ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
10175 ptr = btrfs_file_extent_inline_start(item);
10177 encoded->len = min_t(u64, extent_start + ram_bytes,
10178 inode->vfs_inode.i_size) - iocb->ki_pos;
10179 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10180 btrfs_file_extent_compression(leaf, item));
10183 encoded->compression = ret;
10184 if (encoded->compression) {
10185 size_t inline_size;
10187 inline_size = btrfs_file_extent_inline_item_len(leaf,
10189 if (inline_size > count) {
10193 count = inline_size;
10194 encoded->unencoded_len = ram_bytes;
10195 encoded->unencoded_offset = iocb->ki_pos - extent_start;
10197 count = min_t(u64, count, encoded->len);
10198 encoded->len = count;
10199 encoded->unencoded_len = count;
10200 ptr += iocb->ki_pos - extent_start;
10203 tmp = kmalloc(count, GFP_NOFS);
10208 read_extent_buffer(leaf, tmp, ptr, count);
10209 btrfs_release_path(path);
10210 unlock_extent(io_tree, start, lockend, cached_state);
10211 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10214 ret = copy_to_iter(tmp, count, iter);
10219 btrfs_free_path(path);
10223 struct btrfs_encoded_read_private {
10224 struct btrfs_inode *inode;
10226 wait_queue_head_t wait;
10228 blk_status_t status;
10232 static blk_status_t submit_encoded_read_bio(struct btrfs_inode *inode,
10233 struct bio *bio, int mirror_num)
10235 struct btrfs_encoded_read_private *priv = btrfs_bio(bio)->private;
10236 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10239 if (!priv->skip_csum) {
10240 ret = btrfs_lookup_bio_sums(&inode->vfs_inode, bio, NULL);
10245 atomic_inc(&priv->pending);
10246 btrfs_submit_bio(fs_info, bio, mirror_num);
10250 static blk_status_t btrfs_encoded_read_verify_csum(struct btrfs_bio *bbio)
10252 const bool uptodate = (bbio->bio.bi_status == BLK_STS_OK);
10253 struct btrfs_encoded_read_private *priv = bbio->private;
10254 struct btrfs_inode *inode = priv->inode;
10255 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10256 u32 sectorsize = fs_info->sectorsize;
10257 struct bio_vec *bvec;
10258 struct bvec_iter_all iter_all;
10259 u32 bio_offset = 0;
10261 if (priv->skip_csum || !uptodate)
10262 return bbio->bio.bi_status;
10264 bio_for_each_segment_all(bvec, &bbio->bio, iter_all) {
10265 unsigned int i, nr_sectors, pgoff;
10267 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
10268 pgoff = bvec->bv_offset;
10269 for (i = 0; i < nr_sectors; i++) {
10270 ASSERT(pgoff < PAGE_SIZE);
10271 if (btrfs_check_data_csum(&inode->vfs_inode, bbio, bio_offset,
10272 bvec->bv_page, pgoff))
10273 return BLK_STS_IOERR;
10274 bio_offset += sectorsize;
10275 pgoff += sectorsize;
10281 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
10283 struct btrfs_encoded_read_private *priv = bbio->private;
10284 blk_status_t status;
10286 status = btrfs_encoded_read_verify_csum(bbio);
10289 * The memory barrier implied by the atomic_dec_return() here
10290 * pairs with the memory barrier implied by the
10291 * atomic_dec_return() or io_wait_event() in
10292 * btrfs_encoded_read_regular_fill_pages() to ensure that this
10293 * write is observed before the load of status in
10294 * btrfs_encoded_read_regular_fill_pages().
10296 WRITE_ONCE(priv->status, status);
10298 if (!atomic_dec_return(&priv->pending))
10299 wake_up(&priv->wait);
10300 btrfs_bio_free_csum(bbio);
10301 bio_put(&bbio->bio);
10304 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
10305 u64 file_offset, u64 disk_bytenr,
10306 u64 disk_io_size, struct page **pages)
10308 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10309 struct btrfs_encoded_read_private priv = {
10311 .file_offset = file_offset,
10312 .pending = ATOMIC_INIT(1),
10313 .skip_csum = (inode->flags & BTRFS_INODE_NODATASUM),
10315 unsigned long i = 0;
10319 init_waitqueue_head(&priv.wait);
10321 * Submit bios for the extent, splitting due to bio or stripe limits as
10324 while (cur < disk_io_size) {
10325 struct extent_map *em;
10326 struct btrfs_io_geometry geom;
10327 struct bio *bio = NULL;
10330 em = btrfs_get_chunk_map(fs_info, disk_bytenr + cur,
10331 disk_io_size - cur);
10335 ret = btrfs_get_io_geometry(fs_info, em, BTRFS_MAP_READ,
10336 disk_bytenr + cur, &geom);
10337 free_extent_map(em);
10340 WRITE_ONCE(priv.status, errno_to_blk_status(ret));
10343 remaining = min(geom.len, disk_io_size - cur);
10344 while (bio || remaining) {
10345 size_t bytes = min_t(u64, remaining, PAGE_SIZE);
10348 bio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ,
10349 btrfs_encoded_read_endio,
10351 bio->bi_iter.bi_sector =
10352 (disk_bytenr + cur) >> SECTOR_SHIFT;
10356 bio_add_page(bio, pages[i], bytes, 0) < bytes) {
10357 blk_status_t status;
10359 status = submit_encoded_read_bio(inode, bio, 0);
10361 WRITE_ONCE(priv.status, status);
10371 remaining -= bytes;
10376 if (atomic_dec_return(&priv.pending))
10377 io_wait_event(priv.wait, !atomic_read(&priv.pending));
10378 /* See btrfs_encoded_read_endio() for ordering. */
10379 return blk_status_to_errno(READ_ONCE(priv.status));
10382 static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
10383 struct iov_iter *iter,
10384 u64 start, u64 lockend,
10385 struct extent_state **cached_state,
10386 u64 disk_bytenr, u64 disk_io_size,
10387 size_t count, bool compressed,
10390 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10391 struct extent_io_tree *io_tree = &inode->io_tree;
10392 struct page **pages;
10393 unsigned long nr_pages, i;
10395 size_t page_offset;
10398 nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
10399 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
10402 ret = btrfs_alloc_page_array(nr_pages, pages);
10408 ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
10409 disk_io_size, pages);
10413 unlock_extent(io_tree, start, lockend, cached_state);
10414 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10421 i = (iocb->ki_pos - start) >> PAGE_SHIFT;
10422 page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
10425 while (cur < count) {
10426 size_t bytes = min_t(size_t, count - cur,
10427 PAGE_SIZE - page_offset);
10429 if (copy_page_to_iter(pages[i], page_offset, bytes,
10440 for (i = 0; i < nr_pages; i++) {
10442 __free_page(pages[i]);
10448 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
10449 struct btrfs_ioctl_encoded_io_args *encoded)
10451 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10452 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10453 struct extent_io_tree *io_tree = &inode->io_tree;
10455 size_t count = iov_iter_count(iter);
10456 u64 start, lockend, disk_bytenr, disk_io_size;
10457 struct extent_state *cached_state = NULL;
10458 struct extent_map *em;
10459 bool unlocked = false;
10461 file_accessed(iocb->ki_filp);
10463 btrfs_inode_lock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10465 if (iocb->ki_pos >= inode->vfs_inode.i_size) {
10466 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10469 start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
10471 * We don't know how long the extent containing iocb->ki_pos is, but if
10472 * it's compressed we know that it won't be longer than this.
10474 lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
10477 struct btrfs_ordered_extent *ordered;
10479 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
10480 lockend - start + 1);
10482 goto out_unlock_inode;
10483 lock_extent(io_tree, start, lockend, &cached_state);
10484 ordered = btrfs_lookup_ordered_range(inode, start,
10485 lockend - start + 1);
10488 btrfs_put_ordered_extent(ordered);
10489 unlock_extent(io_tree, start, lockend, &cached_state);
10493 em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
10496 goto out_unlock_extent;
10499 if (em->block_start == EXTENT_MAP_INLINE) {
10500 u64 extent_start = em->start;
10503 * For inline extents we get everything we need out of the
10506 free_extent_map(em);
10508 ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
10509 &cached_state, extent_start,
10510 count, encoded, &unlocked);
10515 * We only want to return up to EOF even if the extent extends beyond
10518 encoded->len = min_t(u64, extent_map_end(em),
10519 inode->vfs_inode.i_size) - iocb->ki_pos;
10520 if (em->block_start == EXTENT_MAP_HOLE ||
10521 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
10522 disk_bytenr = EXTENT_MAP_HOLE;
10523 count = min_t(u64, count, encoded->len);
10524 encoded->len = count;
10525 encoded->unencoded_len = count;
10526 } else if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10527 disk_bytenr = em->block_start;
10529 * Bail if the buffer isn't large enough to return the whole
10530 * compressed extent.
10532 if (em->block_len > count) {
10536 disk_io_size = em->block_len;
10537 count = em->block_len;
10538 encoded->unencoded_len = em->ram_bytes;
10539 encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
10540 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10541 em->compress_type);
10544 encoded->compression = ret;
10546 disk_bytenr = em->block_start + (start - em->start);
10547 if (encoded->len > count)
10548 encoded->len = count;
10550 * Don't read beyond what we locked. This also limits the page
10551 * allocations that we'll do.
10553 disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
10554 count = start + disk_io_size - iocb->ki_pos;
10555 encoded->len = count;
10556 encoded->unencoded_len = count;
10557 disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
10559 free_extent_map(em);
10562 if (disk_bytenr == EXTENT_MAP_HOLE) {
10563 unlock_extent(io_tree, start, lockend, &cached_state);
10564 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10566 ret = iov_iter_zero(count, iter);
10570 ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
10571 &cached_state, disk_bytenr,
10572 disk_io_size, count,
10573 encoded->compression,
10579 iocb->ki_pos += encoded->len;
10581 free_extent_map(em);
10584 unlock_extent(io_tree, start, lockend, &cached_state);
10587 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10591 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
10592 const struct btrfs_ioctl_encoded_io_args *encoded)
10594 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10595 struct btrfs_root *root = inode->root;
10596 struct btrfs_fs_info *fs_info = root->fs_info;
10597 struct extent_io_tree *io_tree = &inode->io_tree;
10598 struct extent_changeset *data_reserved = NULL;
10599 struct extent_state *cached_state = NULL;
10603 u64 num_bytes, ram_bytes, disk_num_bytes;
10604 unsigned long nr_pages, i;
10605 struct page **pages;
10606 struct btrfs_key ins;
10607 bool extent_reserved = false;
10608 struct extent_map *em;
10611 switch (encoded->compression) {
10612 case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
10613 compression = BTRFS_COMPRESS_ZLIB;
10615 case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
10616 compression = BTRFS_COMPRESS_ZSTD;
10618 case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
10619 case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
10620 case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
10621 case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
10622 case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
10623 /* The sector size must match for LZO. */
10624 if (encoded->compression -
10625 BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
10626 fs_info->sectorsize_bits)
10628 compression = BTRFS_COMPRESS_LZO;
10633 if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
10636 orig_count = iov_iter_count(from);
10638 /* The extent size must be sane. */
10639 if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
10640 orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
10644 * The compressed data must be smaller than the decompressed data.
10646 * It's of course possible for data to compress to larger or the same
10647 * size, but the buffered I/O path falls back to no compression for such
10648 * data, and we don't want to break any assumptions by creating these
10651 * Note that this is less strict than the current check we have that the
10652 * compressed data must be at least one sector smaller than the
10653 * decompressed data. We only want to enforce the weaker requirement
10654 * from old kernels that it is at least one byte smaller.
10656 if (orig_count >= encoded->unencoded_len)
10659 /* The extent must start on a sector boundary. */
10660 start = iocb->ki_pos;
10661 if (!IS_ALIGNED(start, fs_info->sectorsize))
10665 * The extent must end on a sector boundary. However, we allow a write
10666 * which ends at or extends i_size to have an unaligned length; we round
10667 * up the extent size and set i_size to the unaligned end.
10669 if (start + encoded->len < inode->vfs_inode.i_size &&
10670 !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
10673 /* Finally, the offset in the unencoded data must be sector-aligned. */
10674 if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
10677 num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10678 ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10679 end = start + num_bytes - 1;
10682 * If the extent cannot be inline, the compressed data on disk must be
10683 * sector-aligned. For convenience, we extend it with zeroes if it
10686 disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10687 nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
10688 pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
10691 for (i = 0; i < nr_pages; i++) {
10692 size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
10695 pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
10700 kaddr = kmap_local_page(pages[i]);
10701 if (copy_from_iter(kaddr, bytes, from) != bytes) {
10702 kunmap_local(kaddr);
10706 if (bytes < PAGE_SIZE)
10707 memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
10708 kunmap_local(kaddr);
10712 struct btrfs_ordered_extent *ordered;
10714 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
10717 ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10718 start >> PAGE_SHIFT,
10719 end >> PAGE_SHIFT);
10722 lock_extent(io_tree, start, end, &cached_state);
10723 ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10725 !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10728 btrfs_put_ordered_extent(ordered);
10729 unlock_extent(io_tree, start, end, &cached_state);
10734 * We don't use the higher-level delalloc space functions because our
10735 * num_bytes and disk_num_bytes are different.
10737 ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10740 ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10742 goto out_free_data_space;
10743 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10746 goto out_qgroup_free_data;
10748 /* Try an inline extent first. */
10749 if (start == 0 && encoded->unencoded_len == encoded->len &&
10750 encoded->unencoded_offset == 0) {
10751 ret = cow_file_range_inline(inode, encoded->len, orig_count,
10752 compression, pages, true);
10756 goto out_delalloc_release;
10760 ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10761 disk_num_bytes, 0, 0, &ins, 1, 1);
10763 goto out_delalloc_release;
10764 extent_reserved = true;
10766 em = create_io_em(inode, start, num_bytes,
10767 start - encoded->unencoded_offset, ins.objectid,
10768 ins.offset, ins.offset, ram_bytes, compression,
10769 BTRFS_ORDERED_COMPRESSED);
10772 goto out_free_reserved;
10774 free_extent_map(em);
10776 ret = btrfs_add_ordered_extent(inode, start, num_bytes, ram_bytes,
10777 ins.objectid, ins.offset,
10778 encoded->unencoded_offset,
10779 (1 << BTRFS_ORDERED_ENCODED) |
10780 (1 << BTRFS_ORDERED_COMPRESSED),
10783 btrfs_drop_extent_map_range(inode, start, end, false);
10784 goto out_free_reserved;
10786 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10788 if (start + encoded->len > inode->vfs_inode.i_size)
10789 i_size_write(&inode->vfs_inode, start + encoded->len);
10791 unlock_extent(io_tree, start, end, &cached_state);
10793 btrfs_delalloc_release_extents(inode, num_bytes);
10795 if (btrfs_submit_compressed_write(inode, start, num_bytes, ins.objectid,
10796 ins.offset, pages, nr_pages, 0, NULL,
10798 btrfs_writepage_endio_finish_ordered(inode, pages[0], start, end, 0);
10806 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10807 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
10808 out_delalloc_release:
10809 btrfs_delalloc_release_extents(inode, num_bytes);
10810 btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10811 out_qgroup_free_data:
10813 btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes);
10814 out_free_data_space:
10816 * If btrfs_reserve_extent() succeeded, then we already decremented
10819 if (!extent_reserved)
10820 btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
10822 unlock_extent(io_tree, start, end, &cached_state);
10824 for (i = 0; i < nr_pages; i++) {
10826 __free_page(pages[i]);
10831 iocb->ki_pos += encoded->len;
10837 * Add an entry indicating a block group or device which is pinned by a
10838 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10839 * negative errno on failure.
10841 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10842 bool is_block_group)
10844 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10845 struct btrfs_swapfile_pin *sp, *entry;
10846 struct rb_node **p;
10847 struct rb_node *parent = NULL;
10849 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10854 sp->is_block_group = is_block_group;
10855 sp->bg_extent_count = 1;
10857 spin_lock(&fs_info->swapfile_pins_lock);
10858 p = &fs_info->swapfile_pins.rb_node;
10861 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10862 if (sp->ptr < entry->ptr ||
10863 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10864 p = &(*p)->rb_left;
10865 } else if (sp->ptr > entry->ptr ||
10866 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10867 p = &(*p)->rb_right;
10869 if (is_block_group)
10870 entry->bg_extent_count++;
10871 spin_unlock(&fs_info->swapfile_pins_lock);
10876 rb_link_node(&sp->node, parent, p);
10877 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10878 spin_unlock(&fs_info->swapfile_pins_lock);
10882 /* Free all of the entries pinned by this swapfile. */
10883 static void btrfs_free_swapfile_pins(struct inode *inode)
10885 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10886 struct btrfs_swapfile_pin *sp;
10887 struct rb_node *node, *next;
10889 spin_lock(&fs_info->swapfile_pins_lock);
10890 node = rb_first(&fs_info->swapfile_pins);
10892 next = rb_next(node);
10893 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10894 if (sp->inode == inode) {
10895 rb_erase(&sp->node, &fs_info->swapfile_pins);
10896 if (sp->is_block_group) {
10897 btrfs_dec_block_group_swap_extents(sp->ptr,
10898 sp->bg_extent_count);
10899 btrfs_put_block_group(sp->ptr);
10905 spin_unlock(&fs_info->swapfile_pins_lock);
10908 struct btrfs_swap_info {
10914 unsigned long nr_pages;
10918 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10919 struct btrfs_swap_info *bsi)
10921 unsigned long nr_pages;
10922 unsigned long max_pages;
10923 u64 first_ppage, first_ppage_reported, next_ppage;
10927 * Our swapfile may have had its size extended after the swap header was
10928 * written. In that case activating the swapfile should not go beyond
10929 * the max size set in the swap header.
10931 if (bsi->nr_pages >= sis->max)
10934 max_pages = sis->max - bsi->nr_pages;
10935 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10936 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10937 PAGE_SIZE) >> PAGE_SHIFT;
10939 if (first_ppage >= next_ppage)
10941 nr_pages = next_ppage - first_ppage;
10942 nr_pages = min(nr_pages, max_pages);
10944 first_ppage_reported = first_ppage;
10945 if (bsi->start == 0)
10946 first_ppage_reported++;
10947 if (bsi->lowest_ppage > first_ppage_reported)
10948 bsi->lowest_ppage = first_ppage_reported;
10949 if (bsi->highest_ppage < (next_ppage - 1))
10950 bsi->highest_ppage = next_ppage - 1;
10952 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10955 bsi->nr_extents += ret;
10956 bsi->nr_pages += nr_pages;
10960 static void btrfs_swap_deactivate(struct file *file)
10962 struct inode *inode = file_inode(file);
10964 btrfs_free_swapfile_pins(inode);
10965 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10968 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10971 struct inode *inode = file_inode(file);
10972 struct btrfs_root *root = BTRFS_I(inode)->root;
10973 struct btrfs_fs_info *fs_info = root->fs_info;
10974 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10975 struct extent_state *cached_state = NULL;
10976 struct extent_map *em = NULL;
10977 struct btrfs_device *device = NULL;
10978 struct btrfs_swap_info bsi = {
10979 .lowest_ppage = (sector_t)-1ULL,
10986 * If the swap file was just created, make sure delalloc is done. If the
10987 * file changes again after this, the user is doing something stupid and
10988 * we don't really care.
10990 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10995 * The inode is locked, so these flags won't change after we check them.
10997 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10998 btrfs_warn(fs_info, "swapfile must not be compressed");
11001 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
11002 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
11005 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
11006 btrfs_warn(fs_info, "swapfile must not be checksummed");
11011 * Balance or device remove/replace/resize can move stuff around from
11012 * under us. The exclop protection makes sure they aren't running/won't
11013 * run concurrently while we are mapping the swap extents, and
11014 * fs_info->swapfile_pins prevents them from running while the swap
11015 * file is active and moving the extents. Note that this also prevents
11016 * a concurrent device add which isn't actually necessary, but it's not
11017 * really worth the trouble to allow it.
11019 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
11020 btrfs_warn(fs_info,
11021 "cannot activate swapfile while exclusive operation is running");
11026 * Prevent snapshot creation while we are activating the swap file.
11027 * We do not want to race with snapshot creation. If snapshot creation
11028 * already started before we bumped nr_swapfiles from 0 to 1 and
11029 * completes before the first write into the swap file after it is
11030 * activated, than that write would fallback to COW.
11032 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
11033 btrfs_exclop_finish(fs_info);
11034 btrfs_warn(fs_info,
11035 "cannot activate swapfile because snapshot creation is in progress");
11039 * Snapshots can create extents which require COW even if NODATACOW is
11040 * set. We use this counter to prevent snapshots. We must increment it
11041 * before walking the extents because we don't want a concurrent
11042 * snapshot to run after we've already checked the extents.
11044 * It is possible that subvolume is marked for deletion but still not
11045 * removed yet. To prevent this race, we check the root status before
11046 * activating the swapfile.
11048 spin_lock(&root->root_item_lock);
11049 if (btrfs_root_dead(root)) {
11050 spin_unlock(&root->root_item_lock);
11052 btrfs_exclop_finish(fs_info);
11053 btrfs_warn(fs_info,
11054 "cannot activate swapfile because subvolume %llu is being deleted",
11055 root->root_key.objectid);
11058 atomic_inc(&root->nr_swapfiles);
11059 spin_unlock(&root->root_item_lock);
11061 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
11063 lock_extent(io_tree, 0, isize - 1, &cached_state);
11065 while (start < isize) {
11066 u64 logical_block_start, physical_block_start;
11067 struct btrfs_block_group *bg;
11068 u64 len = isize - start;
11070 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
11076 if (em->block_start == EXTENT_MAP_HOLE) {
11077 btrfs_warn(fs_info, "swapfile must not have holes");
11081 if (em->block_start == EXTENT_MAP_INLINE) {
11083 * It's unlikely we'll ever actually find ourselves
11084 * here, as a file small enough to fit inline won't be
11085 * big enough to store more than the swap header, but in
11086 * case something changes in the future, let's catch it
11087 * here rather than later.
11089 btrfs_warn(fs_info, "swapfile must not be inline");
11093 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
11094 btrfs_warn(fs_info, "swapfile must not be compressed");
11099 logical_block_start = em->block_start + (start - em->start);
11100 len = min(len, em->len - (start - em->start));
11101 free_extent_map(em);
11104 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, false, true);
11110 btrfs_warn(fs_info,
11111 "swapfile must not be copy-on-write");
11116 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
11122 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
11123 btrfs_warn(fs_info,
11124 "swapfile must have single data profile");
11129 if (device == NULL) {
11130 device = em->map_lookup->stripes[0].dev;
11131 ret = btrfs_add_swapfile_pin(inode, device, false);
11136 } else if (device != em->map_lookup->stripes[0].dev) {
11137 btrfs_warn(fs_info, "swapfile must be on one device");
11142 physical_block_start = (em->map_lookup->stripes[0].physical +
11143 (logical_block_start - em->start));
11144 len = min(len, em->len - (logical_block_start - em->start));
11145 free_extent_map(em);
11148 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
11150 btrfs_warn(fs_info,
11151 "could not find block group containing swapfile");
11156 if (!btrfs_inc_block_group_swap_extents(bg)) {
11157 btrfs_warn(fs_info,
11158 "block group for swapfile at %llu is read-only%s",
11160 atomic_read(&fs_info->scrubs_running) ?
11161 " (scrub running)" : "");
11162 btrfs_put_block_group(bg);
11167 ret = btrfs_add_swapfile_pin(inode, bg, true);
11169 btrfs_put_block_group(bg);
11176 if (bsi.block_len &&
11177 bsi.block_start + bsi.block_len == physical_block_start) {
11178 bsi.block_len += len;
11180 if (bsi.block_len) {
11181 ret = btrfs_add_swap_extent(sis, &bsi);
11186 bsi.block_start = physical_block_start;
11187 bsi.block_len = len;
11194 ret = btrfs_add_swap_extent(sis, &bsi);
11197 if (!IS_ERR_OR_NULL(em))
11198 free_extent_map(em);
11200 unlock_extent(io_tree, 0, isize - 1, &cached_state);
11203 btrfs_swap_deactivate(file);
11205 btrfs_drew_write_unlock(&root->snapshot_lock);
11207 btrfs_exclop_finish(fs_info);
11213 sis->bdev = device->bdev;
11214 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
11215 sis->max = bsi.nr_pages;
11216 sis->pages = bsi.nr_pages - 1;
11217 sis->highest_bit = bsi.nr_pages - 1;
11218 return bsi.nr_extents;
11221 static void btrfs_swap_deactivate(struct file *file)
11225 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
11228 return -EOPNOTSUPP;
11233 * Update the number of bytes used in the VFS' inode. When we replace extents in
11234 * a range (clone, dedupe, fallocate's zero range), we must update the number of
11235 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
11236 * always get a correct value.
11238 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
11239 const u64 add_bytes,
11240 const u64 del_bytes)
11242 if (add_bytes == del_bytes)
11245 spin_lock(&inode->lock);
11247 inode_sub_bytes(&inode->vfs_inode, del_bytes);
11249 inode_add_bytes(&inode->vfs_inode, add_bytes);
11250 spin_unlock(&inode->lock);
11254 * Verify that there are no ordered extents for a given file range.
11256 * @inode: The target inode.
11257 * @start: Start offset of the file range, should be sector size aligned.
11258 * @end: End offset (inclusive) of the file range, its value +1 should be
11259 * sector size aligned.
11261 * This should typically be used for cases where we locked an inode's VFS lock in
11262 * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
11263 * we have flushed all delalloc in the range, we have waited for all ordered
11264 * extents in the range to complete and finally we have locked the file range in
11265 * the inode's io_tree.
11267 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
11269 struct btrfs_root *root = inode->root;
11270 struct btrfs_ordered_extent *ordered;
11272 if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
11275 ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
11277 btrfs_err(root->fs_info,
11278 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
11279 start, end, btrfs_ino(inode), root->root_key.objectid,
11280 ordered->file_offset,
11281 ordered->file_offset + ordered->num_bytes - 1);
11282 btrfs_put_ordered_extent(ordered);
11285 ASSERT(ordered == NULL);
11288 static const struct inode_operations btrfs_dir_inode_operations = {
11289 .getattr = btrfs_getattr,
11290 .lookup = btrfs_lookup,
11291 .create = btrfs_create,
11292 .unlink = btrfs_unlink,
11293 .link = btrfs_link,
11294 .mkdir = btrfs_mkdir,
11295 .rmdir = btrfs_rmdir,
11296 .rename = btrfs_rename2,
11297 .symlink = btrfs_symlink,
11298 .setattr = btrfs_setattr,
11299 .mknod = btrfs_mknod,
11300 .listxattr = btrfs_listxattr,
11301 .permission = btrfs_permission,
11302 .get_acl = btrfs_get_acl,
11303 .set_acl = btrfs_set_acl,
11304 .update_time = btrfs_update_time,
11305 .tmpfile = btrfs_tmpfile,
11306 .fileattr_get = btrfs_fileattr_get,
11307 .fileattr_set = btrfs_fileattr_set,
11310 static const struct file_operations btrfs_dir_file_operations = {
11311 .llseek = generic_file_llseek,
11312 .read = generic_read_dir,
11313 .iterate_shared = btrfs_real_readdir,
11314 .open = btrfs_opendir,
11315 .unlocked_ioctl = btrfs_ioctl,
11316 #ifdef CONFIG_COMPAT
11317 .compat_ioctl = btrfs_compat_ioctl,
11319 .release = btrfs_release_file,
11320 .fsync = btrfs_sync_file,
11324 * btrfs doesn't support the bmap operation because swapfiles
11325 * use bmap to make a mapping of extents in the file. They assume
11326 * these extents won't change over the life of the file and they
11327 * use the bmap result to do IO directly to the drive.
11329 * the btrfs bmap call would return logical addresses that aren't
11330 * suitable for IO and they also will change frequently as COW
11331 * operations happen. So, swapfile + btrfs == corruption.
11333 * For now we're avoiding this by dropping bmap.
11335 static const struct address_space_operations btrfs_aops = {
11336 .read_folio = btrfs_read_folio,
11337 .writepages = btrfs_writepages,
11338 .readahead = btrfs_readahead,
11339 .direct_IO = noop_direct_IO,
11340 .invalidate_folio = btrfs_invalidate_folio,
11341 .release_folio = btrfs_release_folio,
11342 .migrate_folio = btrfs_migrate_folio,
11343 .dirty_folio = filemap_dirty_folio,
11344 .error_remove_page = generic_error_remove_page,
11345 .swap_activate = btrfs_swap_activate,
11346 .swap_deactivate = btrfs_swap_deactivate,
11349 static const struct inode_operations btrfs_file_inode_operations = {
11350 .getattr = btrfs_getattr,
11351 .setattr = btrfs_setattr,
11352 .listxattr = btrfs_listxattr,
11353 .permission = btrfs_permission,
11354 .fiemap = btrfs_fiemap,
11355 .get_acl = btrfs_get_acl,
11356 .set_acl = btrfs_set_acl,
11357 .update_time = btrfs_update_time,
11358 .fileattr_get = btrfs_fileattr_get,
11359 .fileattr_set = btrfs_fileattr_set,
11361 static const struct inode_operations btrfs_special_inode_operations = {
11362 .getattr = btrfs_getattr,
11363 .setattr = btrfs_setattr,
11364 .permission = btrfs_permission,
11365 .listxattr = btrfs_listxattr,
11366 .get_acl = btrfs_get_acl,
11367 .set_acl = btrfs_set_acl,
11368 .update_time = btrfs_update_time,
11370 static const struct inode_operations btrfs_symlink_inode_operations = {
11371 .get_link = page_get_link,
11372 .getattr = btrfs_getattr,
11373 .setattr = btrfs_setattr,
11374 .permission = btrfs_permission,
11375 .listxattr = btrfs_listxattr,
11376 .update_time = btrfs_update_time,
11379 const struct dentry_operations btrfs_dentry_operations = {
11380 .d_delete = btrfs_dentry_delete,