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;
69 struct btrfs_rename_ctx {
70 /* Output field. Stores the index number of the old directory entry. */
74 static const struct inode_operations btrfs_dir_inode_operations;
75 static const struct inode_operations btrfs_symlink_inode_operations;
76 static const struct inode_operations btrfs_special_inode_operations;
77 static const struct inode_operations btrfs_file_inode_operations;
78 static const struct address_space_operations btrfs_aops;
79 static const struct file_operations btrfs_dir_file_operations;
81 static struct kmem_cache *btrfs_inode_cachep;
82 struct kmem_cache *btrfs_trans_handle_cachep;
83 struct kmem_cache *btrfs_path_cachep;
84 struct kmem_cache *btrfs_free_space_cachep;
85 struct kmem_cache *btrfs_free_space_bitmap_cachep;
87 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
88 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
89 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
90 static noinline int cow_file_range(struct btrfs_inode *inode,
91 struct page *locked_page,
92 u64 start, u64 end, int *page_started,
93 unsigned long *nr_written, int unlock);
94 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
95 u64 len, u64 orig_start, u64 block_start,
96 u64 block_len, u64 orig_block_len,
97 u64 ram_bytes, int compress_type,
100 static void __endio_write_update_ordered(struct btrfs_inode *inode,
101 const u64 offset, const u64 bytes,
102 const bool uptodate);
105 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
107 * ilock_flags can have the following bit set:
109 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
110 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
112 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
114 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
116 if (ilock_flags & BTRFS_ILOCK_SHARED) {
117 if (ilock_flags & BTRFS_ILOCK_TRY) {
118 if (!inode_trylock_shared(inode))
123 inode_lock_shared(inode);
125 if (ilock_flags & BTRFS_ILOCK_TRY) {
126 if (!inode_trylock(inode))
133 if (ilock_flags & BTRFS_ILOCK_MMAP)
134 down_write(&BTRFS_I(inode)->i_mmap_lock);
139 * btrfs_inode_unlock - unock inode i_rwsem
141 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
142 * to decide whether the lock acquired is shared or exclusive.
144 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
146 if (ilock_flags & BTRFS_ILOCK_MMAP)
147 up_write(&BTRFS_I(inode)->i_mmap_lock);
148 if (ilock_flags & BTRFS_ILOCK_SHARED)
149 inode_unlock_shared(inode);
155 * Cleanup all submitted ordered extents in specified range to handle errors
156 * from the btrfs_run_delalloc_range() callback.
158 * NOTE: caller must ensure that when an error happens, it can not call
159 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
160 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
161 * to be released, which we want to happen only when finishing the ordered
162 * extent (btrfs_finish_ordered_io()).
164 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
165 struct page *locked_page,
166 u64 offset, u64 bytes)
168 unsigned long index = offset >> PAGE_SHIFT;
169 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
170 u64 page_start = page_offset(locked_page);
171 u64 page_end = page_start + PAGE_SIZE - 1;
175 while (index <= end_index) {
177 * For locked page, we will call end_extent_writepage() on it
178 * in run_delalloc_range() for the error handling. That
179 * end_extent_writepage() function will call
180 * btrfs_mark_ordered_io_finished() to clear page Ordered and
181 * run the ordered extent accounting.
183 * Here we can't just clear the Ordered bit, or
184 * btrfs_mark_ordered_io_finished() would skip the accounting
185 * for the page range, and the ordered extent will never finish.
187 if (index == (page_offset(locked_page) >> PAGE_SHIFT)) {
191 page = find_get_page(inode->vfs_inode.i_mapping, index);
197 * Here we just clear all Ordered bits for every page in the
198 * range, then __endio_write_update_ordered() will handle
199 * the ordered extent accounting for the range.
201 btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
206 /* The locked page covers the full range, nothing needs to be done */
207 if (bytes + offset <= page_offset(locked_page) + PAGE_SIZE)
210 * In case this page belongs to the delalloc range being instantiated
211 * then skip it, since the first page of a range is going to be
212 * properly cleaned up by the caller of run_delalloc_range
214 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
215 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
216 offset = page_offset(locked_page) + PAGE_SIZE;
219 return __endio_write_update_ordered(inode, offset, bytes, false);
222 static int btrfs_dirty_inode(struct inode *inode);
224 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
225 struct inode *inode, struct inode *dir,
226 const struct qstr *qstr)
230 err = btrfs_init_acl(trans, inode, dir);
232 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
237 * this does all the hard work for inserting an inline extent into
238 * the btree. The caller should have done a btrfs_drop_extents so that
239 * no overlapping inline items exist in the btree
241 static int insert_inline_extent(struct btrfs_trans_handle *trans,
242 struct btrfs_path *path,
243 struct btrfs_inode *inode, bool extent_inserted,
244 size_t size, size_t compressed_size,
246 struct page **compressed_pages,
249 struct btrfs_root *root = inode->root;
250 struct extent_buffer *leaf;
251 struct page *page = NULL;
254 struct btrfs_file_extent_item *ei;
256 size_t cur_size = size;
259 ASSERT((compressed_size > 0 && compressed_pages) ||
260 (compressed_size == 0 && !compressed_pages));
262 if (compressed_size && compressed_pages)
263 cur_size = compressed_size;
265 if (!extent_inserted) {
266 struct btrfs_key key;
269 key.objectid = btrfs_ino(inode);
271 key.type = BTRFS_EXTENT_DATA_KEY;
273 datasize = btrfs_file_extent_calc_inline_size(cur_size);
274 ret = btrfs_insert_empty_item(trans, root, path, &key,
279 leaf = path->nodes[0];
280 ei = btrfs_item_ptr(leaf, path->slots[0],
281 struct btrfs_file_extent_item);
282 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
283 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
284 btrfs_set_file_extent_encryption(leaf, ei, 0);
285 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
286 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
287 ptr = btrfs_file_extent_inline_start(ei);
289 if (compress_type != BTRFS_COMPRESS_NONE) {
292 while (compressed_size > 0) {
293 cpage = compressed_pages[i];
294 cur_size = min_t(unsigned long, compressed_size,
297 kaddr = kmap_atomic(cpage);
298 write_extent_buffer(leaf, kaddr, ptr, cur_size);
299 kunmap_atomic(kaddr);
303 compressed_size -= cur_size;
305 btrfs_set_file_extent_compression(leaf, ei,
308 page = find_get_page(inode->vfs_inode.i_mapping, 0);
309 btrfs_set_file_extent_compression(leaf, ei, 0);
310 kaddr = kmap_atomic(page);
311 write_extent_buffer(leaf, kaddr, ptr, size);
312 kunmap_atomic(kaddr);
315 btrfs_mark_buffer_dirty(leaf);
316 btrfs_release_path(path);
319 * We align size to sectorsize for inline extents just for simplicity
322 ret = btrfs_inode_set_file_extent_range(inode, 0,
323 ALIGN(size, root->fs_info->sectorsize));
328 * We're an inline extent, so nobody can extend the file past i_size
329 * without locking a page we already have locked.
331 * We must do any i_size and inode updates before we unlock the pages.
332 * Otherwise we could end up racing with unlink.
334 i_size = i_size_read(&inode->vfs_inode);
335 if (update_i_size && size > i_size) {
336 i_size_write(&inode->vfs_inode, size);
339 inode->disk_i_size = i_size;
347 * conditionally insert an inline extent into the file. This
348 * does the checks required to make sure the data is small enough
349 * to fit as an inline extent.
351 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 size,
352 size_t compressed_size,
354 struct page **compressed_pages,
357 struct btrfs_drop_extents_args drop_args = { 0 };
358 struct btrfs_root *root = inode->root;
359 struct btrfs_fs_info *fs_info = root->fs_info;
360 struct btrfs_trans_handle *trans;
361 u64 data_len = (compressed_size ?: size);
363 struct btrfs_path *path;
366 * We can create an inline extent if it ends at or beyond the current
367 * i_size, is no larger than a sector (decompressed), and the (possibly
368 * compressed) data fits in a leaf and the configured maximum inline
371 if (size < i_size_read(&inode->vfs_inode) ||
372 size > fs_info->sectorsize ||
373 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
374 data_len > fs_info->max_inline)
377 path = btrfs_alloc_path();
381 trans = btrfs_join_transaction(root);
383 btrfs_free_path(path);
384 return PTR_ERR(trans);
386 trans->block_rsv = &inode->block_rsv;
388 drop_args.path = path;
390 drop_args.end = fs_info->sectorsize;
391 drop_args.drop_cache = true;
392 drop_args.replace_extent = true;
393 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
394 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
396 btrfs_abort_transaction(trans, ret);
400 ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
401 size, compressed_size, compress_type,
402 compressed_pages, update_i_size);
403 if (ret && ret != -ENOSPC) {
404 btrfs_abort_transaction(trans, ret);
406 } else if (ret == -ENOSPC) {
411 btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
412 ret = btrfs_update_inode(trans, root, inode);
413 if (ret && ret != -ENOSPC) {
414 btrfs_abort_transaction(trans, ret);
416 } else if (ret == -ENOSPC) {
421 btrfs_set_inode_full_sync(inode);
424 * Don't forget to free the reserved space, as for inlined extent
425 * it won't count as data extent, free them directly here.
426 * And at reserve time, it's always aligned to page size, so
427 * just free one page here.
429 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
430 btrfs_free_path(path);
431 btrfs_end_transaction(trans);
435 struct async_extent {
440 unsigned long nr_pages;
442 struct list_head list;
447 struct page *locked_page;
450 unsigned int write_flags;
451 struct list_head extents;
452 struct cgroup_subsys_state *blkcg_css;
453 struct btrfs_work work;
454 struct async_cow *async_cow;
459 struct async_chunk chunks[];
462 static noinline int add_async_extent(struct async_chunk *cow,
463 u64 start, u64 ram_size,
466 unsigned long nr_pages,
469 struct async_extent *async_extent;
471 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
472 BUG_ON(!async_extent); /* -ENOMEM */
473 async_extent->start = start;
474 async_extent->ram_size = ram_size;
475 async_extent->compressed_size = compressed_size;
476 async_extent->pages = pages;
477 async_extent->nr_pages = nr_pages;
478 async_extent->compress_type = compress_type;
479 list_add_tail(&async_extent->list, &cow->extents);
484 * Check if the inode has flags compatible with compression
486 static inline bool inode_can_compress(struct btrfs_inode *inode)
488 if (inode->flags & BTRFS_INODE_NODATACOW ||
489 inode->flags & BTRFS_INODE_NODATASUM)
495 * Check if the inode needs to be submitted to compression, based on mount
496 * options, defragmentation, properties or heuristics.
498 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
501 struct btrfs_fs_info *fs_info = inode->root->fs_info;
503 if (!inode_can_compress(inode)) {
504 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
505 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
510 * Special check for subpage.
512 * We lock the full page then run each delalloc range in the page, thus
513 * for the following case, we will hit some subpage specific corner case:
516 * | |///////| |///////|
519 * In above case, both range A and range B will try to unlock the full
520 * page [0, 64K), causing the one finished later will have page
521 * unlocked already, triggering various page lock requirement BUG_ON()s.
523 * So here we add an artificial limit that subpage compression can only
524 * if the range is fully page aligned.
526 * In theory we only need to ensure the first page is fully covered, but
527 * the tailing partial page will be locked until the full compression
528 * finishes, delaying the write of other range.
530 * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
531 * first to prevent any submitted async extent to unlock the full page.
532 * By this, we can ensure for subpage case that only the last async_cow
533 * will unlock the full page.
535 if (fs_info->sectorsize < PAGE_SIZE) {
536 if (!IS_ALIGNED(start, PAGE_SIZE) ||
537 !IS_ALIGNED(end + 1, PAGE_SIZE))
542 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
545 if (inode->defrag_compress)
547 /* bad compression ratios */
548 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
550 if (btrfs_test_opt(fs_info, COMPRESS) ||
551 inode->flags & BTRFS_INODE_COMPRESS ||
552 inode->prop_compress)
553 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
557 static inline void inode_should_defrag(struct btrfs_inode *inode,
558 u64 start, u64 end, u64 num_bytes, u32 small_write)
560 /* If this is a small write inside eof, kick off a defrag */
561 if (num_bytes < small_write &&
562 (start > 0 || end + 1 < inode->disk_i_size))
563 btrfs_add_inode_defrag(NULL, inode, small_write);
567 * we create compressed extents in two phases. The first
568 * phase compresses a range of pages that have already been
569 * locked (both pages and state bits are locked).
571 * This is done inside an ordered work queue, and the compression
572 * is spread across many cpus. The actual IO submission is step
573 * two, and the ordered work queue takes care of making sure that
574 * happens in the same order things were put onto the queue by
575 * writepages and friends.
577 * If this code finds it can't get good compression, it puts an
578 * entry onto the work queue to write the uncompressed bytes. This
579 * makes sure that both compressed inodes and uncompressed inodes
580 * are written in the same order that the flusher thread sent them
583 static noinline int compress_file_range(struct async_chunk *async_chunk)
585 struct inode *inode = async_chunk->inode;
586 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
587 u64 blocksize = fs_info->sectorsize;
588 u64 start = async_chunk->start;
589 u64 end = async_chunk->end;
593 struct page **pages = NULL;
594 unsigned long nr_pages;
595 unsigned long total_compressed = 0;
596 unsigned long total_in = 0;
599 int compress_type = fs_info->compress_type;
600 int compressed_extents = 0;
603 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
607 * We need to save i_size before now because it could change in between
608 * us evaluating the size and assigning it. This is because we lock and
609 * unlock the page in truncate and fallocate, and then modify the i_size
612 * The barriers are to emulate READ_ONCE, remove that once i_size_read
616 i_size = i_size_read(inode);
618 actual_end = min_t(u64, i_size, end + 1);
621 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
622 nr_pages = min_t(unsigned long, nr_pages,
623 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
626 * we don't want to send crud past the end of i_size through
627 * compression, that's just a waste of CPU time. So, if the
628 * end of the file is before the start of our current
629 * requested range of bytes, we bail out to the uncompressed
630 * cleanup code that can deal with all of this.
632 * It isn't really the fastest way to fix things, but this is a
633 * very uncommon corner.
635 if (actual_end <= start)
636 goto cleanup_and_bail_uncompressed;
638 total_compressed = actual_end - start;
641 * Skip compression for a small file range(<=blocksize) that
642 * isn't an inline extent, since it doesn't save disk space at all.
644 if (total_compressed <= blocksize &&
645 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
646 goto cleanup_and_bail_uncompressed;
649 * For subpage case, we require full page alignment for the sector
651 * Thus we must also check against @actual_end, not just @end.
653 if (blocksize < PAGE_SIZE) {
654 if (!IS_ALIGNED(start, PAGE_SIZE) ||
655 !IS_ALIGNED(round_up(actual_end, blocksize), PAGE_SIZE))
656 goto cleanup_and_bail_uncompressed;
659 total_compressed = min_t(unsigned long, total_compressed,
660 BTRFS_MAX_UNCOMPRESSED);
665 * we do compression for mount -o compress and when the
666 * inode has not been flagged as nocompress. This flag can
667 * change at any time if we discover bad compression ratios.
669 if (inode_need_compress(BTRFS_I(inode), start, end)) {
671 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
673 /* just bail out to the uncompressed code */
678 if (BTRFS_I(inode)->defrag_compress)
679 compress_type = BTRFS_I(inode)->defrag_compress;
680 else if (BTRFS_I(inode)->prop_compress)
681 compress_type = BTRFS_I(inode)->prop_compress;
684 * we need to call clear_page_dirty_for_io on each
685 * page in the range. Otherwise applications with the file
686 * mmap'd can wander in and change the page contents while
687 * we are compressing them.
689 * If the compression fails for any reason, we set the pages
690 * dirty again later on.
692 * Note that the remaining part is redirtied, the start pointer
693 * has moved, the end is the original one.
696 extent_range_clear_dirty_for_io(inode, start, end);
700 /* Compression level is applied here and only here */
701 ret = btrfs_compress_pages(
702 compress_type | (fs_info->compress_level << 4),
703 inode->i_mapping, start,
710 unsigned long offset = offset_in_page(total_compressed);
711 struct page *page = pages[nr_pages - 1];
713 /* zero the tail end of the last page, we might be
714 * sending it down to disk
717 memzero_page(page, offset, PAGE_SIZE - offset);
723 * Check cow_file_range() for why we don't even try to create inline
724 * extent for subpage case.
726 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
727 /* lets try to make an inline extent */
728 if (ret || total_in < actual_end) {
729 /* we didn't compress the entire range, try
730 * to make an uncompressed inline extent.
732 ret = cow_file_range_inline(BTRFS_I(inode), actual_end,
733 0, BTRFS_COMPRESS_NONE,
736 /* try making a compressed inline extent */
737 ret = cow_file_range_inline(BTRFS_I(inode), actual_end,
739 compress_type, pages,
743 unsigned long clear_flags = EXTENT_DELALLOC |
744 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
745 EXTENT_DO_ACCOUNTING;
746 unsigned long page_error_op;
748 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
751 * inline extent creation worked or returned error,
752 * we don't need to create any more async work items.
753 * Unlock and free up our temp pages.
755 * We use DO_ACCOUNTING here because we need the
756 * delalloc_release_metadata to be done _after_ we drop
757 * our outstanding extent for clearing delalloc for this
760 extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
764 PAGE_START_WRITEBACK |
769 * Ensure we only free the compressed pages if we have
770 * them allocated, as we can still reach here with
771 * inode_need_compress() == false.
774 for (i = 0; i < nr_pages; i++) {
775 WARN_ON(pages[i]->mapping);
786 * we aren't doing an inline extent round the compressed size
787 * up to a block size boundary so the allocator does sane
790 total_compressed = ALIGN(total_compressed, blocksize);
793 * one last check to make sure the compression is really a
794 * win, compare the page count read with the blocks on disk,
795 * compression must free at least one sector size
797 total_in = round_up(total_in, fs_info->sectorsize);
798 if (total_compressed + blocksize <= total_in) {
799 compressed_extents++;
802 * The async work queues will take care of doing actual
803 * allocation on disk for these compressed pages, and
804 * will submit them to the elevator.
806 add_async_extent(async_chunk, start, total_in,
807 total_compressed, pages, nr_pages,
810 if (start + total_in < end) {
816 return compressed_extents;
821 * the compression code ran but failed to make things smaller,
822 * free any pages it allocated and our page pointer array
824 for (i = 0; i < nr_pages; i++) {
825 WARN_ON(pages[i]->mapping);
830 total_compressed = 0;
833 /* flag the file so we don't compress in the future */
834 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
835 !(BTRFS_I(inode)->prop_compress)) {
836 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
839 cleanup_and_bail_uncompressed:
841 * No compression, but we still need to write the pages in the file
842 * we've been given so far. redirty the locked page if it corresponds
843 * to our extent and set things up for the async work queue to run
844 * cow_file_range to do the normal delalloc dance.
846 if (async_chunk->locked_page &&
847 (page_offset(async_chunk->locked_page) >= start &&
848 page_offset(async_chunk->locked_page)) <= end) {
849 __set_page_dirty_nobuffers(async_chunk->locked_page);
850 /* unlocked later on in the async handlers */
854 extent_range_redirty_for_io(inode, start, end);
855 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
856 BTRFS_COMPRESS_NONE);
857 compressed_extents++;
859 return compressed_extents;
862 static void free_async_extent_pages(struct async_extent *async_extent)
866 if (!async_extent->pages)
869 for (i = 0; i < async_extent->nr_pages; i++) {
870 WARN_ON(async_extent->pages[i]->mapping);
871 put_page(async_extent->pages[i]);
873 kfree(async_extent->pages);
874 async_extent->nr_pages = 0;
875 async_extent->pages = NULL;
878 static int submit_uncompressed_range(struct btrfs_inode *inode,
879 struct async_extent *async_extent,
880 struct page *locked_page)
882 u64 start = async_extent->start;
883 u64 end = async_extent->start + async_extent->ram_size - 1;
884 unsigned long nr_written = 0;
885 int page_started = 0;
889 * Call cow_file_range() to run the delalloc range directly, since we
890 * won't go to NOCOW or async path again.
892 * Also we call cow_file_range() with @unlock_page == 0, so that we
893 * can directly submit them without interruption.
895 ret = cow_file_range(inode, locked_page, start, end, &page_started,
897 /* Inline extent inserted, page gets unlocked and everything is done */
904 unlock_page(locked_page);
908 ret = extent_write_locked_range(&inode->vfs_inode, start, end);
909 /* All pages will be unlocked, including @locked_page */
915 static int submit_one_async_extent(struct btrfs_inode *inode,
916 struct async_chunk *async_chunk,
917 struct async_extent *async_extent,
920 struct extent_io_tree *io_tree = &inode->io_tree;
921 struct btrfs_root *root = inode->root;
922 struct btrfs_fs_info *fs_info = root->fs_info;
923 struct btrfs_key ins;
924 struct page *locked_page = NULL;
925 struct extent_map *em;
927 u64 start = async_extent->start;
928 u64 end = async_extent->start + async_extent->ram_size - 1;
931 * If async_chunk->locked_page is in the async_extent range, we need to
934 if (async_chunk->locked_page) {
935 u64 locked_page_start = page_offset(async_chunk->locked_page);
936 u64 locked_page_end = locked_page_start + PAGE_SIZE - 1;
938 if (!(start >= locked_page_end || end <= locked_page_start))
939 locked_page = async_chunk->locked_page;
941 lock_extent(io_tree, start, end);
943 /* We have fall back to uncompressed write */
944 if (!async_extent->pages)
945 return submit_uncompressed_range(inode, async_extent, locked_page);
947 ret = btrfs_reserve_extent(root, async_extent->ram_size,
948 async_extent->compressed_size,
949 async_extent->compressed_size,
950 0, *alloc_hint, &ins, 1, 1);
952 free_async_extent_pages(async_extent);
954 * Here we used to try again by going back to non-compressed
955 * path for ENOSPC. But we can't reserve space even for
956 * compressed size, how could it work for uncompressed size
957 * which requires larger size? So here we directly go error
963 /* Here we're doing allocation and writeback of the compressed pages */
964 em = create_io_em(inode, start,
965 async_extent->ram_size, /* len */
966 start, /* orig_start */
967 ins.objectid, /* block_start */
968 ins.offset, /* block_len */
969 ins.offset, /* orig_block_len */
970 async_extent->ram_size, /* ram_bytes */
971 async_extent->compress_type,
972 BTRFS_ORDERED_COMPRESSED);
975 goto out_free_reserve;
979 ret = btrfs_add_ordered_extent(inode, start, /* file_offset */
980 async_extent->ram_size, /* num_bytes */
981 async_extent->ram_size, /* ram_bytes */
982 ins.objectid, /* disk_bytenr */
983 ins.offset, /* disk_num_bytes */
985 1 << BTRFS_ORDERED_COMPRESSED,
986 async_extent->compress_type);
988 btrfs_drop_extent_cache(inode, start, end, 0);
989 goto out_free_reserve;
991 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
993 /* Clear dirty, set writeback and unlock the pages. */
994 extent_clear_unlock_delalloc(inode, start, end,
995 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
996 PAGE_UNLOCK | PAGE_START_WRITEBACK);
997 if (btrfs_submit_compressed_write(inode, start, /* file_offset */
998 async_extent->ram_size, /* num_bytes */
999 ins.objectid, /* disk_bytenr */
1000 ins.offset, /* compressed_len */
1001 async_extent->pages, /* compressed_pages */
1002 async_extent->nr_pages,
1003 async_chunk->write_flags,
1004 async_chunk->blkcg_css, true)) {
1005 const u64 start = async_extent->start;
1006 const u64 end = start + async_extent->ram_size - 1;
1008 btrfs_writepage_endio_finish_ordered(inode, NULL, start, end, 0);
1010 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
1011 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1012 free_async_extent_pages(async_extent);
1014 *alloc_hint = ins.objectid + ins.offset;
1015 kfree(async_extent);
1019 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1020 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1022 extent_clear_unlock_delalloc(inode, start, end,
1023 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
1024 EXTENT_DELALLOC_NEW |
1025 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
1026 PAGE_UNLOCK | PAGE_START_WRITEBACK |
1027 PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1028 free_async_extent_pages(async_extent);
1029 kfree(async_extent);
1034 * Phase two of compressed writeback. This is the ordered portion of the code,
1035 * which only gets called in the order the work was queued. We walk all the
1036 * async extents created by compress_file_range and send them down to the disk.
1038 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
1040 struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
1041 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1042 struct async_extent *async_extent;
1046 while (!list_empty(&async_chunk->extents)) {
1050 async_extent = list_entry(async_chunk->extents.next,
1051 struct async_extent, list);
1052 list_del(&async_extent->list);
1053 extent_start = async_extent->start;
1054 ram_size = async_extent->ram_size;
1056 ret = submit_one_async_extent(inode, async_chunk, async_extent,
1058 btrfs_debug(fs_info,
1059 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1060 inode->root->root_key.objectid,
1061 btrfs_ino(inode), extent_start, ram_size, ret);
1065 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1068 struct extent_map_tree *em_tree = &inode->extent_tree;
1069 struct extent_map *em;
1072 read_lock(&em_tree->lock);
1073 em = search_extent_mapping(em_tree, start, num_bytes);
1076 * if block start isn't an actual block number then find the
1077 * first block in this inode and use that as a hint. If that
1078 * block is also bogus then just don't worry about it.
1080 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1081 free_extent_map(em);
1082 em = search_extent_mapping(em_tree, 0, 0);
1083 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1084 alloc_hint = em->block_start;
1086 free_extent_map(em);
1088 alloc_hint = em->block_start;
1089 free_extent_map(em);
1092 read_unlock(&em_tree->lock);
1098 * when extent_io.c finds a delayed allocation range in the file,
1099 * the call backs end up in this code. The basic idea is to
1100 * allocate extents on disk for the range, and create ordered data structs
1101 * in ram to track those extents.
1103 * locked_page is the page that writepage had locked already. We use
1104 * it to make sure we don't do extra locks or unlocks.
1106 * *page_started is set to one if we unlock locked_page and do everything
1107 * required to start IO on it. It may be clean and already done with
1108 * IO when we return.
1110 static noinline int cow_file_range(struct btrfs_inode *inode,
1111 struct page *locked_page,
1112 u64 start, u64 end, int *page_started,
1113 unsigned long *nr_written, int unlock)
1115 struct btrfs_root *root = inode->root;
1116 struct btrfs_fs_info *fs_info = root->fs_info;
1119 unsigned long ram_size;
1120 u64 cur_alloc_size = 0;
1122 u64 blocksize = fs_info->sectorsize;
1123 struct btrfs_key ins;
1124 struct extent_map *em;
1125 unsigned clear_bits;
1126 unsigned long page_ops;
1127 bool extent_reserved = false;
1130 if (btrfs_is_free_space_inode(inode)) {
1136 num_bytes = ALIGN(end - start + 1, blocksize);
1137 num_bytes = max(blocksize, num_bytes);
1138 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1140 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1143 * Due to the page size limit, for subpage we can only trigger the
1144 * writeback for the dirty sectors of page, that means data writeback
1145 * is doing more writeback than what we want.
1147 * This is especially unexpected for some call sites like fallocate,
1148 * where we only increase i_size after everything is done.
1149 * This means we can trigger inline extent even if we didn't want to.
1150 * So here we skip inline extent creation completely.
1152 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
1153 u64 actual_end = min_t(u64, i_size_read(&inode->vfs_inode),
1156 /* lets try to make an inline extent */
1157 ret = cow_file_range_inline(inode, actual_end, 0,
1158 BTRFS_COMPRESS_NONE, NULL, false);
1161 * We use DO_ACCOUNTING here because we need the
1162 * delalloc_release_metadata to be run _after_ we drop
1163 * our outstanding extent for clearing delalloc for this
1166 extent_clear_unlock_delalloc(inode, start, end,
1168 EXTENT_LOCKED | EXTENT_DELALLOC |
1169 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1170 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1171 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1172 *nr_written = *nr_written +
1173 (end - start + PAGE_SIZE) / PAGE_SIZE;
1176 * locked_page is locked by the caller of
1177 * writepage_delalloc(), not locked by
1178 * __process_pages_contig().
1180 * We can't let __process_pages_contig() to unlock it,
1181 * as it doesn't have any subpage::writers recorded.
1183 * Here we manually unlock the page, since the caller
1184 * can't use page_started to determine if it's an
1185 * inline extent or a compressed extent.
1187 unlock_page(locked_page);
1189 } else if (ret < 0) {
1194 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1195 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1198 * Relocation relies on the relocated extents to have exactly the same
1199 * size as the original extents. Normally writeback for relocation data
1200 * extents follows a NOCOW path because relocation preallocates the
1201 * extents. However, due to an operation such as scrub turning a block
1202 * group to RO mode, it may fallback to COW mode, so we must make sure
1203 * an extent allocated during COW has exactly the requested size and can
1204 * not be split into smaller extents, otherwise relocation breaks and
1205 * fails during the stage where it updates the bytenr of file extent
1208 if (btrfs_is_data_reloc_root(root))
1209 min_alloc_size = num_bytes;
1211 min_alloc_size = fs_info->sectorsize;
1213 while (num_bytes > 0) {
1214 cur_alloc_size = num_bytes;
1215 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1216 min_alloc_size, 0, alloc_hint,
1220 cur_alloc_size = ins.offset;
1221 extent_reserved = true;
1223 ram_size = ins.offset;
1224 em = create_io_em(inode, start, ins.offset, /* len */
1225 start, /* orig_start */
1226 ins.objectid, /* block_start */
1227 ins.offset, /* block_len */
1228 ins.offset, /* orig_block_len */
1229 ram_size, /* ram_bytes */
1230 BTRFS_COMPRESS_NONE, /* compress_type */
1231 BTRFS_ORDERED_REGULAR /* type */);
1236 free_extent_map(em);
1238 ret = btrfs_add_ordered_extent(inode, start, ram_size, ram_size,
1239 ins.objectid, cur_alloc_size, 0,
1240 1 << BTRFS_ORDERED_REGULAR,
1241 BTRFS_COMPRESS_NONE);
1243 goto out_drop_extent_cache;
1245 if (btrfs_is_data_reloc_root(root)) {
1246 ret = btrfs_reloc_clone_csums(inode, start,
1249 * Only drop cache here, and process as normal.
1251 * We must not allow extent_clear_unlock_delalloc()
1252 * at out_unlock label to free meta of this ordered
1253 * extent, as its meta should be freed by
1254 * btrfs_finish_ordered_io().
1256 * So we must continue until @start is increased to
1257 * skip current ordered extent.
1260 btrfs_drop_extent_cache(inode, start,
1261 start + ram_size - 1, 0);
1264 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1267 * We're not doing compressed IO, don't unlock the first page
1268 * (which the caller expects to stay locked), don't clear any
1269 * dirty bits and don't set any writeback bits
1271 * Do set the Ordered (Private2) bit so we know this page was
1272 * properly setup for writepage.
1274 page_ops = unlock ? PAGE_UNLOCK : 0;
1275 page_ops |= PAGE_SET_ORDERED;
1277 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1279 EXTENT_LOCKED | EXTENT_DELALLOC,
1281 if (num_bytes < cur_alloc_size)
1284 num_bytes -= cur_alloc_size;
1285 alloc_hint = ins.objectid + ins.offset;
1286 start += cur_alloc_size;
1287 extent_reserved = false;
1290 * btrfs_reloc_clone_csums() error, since start is increased
1291 * extent_clear_unlock_delalloc() at out_unlock label won't
1292 * free metadata of current ordered extent, we're OK to exit.
1300 out_drop_extent_cache:
1301 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1303 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1304 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1306 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1307 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1308 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1310 * If we reserved an extent for our delalloc range (or a subrange) and
1311 * failed to create the respective ordered extent, then it means that
1312 * when we reserved the extent we decremented the extent's size from
1313 * the data space_info's bytes_may_use counter and incremented the
1314 * space_info's bytes_reserved counter by the same amount. We must make
1315 * sure extent_clear_unlock_delalloc() does not try to decrement again
1316 * the data space_info's bytes_may_use counter, therefore we do not pass
1317 * it the flag EXTENT_CLEAR_DATA_RESV.
1319 if (extent_reserved) {
1320 extent_clear_unlock_delalloc(inode, start,
1321 start + cur_alloc_size - 1,
1325 start += cur_alloc_size;
1329 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1330 clear_bits | EXTENT_CLEAR_DATA_RESV,
1336 * work queue call back to started compression on a file and pages
1338 static noinline void async_cow_start(struct btrfs_work *work)
1340 struct async_chunk *async_chunk;
1341 int compressed_extents;
1343 async_chunk = container_of(work, struct async_chunk, work);
1345 compressed_extents = compress_file_range(async_chunk);
1346 if (compressed_extents == 0) {
1347 btrfs_add_delayed_iput(async_chunk->inode);
1348 async_chunk->inode = NULL;
1353 * work queue call back to submit previously compressed pages
1355 static noinline void async_cow_submit(struct btrfs_work *work)
1357 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1359 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1360 unsigned long nr_pages;
1362 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1366 * ->inode could be NULL if async_chunk_start has failed to compress,
1367 * in which case we don't have anything to submit, yet we need to
1368 * always adjust ->async_delalloc_pages as its paired with the init
1369 * happening in cow_file_range_async
1371 if (async_chunk->inode)
1372 submit_compressed_extents(async_chunk);
1374 /* atomic_sub_return implies a barrier */
1375 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1377 cond_wake_up_nomb(&fs_info->async_submit_wait);
1380 static noinline void async_cow_free(struct btrfs_work *work)
1382 struct async_chunk *async_chunk;
1383 struct async_cow *async_cow;
1385 async_chunk = container_of(work, struct async_chunk, work);
1386 if (async_chunk->inode)
1387 btrfs_add_delayed_iput(async_chunk->inode);
1388 if (async_chunk->blkcg_css)
1389 css_put(async_chunk->blkcg_css);
1391 async_cow = async_chunk->async_cow;
1392 if (atomic_dec_and_test(&async_cow->num_chunks))
1396 static int cow_file_range_async(struct btrfs_inode *inode,
1397 struct writeback_control *wbc,
1398 struct page *locked_page,
1399 u64 start, u64 end, int *page_started,
1400 unsigned long *nr_written)
1402 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1403 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1404 struct async_cow *ctx;
1405 struct async_chunk *async_chunk;
1406 unsigned long nr_pages;
1408 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1410 bool should_compress;
1412 const unsigned int write_flags = wbc_to_write_flags(wbc);
1414 unlock_extent(&inode->io_tree, start, end);
1416 if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1417 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1419 should_compress = false;
1421 should_compress = true;
1424 nofs_flag = memalloc_nofs_save();
1425 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1426 memalloc_nofs_restore(nofs_flag);
1429 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1430 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1431 EXTENT_DO_ACCOUNTING;
1432 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1433 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1435 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1436 clear_bits, page_ops);
1440 async_chunk = ctx->chunks;
1441 atomic_set(&ctx->num_chunks, num_chunks);
1443 for (i = 0; i < num_chunks; i++) {
1444 if (should_compress)
1445 cur_end = min(end, start + SZ_512K - 1);
1450 * igrab is called higher up in the call chain, take only the
1451 * lightweight reference for the callback lifetime
1453 ihold(&inode->vfs_inode);
1454 async_chunk[i].async_cow = ctx;
1455 async_chunk[i].inode = &inode->vfs_inode;
1456 async_chunk[i].start = start;
1457 async_chunk[i].end = cur_end;
1458 async_chunk[i].write_flags = write_flags;
1459 INIT_LIST_HEAD(&async_chunk[i].extents);
1462 * The locked_page comes all the way from writepage and its
1463 * the original page we were actually given. As we spread
1464 * this large delalloc region across multiple async_chunk
1465 * structs, only the first struct needs a pointer to locked_page
1467 * This way we don't need racey decisions about who is supposed
1472 * Depending on the compressibility, the pages might or
1473 * might not go through async. We want all of them to
1474 * be accounted against wbc once. Let's do it here
1475 * before the paths diverge. wbc accounting is used
1476 * only for foreign writeback detection and doesn't
1477 * need full accuracy. Just account the whole thing
1478 * against the first page.
1480 wbc_account_cgroup_owner(wbc, locked_page,
1482 async_chunk[i].locked_page = locked_page;
1485 async_chunk[i].locked_page = NULL;
1488 if (blkcg_css != blkcg_root_css) {
1490 async_chunk[i].blkcg_css = blkcg_css;
1492 async_chunk[i].blkcg_css = NULL;
1495 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1496 async_cow_submit, async_cow_free);
1498 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1499 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1501 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1503 *nr_written += nr_pages;
1504 start = cur_end + 1;
1510 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1511 struct page *locked_page, u64 start,
1512 u64 end, int *page_started,
1513 unsigned long *nr_written)
1517 ret = cow_file_range(inode, locked_page, start, end, page_started,
1525 __set_page_dirty_nobuffers(locked_page);
1526 account_page_redirty(locked_page);
1527 extent_write_locked_range(&inode->vfs_inode, start, end);
1533 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1534 u64 bytenr, u64 num_bytes)
1536 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bytenr);
1537 struct btrfs_ordered_sum *sums;
1541 ret = btrfs_lookup_csums_range(csum_root, bytenr,
1542 bytenr + num_bytes - 1, &list, 0);
1543 if (ret == 0 && list_empty(&list))
1546 while (!list_empty(&list)) {
1547 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1548 list_del(&sums->list);
1556 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1557 const u64 start, const u64 end,
1558 int *page_started, unsigned long *nr_written)
1560 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1561 const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1562 const u64 range_bytes = end + 1 - start;
1563 struct extent_io_tree *io_tree = &inode->io_tree;
1564 u64 range_start = start;
1568 * If EXTENT_NORESERVE is set it means that when the buffered write was
1569 * made we had not enough available data space and therefore we did not
1570 * reserve data space for it, since we though we could do NOCOW for the
1571 * respective file range (either there is prealloc extent or the inode
1572 * has the NOCOW bit set).
1574 * However when we need to fallback to COW mode (because for example the
1575 * block group for the corresponding extent was turned to RO mode by a
1576 * scrub or relocation) we need to do the following:
1578 * 1) We increment the bytes_may_use counter of the data space info.
1579 * If COW succeeds, it allocates a new data extent and after doing
1580 * that it decrements the space info's bytes_may_use counter and
1581 * increments its bytes_reserved counter by the same amount (we do
1582 * this at btrfs_add_reserved_bytes()). So we need to increment the
1583 * bytes_may_use counter to compensate (when space is reserved at
1584 * buffered write time, the bytes_may_use counter is incremented);
1586 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1587 * that if the COW path fails for any reason, it decrements (through
1588 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1589 * data space info, which we incremented in the step above.
1591 * If we need to fallback to cow and the inode corresponds to a free
1592 * space cache inode or an inode of the data relocation tree, we must
1593 * also increment bytes_may_use of the data space_info for the same
1594 * reason. Space caches and relocated data extents always get a prealloc
1595 * extent for them, however scrub or balance may have set the block
1596 * group that contains that extent to RO mode and therefore force COW
1597 * when starting writeback.
1599 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1600 EXTENT_NORESERVE, 0);
1601 if (count > 0 || is_space_ino || is_reloc_ino) {
1603 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1604 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1606 if (is_space_ino || is_reloc_ino)
1607 bytes = range_bytes;
1609 spin_lock(&sinfo->lock);
1610 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1611 spin_unlock(&sinfo->lock);
1614 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1618 return cow_file_range(inode, locked_page, start, end, page_started,
1623 * when nowcow writeback call back. This checks for snapshots or COW copies
1624 * of the extents that exist in the file, and COWs the file as required.
1626 * If no cow copies or snapshots exist, we write directly to the existing
1629 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1630 struct page *locked_page,
1631 const u64 start, const u64 end,
1633 unsigned long *nr_written)
1635 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1636 struct btrfs_root *root = inode->root;
1637 struct btrfs_path *path;
1638 u64 cow_start = (u64)-1;
1639 u64 cur_offset = start;
1641 bool check_prev = true;
1642 const bool freespace_inode = btrfs_is_free_space_inode(inode);
1643 u64 ino = btrfs_ino(inode);
1645 u64 disk_bytenr = 0;
1646 const bool force = inode->flags & BTRFS_INODE_NODATACOW;
1648 path = btrfs_alloc_path();
1650 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1651 EXTENT_LOCKED | EXTENT_DELALLOC |
1652 EXTENT_DO_ACCOUNTING |
1653 EXTENT_DEFRAG, PAGE_UNLOCK |
1654 PAGE_START_WRITEBACK |
1655 PAGE_END_WRITEBACK);
1660 struct btrfs_key found_key;
1661 struct btrfs_file_extent_item *fi;
1662 struct extent_buffer *leaf;
1672 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1678 * If there is no extent for our range when doing the initial
1679 * search, then go back to the previous slot as it will be the
1680 * one containing the search offset
1682 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1683 leaf = path->nodes[0];
1684 btrfs_item_key_to_cpu(leaf, &found_key,
1685 path->slots[0] - 1);
1686 if (found_key.objectid == ino &&
1687 found_key.type == BTRFS_EXTENT_DATA_KEY)
1692 /* Go to next leaf if we have exhausted the current one */
1693 leaf = path->nodes[0];
1694 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1695 ret = btrfs_next_leaf(root, path);
1697 if (cow_start != (u64)-1)
1698 cur_offset = cow_start;
1703 leaf = path->nodes[0];
1706 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1708 /* Didn't find anything for our INO */
1709 if (found_key.objectid > ino)
1712 * Keep searching until we find an EXTENT_ITEM or there are no
1713 * more extents for this inode
1715 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1716 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1721 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1722 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1723 found_key.offset > end)
1727 * If the found extent starts after requested offset, then
1728 * adjust extent_end to be right before this extent begins
1730 if (found_key.offset > cur_offset) {
1731 extent_end = found_key.offset;
1737 * Found extent which begins before our range and potentially
1740 fi = btrfs_item_ptr(leaf, path->slots[0],
1741 struct btrfs_file_extent_item);
1742 extent_type = btrfs_file_extent_type(leaf, fi);
1744 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1745 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1746 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1747 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1748 extent_offset = btrfs_file_extent_offset(leaf, fi);
1749 extent_end = found_key.offset +
1750 btrfs_file_extent_num_bytes(leaf, fi);
1752 btrfs_file_extent_disk_num_bytes(leaf, fi);
1754 * If the extent we got ends before our current offset,
1755 * skip to the next extent.
1757 if (extent_end <= cur_offset) {
1762 if (disk_bytenr == 0)
1764 /* Skip compressed/encrypted/encoded extents */
1765 if (btrfs_file_extent_compression(leaf, fi) ||
1766 btrfs_file_extent_encryption(leaf, fi) ||
1767 btrfs_file_extent_other_encoding(leaf, fi))
1770 * If extent is created before the last volume's snapshot
1771 * this implies the extent is shared, hence we can't do
1772 * nocow. This is the same check as in
1773 * btrfs_cross_ref_exist but without calling
1774 * btrfs_search_slot.
1776 if (!freespace_inode &&
1777 btrfs_file_extent_generation(leaf, fi) <=
1778 btrfs_root_last_snapshot(&root->root_item))
1780 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1784 * The following checks can be expensive, as they need to
1785 * take other locks and do btree or rbtree searches, so
1786 * release the path to avoid blocking other tasks for too
1789 btrfs_release_path(path);
1791 ret = btrfs_cross_ref_exist(root, ino,
1793 extent_offset, disk_bytenr, false);
1796 * ret could be -EIO if the above fails to read
1800 if (cow_start != (u64)-1)
1801 cur_offset = cow_start;
1805 WARN_ON_ONCE(freespace_inode);
1808 disk_bytenr += extent_offset;
1809 disk_bytenr += cur_offset - found_key.offset;
1810 num_bytes = min(end + 1, extent_end) - cur_offset;
1812 * If there are pending snapshots for this root, we
1813 * fall into common COW way
1815 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1818 * force cow if csum exists in the range.
1819 * this ensure that csum for a given extent are
1820 * either valid or do not exist.
1822 ret = csum_exist_in_range(fs_info, disk_bytenr,
1826 * ret could be -EIO if the above fails to read
1830 if (cow_start != (u64)-1)
1831 cur_offset = cow_start;
1834 WARN_ON_ONCE(freespace_inode);
1837 /* If the extent's block group is RO, we must COW */
1838 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1841 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1842 extent_end = found_key.offset + ram_bytes;
1843 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1844 /* Skip extents outside of our requested range */
1845 if (extent_end <= start) {
1850 /* If this triggers then we have a memory corruption */
1855 * If nocow is false then record the beginning of the range
1856 * that needs to be COWed
1859 if (cow_start == (u64)-1)
1860 cow_start = cur_offset;
1861 cur_offset = extent_end;
1862 if (cur_offset > end)
1864 if (!path->nodes[0])
1871 * COW range from cow_start to found_key.offset - 1. As the key
1872 * will contain the beginning of the first extent that can be
1873 * NOCOW, following one which needs to be COW'ed
1875 if (cow_start != (u64)-1) {
1876 ret = fallback_to_cow(inode, locked_page,
1877 cow_start, found_key.offset - 1,
1878 page_started, nr_written);
1881 cow_start = (u64)-1;
1884 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1885 u64 orig_start = found_key.offset - extent_offset;
1886 struct extent_map *em;
1888 em = create_io_em(inode, cur_offset, num_bytes,
1890 disk_bytenr, /* block_start */
1891 num_bytes, /* block_len */
1892 disk_num_bytes, /* orig_block_len */
1893 ram_bytes, BTRFS_COMPRESS_NONE,
1894 BTRFS_ORDERED_PREALLOC);
1899 free_extent_map(em);
1900 ret = btrfs_add_ordered_extent(inode,
1901 cur_offset, num_bytes, num_bytes,
1902 disk_bytenr, num_bytes, 0,
1903 1 << BTRFS_ORDERED_PREALLOC,
1904 BTRFS_COMPRESS_NONE);
1906 btrfs_drop_extent_cache(inode, cur_offset,
1907 cur_offset + num_bytes - 1,
1912 ret = btrfs_add_ordered_extent(inode, cur_offset,
1913 num_bytes, num_bytes,
1914 disk_bytenr, num_bytes,
1916 1 << BTRFS_ORDERED_NOCOW,
1917 BTRFS_COMPRESS_NONE);
1923 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1926 if (btrfs_is_data_reloc_root(root))
1928 * Error handled later, as we must prevent
1929 * extent_clear_unlock_delalloc() in error handler
1930 * from freeing metadata of created ordered extent.
1932 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1935 extent_clear_unlock_delalloc(inode, cur_offset,
1936 cur_offset + num_bytes - 1,
1937 locked_page, EXTENT_LOCKED |
1939 EXTENT_CLEAR_DATA_RESV,
1940 PAGE_UNLOCK | PAGE_SET_ORDERED);
1942 cur_offset = extent_end;
1945 * btrfs_reloc_clone_csums() error, now we're OK to call error
1946 * handler, as metadata for created ordered extent will only
1947 * be freed by btrfs_finish_ordered_io().
1951 if (cur_offset > end)
1954 btrfs_release_path(path);
1956 if (cur_offset <= end && cow_start == (u64)-1)
1957 cow_start = cur_offset;
1959 if (cow_start != (u64)-1) {
1961 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1962 page_started, nr_written);
1969 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1971 if (ret && cur_offset < end)
1972 extent_clear_unlock_delalloc(inode, cur_offset, end,
1973 locked_page, EXTENT_LOCKED |
1974 EXTENT_DELALLOC | EXTENT_DEFRAG |
1975 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1976 PAGE_START_WRITEBACK |
1977 PAGE_END_WRITEBACK);
1978 btrfs_free_path(path);
1982 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
1984 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
1985 if (inode->defrag_bytes &&
1986 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
1995 * Function to process delayed allocation (create CoW) for ranges which are
1996 * being touched for the first time.
1998 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1999 u64 start, u64 end, int *page_started, unsigned long *nr_written,
2000 struct writeback_control *wbc)
2003 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2006 * The range must cover part of the @locked_page, or the returned
2007 * @page_started can confuse the caller.
2009 ASSERT(!(end <= page_offset(locked_page) ||
2010 start >= page_offset(locked_page) + PAGE_SIZE));
2012 if (should_nocow(inode, start, end)) {
2014 * Normally on a zoned device we're only doing COW writes, but
2015 * in case of relocation on a zoned filesystem we have taken
2016 * precaution, that we're only writing sequentially. It's safe
2017 * to use run_delalloc_nocow() here, like for regular
2018 * preallocated inodes.
2021 (zoned && btrfs_is_data_reloc_root(inode->root)));
2022 ret = run_delalloc_nocow(inode, locked_page, start, end,
2023 page_started, nr_written);
2024 } else if (!inode_can_compress(inode) ||
2025 !inode_need_compress(inode, start, end)) {
2027 ret = run_delalloc_zoned(inode, locked_page, start, end,
2028 page_started, nr_written);
2030 ret = cow_file_range(inode, locked_page, start, end,
2031 page_started, nr_written, 1);
2033 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
2034 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
2035 page_started, nr_written);
2039 btrfs_cleanup_ordered_extents(inode, locked_page, start,
2044 void btrfs_split_delalloc_extent(struct inode *inode,
2045 struct extent_state *orig, u64 split)
2049 /* not delalloc, ignore it */
2050 if (!(orig->state & EXTENT_DELALLOC))
2053 size = orig->end - orig->start + 1;
2054 if (size > BTRFS_MAX_EXTENT_SIZE) {
2059 * See the explanation in btrfs_merge_delalloc_extent, the same
2060 * applies here, just in reverse.
2062 new_size = orig->end - split + 1;
2063 num_extents = count_max_extents(new_size);
2064 new_size = split - orig->start;
2065 num_extents += count_max_extents(new_size);
2066 if (count_max_extents(size) >= num_extents)
2070 spin_lock(&BTRFS_I(inode)->lock);
2071 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
2072 spin_unlock(&BTRFS_I(inode)->lock);
2076 * Handle merged delayed allocation extents so we can keep track of new extents
2077 * that are just merged onto old extents, such as when we are doing sequential
2078 * writes, so we can properly account for the metadata space we'll need.
2080 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
2081 struct extent_state *other)
2083 u64 new_size, old_size;
2086 /* not delalloc, ignore it */
2087 if (!(other->state & EXTENT_DELALLOC))
2090 if (new->start > other->start)
2091 new_size = new->end - other->start + 1;
2093 new_size = other->end - new->start + 1;
2095 /* we're not bigger than the max, unreserve the space and go */
2096 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
2097 spin_lock(&BTRFS_I(inode)->lock);
2098 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2099 spin_unlock(&BTRFS_I(inode)->lock);
2104 * We have to add up either side to figure out how many extents were
2105 * accounted for before we merged into one big extent. If the number of
2106 * extents we accounted for is <= the amount we need for the new range
2107 * then we can return, otherwise drop. Think of it like this
2111 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2112 * need 2 outstanding extents, on one side we have 1 and the other side
2113 * we have 1 so they are == and we can return. But in this case
2115 * [MAX_SIZE+4k][MAX_SIZE+4k]
2117 * Each range on their own accounts for 2 extents, but merged together
2118 * they are only 3 extents worth of accounting, so we need to drop in
2121 old_size = other->end - other->start + 1;
2122 num_extents = count_max_extents(old_size);
2123 old_size = new->end - new->start + 1;
2124 num_extents += count_max_extents(old_size);
2125 if (count_max_extents(new_size) >= num_extents)
2128 spin_lock(&BTRFS_I(inode)->lock);
2129 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2130 spin_unlock(&BTRFS_I(inode)->lock);
2133 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2134 struct inode *inode)
2136 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2138 spin_lock(&root->delalloc_lock);
2139 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2140 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2141 &root->delalloc_inodes);
2142 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2143 &BTRFS_I(inode)->runtime_flags);
2144 root->nr_delalloc_inodes++;
2145 if (root->nr_delalloc_inodes == 1) {
2146 spin_lock(&fs_info->delalloc_root_lock);
2147 BUG_ON(!list_empty(&root->delalloc_root));
2148 list_add_tail(&root->delalloc_root,
2149 &fs_info->delalloc_roots);
2150 spin_unlock(&fs_info->delalloc_root_lock);
2153 spin_unlock(&root->delalloc_lock);
2157 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2158 struct btrfs_inode *inode)
2160 struct btrfs_fs_info *fs_info = root->fs_info;
2162 if (!list_empty(&inode->delalloc_inodes)) {
2163 list_del_init(&inode->delalloc_inodes);
2164 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2165 &inode->runtime_flags);
2166 root->nr_delalloc_inodes--;
2167 if (!root->nr_delalloc_inodes) {
2168 ASSERT(list_empty(&root->delalloc_inodes));
2169 spin_lock(&fs_info->delalloc_root_lock);
2170 BUG_ON(list_empty(&root->delalloc_root));
2171 list_del_init(&root->delalloc_root);
2172 spin_unlock(&fs_info->delalloc_root_lock);
2177 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2178 struct btrfs_inode *inode)
2180 spin_lock(&root->delalloc_lock);
2181 __btrfs_del_delalloc_inode(root, inode);
2182 spin_unlock(&root->delalloc_lock);
2186 * Properly track delayed allocation bytes in the inode and to maintain the
2187 * list of inodes that have pending delalloc work to be done.
2189 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2192 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2194 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2197 * set_bit and clear bit hooks normally require _irqsave/restore
2198 * but in this case, we are only testing for the DELALLOC
2199 * bit, which is only set or cleared with irqs on
2201 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2202 struct btrfs_root *root = BTRFS_I(inode)->root;
2203 u64 len = state->end + 1 - state->start;
2204 u32 num_extents = count_max_extents(len);
2205 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2207 spin_lock(&BTRFS_I(inode)->lock);
2208 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2209 spin_unlock(&BTRFS_I(inode)->lock);
2211 /* For sanity tests */
2212 if (btrfs_is_testing(fs_info))
2215 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2216 fs_info->delalloc_batch);
2217 spin_lock(&BTRFS_I(inode)->lock);
2218 BTRFS_I(inode)->delalloc_bytes += len;
2219 if (*bits & EXTENT_DEFRAG)
2220 BTRFS_I(inode)->defrag_bytes += len;
2221 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2222 &BTRFS_I(inode)->runtime_flags))
2223 btrfs_add_delalloc_inodes(root, inode);
2224 spin_unlock(&BTRFS_I(inode)->lock);
2227 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2228 (*bits & EXTENT_DELALLOC_NEW)) {
2229 spin_lock(&BTRFS_I(inode)->lock);
2230 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2232 spin_unlock(&BTRFS_I(inode)->lock);
2237 * Once a range is no longer delalloc this function ensures that proper
2238 * accounting happens.
2240 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2241 struct extent_state *state, unsigned *bits)
2243 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2244 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2245 u64 len = state->end + 1 - state->start;
2246 u32 num_extents = count_max_extents(len);
2248 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2249 spin_lock(&inode->lock);
2250 inode->defrag_bytes -= len;
2251 spin_unlock(&inode->lock);
2255 * set_bit and clear bit hooks normally require _irqsave/restore
2256 * but in this case, we are only testing for the DELALLOC
2257 * bit, which is only set or cleared with irqs on
2259 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2260 struct btrfs_root *root = inode->root;
2261 bool do_list = !btrfs_is_free_space_inode(inode);
2263 spin_lock(&inode->lock);
2264 btrfs_mod_outstanding_extents(inode, -num_extents);
2265 spin_unlock(&inode->lock);
2268 * We don't reserve metadata space for space cache inodes so we
2269 * don't need to call delalloc_release_metadata if there is an
2272 if (*bits & EXTENT_CLEAR_META_RESV &&
2273 root != fs_info->tree_root)
2274 btrfs_delalloc_release_metadata(inode, len, false);
2276 /* For sanity tests. */
2277 if (btrfs_is_testing(fs_info))
2280 if (!btrfs_is_data_reloc_root(root) &&
2281 do_list && !(state->state & EXTENT_NORESERVE) &&
2282 (*bits & EXTENT_CLEAR_DATA_RESV))
2283 btrfs_free_reserved_data_space_noquota(fs_info, len);
2285 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2286 fs_info->delalloc_batch);
2287 spin_lock(&inode->lock);
2288 inode->delalloc_bytes -= len;
2289 if (do_list && inode->delalloc_bytes == 0 &&
2290 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2291 &inode->runtime_flags))
2292 btrfs_del_delalloc_inode(root, inode);
2293 spin_unlock(&inode->lock);
2296 if ((state->state & EXTENT_DELALLOC_NEW) &&
2297 (*bits & EXTENT_DELALLOC_NEW)) {
2298 spin_lock(&inode->lock);
2299 ASSERT(inode->new_delalloc_bytes >= len);
2300 inode->new_delalloc_bytes -= len;
2301 if (*bits & EXTENT_ADD_INODE_BYTES)
2302 inode_add_bytes(&inode->vfs_inode, len);
2303 spin_unlock(&inode->lock);
2308 * in order to insert checksums into the metadata in large chunks,
2309 * we wait until bio submission time. All the pages in the bio are
2310 * checksummed and sums are attached onto the ordered extent record.
2312 * At IO completion time the cums attached on the ordered extent record
2313 * are inserted into the btree
2315 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2316 u64 dio_file_offset)
2318 return btrfs_csum_one_bio(BTRFS_I(inode), bio, (u64)-1, false);
2322 * Split an extent_map at [start, start + len]
2324 * This function is intended to be used only for extract_ordered_extent().
2326 static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
2329 struct extent_map_tree *em_tree = &inode->extent_tree;
2330 struct extent_map *em;
2331 struct extent_map *split_pre = NULL;
2332 struct extent_map *split_mid = NULL;
2333 struct extent_map *split_post = NULL;
2335 unsigned long flags;
2338 if (pre == 0 && post == 0)
2341 split_pre = alloc_extent_map();
2343 split_mid = alloc_extent_map();
2345 split_post = alloc_extent_map();
2346 if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
2351 ASSERT(pre + post < len);
2353 lock_extent(&inode->io_tree, start, start + len - 1);
2354 write_lock(&em_tree->lock);
2355 em = lookup_extent_mapping(em_tree, start, len);
2361 ASSERT(em->len == len);
2362 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2363 ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
2364 ASSERT(test_bit(EXTENT_FLAG_PINNED, &em->flags));
2365 ASSERT(!test_bit(EXTENT_FLAG_LOGGING, &em->flags));
2366 ASSERT(!list_empty(&em->list));
2369 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
2371 /* First, replace the em with a new extent_map starting from * em->start */
2372 split_pre->start = em->start;
2373 split_pre->len = (pre ? pre : em->len - post);
2374 split_pre->orig_start = split_pre->start;
2375 split_pre->block_start = em->block_start;
2376 split_pre->block_len = split_pre->len;
2377 split_pre->orig_block_len = split_pre->block_len;
2378 split_pre->ram_bytes = split_pre->len;
2379 split_pre->flags = flags;
2380 split_pre->compress_type = em->compress_type;
2381 split_pre->generation = em->generation;
2383 replace_extent_mapping(em_tree, em, split_pre, 1);
2386 * Now we only have an extent_map at:
2387 * [em->start, em->start + pre] if pre != 0
2388 * [em->start, em->start + em->len - post] if pre == 0
2392 /* Insert the middle extent_map */
2393 split_mid->start = em->start + pre;
2394 split_mid->len = em->len - pre - post;
2395 split_mid->orig_start = split_mid->start;
2396 split_mid->block_start = em->block_start + pre;
2397 split_mid->block_len = split_mid->len;
2398 split_mid->orig_block_len = split_mid->block_len;
2399 split_mid->ram_bytes = split_mid->len;
2400 split_mid->flags = flags;
2401 split_mid->compress_type = em->compress_type;
2402 split_mid->generation = em->generation;
2403 add_extent_mapping(em_tree, split_mid, 1);
2407 split_post->start = em->start + em->len - post;
2408 split_post->len = post;
2409 split_post->orig_start = split_post->start;
2410 split_post->block_start = em->block_start + em->len - post;
2411 split_post->block_len = split_post->len;
2412 split_post->orig_block_len = split_post->block_len;
2413 split_post->ram_bytes = split_post->len;
2414 split_post->flags = flags;
2415 split_post->compress_type = em->compress_type;
2416 split_post->generation = em->generation;
2417 add_extent_mapping(em_tree, split_post, 1);
2421 free_extent_map(em);
2422 /* Once for the tree */
2423 free_extent_map(em);
2426 write_unlock(&em_tree->lock);
2427 unlock_extent(&inode->io_tree, start, start + len - 1);
2429 free_extent_map(split_pre);
2430 free_extent_map(split_mid);
2431 free_extent_map(split_post);
2436 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2437 struct bio *bio, loff_t file_offset)
2439 struct btrfs_ordered_extent *ordered;
2440 u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2442 u64 len = bio->bi_iter.bi_size;
2443 u64 end = start + len;
2448 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2449 if (WARN_ON_ONCE(!ordered))
2450 return BLK_STS_IOERR;
2452 /* No need to split */
2453 if (ordered->disk_num_bytes == len)
2456 /* We cannot split once end_bio'd ordered extent */
2457 if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2462 /* We cannot split a compressed ordered extent */
2463 if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2468 ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2469 /* bio must be in one ordered extent */
2470 if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2475 /* Checksum list should be empty */
2476 if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2481 file_len = ordered->num_bytes;
2482 pre = start - ordered->disk_bytenr;
2483 post = ordered_end - end;
2485 ret = btrfs_split_ordered_extent(ordered, pre, post);
2488 ret = split_zoned_em(inode, file_offset, file_len, pre, post);
2491 btrfs_put_ordered_extent(ordered);
2493 return errno_to_blk_status(ret);
2497 * extent_io.c submission hook. This does the right thing for csum calculation
2498 * on write, or reading the csums from the tree before a read.
2500 * Rules about async/sync submit,
2501 * a) read: sync submit
2503 * b) write without checksum: sync submit
2505 * c) write with checksum:
2506 * c-1) if bio is issued by fsync: sync submit
2507 * (sync_writers != 0)
2509 * c-2) if root is reloc root: sync submit
2510 * (only in case of buffered IO)
2512 * c-3) otherwise: async submit
2514 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2515 int mirror_num, unsigned long bio_flags)
2518 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2519 struct btrfs_root *root = BTRFS_I(inode)->root;
2520 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2521 blk_status_t ret = 0;
2523 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2525 skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2526 test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2528 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2529 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2531 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2532 struct page *page = bio_first_bvec_all(bio)->bv_page;
2533 loff_t file_offset = page_offset(page);
2535 ret = extract_ordered_extent(BTRFS_I(inode), bio, file_offset);
2540 if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
2541 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2545 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2547 * btrfs_submit_compressed_read will handle completing
2548 * the bio if there were any errors, so just return
2551 ret = btrfs_submit_compressed_read(inode, bio,
2557 * Lookup bio sums does extra checks around whether we
2558 * need to csum or not, which is why we ignore skip_sum
2561 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2566 } else if (async && !skip_sum) {
2567 /* csum items have already been cloned */
2568 if (btrfs_is_data_reloc_root(root))
2570 /* we're doing a write, do the async checksumming */
2571 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2572 0, btrfs_submit_bio_start);
2574 } else if (!skip_sum) {
2575 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, (u64)-1, false);
2581 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2585 bio->bi_status = ret;
2593 * given a list of ordered sums record them in the inode. This happens
2594 * at IO completion time based on sums calculated at bio submission time.
2596 static int add_pending_csums(struct btrfs_trans_handle *trans,
2597 struct list_head *list)
2599 struct btrfs_ordered_sum *sum;
2600 struct btrfs_root *csum_root = NULL;
2603 list_for_each_entry(sum, list, list) {
2604 trans->adding_csums = true;
2606 csum_root = btrfs_csum_root(trans->fs_info,
2608 ret = btrfs_csum_file_blocks(trans, csum_root, sum);
2609 trans->adding_csums = false;
2616 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2619 struct extent_state **cached_state)
2621 u64 search_start = start;
2622 const u64 end = start + len - 1;
2624 while (search_start < end) {
2625 const u64 search_len = end - search_start + 1;
2626 struct extent_map *em;
2630 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2634 if (em->block_start != EXTENT_MAP_HOLE)
2638 if (em->start < search_start)
2639 em_len -= search_start - em->start;
2640 if (em_len > search_len)
2641 em_len = search_len;
2643 ret = set_extent_bit(&inode->io_tree, search_start,
2644 search_start + em_len - 1,
2645 EXTENT_DELALLOC_NEW, 0, NULL, cached_state,
2648 search_start = extent_map_end(em);
2649 free_extent_map(em);
2656 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2657 unsigned int extra_bits,
2658 struct extent_state **cached_state)
2660 WARN_ON(PAGE_ALIGNED(end));
2662 if (start >= i_size_read(&inode->vfs_inode) &&
2663 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2665 * There can't be any extents following eof in this case so just
2666 * set the delalloc new bit for the range directly.
2668 extra_bits |= EXTENT_DELALLOC_NEW;
2672 ret = btrfs_find_new_delalloc_bytes(inode, start,
2679 return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2683 /* see btrfs_writepage_start_hook for details on why this is required */
2684 struct btrfs_writepage_fixup {
2686 struct inode *inode;
2687 struct btrfs_work work;
2690 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2692 struct btrfs_writepage_fixup *fixup;
2693 struct btrfs_ordered_extent *ordered;
2694 struct extent_state *cached_state = NULL;
2695 struct extent_changeset *data_reserved = NULL;
2697 struct btrfs_inode *inode;
2701 bool free_delalloc_space = true;
2703 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2705 inode = BTRFS_I(fixup->inode);
2706 page_start = page_offset(page);
2707 page_end = page_offset(page) + PAGE_SIZE - 1;
2710 * This is similar to page_mkwrite, we need to reserve the space before
2711 * we take the page lock.
2713 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2719 * Before we queued this fixup, we took a reference on the page.
2720 * page->mapping may go NULL, but it shouldn't be moved to a different
2723 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2725 * Unfortunately this is a little tricky, either
2727 * 1) We got here and our page had already been dealt with and
2728 * we reserved our space, thus ret == 0, so we need to just
2729 * drop our space reservation and bail. This can happen the
2730 * first time we come into the fixup worker, or could happen
2731 * while waiting for the ordered extent.
2732 * 2) Our page was already dealt with, but we happened to get an
2733 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2734 * this case we obviously don't have anything to release, but
2735 * because the page was already dealt with we don't want to
2736 * mark the page with an error, so make sure we're resetting
2737 * ret to 0. This is why we have this check _before_ the ret
2738 * check, because we do not want to have a surprise ENOSPC
2739 * when the page was already properly dealt with.
2742 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2743 btrfs_delalloc_release_space(inode, data_reserved,
2744 page_start, PAGE_SIZE,
2752 * We can't mess with the page state unless it is locked, so now that
2753 * it is locked bail if we failed to make our space reservation.
2758 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2760 /* already ordered? We're done */
2761 if (PageOrdered(page))
2764 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2766 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2769 btrfs_start_ordered_extent(ordered, 1);
2770 btrfs_put_ordered_extent(ordered);
2774 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2780 * Everything went as planned, we're now the owner of a dirty page with
2781 * delayed allocation bits set and space reserved for our COW
2784 * The page was dirty when we started, nothing should have cleaned it.
2786 BUG_ON(!PageDirty(page));
2787 free_delalloc_space = false;
2789 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2790 if (free_delalloc_space)
2791 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2793 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2798 * We hit ENOSPC or other errors. Update the mapping and page
2799 * to reflect the errors and clean the page.
2801 mapping_set_error(page->mapping, ret);
2802 end_extent_writepage(page, ret, page_start, page_end);
2803 clear_page_dirty_for_io(page);
2806 btrfs_page_clear_checked(inode->root->fs_info, page, page_start, PAGE_SIZE);
2810 extent_changeset_free(data_reserved);
2812 * As a precaution, do a delayed iput in case it would be the last iput
2813 * that could need flushing space. Recursing back to fixup worker would
2816 btrfs_add_delayed_iput(&inode->vfs_inode);
2820 * There are a few paths in the higher layers of the kernel that directly
2821 * set the page dirty bit without asking the filesystem if it is a
2822 * good idea. This causes problems because we want to make sure COW
2823 * properly happens and the data=ordered rules are followed.
2825 * In our case any range that doesn't have the ORDERED bit set
2826 * hasn't been properly setup for IO. We kick off an async process
2827 * to fix it up. The async helper will wait for ordered extents, set
2828 * the delalloc bit and make it safe to write the page.
2830 int btrfs_writepage_cow_fixup(struct page *page)
2832 struct inode *inode = page->mapping->host;
2833 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2834 struct btrfs_writepage_fixup *fixup;
2836 /* This page has ordered extent covering it already */
2837 if (PageOrdered(page))
2841 * PageChecked is set below when we create a fixup worker for this page,
2842 * don't try to create another one if we're already PageChecked()
2844 * The extent_io writepage code will redirty the page if we send back
2847 if (PageChecked(page))
2850 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2855 * We are already holding a reference to this inode from
2856 * write_cache_pages. We need to hold it because the space reservation
2857 * takes place outside of the page lock, and we can't trust
2858 * page->mapping outside of the page lock.
2861 btrfs_page_set_checked(fs_info, page, page_offset(page), PAGE_SIZE);
2863 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2865 fixup->inode = inode;
2866 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2871 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2872 struct btrfs_inode *inode, u64 file_pos,
2873 struct btrfs_file_extent_item *stack_fi,
2874 const bool update_inode_bytes,
2875 u64 qgroup_reserved)
2877 struct btrfs_root *root = inode->root;
2878 const u64 sectorsize = root->fs_info->sectorsize;
2879 struct btrfs_path *path;
2880 struct extent_buffer *leaf;
2881 struct btrfs_key ins;
2882 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2883 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2884 u64 offset = btrfs_stack_file_extent_offset(stack_fi);
2885 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2886 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2887 struct btrfs_drop_extents_args drop_args = { 0 };
2890 path = btrfs_alloc_path();
2895 * we may be replacing one extent in the tree with another.
2896 * The new extent is pinned in the extent map, and we don't want
2897 * to drop it from the cache until it is completely in the btree.
2899 * So, tell btrfs_drop_extents to leave this extent in the cache.
2900 * the caller is expected to unpin it and allow it to be merged
2903 drop_args.path = path;
2904 drop_args.start = file_pos;
2905 drop_args.end = file_pos + num_bytes;
2906 drop_args.replace_extent = true;
2907 drop_args.extent_item_size = sizeof(*stack_fi);
2908 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2912 if (!drop_args.extent_inserted) {
2913 ins.objectid = btrfs_ino(inode);
2914 ins.offset = file_pos;
2915 ins.type = BTRFS_EXTENT_DATA_KEY;
2917 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2922 leaf = path->nodes[0];
2923 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2924 write_extent_buffer(leaf, stack_fi,
2925 btrfs_item_ptr_offset(leaf, path->slots[0]),
2926 sizeof(struct btrfs_file_extent_item));
2928 btrfs_mark_buffer_dirty(leaf);
2929 btrfs_release_path(path);
2932 * If we dropped an inline extent here, we know the range where it is
2933 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2934 * number of bytes only for that range containing the inline extent.
2935 * The remaining of the range will be processed when clearning the
2936 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2938 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2939 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2941 inline_size = drop_args.bytes_found - inline_size;
2942 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2943 drop_args.bytes_found -= inline_size;
2944 num_bytes -= sectorsize;
2947 if (update_inode_bytes)
2948 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2950 ins.objectid = disk_bytenr;
2951 ins.offset = disk_num_bytes;
2952 ins.type = BTRFS_EXTENT_ITEM_KEY;
2954 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2958 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2960 qgroup_reserved, &ins);
2962 btrfs_free_path(path);
2967 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2970 struct btrfs_block_group *cache;
2972 cache = btrfs_lookup_block_group(fs_info, start);
2975 spin_lock(&cache->lock);
2976 cache->delalloc_bytes -= len;
2977 spin_unlock(&cache->lock);
2979 btrfs_put_block_group(cache);
2982 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2983 struct btrfs_ordered_extent *oe)
2985 struct btrfs_file_extent_item stack_fi;
2986 bool update_inode_bytes;
2987 u64 num_bytes = oe->num_bytes;
2988 u64 ram_bytes = oe->ram_bytes;
2990 memset(&stack_fi, 0, sizeof(stack_fi));
2991 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2992 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2993 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2994 oe->disk_num_bytes);
2995 btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
2996 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2997 num_bytes = ram_bytes = oe->truncated_len;
2998 btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
2999 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
3000 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3001 /* Encryption and other encoding is reserved and all 0 */
3004 * For delalloc, when completing an ordered extent we update the inode's
3005 * bytes when clearing the range in the inode's io tree, so pass false
3006 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3007 * except if the ordered extent was truncated.
3009 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3010 test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
3011 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3013 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
3014 oe->file_offset, &stack_fi,
3015 update_inode_bytes, oe->qgroup_rsv);
3019 * As ordered data IO finishes, this gets called so we can finish
3020 * an ordered extent if the range of bytes in the file it covers are
3023 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3025 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
3026 struct btrfs_root *root = inode->root;
3027 struct btrfs_fs_info *fs_info = root->fs_info;
3028 struct btrfs_trans_handle *trans = NULL;
3029 struct extent_io_tree *io_tree = &inode->io_tree;
3030 struct extent_state *cached_state = NULL;
3032 int compress_type = 0;
3034 u64 logical_len = ordered_extent->num_bytes;
3035 bool freespace_inode;
3036 bool truncated = false;
3037 bool clear_reserved_extent = true;
3038 unsigned int clear_bits = EXTENT_DEFRAG;
3040 start = ordered_extent->file_offset;
3041 end = start + ordered_extent->num_bytes - 1;
3043 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3044 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3045 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3046 !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3047 clear_bits |= EXTENT_DELALLOC_NEW;
3049 freespace_inode = btrfs_is_free_space_inode(inode);
3051 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3056 /* A valid bdev implies a write on a sequential zone */
3057 if (ordered_extent->bdev) {
3058 btrfs_rewrite_logical_zoned(ordered_extent);
3059 btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3060 ordered_extent->disk_num_bytes);
3063 btrfs_free_io_failure_record(inode, start, end);
3065 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3067 logical_len = ordered_extent->truncated_len;
3068 /* Truncated the entire extent, don't bother adding */
3073 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3074 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3076 btrfs_inode_safe_disk_i_size_write(inode, 0);
3077 if (freespace_inode)
3078 trans = btrfs_join_transaction_spacecache(root);
3080 trans = btrfs_join_transaction(root);
3081 if (IS_ERR(trans)) {
3082 ret = PTR_ERR(trans);
3086 trans->block_rsv = &inode->block_rsv;
3087 ret = btrfs_update_inode_fallback(trans, root, inode);
3088 if (ret) /* -ENOMEM or corruption */
3089 btrfs_abort_transaction(trans, ret);
3093 clear_bits |= EXTENT_LOCKED;
3094 lock_extent_bits(io_tree, start, end, &cached_state);
3096 if (freespace_inode)
3097 trans = btrfs_join_transaction_spacecache(root);
3099 trans = btrfs_join_transaction(root);
3100 if (IS_ERR(trans)) {
3101 ret = PTR_ERR(trans);
3106 trans->block_rsv = &inode->block_rsv;
3108 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3109 compress_type = ordered_extent->compress_type;
3110 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3111 BUG_ON(compress_type);
3112 ret = btrfs_mark_extent_written(trans, inode,
3113 ordered_extent->file_offset,
3114 ordered_extent->file_offset +
3117 BUG_ON(root == fs_info->tree_root);
3118 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3120 clear_reserved_extent = false;
3121 btrfs_release_delalloc_bytes(fs_info,
3122 ordered_extent->disk_bytenr,
3123 ordered_extent->disk_num_bytes);
3126 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3127 ordered_extent->num_bytes, trans->transid);
3129 btrfs_abort_transaction(trans, ret);
3133 ret = add_pending_csums(trans, &ordered_extent->list);
3135 btrfs_abort_transaction(trans, ret);
3140 * If this is a new delalloc range, clear its new delalloc flag to
3141 * update the inode's number of bytes. This needs to be done first
3142 * before updating the inode item.
3144 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3145 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3146 clear_extent_bit(&inode->io_tree, start, end,
3147 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3148 0, 0, &cached_state);
3150 btrfs_inode_safe_disk_i_size_write(inode, 0);
3151 ret = btrfs_update_inode_fallback(trans, root, inode);
3152 if (ret) { /* -ENOMEM or corruption */
3153 btrfs_abort_transaction(trans, ret);
3158 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3159 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
3163 btrfs_end_transaction(trans);
3165 if (ret || truncated) {
3166 u64 unwritten_start = start;
3169 * If we failed to finish this ordered extent for any reason we
3170 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3171 * extent, and mark the inode with the error if it wasn't
3172 * already set. Any error during writeback would have already
3173 * set the mapping error, so we need to set it if we're the ones
3174 * marking this ordered extent as failed.
3176 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3177 &ordered_extent->flags))
3178 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3181 unwritten_start += logical_len;
3182 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3184 /* Drop the cache for the part of the extent we didn't write. */
3185 btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
3188 * If the ordered extent had an IOERR or something else went
3189 * wrong we need to return the space for this ordered extent
3190 * back to the allocator. We only free the extent in the
3191 * truncated case if we didn't write out the extent at all.
3193 * If we made it past insert_reserved_file_extent before we
3194 * errored out then we don't need to do this as the accounting
3195 * has already been done.
3197 if ((ret || !logical_len) &&
3198 clear_reserved_extent &&
3199 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3200 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3202 * Discard the range before returning it back to the
3205 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3206 btrfs_discard_extent(fs_info,
3207 ordered_extent->disk_bytenr,
3208 ordered_extent->disk_num_bytes,
3210 btrfs_free_reserved_extent(fs_info,
3211 ordered_extent->disk_bytenr,
3212 ordered_extent->disk_num_bytes, 1);
3217 * This needs to be done to make sure anybody waiting knows we are done
3218 * updating everything for this ordered extent.
3220 btrfs_remove_ordered_extent(inode, ordered_extent);
3223 btrfs_put_ordered_extent(ordered_extent);
3224 /* once for the tree */
3225 btrfs_put_ordered_extent(ordered_extent);
3230 static void finish_ordered_fn(struct btrfs_work *work)
3232 struct btrfs_ordered_extent *ordered_extent;
3233 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3234 btrfs_finish_ordered_io(ordered_extent);
3237 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3238 struct page *page, u64 start,
3239 u64 end, bool uptodate)
3241 trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3243 btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start,
3244 finish_ordered_fn, uptodate);
3248 * check_data_csum - verify checksum of one sector of uncompressed data
3250 * @io_bio: btrfs_io_bio which contains the csum
3251 * @bio_offset: offset to the beginning of the bio (in bytes)
3252 * @page: page where is the data to be verified
3253 * @pgoff: offset inside the page
3254 * @start: logical offset in the file
3256 * The length of such check is always one sector size.
3258 static int check_data_csum(struct inode *inode, struct btrfs_bio *bbio,
3259 u32 bio_offset, struct page *page, u32 pgoff,
3262 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3263 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3265 u32 len = fs_info->sectorsize;
3266 const u32 csum_size = fs_info->csum_size;
3267 unsigned int offset_sectors;
3269 u8 csum[BTRFS_CSUM_SIZE];
3271 ASSERT(pgoff + len <= PAGE_SIZE);
3273 offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3274 csum_expected = ((u8 *)bbio->csum) + offset_sectors * csum_size;
3276 kaddr = kmap_atomic(page);
3277 shash->tfm = fs_info->csum_shash;
3279 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3281 if (memcmp(csum, csum_expected, csum_size))
3284 kunmap_atomic(kaddr);
3287 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3290 btrfs_dev_stat_inc_and_print(bbio->device,
3291 BTRFS_DEV_STAT_CORRUPTION_ERRS);
3292 memset(kaddr + pgoff, 1, len);
3293 flush_dcache_page(page);
3294 kunmap_atomic(kaddr);
3299 * When reads are done, we need to check csums to verify the data is correct.
3300 * if there's a match, we allow the bio to finish. If not, the code in
3301 * extent_io.c will try to find good copies for us.
3303 * @bio_offset: offset to the beginning of the bio (in bytes)
3304 * @start: file offset of the range start
3305 * @end: file offset of the range end (inclusive)
3307 * Return a bitmap where bit set means a csum mismatch, and bit not set means
3310 unsigned int btrfs_verify_data_csum(struct btrfs_bio *bbio,
3311 u32 bio_offset, struct page *page,
3314 struct inode *inode = page->mapping->host;
3315 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3316 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3317 struct btrfs_root *root = BTRFS_I(inode)->root;
3318 const u32 sectorsize = root->fs_info->sectorsize;
3320 unsigned int result = 0;
3322 if (btrfs_page_test_checked(fs_info, page, start, end + 1 - start)) {
3323 btrfs_page_clear_checked(fs_info, page, start, end + 1 - start);
3328 * This only happens for NODATASUM or compressed read.
3329 * Normally this should be covered by above check for compressed read
3330 * or the next check for NODATASUM. Just do a quicker exit here.
3332 if (bbio->csum == NULL)
3335 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3338 if (unlikely(test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state)))
3341 ASSERT(page_offset(page) <= start &&
3342 end <= page_offset(page) + PAGE_SIZE - 1);
3343 for (pg_off = offset_in_page(start);
3344 pg_off < offset_in_page(end);
3345 pg_off += sectorsize, bio_offset += sectorsize) {
3346 u64 file_offset = pg_off + page_offset(page);
3349 if (btrfs_is_data_reloc_root(root) &&
3350 test_range_bit(io_tree, file_offset,
3351 file_offset + sectorsize - 1,
3352 EXTENT_NODATASUM, 1, NULL)) {
3353 /* Skip the range without csum for data reloc inode */
3354 clear_extent_bits(io_tree, file_offset,
3355 file_offset + sectorsize - 1,
3359 ret = check_data_csum(inode, bbio, bio_offset, page, pg_off,
3360 page_offset(page) + pg_off);
3362 const int nr_bit = (pg_off - offset_in_page(start)) >>
3363 root->fs_info->sectorsize_bits;
3365 result |= (1U << nr_bit);
3372 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3374 * @inode: The inode we want to perform iput on
3376 * This function uses the generic vfs_inode::i_count to track whether we should
3377 * just decrement it (in case it's > 1) or if this is the last iput then link
3378 * the inode to the delayed iput machinery. Delayed iputs are processed at
3379 * transaction commit time/superblock commit/cleaner kthread.
3381 void btrfs_add_delayed_iput(struct inode *inode)
3383 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3384 struct btrfs_inode *binode = BTRFS_I(inode);
3386 if (atomic_add_unless(&inode->i_count, -1, 1))
3389 atomic_inc(&fs_info->nr_delayed_iputs);
3390 spin_lock(&fs_info->delayed_iput_lock);
3391 ASSERT(list_empty(&binode->delayed_iput));
3392 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3393 spin_unlock(&fs_info->delayed_iput_lock);
3394 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3395 wake_up_process(fs_info->cleaner_kthread);
3398 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3399 struct btrfs_inode *inode)
3401 list_del_init(&inode->delayed_iput);
3402 spin_unlock(&fs_info->delayed_iput_lock);
3403 iput(&inode->vfs_inode);
3404 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3405 wake_up(&fs_info->delayed_iputs_wait);
3406 spin_lock(&fs_info->delayed_iput_lock);
3409 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3410 struct btrfs_inode *inode)
3412 if (!list_empty(&inode->delayed_iput)) {
3413 spin_lock(&fs_info->delayed_iput_lock);
3414 if (!list_empty(&inode->delayed_iput))
3415 run_delayed_iput_locked(fs_info, inode);
3416 spin_unlock(&fs_info->delayed_iput_lock);
3420 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3423 spin_lock(&fs_info->delayed_iput_lock);
3424 while (!list_empty(&fs_info->delayed_iputs)) {
3425 struct btrfs_inode *inode;
3427 inode = list_first_entry(&fs_info->delayed_iputs,
3428 struct btrfs_inode, delayed_iput);
3429 run_delayed_iput_locked(fs_info, inode);
3430 cond_resched_lock(&fs_info->delayed_iput_lock);
3432 spin_unlock(&fs_info->delayed_iput_lock);
3436 * Wait for flushing all delayed iputs
3438 * @fs_info: the filesystem
3440 * This will wait on any delayed iputs that are currently running with KILLABLE
3441 * set. Once they are all done running we will return, unless we are killed in
3442 * which case we return EINTR. This helps in user operations like fallocate etc
3443 * that might get blocked on the iputs.
3445 * Return EINTR if we were killed, 0 if nothing's pending
3447 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3449 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3450 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3457 * This creates an orphan entry for the given inode in case something goes wrong
3458 * in the middle of an unlink.
3460 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3461 struct btrfs_inode *inode)
3465 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3466 if (ret && ret != -EEXIST) {
3467 btrfs_abort_transaction(trans, ret);
3475 * We have done the delete so we can go ahead and remove the orphan item for
3476 * this particular inode.
3478 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3479 struct btrfs_inode *inode)
3481 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3485 * this cleans up any orphans that may be left on the list from the last use
3488 int btrfs_orphan_cleanup(struct btrfs_root *root)
3490 struct btrfs_fs_info *fs_info = root->fs_info;
3491 struct btrfs_path *path;
3492 struct extent_buffer *leaf;
3493 struct btrfs_key key, found_key;
3494 struct btrfs_trans_handle *trans;
3495 struct inode *inode;
3496 u64 last_objectid = 0;
3497 int ret = 0, nr_unlink = 0;
3499 if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3502 path = btrfs_alloc_path();
3507 path->reada = READA_BACK;
3509 key.objectid = BTRFS_ORPHAN_OBJECTID;
3510 key.type = BTRFS_ORPHAN_ITEM_KEY;
3511 key.offset = (u64)-1;
3514 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3519 * if ret == 0 means we found what we were searching for, which
3520 * is weird, but possible, so only screw with path if we didn't
3521 * find the key and see if we have stuff that matches
3525 if (path->slots[0] == 0)
3530 /* pull out the item */
3531 leaf = path->nodes[0];
3532 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3534 /* make sure the item matches what we want */
3535 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3537 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3540 /* release the path since we're done with it */
3541 btrfs_release_path(path);
3544 * this is where we are basically btrfs_lookup, without the
3545 * crossing root thing. we store the inode number in the
3546 * offset of the orphan item.
3549 if (found_key.offset == last_objectid) {
3551 "Error removing orphan entry, stopping orphan cleanup");
3556 last_objectid = found_key.offset;
3558 found_key.objectid = found_key.offset;
3559 found_key.type = BTRFS_INODE_ITEM_KEY;
3560 found_key.offset = 0;
3561 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3562 ret = PTR_ERR_OR_ZERO(inode);
3563 if (ret && ret != -ENOENT)
3566 if (ret == -ENOENT && root == fs_info->tree_root) {
3567 struct btrfs_root *dead_root;
3568 int is_dead_root = 0;
3571 * This is an orphan in the tree root. Currently these
3572 * could come from 2 sources:
3573 * a) a root (snapshot/subvolume) deletion in progress
3574 * b) a free space cache inode
3575 * We need to distinguish those two, as the orphan item
3576 * for a root must not get deleted before the deletion
3577 * of the snapshot/subvolume's tree completes.
3579 * btrfs_find_orphan_roots() ran before us, which has
3580 * found all deleted roots and loaded them into
3581 * fs_info->fs_roots_radix. So here we can find if an
3582 * orphan item corresponds to a deleted root by looking
3583 * up the root from that radix tree.
3586 spin_lock(&fs_info->fs_roots_radix_lock);
3587 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3588 (unsigned long)found_key.objectid);
3589 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3591 spin_unlock(&fs_info->fs_roots_radix_lock);
3594 /* prevent this orphan from being found again */
3595 key.offset = found_key.objectid - 1;
3602 * If we have an inode with links, there are a couple of
3605 * 1. We were halfway through creating fsverity metadata for the
3606 * file. In that case, the orphan item represents incomplete
3607 * fsverity metadata which must be cleaned up with
3608 * btrfs_drop_verity_items and deleting the orphan item.
3610 * 2. Old kernels (before v3.12) used to create an
3611 * orphan item for truncate indicating that there were possibly
3612 * extent items past i_size that needed to be deleted. In v3.12,
3613 * truncate was changed to update i_size in sync with the extent
3614 * items, but the (useless) orphan item was still created. Since
3615 * v4.18, we don't create the orphan item for truncate at all.
3617 * So, this item could mean that we need to do a truncate, but
3618 * only if this filesystem was last used on a pre-v3.12 kernel
3619 * and was not cleanly unmounted. The odds of that are quite
3620 * slim, and it's a pain to do the truncate now, so just delete
3623 * It's also possible that this orphan item was supposed to be
3624 * deleted but wasn't. The inode number may have been reused,
3625 * but either way, we can delete the orphan item.
3627 if (ret == -ENOENT || inode->i_nlink) {
3629 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3634 trans = btrfs_start_transaction(root, 1);
3635 if (IS_ERR(trans)) {
3636 ret = PTR_ERR(trans);
3639 btrfs_debug(fs_info, "auto deleting %Lu",
3640 found_key.objectid);
3641 ret = btrfs_del_orphan_item(trans, root,
3642 found_key.objectid);
3643 btrfs_end_transaction(trans);
3651 /* this will do delete_inode and everything for us */
3654 /* release the path since we're done with it */
3655 btrfs_release_path(path);
3657 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3658 trans = btrfs_join_transaction(root);
3660 btrfs_end_transaction(trans);
3664 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3668 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3669 btrfs_free_path(path);
3674 * very simple check to peek ahead in the leaf looking for xattrs. If we
3675 * don't find any xattrs, we know there can't be any acls.
3677 * slot is the slot the inode is in, objectid is the objectid of the inode
3679 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3680 int slot, u64 objectid,
3681 int *first_xattr_slot)
3683 u32 nritems = btrfs_header_nritems(leaf);
3684 struct btrfs_key found_key;
3685 static u64 xattr_access = 0;
3686 static u64 xattr_default = 0;
3689 if (!xattr_access) {
3690 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3691 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3692 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3693 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3697 *first_xattr_slot = -1;
3698 while (slot < nritems) {
3699 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3701 /* we found a different objectid, there must not be acls */
3702 if (found_key.objectid != objectid)
3705 /* we found an xattr, assume we've got an acl */
3706 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3707 if (*first_xattr_slot == -1)
3708 *first_xattr_slot = slot;
3709 if (found_key.offset == xattr_access ||
3710 found_key.offset == xattr_default)
3715 * we found a key greater than an xattr key, there can't
3716 * be any acls later on
3718 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3725 * it goes inode, inode backrefs, xattrs, extents,
3726 * so if there are a ton of hard links to an inode there can
3727 * be a lot of backrefs. Don't waste time searching too hard,
3728 * this is just an optimization
3733 /* we hit the end of the leaf before we found an xattr or
3734 * something larger than an xattr. We have to assume the inode
3737 if (*first_xattr_slot == -1)
3738 *first_xattr_slot = slot;
3743 * read an inode from the btree into the in-memory inode
3745 static int btrfs_read_locked_inode(struct inode *inode,
3746 struct btrfs_path *in_path)
3748 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3749 struct btrfs_path *path = in_path;
3750 struct extent_buffer *leaf;
3751 struct btrfs_inode_item *inode_item;
3752 struct btrfs_root *root = BTRFS_I(inode)->root;
3753 struct btrfs_key location;
3758 bool filled = false;
3759 int first_xattr_slot;
3761 ret = btrfs_fill_inode(inode, &rdev);
3766 path = btrfs_alloc_path();
3771 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3773 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3775 if (path != in_path)
3776 btrfs_free_path(path);
3780 leaf = path->nodes[0];
3785 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3786 struct btrfs_inode_item);
3787 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3788 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3789 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3790 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3791 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3792 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3793 round_up(i_size_read(inode), fs_info->sectorsize));
3795 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3796 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3798 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3799 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3801 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3802 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3804 BTRFS_I(inode)->i_otime.tv_sec =
3805 btrfs_timespec_sec(leaf, &inode_item->otime);
3806 BTRFS_I(inode)->i_otime.tv_nsec =
3807 btrfs_timespec_nsec(leaf, &inode_item->otime);
3809 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3810 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3811 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3813 inode_set_iversion_queried(inode,
3814 btrfs_inode_sequence(leaf, inode_item));
3815 inode->i_generation = BTRFS_I(inode)->generation;
3817 rdev = btrfs_inode_rdev(leaf, inode_item);
3819 BTRFS_I(inode)->index_cnt = (u64)-1;
3820 btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
3821 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
3825 * If we were modified in the current generation and evicted from memory
3826 * and then re-read we need to do a full sync since we don't have any
3827 * idea about which extents were modified before we were evicted from
3830 * This is required for both inode re-read from disk and delayed inode
3831 * in delayed_nodes_tree.
3833 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3834 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3835 &BTRFS_I(inode)->runtime_flags);
3838 * We don't persist the id of the transaction where an unlink operation
3839 * against the inode was last made. So here we assume the inode might
3840 * have been evicted, and therefore the exact value of last_unlink_trans
3841 * lost, and set it to last_trans to avoid metadata inconsistencies
3842 * between the inode and its parent if the inode is fsync'ed and the log
3843 * replayed. For example, in the scenario:
3846 * ln mydir/foo mydir/bar
3849 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3850 * xfs_io -c fsync mydir/foo
3852 * mount fs, triggers fsync log replay
3854 * We must make sure that when we fsync our inode foo we also log its
3855 * parent inode, otherwise after log replay the parent still has the
3856 * dentry with the "bar" name but our inode foo has a link count of 1
3857 * and doesn't have an inode ref with the name "bar" anymore.
3859 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3860 * but it guarantees correctness at the expense of occasional full
3861 * transaction commits on fsync if our inode is a directory, or if our
3862 * inode is not a directory, logging its parent unnecessarily.
3864 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3867 * Same logic as for last_unlink_trans. We don't persist the generation
3868 * of the last transaction where this inode was used for a reflink
3869 * operation, so after eviction and reloading the inode we must be
3870 * pessimistic and assume the last transaction that modified the inode.
3872 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3875 if (inode->i_nlink != 1 ||
3876 path->slots[0] >= btrfs_header_nritems(leaf))
3879 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3880 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3883 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3884 if (location.type == BTRFS_INODE_REF_KEY) {
3885 struct btrfs_inode_ref *ref;
3887 ref = (struct btrfs_inode_ref *)ptr;
3888 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3889 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3890 struct btrfs_inode_extref *extref;
3892 extref = (struct btrfs_inode_extref *)ptr;
3893 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3898 * try to precache a NULL acl entry for files that don't have
3899 * any xattrs or acls
3901 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3902 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3903 if (first_xattr_slot != -1) {
3904 path->slots[0] = first_xattr_slot;
3905 ret = btrfs_load_inode_props(inode, path);
3908 "error loading props for ino %llu (root %llu): %d",
3909 btrfs_ino(BTRFS_I(inode)),
3910 root->root_key.objectid, ret);
3912 if (path != in_path)
3913 btrfs_free_path(path);
3916 cache_no_acl(inode);
3918 switch (inode->i_mode & S_IFMT) {
3920 inode->i_mapping->a_ops = &btrfs_aops;
3921 inode->i_fop = &btrfs_file_operations;
3922 inode->i_op = &btrfs_file_inode_operations;
3925 inode->i_fop = &btrfs_dir_file_operations;
3926 inode->i_op = &btrfs_dir_inode_operations;
3929 inode->i_op = &btrfs_symlink_inode_operations;
3930 inode_nohighmem(inode);
3931 inode->i_mapping->a_ops = &btrfs_aops;
3934 inode->i_op = &btrfs_special_inode_operations;
3935 init_special_inode(inode, inode->i_mode, rdev);
3939 btrfs_sync_inode_flags_to_i_flags(inode);
3944 * given a leaf and an inode, copy the inode fields into the leaf
3946 static void fill_inode_item(struct btrfs_trans_handle *trans,
3947 struct extent_buffer *leaf,
3948 struct btrfs_inode_item *item,
3949 struct inode *inode)
3951 struct btrfs_map_token token;
3954 btrfs_init_map_token(&token, leaf);
3956 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3957 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3958 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3959 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3960 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3962 btrfs_set_token_timespec_sec(&token, &item->atime,
3963 inode->i_atime.tv_sec);
3964 btrfs_set_token_timespec_nsec(&token, &item->atime,
3965 inode->i_atime.tv_nsec);
3967 btrfs_set_token_timespec_sec(&token, &item->mtime,
3968 inode->i_mtime.tv_sec);
3969 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3970 inode->i_mtime.tv_nsec);
3972 btrfs_set_token_timespec_sec(&token, &item->ctime,
3973 inode->i_ctime.tv_sec);
3974 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3975 inode->i_ctime.tv_nsec);
3977 btrfs_set_token_timespec_sec(&token, &item->otime,
3978 BTRFS_I(inode)->i_otime.tv_sec);
3979 btrfs_set_token_timespec_nsec(&token, &item->otime,
3980 BTRFS_I(inode)->i_otime.tv_nsec);
3982 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3983 btrfs_set_token_inode_generation(&token, item,
3984 BTRFS_I(inode)->generation);
3985 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3986 btrfs_set_token_inode_transid(&token, item, trans->transid);
3987 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3988 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
3989 BTRFS_I(inode)->ro_flags);
3990 btrfs_set_token_inode_flags(&token, item, flags);
3991 btrfs_set_token_inode_block_group(&token, item, 0);
3995 * copy everything in the in-memory inode into the btree.
3997 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3998 struct btrfs_root *root,
3999 struct btrfs_inode *inode)
4001 struct btrfs_inode_item *inode_item;
4002 struct btrfs_path *path;
4003 struct extent_buffer *leaf;
4006 path = btrfs_alloc_path();
4010 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
4017 leaf = path->nodes[0];
4018 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4019 struct btrfs_inode_item);
4021 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4022 btrfs_mark_buffer_dirty(leaf);
4023 btrfs_set_inode_last_trans(trans, inode);
4026 btrfs_free_path(path);
4031 * copy everything in the in-memory inode into the btree.
4033 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4034 struct btrfs_root *root,
4035 struct btrfs_inode *inode)
4037 struct btrfs_fs_info *fs_info = root->fs_info;
4041 * If the inode is a free space inode, we can deadlock during commit
4042 * if we put it into the delayed code.
4044 * The data relocation inode should also be directly updated
4047 if (!btrfs_is_free_space_inode(inode)
4048 && !btrfs_is_data_reloc_root(root)
4049 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4050 btrfs_update_root_times(trans, root);
4052 ret = btrfs_delayed_update_inode(trans, root, inode);
4054 btrfs_set_inode_last_trans(trans, inode);
4058 return btrfs_update_inode_item(trans, root, inode);
4061 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4062 struct btrfs_root *root, struct btrfs_inode *inode)
4066 ret = btrfs_update_inode(trans, root, inode);
4068 return btrfs_update_inode_item(trans, root, inode);
4073 * unlink helper that gets used here in inode.c and in the tree logging
4074 * recovery code. It remove a link in a directory with a given name, and
4075 * also drops the back refs in the inode to the directory
4077 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4078 struct btrfs_inode *dir,
4079 struct btrfs_inode *inode,
4080 const char *name, int name_len,
4081 struct btrfs_rename_ctx *rename_ctx)
4083 struct btrfs_root *root = dir->root;
4084 struct btrfs_fs_info *fs_info = root->fs_info;
4085 struct btrfs_path *path;
4087 struct btrfs_dir_item *di;
4089 u64 ino = btrfs_ino(inode);
4090 u64 dir_ino = btrfs_ino(dir);
4092 path = btrfs_alloc_path();
4098 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4099 name, name_len, -1);
4100 if (IS_ERR_OR_NULL(di)) {
4101 ret = di ? PTR_ERR(di) : -ENOENT;
4104 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4107 btrfs_release_path(path);
4110 * If we don't have dir index, we have to get it by looking up
4111 * the inode ref, since we get the inode ref, remove it directly,
4112 * it is unnecessary to do delayed deletion.
4114 * But if we have dir index, needn't search inode ref to get it.
4115 * Since the inode ref is close to the inode item, it is better
4116 * that we delay to delete it, and just do this deletion when
4117 * we update the inode item.
4119 if (inode->dir_index) {
4120 ret = btrfs_delayed_delete_inode_ref(inode);
4122 index = inode->dir_index;
4127 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4131 "failed to delete reference to %.*s, inode %llu parent %llu",
4132 name_len, name, ino, dir_ino);
4133 btrfs_abort_transaction(trans, ret);
4138 rename_ctx->index = index;
4140 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4142 btrfs_abort_transaction(trans, ret);
4147 * If we are in a rename context, we don't need to update anything in the
4148 * log. That will be done later during the rename by btrfs_log_new_name().
4149 * Besides that, doing it here would only cause extra unncessary btree
4150 * operations on the log tree, increasing latency for applications.
4153 btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4155 btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4160 * If we have a pending delayed iput we could end up with the final iput
4161 * being run in btrfs-cleaner context. If we have enough of these built
4162 * up we can end up burning a lot of time in btrfs-cleaner without any
4163 * way to throttle the unlinks. Since we're currently holding a ref on
4164 * the inode we can run the delayed iput here without any issues as the
4165 * final iput won't be done until after we drop the ref we're currently
4168 btrfs_run_delayed_iput(fs_info, inode);
4170 btrfs_free_path(path);
4174 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4175 inode_inc_iversion(&inode->vfs_inode);
4176 inode_inc_iversion(&dir->vfs_inode);
4177 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4178 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4179 ret = btrfs_update_inode(trans, root, dir);
4184 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4185 struct btrfs_inode *dir, struct btrfs_inode *inode,
4186 const char *name, int name_len)
4189 ret = __btrfs_unlink_inode(trans, dir, inode, name, name_len, NULL);
4191 drop_nlink(&inode->vfs_inode);
4192 ret = btrfs_update_inode(trans, inode->root, inode);
4198 * helper to start transaction for unlink and rmdir.
4200 * unlink and rmdir are special in btrfs, they do not always free space, so
4201 * if we cannot make our reservations the normal way try and see if there is
4202 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4203 * allow the unlink to occur.
4205 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4207 struct btrfs_root *root = BTRFS_I(dir)->root;
4210 * 1 for the possible orphan item
4211 * 1 for the dir item
4212 * 1 for the dir index
4213 * 1 for the inode ref
4216 return btrfs_start_transaction_fallback_global_rsv(root, 5);
4219 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4221 struct btrfs_trans_handle *trans;
4222 struct inode *inode = d_inode(dentry);
4225 trans = __unlink_start_trans(dir);
4227 return PTR_ERR(trans);
4229 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4232 ret = btrfs_unlink_inode(trans, BTRFS_I(dir),
4233 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4234 dentry->d_name.len);
4238 if (inode->i_nlink == 0) {
4239 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4245 btrfs_end_transaction(trans);
4246 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4250 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4251 struct inode *dir, struct dentry *dentry)
4253 struct btrfs_root *root = BTRFS_I(dir)->root;
4254 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4255 struct btrfs_path *path;
4256 struct extent_buffer *leaf;
4257 struct btrfs_dir_item *di;
4258 struct btrfs_key key;
4259 const char *name = dentry->d_name.name;
4260 int name_len = dentry->d_name.len;
4264 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4266 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4267 objectid = inode->root->root_key.objectid;
4268 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4269 objectid = inode->location.objectid;
4275 path = btrfs_alloc_path();
4279 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4280 name, name_len, -1);
4281 if (IS_ERR_OR_NULL(di)) {
4282 ret = di ? PTR_ERR(di) : -ENOENT;
4286 leaf = path->nodes[0];
4287 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4288 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4289 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4291 btrfs_abort_transaction(trans, ret);
4294 btrfs_release_path(path);
4297 * This is a placeholder inode for a subvolume we didn't have a
4298 * reference to at the time of the snapshot creation. In the meantime
4299 * we could have renamed the real subvol link into our snapshot, so
4300 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4301 * Instead simply lookup the dir_index_item for this entry so we can
4302 * remove it. Otherwise we know we have a ref to the root and we can
4303 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4305 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4306 di = btrfs_search_dir_index_item(root, path, dir_ino,
4308 if (IS_ERR_OR_NULL(di)) {
4313 btrfs_abort_transaction(trans, ret);
4317 leaf = path->nodes[0];
4318 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4320 btrfs_release_path(path);
4322 ret = btrfs_del_root_ref(trans, objectid,
4323 root->root_key.objectid, dir_ino,
4324 &index, name, name_len);
4326 btrfs_abort_transaction(trans, ret);
4331 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4333 btrfs_abort_transaction(trans, ret);
4337 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4338 inode_inc_iversion(dir);
4339 dir->i_mtime = dir->i_ctime = current_time(dir);
4340 ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4342 btrfs_abort_transaction(trans, ret);
4344 btrfs_free_path(path);
4349 * Helper to check if the subvolume references other subvolumes or if it's
4352 static noinline int may_destroy_subvol(struct btrfs_root *root)
4354 struct btrfs_fs_info *fs_info = root->fs_info;
4355 struct btrfs_path *path;
4356 struct btrfs_dir_item *di;
4357 struct btrfs_key key;
4361 path = btrfs_alloc_path();
4365 /* Make sure this root isn't set as the default subvol */
4366 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4367 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4368 dir_id, "default", 7, 0);
4369 if (di && !IS_ERR(di)) {
4370 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4371 if (key.objectid == root->root_key.objectid) {
4374 "deleting default subvolume %llu is not allowed",
4378 btrfs_release_path(path);
4381 key.objectid = root->root_key.objectid;
4382 key.type = BTRFS_ROOT_REF_KEY;
4383 key.offset = (u64)-1;
4385 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4391 if (path->slots[0] > 0) {
4393 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4394 if (key.objectid == root->root_key.objectid &&
4395 key.type == BTRFS_ROOT_REF_KEY)
4399 btrfs_free_path(path);
4403 /* Delete all dentries for inodes belonging to the root */
4404 static void btrfs_prune_dentries(struct btrfs_root *root)
4406 struct btrfs_fs_info *fs_info = root->fs_info;
4407 struct rb_node *node;
4408 struct rb_node *prev;
4409 struct btrfs_inode *entry;
4410 struct inode *inode;
4413 if (!BTRFS_FS_ERROR(fs_info))
4414 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4416 spin_lock(&root->inode_lock);
4418 node = root->inode_tree.rb_node;
4422 entry = rb_entry(node, struct btrfs_inode, rb_node);
4424 if (objectid < btrfs_ino(entry))
4425 node = node->rb_left;
4426 else if (objectid > btrfs_ino(entry))
4427 node = node->rb_right;
4433 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4434 if (objectid <= btrfs_ino(entry)) {
4438 prev = rb_next(prev);
4442 entry = rb_entry(node, struct btrfs_inode, rb_node);
4443 objectid = btrfs_ino(entry) + 1;
4444 inode = igrab(&entry->vfs_inode);
4446 spin_unlock(&root->inode_lock);
4447 if (atomic_read(&inode->i_count) > 1)
4448 d_prune_aliases(inode);
4450 * btrfs_drop_inode will have it removed from the inode
4451 * cache when its usage count hits zero.
4455 spin_lock(&root->inode_lock);
4459 if (cond_resched_lock(&root->inode_lock))
4462 node = rb_next(node);
4464 spin_unlock(&root->inode_lock);
4467 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4469 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4470 struct btrfs_root *root = BTRFS_I(dir)->root;
4471 struct inode *inode = d_inode(dentry);
4472 struct btrfs_root *dest = BTRFS_I(inode)->root;
4473 struct btrfs_trans_handle *trans;
4474 struct btrfs_block_rsv block_rsv;
4479 * Don't allow to delete a subvolume with send in progress. This is
4480 * inside the inode lock so the error handling that has to drop the bit
4481 * again is not run concurrently.
4483 spin_lock(&dest->root_item_lock);
4484 if (dest->send_in_progress) {
4485 spin_unlock(&dest->root_item_lock);
4487 "attempt to delete subvolume %llu during send",
4488 dest->root_key.objectid);
4491 root_flags = btrfs_root_flags(&dest->root_item);
4492 btrfs_set_root_flags(&dest->root_item,
4493 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4494 spin_unlock(&dest->root_item_lock);
4496 down_write(&fs_info->subvol_sem);
4498 ret = may_destroy_subvol(dest);
4502 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4504 * One for dir inode,
4505 * two for dir entries,
4506 * two for root ref/backref.
4508 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4512 trans = btrfs_start_transaction(root, 0);
4513 if (IS_ERR(trans)) {
4514 ret = PTR_ERR(trans);
4517 trans->block_rsv = &block_rsv;
4518 trans->bytes_reserved = block_rsv.size;
4520 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4522 ret = btrfs_unlink_subvol(trans, dir, dentry);
4524 btrfs_abort_transaction(trans, ret);
4528 ret = btrfs_record_root_in_trans(trans, dest);
4530 btrfs_abort_transaction(trans, ret);
4534 memset(&dest->root_item.drop_progress, 0,
4535 sizeof(dest->root_item.drop_progress));
4536 btrfs_set_root_drop_level(&dest->root_item, 0);
4537 btrfs_set_root_refs(&dest->root_item, 0);
4539 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4540 ret = btrfs_insert_orphan_item(trans,
4542 dest->root_key.objectid);
4544 btrfs_abort_transaction(trans, ret);
4549 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4550 BTRFS_UUID_KEY_SUBVOL,
4551 dest->root_key.objectid);
4552 if (ret && ret != -ENOENT) {
4553 btrfs_abort_transaction(trans, ret);
4556 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4557 ret = btrfs_uuid_tree_remove(trans,
4558 dest->root_item.received_uuid,
4559 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4560 dest->root_key.objectid);
4561 if (ret && ret != -ENOENT) {
4562 btrfs_abort_transaction(trans, ret);
4567 free_anon_bdev(dest->anon_dev);
4570 trans->block_rsv = NULL;
4571 trans->bytes_reserved = 0;
4572 ret = btrfs_end_transaction(trans);
4573 inode->i_flags |= S_DEAD;
4575 btrfs_subvolume_release_metadata(root, &block_rsv);
4577 up_write(&fs_info->subvol_sem);
4579 spin_lock(&dest->root_item_lock);
4580 root_flags = btrfs_root_flags(&dest->root_item);
4581 btrfs_set_root_flags(&dest->root_item,
4582 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4583 spin_unlock(&dest->root_item_lock);
4585 d_invalidate(dentry);
4586 btrfs_prune_dentries(dest);
4587 ASSERT(dest->send_in_progress == 0);
4593 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4595 struct inode *inode = d_inode(dentry);
4596 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
4598 struct btrfs_trans_handle *trans;
4599 u64 last_unlink_trans;
4601 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4603 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
4604 if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4606 "extent tree v2 doesn't support snapshot deletion yet");
4609 return btrfs_delete_subvolume(dir, dentry);
4612 trans = __unlink_start_trans(dir);
4614 return PTR_ERR(trans);
4616 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4617 err = btrfs_unlink_subvol(trans, dir, dentry);
4621 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4625 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4627 /* now the directory is empty */
4628 err = btrfs_unlink_inode(trans, BTRFS_I(dir),
4629 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4630 dentry->d_name.len);
4632 btrfs_i_size_write(BTRFS_I(inode), 0);
4634 * Propagate the last_unlink_trans value of the deleted dir to
4635 * its parent directory. This is to prevent an unrecoverable
4636 * log tree in the case we do something like this:
4638 * 2) create snapshot under dir foo
4639 * 3) delete the snapshot
4642 * 6) fsync foo or some file inside foo
4644 if (last_unlink_trans >= trans->transid)
4645 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4648 btrfs_end_transaction(trans);
4649 btrfs_btree_balance_dirty(fs_info);
4655 * btrfs_truncate_block - read, zero a chunk and write a block
4656 * @inode - inode that we're zeroing
4657 * @from - the offset to start zeroing
4658 * @len - the length to zero, 0 to zero the entire range respective to the
4660 * @front - zero up to the offset instead of from the offset on
4662 * This will find the block for the "from" offset and cow the block and zero the
4663 * part we want to zero. This is used with truncate and hole punching.
4665 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4668 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4669 struct address_space *mapping = inode->vfs_inode.i_mapping;
4670 struct extent_io_tree *io_tree = &inode->io_tree;
4671 struct btrfs_ordered_extent *ordered;
4672 struct extent_state *cached_state = NULL;
4673 struct extent_changeset *data_reserved = NULL;
4674 bool only_release_metadata = false;
4675 u32 blocksize = fs_info->sectorsize;
4676 pgoff_t index = from >> PAGE_SHIFT;
4677 unsigned offset = from & (blocksize - 1);
4679 gfp_t mask = btrfs_alloc_write_mask(mapping);
4680 size_t write_bytes = blocksize;
4685 if (IS_ALIGNED(offset, blocksize) &&
4686 (!len || IS_ALIGNED(len, blocksize)))
4689 block_start = round_down(from, blocksize);
4690 block_end = block_start + blocksize - 1;
4692 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4695 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
4696 /* For nocow case, no need to reserve data space */
4697 only_release_metadata = true;
4702 ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize);
4704 if (!only_release_metadata)
4705 btrfs_free_reserved_data_space(inode, data_reserved,
4706 block_start, blocksize);
4710 page = find_or_create_page(mapping, index, mask);
4712 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4714 btrfs_delalloc_release_extents(inode, blocksize);
4718 ret = set_page_extent_mapped(page);
4722 if (!PageUptodate(page)) {
4723 ret = btrfs_readpage(NULL, page);
4725 if (page->mapping != mapping) {
4730 if (!PageUptodate(page)) {
4735 wait_on_page_writeback(page);
4737 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4739 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4741 unlock_extent_cached(io_tree, block_start, block_end,
4745 btrfs_start_ordered_extent(ordered, 1);
4746 btrfs_put_ordered_extent(ordered);
4750 clear_extent_bit(&inode->io_tree, block_start, block_end,
4751 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4752 0, 0, &cached_state);
4754 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4757 unlock_extent_cached(io_tree, block_start, block_end,
4762 if (offset != blocksize) {
4764 len = blocksize - offset;
4766 memzero_page(page, (block_start - page_offset(page)),
4769 memzero_page(page, (block_start - page_offset(page)) + offset,
4771 flush_dcache_page(page);
4773 btrfs_page_clear_checked(fs_info, page, block_start,
4774 block_end + 1 - block_start);
4775 btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
4776 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4778 if (only_release_metadata)
4779 set_extent_bit(&inode->io_tree, block_start, block_end,
4780 EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
4784 if (only_release_metadata)
4785 btrfs_delalloc_release_metadata(inode, blocksize, true);
4787 btrfs_delalloc_release_space(inode, data_reserved,
4788 block_start, blocksize, true);
4790 btrfs_delalloc_release_extents(inode, blocksize);
4794 if (only_release_metadata)
4795 btrfs_check_nocow_unlock(inode);
4796 extent_changeset_free(data_reserved);
4800 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4801 u64 offset, u64 len)
4803 struct btrfs_fs_info *fs_info = root->fs_info;
4804 struct btrfs_trans_handle *trans;
4805 struct btrfs_drop_extents_args drop_args = { 0 };
4809 * If NO_HOLES is enabled, we don't need to do anything.
4810 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
4811 * or btrfs_update_inode() will be called, which guarantee that the next
4812 * fsync will know this inode was changed and needs to be logged.
4814 if (btrfs_fs_incompat(fs_info, NO_HOLES))
4818 * 1 - for the one we're dropping
4819 * 1 - for the one we're adding
4820 * 1 - for updating the inode.
4822 trans = btrfs_start_transaction(root, 3);
4824 return PTR_ERR(trans);
4826 drop_args.start = offset;
4827 drop_args.end = offset + len;
4828 drop_args.drop_cache = true;
4830 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4832 btrfs_abort_transaction(trans, ret);
4833 btrfs_end_transaction(trans);
4837 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
4838 offset, 0, 0, len, 0, len, 0, 0, 0);
4840 btrfs_abort_transaction(trans, ret);
4842 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
4843 btrfs_update_inode(trans, root, inode);
4845 btrfs_end_transaction(trans);
4850 * This function puts in dummy file extents for the area we're creating a hole
4851 * for. So if we are truncating this file to a larger size we need to insert
4852 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4853 * the range between oldsize and size
4855 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
4857 struct btrfs_root *root = inode->root;
4858 struct btrfs_fs_info *fs_info = root->fs_info;
4859 struct extent_io_tree *io_tree = &inode->io_tree;
4860 struct extent_map *em = NULL;
4861 struct extent_state *cached_state = NULL;
4862 struct extent_map_tree *em_tree = &inode->extent_tree;
4863 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4864 u64 block_end = ALIGN(size, fs_info->sectorsize);
4871 * If our size started in the middle of a block we need to zero out the
4872 * rest of the block before we expand the i_size, otherwise we could
4873 * expose stale data.
4875 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4879 if (size <= hole_start)
4882 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
4884 cur_offset = hole_start;
4886 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4887 block_end - cur_offset);
4893 last_byte = min(extent_map_end(em), block_end);
4894 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4895 hole_size = last_byte - cur_offset;
4897 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4898 struct extent_map *hole_em;
4900 err = maybe_insert_hole(root, inode, cur_offset,
4905 err = btrfs_inode_set_file_extent_range(inode,
4906 cur_offset, hole_size);
4910 btrfs_drop_extent_cache(inode, cur_offset,
4911 cur_offset + hole_size - 1, 0);
4912 hole_em = alloc_extent_map();
4914 btrfs_set_inode_full_sync(inode);
4917 hole_em->start = cur_offset;
4918 hole_em->len = hole_size;
4919 hole_em->orig_start = cur_offset;
4921 hole_em->block_start = EXTENT_MAP_HOLE;
4922 hole_em->block_len = 0;
4923 hole_em->orig_block_len = 0;
4924 hole_em->ram_bytes = hole_size;
4925 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4926 hole_em->generation = fs_info->generation;
4929 write_lock(&em_tree->lock);
4930 err = add_extent_mapping(em_tree, hole_em, 1);
4931 write_unlock(&em_tree->lock);
4934 btrfs_drop_extent_cache(inode, cur_offset,
4938 free_extent_map(hole_em);
4940 err = btrfs_inode_set_file_extent_range(inode,
4941 cur_offset, hole_size);
4946 free_extent_map(em);
4948 cur_offset = last_byte;
4949 if (cur_offset >= block_end)
4952 free_extent_map(em);
4953 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4957 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4959 struct btrfs_root *root = BTRFS_I(inode)->root;
4960 struct btrfs_trans_handle *trans;
4961 loff_t oldsize = i_size_read(inode);
4962 loff_t newsize = attr->ia_size;
4963 int mask = attr->ia_valid;
4967 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4968 * special case where we need to update the times despite not having
4969 * these flags set. For all other operations the VFS set these flags
4970 * explicitly if it wants a timestamp update.
4972 if (newsize != oldsize) {
4973 inode_inc_iversion(inode);
4974 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4975 inode->i_ctime = inode->i_mtime =
4976 current_time(inode);
4979 if (newsize > oldsize) {
4981 * Don't do an expanding truncate while snapshotting is ongoing.
4982 * This is to ensure the snapshot captures a fully consistent
4983 * state of this file - if the snapshot captures this expanding
4984 * truncation, it must capture all writes that happened before
4987 btrfs_drew_write_lock(&root->snapshot_lock);
4988 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
4990 btrfs_drew_write_unlock(&root->snapshot_lock);
4994 trans = btrfs_start_transaction(root, 1);
4995 if (IS_ERR(trans)) {
4996 btrfs_drew_write_unlock(&root->snapshot_lock);
4997 return PTR_ERR(trans);
5000 i_size_write(inode, newsize);
5001 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5002 pagecache_isize_extended(inode, oldsize, newsize);
5003 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5004 btrfs_drew_write_unlock(&root->snapshot_lock);
5005 btrfs_end_transaction(trans);
5007 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5009 if (btrfs_is_zoned(fs_info)) {
5010 ret = btrfs_wait_ordered_range(inode,
5011 ALIGN(newsize, fs_info->sectorsize),
5018 * We're truncating a file that used to have good data down to
5019 * zero. Make sure any new writes to the file get on disk
5023 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5024 &BTRFS_I(inode)->runtime_flags);
5026 truncate_setsize(inode, newsize);
5028 inode_dio_wait(inode);
5030 ret = btrfs_truncate(inode, newsize == oldsize);
5031 if (ret && inode->i_nlink) {
5035 * Truncate failed, so fix up the in-memory size. We
5036 * adjusted disk_i_size down as we removed extents, so
5037 * wait for disk_i_size to be stable and then update the
5038 * in-memory size to match.
5040 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5043 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5050 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5053 struct inode *inode = d_inode(dentry);
5054 struct btrfs_root *root = BTRFS_I(inode)->root;
5057 if (btrfs_root_readonly(root))
5060 err = setattr_prepare(mnt_userns, dentry, attr);
5064 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5065 err = btrfs_setsize(inode, attr);
5070 if (attr->ia_valid) {
5071 setattr_copy(mnt_userns, inode, attr);
5072 inode_inc_iversion(inode);
5073 err = btrfs_dirty_inode(inode);
5075 if (!err && attr->ia_valid & ATTR_MODE)
5076 err = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5083 * While truncating the inode pages during eviction, we get the VFS
5084 * calling btrfs_invalidate_folio() against each folio of the inode. This
5085 * is slow because the calls to btrfs_invalidate_folio() result in a
5086 * huge amount of calls to lock_extent_bits() and clear_extent_bit(),
5087 * which keep merging and splitting extent_state structures over and over,
5088 * wasting lots of time.
5090 * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5091 * skip all those expensive operations on a per folio basis and do only
5092 * the ordered io finishing, while we release here the extent_map and
5093 * extent_state structures, without the excessive merging and splitting.
5095 static void evict_inode_truncate_pages(struct inode *inode)
5097 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5098 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5099 struct rb_node *node;
5101 ASSERT(inode->i_state & I_FREEING);
5102 truncate_inode_pages_final(&inode->i_data);
5104 write_lock(&map_tree->lock);
5105 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5106 struct extent_map *em;
5108 node = rb_first_cached(&map_tree->map);
5109 em = rb_entry(node, struct extent_map, rb_node);
5110 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5111 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5112 remove_extent_mapping(map_tree, em);
5113 free_extent_map(em);
5114 if (need_resched()) {
5115 write_unlock(&map_tree->lock);
5117 write_lock(&map_tree->lock);
5120 write_unlock(&map_tree->lock);
5123 * Keep looping until we have no more ranges in the io tree.
5124 * We can have ongoing bios started by readahead that have
5125 * their endio callback (extent_io.c:end_bio_extent_readpage)
5126 * still in progress (unlocked the pages in the bio but did not yet
5127 * unlocked the ranges in the io tree). Therefore this means some
5128 * ranges can still be locked and eviction started because before
5129 * submitting those bios, which are executed by a separate task (work
5130 * queue kthread), inode references (inode->i_count) were not taken
5131 * (which would be dropped in the end io callback of each bio).
5132 * Therefore here we effectively end up waiting for those bios and
5133 * anyone else holding locked ranges without having bumped the inode's
5134 * reference count - if we don't do it, when they access the inode's
5135 * io_tree to unlock a range it may be too late, leading to an
5136 * use-after-free issue.
5138 spin_lock(&io_tree->lock);
5139 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5140 struct extent_state *state;
5141 struct extent_state *cached_state = NULL;
5144 unsigned state_flags;
5146 node = rb_first(&io_tree->state);
5147 state = rb_entry(node, struct extent_state, rb_node);
5148 start = state->start;
5150 state_flags = state->state;
5151 spin_unlock(&io_tree->lock);
5153 lock_extent_bits(io_tree, start, end, &cached_state);
5156 * If still has DELALLOC flag, the extent didn't reach disk,
5157 * and its reserved space won't be freed by delayed_ref.
5158 * So we need to free its reserved space here.
5159 * (Refer to comment in btrfs_invalidate_folio, case 2)
5161 * Note, end is the bytenr of last byte, so we need + 1 here.
5163 if (state_flags & EXTENT_DELALLOC)
5164 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5167 clear_extent_bit(io_tree, start, end,
5168 EXTENT_LOCKED | EXTENT_DELALLOC |
5169 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5173 spin_lock(&io_tree->lock);
5175 spin_unlock(&io_tree->lock);
5178 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5179 struct btrfs_block_rsv *rsv)
5181 struct btrfs_fs_info *fs_info = root->fs_info;
5182 struct btrfs_trans_handle *trans;
5183 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5187 * Eviction should be taking place at some place safe because of our
5188 * delayed iputs. However the normal flushing code will run delayed
5189 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5191 * We reserve the delayed_refs_extra here again because we can't use
5192 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5193 * above. We reserve our extra bit here because we generate a ton of
5194 * delayed refs activity by truncating.
5196 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5197 * if we fail to make this reservation we can re-try without the
5198 * delayed_refs_extra so we can make some forward progress.
5200 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5201 BTRFS_RESERVE_FLUSH_EVICT);
5203 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5204 BTRFS_RESERVE_FLUSH_EVICT);
5207 "could not allocate space for delete; will truncate on mount");
5208 return ERR_PTR(-ENOSPC);
5210 delayed_refs_extra = 0;
5213 trans = btrfs_join_transaction(root);
5217 if (delayed_refs_extra) {
5218 trans->block_rsv = &fs_info->trans_block_rsv;
5219 trans->bytes_reserved = delayed_refs_extra;
5220 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5221 delayed_refs_extra, 1);
5226 void btrfs_evict_inode(struct inode *inode)
5228 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5229 struct btrfs_trans_handle *trans;
5230 struct btrfs_root *root = BTRFS_I(inode)->root;
5231 struct btrfs_block_rsv *rsv;
5234 trace_btrfs_inode_evict(inode);
5237 fsverity_cleanup_inode(inode);
5242 evict_inode_truncate_pages(inode);
5244 if (inode->i_nlink &&
5245 ((btrfs_root_refs(&root->root_item) != 0 &&
5246 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5247 btrfs_is_free_space_inode(BTRFS_I(inode))))
5250 if (is_bad_inode(inode))
5253 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5255 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5258 if (inode->i_nlink > 0) {
5259 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5260 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5265 * This makes sure the inode item in tree is uptodate and the space for
5266 * the inode update is released.
5268 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5273 * This drops any pending insert or delete operations we have for this
5274 * inode. We could have a delayed dir index deletion queued up, but
5275 * we're removing the inode completely so that'll be taken care of in
5278 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5280 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5283 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5286 btrfs_i_size_write(BTRFS_I(inode), 0);
5289 struct btrfs_truncate_control control = {
5290 .inode = BTRFS_I(inode),
5291 .ino = btrfs_ino(BTRFS_I(inode)),
5296 trans = evict_refill_and_join(root, rsv);
5300 trans->block_rsv = rsv;
5302 ret = btrfs_truncate_inode_items(trans, root, &control);
5303 trans->block_rsv = &fs_info->trans_block_rsv;
5304 btrfs_end_transaction(trans);
5305 btrfs_btree_balance_dirty(fs_info);
5306 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5313 * Errors here aren't a big deal, it just means we leave orphan items in
5314 * the tree. They will be cleaned up on the next mount. If the inode
5315 * number gets reused, cleanup deletes the orphan item without doing
5316 * anything, and unlink reuses the existing orphan item.
5318 * If it turns out that we are dropping too many of these, we might want
5319 * to add a mechanism for retrying these after a commit.
5321 trans = evict_refill_and_join(root, rsv);
5322 if (!IS_ERR(trans)) {
5323 trans->block_rsv = rsv;
5324 btrfs_orphan_del(trans, BTRFS_I(inode));
5325 trans->block_rsv = &fs_info->trans_block_rsv;
5326 btrfs_end_transaction(trans);
5330 btrfs_free_block_rsv(fs_info, rsv);
5333 * If we didn't successfully delete, the orphan item will still be in
5334 * the tree and we'll retry on the next mount. Again, we might also want
5335 * to retry these periodically in the future.
5337 btrfs_remove_delayed_node(BTRFS_I(inode));
5338 fsverity_cleanup_inode(inode);
5343 * Return the key found in the dir entry in the location pointer, fill @type
5344 * with BTRFS_FT_*, and return 0.
5346 * If no dir entries were found, returns -ENOENT.
5347 * If found a corrupted location in dir entry, returns -EUCLEAN.
5349 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5350 struct btrfs_key *location, u8 *type)
5352 const char *name = dentry->d_name.name;
5353 int namelen = dentry->d_name.len;
5354 struct btrfs_dir_item *di;
5355 struct btrfs_path *path;
5356 struct btrfs_root *root = BTRFS_I(dir)->root;
5359 path = btrfs_alloc_path();
5363 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5365 if (IS_ERR_OR_NULL(di)) {
5366 ret = di ? PTR_ERR(di) : -ENOENT;
5370 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5371 if (location->type != BTRFS_INODE_ITEM_KEY &&
5372 location->type != BTRFS_ROOT_ITEM_KEY) {
5374 btrfs_warn(root->fs_info,
5375 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5376 __func__, name, btrfs_ino(BTRFS_I(dir)),
5377 location->objectid, location->type, location->offset);
5380 *type = btrfs_dir_type(path->nodes[0], di);
5382 btrfs_free_path(path);
5387 * when we hit a tree root in a directory, the btrfs part of the inode
5388 * needs to be changed to reflect the root directory of the tree root. This
5389 * is kind of like crossing a mount point.
5391 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5393 struct dentry *dentry,
5394 struct btrfs_key *location,
5395 struct btrfs_root **sub_root)
5397 struct btrfs_path *path;
5398 struct btrfs_root *new_root;
5399 struct btrfs_root_ref *ref;
5400 struct extent_buffer *leaf;
5401 struct btrfs_key key;
5405 path = btrfs_alloc_path();
5412 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5413 key.type = BTRFS_ROOT_REF_KEY;
5414 key.offset = location->objectid;
5416 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5423 leaf = path->nodes[0];
5424 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5425 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5426 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5429 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5430 (unsigned long)(ref + 1),
5431 dentry->d_name.len);
5435 btrfs_release_path(path);
5437 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5438 if (IS_ERR(new_root)) {
5439 err = PTR_ERR(new_root);
5443 *sub_root = new_root;
5444 location->objectid = btrfs_root_dirid(&new_root->root_item);
5445 location->type = BTRFS_INODE_ITEM_KEY;
5446 location->offset = 0;
5449 btrfs_free_path(path);
5453 static void inode_tree_add(struct inode *inode)
5455 struct btrfs_root *root = BTRFS_I(inode)->root;
5456 struct btrfs_inode *entry;
5458 struct rb_node *parent;
5459 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5460 u64 ino = btrfs_ino(BTRFS_I(inode));
5462 if (inode_unhashed(inode))
5465 spin_lock(&root->inode_lock);
5466 p = &root->inode_tree.rb_node;
5469 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5471 if (ino < btrfs_ino(entry))
5472 p = &parent->rb_left;
5473 else if (ino > btrfs_ino(entry))
5474 p = &parent->rb_right;
5476 WARN_ON(!(entry->vfs_inode.i_state &
5477 (I_WILL_FREE | I_FREEING)));
5478 rb_replace_node(parent, new, &root->inode_tree);
5479 RB_CLEAR_NODE(parent);
5480 spin_unlock(&root->inode_lock);
5484 rb_link_node(new, parent, p);
5485 rb_insert_color(new, &root->inode_tree);
5486 spin_unlock(&root->inode_lock);
5489 static void inode_tree_del(struct btrfs_inode *inode)
5491 struct btrfs_root *root = inode->root;
5494 spin_lock(&root->inode_lock);
5495 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5496 rb_erase(&inode->rb_node, &root->inode_tree);
5497 RB_CLEAR_NODE(&inode->rb_node);
5498 empty = RB_EMPTY_ROOT(&root->inode_tree);
5500 spin_unlock(&root->inode_lock);
5502 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5503 spin_lock(&root->inode_lock);
5504 empty = RB_EMPTY_ROOT(&root->inode_tree);
5505 spin_unlock(&root->inode_lock);
5507 btrfs_add_dead_root(root);
5512 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5514 struct btrfs_iget_args *args = p;
5516 inode->i_ino = args->ino;
5517 BTRFS_I(inode)->location.objectid = args->ino;
5518 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5519 BTRFS_I(inode)->location.offset = 0;
5520 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5521 BUG_ON(args->root && !BTRFS_I(inode)->root);
5525 static int btrfs_find_actor(struct inode *inode, void *opaque)
5527 struct btrfs_iget_args *args = opaque;
5529 return args->ino == BTRFS_I(inode)->location.objectid &&
5530 args->root == BTRFS_I(inode)->root;
5533 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5534 struct btrfs_root *root)
5536 struct inode *inode;
5537 struct btrfs_iget_args args;
5538 unsigned long hashval = btrfs_inode_hash(ino, root);
5543 inode = iget5_locked(s, hashval, btrfs_find_actor,
5544 btrfs_init_locked_inode,
5550 * Get an inode object given its inode number and corresponding root.
5551 * Path can be preallocated to prevent recursing back to iget through
5552 * allocator. NULL is also valid but may require an additional allocation
5555 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5556 struct btrfs_root *root, struct btrfs_path *path)
5558 struct inode *inode;
5560 inode = btrfs_iget_locked(s, ino, root);
5562 return ERR_PTR(-ENOMEM);
5564 if (inode->i_state & I_NEW) {
5567 ret = btrfs_read_locked_inode(inode, path);
5569 inode_tree_add(inode);
5570 unlock_new_inode(inode);
5574 * ret > 0 can come from btrfs_search_slot called by
5575 * btrfs_read_locked_inode, this means the inode item
5580 inode = ERR_PTR(ret);
5587 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5589 return btrfs_iget_path(s, ino, root, NULL);
5592 static struct inode *new_simple_dir(struct super_block *s,
5593 struct btrfs_key *key,
5594 struct btrfs_root *root)
5596 struct inode *inode = new_inode(s);
5599 return ERR_PTR(-ENOMEM);
5601 BTRFS_I(inode)->root = btrfs_grab_root(root);
5602 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5603 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5605 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5607 * We only need lookup, the rest is read-only and there's no inode
5608 * associated with the dentry
5610 inode->i_op = &simple_dir_inode_operations;
5611 inode->i_opflags &= ~IOP_XATTR;
5612 inode->i_fop = &simple_dir_operations;
5613 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5614 inode->i_mtime = current_time(inode);
5615 inode->i_atime = inode->i_mtime;
5616 inode->i_ctime = inode->i_mtime;
5617 BTRFS_I(inode)->i_otime = inode->i_mtime;
5622 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5623 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5624 static_assert(BTRFS_FT_DIR == FT_DIR);
5625 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5626 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5627 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5628 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5629 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5631 static inline u8 btrfs_inode_type(struct inode *inode)
5633 return fs_umode_to_ftype(inode->i_mode);
5636 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5638 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5639 struct inode *inode;
5640 struct btrfs_root *root = BTRFS_I(dir)->root;
5641 struct btrfs_root *sub_root = root;
5642 struct btrfs_key location;
5646 if (dentry->d_name.len > BTRFS_NAME_LEN)
5647 return ERR_PTR(-ENAMETOOLONG);
5649 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5651 return ERR_PTR(ret);
5653 if (location.type == BTRFS_INODE_ITEM_KEY) {
5654 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5658 /* Do extra check against inode mode with di_type */
5659 if (btrfs_inode_type(inode) != di_type) {
5661 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5662 inode->i_mode, btrfs_inode_type(inode),
5665 return ERR_PTR(-EUCLEAN);
5670 ret = fixup_tree_root_location(fs_info, dir, dentry,
5671 &location, &sub_root);
5674 inode = ERR_PTR(ret);
5676 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5678 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5680 if (root != sub_root)
5681 btrfs_put_root(sub_root);
5683 if (!IS_ERR(inode) && root != sub_root) {
5684 down_read(&fs_info->cleanup_work_sem);
5685 if (!sb_rdonly(inode->i_sb))
5686 ret = btrfs_orphan_cleanup(sub_root);
5687 up_read(&fs_info->cleanup_work_sem);
5690 inode = ERR_PTR(ret);
5697 static int btrfs_dentry_delete(const struct dentry *dentry)
5699 struct btrfs_root *root;
5700 struct inode *inode = d_inode(dentry);
5702 if (!inode && !IS_ROOT(dentry))
5703 inode = d_inode(dentry->d_parent);
5706 root = BTRFS_I(inode)->root;
5707 if (btrfs_root_refs(&root->root_item) == 0)
5710 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5716 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5719 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5721 if (inode == ERR_PTR(-ENOENT))
5723 return d_splice_alias(inode, dentry);
5727 * All this infrastructure exists because dir_emit can fault, and we are holding
5728 * the tree lock when doing readdir. For now just allocate a buffer and copy
5729 * our information into that, and then dir_emit from the buffer. This is
5730 * similar to what NFS does, only we don't keep the buffer around in pagecache
5731 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5732 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5735 static int btrfs_opendir(struct inode *inode, struct file *file)
5737 struct btrfs_file_private *private;
5739 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5742 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5743 if (!private->filldir_buf) {
5747 file->private_data = private;
5758 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5761 struct dir_entry *entry = addr;
5762 char *name = (char *)(entry + 1);
5764 ctx->pos = get_unaligned(&entry->offset);
5765 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5766 get_unaligned(&entry->ino),
5767 get_unaligned(&entry->type)))
5769 addr += sizeof(struct dir_entry) +
5770 get_unaligned(&entry->name_len);
5776 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5778 struct inode *inode = file_inode(file);
5779 struct btrfs_root *root = BTRFS_I(inode)->root;
5780 struct btrfs_file_private *private = file->private_data;
5781 struct btrfs_dir_item *di;
5782 struct btrfs_key key;
5783 struct btrfs_key found_key;
5784 struct btrfs_path *path;
5786 struct list_head ins_list;
5787 struct list_head del_list;
5789 struct extent_buffer *leaf;
5796 struct btrfs_key location;
5798 if (!dir_emit_dots(file, ctx))
5801 path = btrfs_alloc_path();
5805 addr = private->filldir_buf;
5806 path->reada = READA_FORWARD;
5808 INIT_LIST_HEAD(&ins_list);
5809 INIT_LIST_HEAD(&del_list);
5810 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5813 key.type = BTRFS_DIR_INDEX_KEY;
5814 key.offset = ctx->pos;
5815 key.objectid = btrfs_ino(BTRFS_I(inode));
5817 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5822 struct dir_entry *entry;
5824 leaf = path->nodes[0];
5825 slot = path->slots[0];
5826 if (slot >= btrfs_header_nritems(leaf)) {
5827 ret = btrfs_next_leaf(root, path);
5835 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5837 if (found_key.objectid != key.objectid)
5839 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5841 if (found_key.offset < ctx->pos)
5843 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5845 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5846 name_len = btrfs_dir_name_len(leaf, di);
5847 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5849 btrfs_release_path(path);
5850 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5853 addr = private->filldir_buf;
5860 put_unaligned(name_len, &entry->name_len);
5861 name_ptr = (char *)(entry + 1);
5862 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5864 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5866 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5867 put_unaligned(location.objectid, &entry->ino);
5868 put_unaligned(found_key.offset, &entry->offset);
5870 addr += sizeof(struct dir_entry) + name_len;
5871 total_len += sizeof(struct dir_entry) + name_len;
5875 btrfs_release_path(path);
5877 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5881 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5886 * Stop new entries from being returned after we return the last
5889 * New directory entries are assigned a strictly increasing
5890 * offset. This means that new entries created during readdir
5891 * are *guaranteed* to be seen in the future by that readdir.
5892 * This has broken buggy programs which operate on names as
5893 * they're returned by readdir. Until we re-use freed offsets
5894 * we have this hack to stop new entries from being returned
5895 * under the assumption that they'll never reach this huge
5898 * This is being careful not to overflow 32bit loff_t unless the
5899 * last entry requires it because doing so has broken 32bit apps
5902 if (ctx->pos >= INT_MAX)
5903 ctx->pos = LLONG_MAX;
5910 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5911 btrfs_free_path(path);
5916 * This is somewhat expensive, updating the tree every time the
5917 * inode changes. But, it is most likely to find the inode in cache.
5918 * FIXME, needs more benchmarking...there are no reasons other than performance
5919 * to keep or drop this code.
5921 static int btrfs_dirty_inode(struct inode *inode)
5923 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5924 struct btrfs_root *root = BTRFS_I(inode)->root;
5925 struct btrfs_trans_handle *trans;
5928 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5931 trans = btrfs_join_transaction(root);
5933 return PTR_ERR(trans);
5935 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5936 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
5937 /* whoops, lets try again with the full transaction */
5938 btrfs_end_transaction(trans);
5939 trans = btrfs_start_transaction(root, 1);
5941 return PTR_ERR(trans);
5943 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5945 btrfs_end_transaction(trans);
5946 if (BTRFS_I(inode)->delayed_node)
5947 btrfs_balance_delayed_items(fs_info);
5953 * This is a copy of file_update_time. We need this so we can return error on
5954 * ENOSPC for updating the inode in the case of file write and mmap writes.
5956 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5959 struct btrfs_root *root = BTRFS_I(inode)->root;
5960 bool dirty = flags & ~S_VERSION;
5962 if (btrfs_root_readonly(root))
5965 if (flags & S_VERSION)
5966 dirty |= inode_maybe_inc_iversion(inode, dirty);
5967 if (flags & S_CTIME)
5968 inode->i_ctime = *now;
5969 if (flags & S_MTIME)
5970 inode->i_mtime = *now;
5971 if (flags & S_ATIME)
5972 inode->i_atime = *now;
5973 return dirty ? btrfs_dirty_inode(inode) : 0;
5977 * find the highest existing sequence number in a directory
5978 * and then set the in-memory index_cnt variable to reflect
5979 * free sequence numbers
5981 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5983 struct btrfs_root *root = inode->root;
5984 struct btrfs_key key, found_key;
5985 struct btrfs_path *path;
5986 struct extent_buffer *leaf;
5989 key.objectid = btrfs_ino(inode);
5990 key.type = BTRFS_DIR_INDEX_KEY;
5991 key.offset = (u64)-1;
5993 path = btrfs_alloc_path();
5997 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6000 /* FIXME: we should be able to handle this */
6005 if (path->slots[0] == 0) {
6006 inode->index_cnt = BTRFS_DIR_START_INDEX;
6012 leaf = path->nodes[0];
6013 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6015 if (found_key.objectid != btrfs_ino(inode) ||
6016 found_key.type != BTRFS_DIR_INDEX_KEY) {
6017 inode->index_cnt = BTRFS_DIR_START_INDEX;
6021 inode->index_cnt = found_key.offset + 1;
6023 btrfs_free_path(path);
6028 * helper to find a free sequence number in a given directory. This current
6029 * code is very simple, later versions will do smarter things in the btree
6031 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6035 if (dir->index_cnt == (u64)-1) {
6036 ret = btrfs_inode_delayed_dir_index_count(dir);
6038 ret = btrfs_set_inode_index_count(dir);
6044 *index = dir->index_cnt;
6050 static int btrfs_insert_inode_locked(struct inode *inode)
6052 struct btrfs_iget_args args;
6054 args.ino = BTRFS_I(inode)->location.objectid;
6055 args.root = BTRFS_I(inode)->root;
6057 return insert_inode_locked4(inode,
6058 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6059 btrfs_find_actor, &args);
6063 * Inherit flags from the parent inode.
6065 * Currently only the compression flags and the cow flags are inherited.
6067 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6074 flags = BTRFS_I(dir)->flags;
6076 if (flags & BTRFS_INODE_NOCOMPRESS) {
6077 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6078 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6079 } else if (flags & BTRFS_INODE_COMPRESS) {
6080 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6081 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6084 if (flags & BTRFS_INODE_NODATACOW) {
6085 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6086 if (S_ISREG(inode->i_mode))
6087 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6090 btrfs_sync_inode_flags_to_i_flags(inode);
6093 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6094 struct btrfs_root *root,
6095 struct user_namespace *mnt_userns,
6097 const char *name, int name_len,
6098 u64 ref_objectid, u64 objectid,
6099 umode_t mode, u64 *index)
6101 struct btrfs_fs_info *fs_info = root->fs_info;
6102 struct inode *inode;
6103 struct btrfs_inode_item *inode_item;
6104 struct btrfs_key *location;
6105 struct btrfs_path *path;
6106 struct btrfs_inode_ref *ref;
6107 struct btrfs_key key[2];
6109 struct btrfs_item_batch batch;
6111 unsigned int nofs_flag;
6114 path = btrfs_alloc_path();
6116 return ERR_PTR(-ENOMEM);
6118 nofs_flag = memalloc_nofs_save();
6119 inode = new_inode(fs_info->sb);
6120 memalloc_nofs_restore(nofs_flag);
6122 btrfs_free_path(path);
6123 return ERR_PTR(-ENOMEM);
6127 * O_TMPFILE, set link count to 0, so that after this point,
6128 * we fill in an inode item with the correct link count.
6131 set_nlink(inode, 0);
6134 * we have to initialize this early, so we can reclaim the inode
6135 * number if we fail afterwards in this function.
6137 inode->i_ino = objectid;
6140 trace_btrfs_inode_request(dir);
6142 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6144 btrfs_free_path(path);
6146 return ERR_PTR(ret);
6152 * index_cnt is ignored for everything but a dir,
6153 * btrfs_set_inode_index_count has an explanation for the magic
6156 BTRFS_I(inode)->index_cnt = 2;
6157 BTRFS_I(inode)->dir_index = *index;
6158 BTRFS_I(inode)->root = btrfs_grab_root(root);
6159 BTRFS_I(inode)->generation = trans->transid;
6160 inode->i_generation = BTRFS_I(inode)->generation;
6163 * We could have gotten an inode number from somebody who was fsynced
6164 * and then removed in this same transaction, so let's just set full
6165 * sync since it will be a full sync anyway and this will blow away the
6166 * old info in the log.
6168 btrfs_set_inode_full_sync(BTRFS_I(inode));
6170 key[0].objectid = objectid;
6171 key[0].type = BTRFS_INODE_ITEM_KEY;
6174 sizes[0] = sizeof(struct btrfs_inode_item);
6178 * Start new inodes with an inode_ref. This is slightly more
6179 * efficient for small numbers of hard links since they will
6180 * be packed into one item. Extended refs will kick in if we
6181 * add more hard links than can fit in the ref item.
6183 key[1].objectid = objectid;
6184 key[1].type = BTRFS_INODE_REF_KEY;
6185 key[1].offset = ref_objectid;
6187 sizes[1] = name_len + sizeof(*ref);
6190 location = &BTRFS_I(inode)->location;
6191 location->objectid = objectid;
6192 location->offset = 0;
6193 location->type = BTRFS_INODE_ITEM_KEY;
6195 ret = btrfs_insert_inode_locked(inode);
6201 batch.keys = &key[0];
6202 batch.data_sizes = &sizes[0];
6203 batch.total_data_size = sizes[0] + (name ? sizes[1] : 0);
6204 batch.nr = name ? 2 : 1;
6205 ret = btrfs_insert_empty_items(trans, root, path, &batch);
6209 inode_init_owner(mnt_userns, inode, dir, mode);
6210 inode_set_bytes(inode, 0);
6212 inode->i_mtime = current_time(inode);
6213 inode->i_atime = inode->i_mtime;
6214 inode->i_ctime = inode->i_mtime;
6215 BTRFS_I(inode)->i_otime = inode->i_mtime;
6217 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6218 struct btrfs_inode_item);
6219 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6220 sizeof(*inode_item));
6221 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6224 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6225 struct btrfs_inode_ref);
6226 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6227 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6228 ptr = (unsigned long)(ref + 1);
6229 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6232 btrfs_mark_buffer_dirty(path->nodes[0]);
6233 btrfs_free_path(path);
6235 btrfs_inherit_iflags(inode, dir);
6237 if (S_ISREG(mode)) {
6238 if (btrfs_test_opt(fs_info, NODATASUM))
6239 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6240 if (btrfs_test_opt(fs_info, NODATACOW))
6241 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6242 BTRFS_INODE_NODATASUM;
6245 inode_tree_add(inode);
6247 trace_btrfs_inode_new(inode);
6248 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6250 btrfs_update_root_times(trans, root);
6252 ret = btrfs_inode_inherit_props(trans, inode, dir);
6255 "error inheriting props for ino %llu (root %llu): %d",
6256 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6261 discard_new_inode(inode);
6264 BTRFS_I(dir)->index_cnt--;
6265 btrfs_free_path(path);
6266 return ERR_PTR(ret);
6270 * utility function to add 'inode' into 'parent_inode' with
6271 * a give name and a given sequence number.
6272 * if 'add_backref' is true, also insert a backref from the
6273 * inode to the parent directory.
6275 int btrfs_add_link(struct btrfs_trans_handle *trans,
6276 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6277 const char *name, int name_len, int add_backref, u64 index)
6280 struct btrfs_key key;
6281 struct btrfs_root *root = parent_inode->root;
6282 u64 ino = btrfs_ino(inode);
6283 u64 parent_ino = btrfs_ino(parent_inode);
6285 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6286 memcpy(&key, &inode->root->root_key, sizeof(key));
6289 key.type = BTRFS_INODE_ITEM_KEY;
6293 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6294 ret = btrfs_add_root_ref(trans, key.objectid,
6295 root->root_key.objectid, parent_ino,
6296 index, name, name_len);
6297 } else if (add_backref) {
6298 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6302 /* Nothing to clean up yet */
6306 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6307 btrfs_inode_type(&inode->vfs_inode), index);
6308 if (ret == -EEXIST || ret == -EOVERFLOW)
6311 btrfs_abort_transaction(trans, ret);
6315 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6317 inode_inc_iversion(&parent_inode->vfs_inode);
6319 * If we are replaying a log tree, we do not want to update the mtime
6320 * and ctime of the parent directory with the current time, since the
6321 * log replay procedure is responsible for setting them to their correct
6322 * values (the ones it had when the fsync was done).
6324 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6325 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6327 parent_inode->vfs_inode.i_mtime = now;
6328 parent_inode->vfs_inode.i_ctime = now;
6330 ret = btrfs_update_inode(trans, root, parent_inode);
6332 btrfs_abort_transaction(trans, ret);
6336 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6339 err = btrfs_del_root_ref(trans, key.objectid,
6340 root->root_key.objectid, parent_ino,
6341 &local_index, name, name_len);
6343 btrfs_abort_transaction(trans, err);
6344 } else if (add_backref) {
6348 err = btrfs_del_inode_ref(trans, root, name, name_len,
6349 ino, parent_ino, &local_index);
6351 btrfs_abort_transaction(trans, err);
6354 /* Return the original error code */
6358 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6359 struct btrfs_inode *dir, struct dentry *dentry,
6360 struct btrfs_inode *inode, int backref, u64 index)
6362 int err = btrfs_add_link(trans, dir, inode,
6363 dentry->d_name.name, dentry->d_name.len,
6370 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6371 struct dentry *dentry, umode_t mode, dev_t rdev)
6373 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6374 struct btrfs_trans_handle *trans;
6375 struct btrfs_root *root = BTRFS_I(dir)->root;
6376 struct inode *inode = NULL;
6382 * 2 for inode item and ref
6384 * 1 for xattr if selinux is on
6386 trans = btrfs_start_transaction(root, 5);
6388 return PTR_ERR(trans);
6390 err = btrfs_get_free_objectid(root, &objectid);
6394 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6395 dentry->d_name.name, dentry->d_name.len,
6396 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
6397 if (IS_ERR(inode)) {
6398 err = PTR_ERR(inode);
6404 * If the active LSM wants to access the inode during
6405 * d_instantiate it needs these. Smack checks to see
6406 * if the filesystem supports xattrs by looking at the
6409 inode->i_op = &btrfs_special_inode_operations;
6410 init_special_inode(inode, inode->i_mode, rdev);
6412 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6416 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6421 btrfs_update_inode(trans, root, BTRFS_I(inode));
6422 d_instantiate_new(dentry, inode);
6425 btrfs_end_transaction(trans);
6426 btrfs_btree_balance_dirty(fs_info);
6428 inode_dec_link_count(inode);
6429 discard_new_inode(inode);
6434 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6435 struct dentry *dentry, umode_t mode, bool excl)
6437 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6438 struct btrfs_trans_handle *trans;
6439 struct btrfs_root *root = BTRFS_I(dir)->root;
6440 struct inode *inode = NULL;
6446 * 2 for inode item and ref
6448 * 1 for xattr if selinux is on
6450 trans = btrfs_start_transaction(root, 5);
6452 return PTR_ERR(trans);
6454 err = btrfs_get_free_objectid(root, &objectid);
6458 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6459 dentry->d_name.name, dentry->d_name.len,
6460 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
6461 if (IS_ERR(inode)) {
6462 err = PTR_ERR(inode);
6467 * If the active LSM wants to access the inode during
6468 * d_instantiate it needs these. Smack checks to see
6469 * if the filesystem supports xattrs by looking at the
6472 inode->i_fop = &btrfs_file_operations;
6473 inode->i_op = &btrfs_file_inode_operations;
6474 inode->i_mapping->a_ops = &btrfs_aops;
6476 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6480 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6484 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6489 d_instantiate_new(dentry, inode);
6492 btrfs_end_transaction(trans);
6494 inode_dec_link_count(inode);
6495 discard_new_inode(inode);
6497 btrfs_btree_balance_dirty(fs_info);
6501 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6502 struct dentry *dentry)
6504 struct btrfs_trans_handle *trans = NULL;
6505 struct btrfs_root *root = BTRFS_I(dir)->root;
6506 struct inode *inode = d_inode(old_dentry);
6507 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6512 /* do not allow sys_link's with other subvols of the same device */
6513 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6516 if (inode->i_nlink >= BTRFS_LINK_MAX)
6519 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6524 * 2 items for inode and inode ref
6525 * 2 items for dir items
6526 * 1 item for parent inode
6527 * 1 item for orphan item deletion if O_TMPFILE
6529 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6530 if (IS_ERR(trans)) {
6531 err = PTR_ERR(trans);
6536 /* There are several dir indexes for this inode, clear the cache. */
6537 BTRFS_I(inode)->dir_index = 0ULL;
6539 inode_inc_iversion(inode);
6540 inode->i_ctime = current_time(inode);
6542 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6544 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6550 struct dentry *parent = dentry->d_parent;
6552 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6555 if (inode->i_nlink == 1) {
6557 * If new hard link count is 1, it's a file created
6558 * with open(2) O_TMPFILE flag.
6560 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6564 d_instantiate(dentry, inode);
6565 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6570 btrfs_end_transaction(trans);
6572 inode_dec_link_count(inode);
6575 btrfs_btree_balance_dirty(fs_info);
6579 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6580 struct dentry *dentry, umode_t mode)
6582 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6583 struct inode *inode = NULL;
6584 struct btrfs_trans_handle *trans;
6585 struct btrfs_root *root = BTRFS_I(dir)->root;
6591 * 2 items for inode and ref
6592 * 2 items for dir items
6593 * 1 for xattr if selinux is on
6595 trans = btrfs_start_transaction(root, 5);
6597 return PTR_ERR(trans);
6599 err = btrfs_get_free_objectid(root, &objectid);
6603 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
6604 dentry->d_name.name, dentry->d_name.len,
6605 btrfs_ino(BTRFS_I(dir)), objectid,
6606 S_IFDIR | mode, &index);
6607 if (IS_ERR(inode)) {
6608 err = PTR_ERR(inode);
6613 /* these must be set before we unlock the inode */
6614 inode->i_op = &btrfs_dir_inode_operations;
6615 inode->i_fop = &btrfs_dir_file_operations;
6617 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6621 btrfs_i_size_write(BTRFS_I(inode), 0);
6622 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6626 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6627 dentry->d_name.name,
6628 dentry->d_name.len, 0, index);
6632 d_instantiate_new(dentry, inode);
6635 btrfs_end_transaction(trans);
6637 inode_dec_link_count(inode);
6638 discard_new_inode(inode);
6640 btrfs_btree_balance_dirty(fs_info);
6644 static noinline int uncompress_inline(struct btrfs_path *path,
6646 size_t pg_offset, u64 extent_offset,
6647 struct btrfs_file_extent_item *item)
6650 struct extent_buffer *leaf = path->nodes[0];
6653 unsigned long inline_size;
6657 WARN_ON(pg_offset != 0);
6658 compress_type = btrfs_file_extent_compression(leaf, item);
6659 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6660 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6661 tmp = kmalloc(inline_size, GFP_NOFS);
6664 ptr = btrfs_file_extent_inline_start(item);
6666 read_extent_buffer(leaf, tmp, ptr, inline_size);
6668 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6669 ret = btrfs_decompress(compress_type, tmp, page,
6670 extent_offset, inline_size, max_size);
6673 * decompression code contains a memset to fill in any space between the end
6674 * of the uncompressed data and the end of max_size in case the decompressed
6675 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6676 * the end of an inline extent and the beginning of the next block, so we
6677 * cover that region here.
6680 if (max_size + pg_offset < PAGE_SIZE)
6681 memzero_page(page, pg_offset + max_size,
6682 PAGE_SIZE - max_size - pg_offset);
6688 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6689 * @inode: file to search in
6690 * @page: page to read extent data into if the extent is inline
6691 * @pg_offset: offset into @page to copy to
6692 * @start: file offset
6693 * @len: length of range starting at @start
6695 * This returns the first &struct extent_map which overlaps with the given
6696 * range, reading it from the B-tree and caching it if necessary. Note that
6697 * there may be more extents which overlap the given range after the returned
6700 * If @page is not NULL and the extent is inline, this also reads the extent
6701 * data directly into the page and marks the extent up to date in the io_tree.
6703 * Return: ERR_PTR on error, non-NULL extent_map on success.
6705 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6706 struct page *page, size_t pg_offset,
6709 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6711 u64 extent_start = 0;
6713 u64 objectid = btrfs_ino(inode);
6714 int extent_type = -1;
6715 struct btrfs_path *path = NULL;
6716 struct btrfs_root *root = inode->root;
6717 struct btrfs_file_extent_item *item;
6718 struct extent_buffer *leaf;
6719 struct btrfs_key found_key;
6720 struct extent_map *em = NULL;
6721 struct extent_map_tree *em_tree = &inode->extent_tree;
6722 struct extent_io_tree *io_tree = &inode->io_tree;
6724 read_lock(&em_tree->lock);
6725 em = lookup_extent_mapping(em_tree, start, len);
6726 read_unlock(&em_tree->lock);
6729 if (em->start > start || em->start + em->len <= start)
6730 free_extent_map(em);
6731 else if (em->block_start == EXTENT_MAP_INLINE && page)
6732 free_extent_map(em);
6736 em = alloc_extent_map();
6741 em->start = EXTENT_MAP_HOLE;
6742 em->orig_start = EXTENT_MAP_HOLE;
6744 em->block_len = (u64)-1;
6746 path = btrfs_alloc_path();
6752 /* Chances are we'll be called again, so go ahead and do readahead */
6753 path->reada = READA_FORWARD;
6756 * The same explanation in load_free_space_cache applies here as well,
6757 * we only read when we're loading the free space cache, and at that
6758 * point the commit_root has everything we need.
6760 if (btrfs_is_free_space_inode(inode)) {
6761 path->search_commit_root = 1;
6762 path->skip_locking = 1;
6765 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6768 } else if (ret > 0) {
6769 if (path->slots[0] == 0)
6775 leaf = path->nodes[0];
6776 item = btrfs_item_ptr(leaf, path->slots[0],
6777 struct btrfs_file_extent_item);
6778 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6779 if (found_key.objectid != objectid ||
6780 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6782 * If we backup past the first extent we want to move forward
6783 * and see if there is an extent in front of us, otherwise we'll
6784 * say there is a hole for our whole search range which can
6791 extent_type = btrfs_file_extent_type(leaf, item);
6792 extent_start = found_key.offset;
6793 extent_end = btrfs_file_extent_end(path);
6794 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6795 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6796 /* Only regular file could have regular/prealloc extent */
6797 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6800 "regular/prealloc extent found for non-regular inode %llu",
6804 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6806 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6807 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6812 if (start >= extent_end) {
6814 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6815 ret = btrfs_next_leaf(root, path);
6821 leaf = path->nodes[0];
6823 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6824 if (found_key.objectid != objectid ||
6825 found_key.type != BTRFS_EXTENT_DATA_KEY)
6827 if (start + len <= found_key.offset)
6829 if (start > found_key.offset)
6832 /* New extent overlaps with existing one */
6834 em->orig_start = start;
6835 em->len = found_key.offset - start;
6836 em->block_start = EXTENT_MAP_HOLE;
6840 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6842 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6843 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6845 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6849 size_t extent_offset;
6855 size = btrfs_file_extent_ram_bytes(leaf, item);
6856 extent_offset = page_offset(page) + pg_offset - extent_start;
6857 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6858 size - extent_offset);
6859 em->start = extent_start + extent_offset;
6860 em->len = ALIGN(copy_size, fs_info->sectorsize);
6861 em->orig_block_len = em->len;
6862 em->orig_start = em->start;
6863 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6865 if (!PageUptodate(page)) {
6866 if (btrfs_file_extent_compression(leaf, item) !=
6867 BTRFS_COMPRESS_NONE) {
6868 ret = uncompress_inline(path, page, pg_offset,
6869 extent_offset, item);
6873 map = kmap_local_page(page);
6874 read_extent_buffer(leaf, map + pg_offset, ptr,
6876 if (pg_offset + copy_size < PAGE_SIZE) {
6877 memset(map + pg_offset + copy_size, 0,
6878 PAGE_SIZE - pg_offset -
6883 flush_dcache_page(page);
6885 set_extent_uptodate(io_tree, em->start,
6886 extent_map_end(em) - 1, NULL, GFP_NOFS);
6891 em->orig_start = start;
6893 em->block_start = EXTENT_MAP_HOLE;
6896 btrfs_release_path(path);
6897 if (em->start > start || extent_map_end(em) <= start) {
6899 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6900 em->start, em->len, start, len);
6905 write_lock(&em_tree->lock);
6906 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6907 write_unlock(&em_tree->lock);
6909 btrfs_free_path(path);
6911 trace_btrfs_get_extent(root, inode, em);
6914 free_extent_map(em);
6915 return ERR_PTR(ret);
6920 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6923 struct extent_map *em;
6924 struct extent_map *hole_em = NULL;
6925 u64 delalloc_start = start;
6931 em = btrfs_get_extent(inode, NULL, 0, start, len);
6935 * If our em maps to:
6937 * - a pre-alloc extent,
6938 * there might actually be delalloc bytes behind it.
6940 if (em->block_start != EXTENT_MAP_HOLE &&
6941 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6946 /* check to see if we've wrapped (len == -1 or similar) */
6955 /* ok, we didn't find anything, lets look for delalloc */
6956 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6957 end, len, EXTENT_DELALLOC, 1);
6958 delalloc_end = delalloc_start + delalloc_len;
6959 if (delalloc_end < delalloc_start)
6960 delalloc_end = (u64)-1;
6963 * We didn't find anything useful, return the original results from
6966 if (delalloc_start > end || delalloc_end <= start) {
6973 * Adjust the delalloc_start to make sure it doesn't go backwards from
6974 * the start they passed in
6976 delalloc_start = max(start, delalloc_start);
6977 delalloc_len = delalloc_end - delalloc_start;
6979 if (delalloc_len > 0) {
6982 const u64 hole_end = extent_map_end(hole_em);
6984 em = alloc_extent_map();
6992 * When btrfs_get_extent can't find anything it returns one
6995 * Make sure what it found really fits our range, and adjust to
6996 * make sure it is based on the start from the caller
6998 if (hole_end <= start || hole_em->start > end) {
6999 free_extent_map(hole_em);
7002 hole_start = max(hole_em->start, start);
7003 hole_len = hole_end - hole_start;
7006 if (hole_em && delalloc_start > hole_start) {
7008 * Our hole starts before our delalloc, so we have to
7009 * return just the parts of the hole that go until the
7012 em->len = min(hole_len, delalloc_start - hole_start);
7013 em->start = hole_start;
7014 em->orig_start = hole_start;
7016 * Don't adjust block start at all, it is fixed at
7019 em->block_start = hole_em->block_start;
7020 em->block_len = hole_len;
7021 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7022 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7025 * Hole is out of passed range or it starts after
7028 em->start = delalloc_start;
7029 em->len = delalloc_len;
7030 em->orig_start = delalloc_start;
7031 em->block_start = EXTENT_MAP_DELALLOC;
7032 em->block_len = delalloc_len;
7039 free_extent_map(hole_em);
7041 free_extent_map(em);
7042 return ERR_PTR(err);
7047 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7050 const u64 orig_start,
7051 const u64 block_start,
7052 const u64 block_len,
7053 const u64 orig_block_len,
7054 const u64 ram_bytes,
7057 struct extent_map *em = NULL;
7060 if (type != BTRFS_ORDERED_NOCOW) {
7061 em = create_io_em(inode, start, len, orig_start, block_start,
7062 block_len, orig_block_len, ram_bytes,
7063 BTRFS_COMPRESS_NONE, /* compress_type */
7068 ret = btrfs_add_ordered_extent(inode, start, len, len, block_start,
7071 (1 << BTRFS_ORDERED_DIRECT),
7072 BTRFS_COMPRESS_NONE);
7075 free_extent_map(em);
7076 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7085 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7088 struct btrfs_root *root = inode->root;
7089 struct btrfs_fs_info *fs_info = root->fs_info;
7090 struct extent_map *em;
7091 struct btrfs_key ins;
7095 alloc_hint = get_extent_allocation_hint(inode, start, len);
7096 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7097 0, alloc_hint, &ins, 1, 1);
7099 return ERR_PTR(ret);
7101 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7102 ins.objectid, ins.offset, ins.offset,
7103 ins.offset, BTRFS_ORDERED_REGULAR);
7104 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7106 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7112 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7114 struct btrfs_block_group *block_group;
7115 bool readonly = false;
7117 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7118 if (!block_group || block_group->ro)
7121 btrfs_put_block_group(block_group);
7126 * Check if we can do nocow write into the range [@offset, @offset + @len)
7128 * @offset: File offset
7129 * @len: The length to write, will be updated to the nocow writeable
7131 * @orig_start: (optional) Return the original file offset of the file extent
7132 * @orig_len: (optional) Return the original on-disk length of the file extent
7133 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7134 * @strict: if true, omit optimizations that might force us into unnecessary
7135 * cow. e.g., don't trust generation number.
7138 * >0 and update @len if we can do nocow write
7139 * 0 if we can't do nocow write
7140 * <0 if error happened
7142 * NOTE: This only checks the file extents, caller is responsible to wait for
7143 * any ordered extents.
7145 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7146 u64 *orig_start, u64 *orig_block_len,
7147 u64 *ram_bytes, bool strict)
7149 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7150 struct btrfs_path *path;
7152 struct extent_buffer *leaf;
7153 struct btrfs_root *root = BTRFS_I(inode)->root;
7154 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7155 struct btrfs_file_extent_item *fi;
7156 struct btrfs_key key;
7163 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7165 path = btrfs_alloc_path();
7169 ret = btrfs_lookup_file_extent(NULL, root, path,
7170 btrfs_ino(BTRFS_I(inode)), offset, 0);
7174 slot = path->slots[0];
7177 /* can't find the item, must cow */
7184 leaf = path->nodes[0];
7185 btrfs_item_key_to_cpu(leaf, &key, slot);
7186 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7187 key.type != BTRFS_EXTENT_DATA_KEY) {
7188 /* not our file or wrong item type, must cow */
7192 if (key.offset > offset) {
7193 /* Wrong offset, must cow */
7197 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7198 found_type = btrfs_file_extent_type(leaf, fi);
7199 if (found_type != BTRFS_FILE_EXTENT_REG &&
7200 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7201 /* not a regular extent, must cow */
7205 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7208 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7209 if (extent_end <= offset)
7212 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7213 if (disk_bytenr == 0)
7216 if (btrfs_file_extent_compression(leaf, fi) ||
7217 btrfs_file_extent_encryption(leaf, fi) ||
7218 btrfs_file_extent_other_encoding(leaf, fi))
7222 * Do the same check as in btrfs_cross_ref_exist but without the
7223 * unnecessary search.
7226 (btrfs_file_extent_generation(leaf, fi) <=
7227 btrfs_root_last_snapshot(&root->root_item)))
7230 backref_offset = btrfs_file_extent_offset(leaf, fi);
7233 *orig_start = key.offset - backref_offset;
7234 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7235 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7238 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7241 num_bytes = min(offset + *len, extent_end) - offset;
7242 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7245 range_end = round_up(offset + num_bytes,
7246 root->fs_info->sectorsize) - 1;
7247 ret = test_range_bit(io_tree, offset, range_end,
7248 EXTENT_DELALLOC, 0, NULL);
7255 btrfs_release_path(path);
7258 * look for other files referencing this extent, if we
7259 * find any we must cow
7262 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7263 key.offset - backref_offset, disk_bytenr,
7271 * adjust disk_bytenr and num_bytes to cover just the bytes
7272 * in this extent we are about to write. If there
7273 * are any csums in that range we have to cow in order
7274 * to keep the csums correct
7276 disk_bytenr += backref_offset;
7277 disk_bytenr += offset - key.offset;
7278 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7281 * all of the above have passed, it is safe to overwrite this extent
7287 btrfs_free_path(path);
7291 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7292 struct extent_state **cached_state, bool writing)
7294 struct btrfs_ordered_extent *ordered;
7298 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7301 * We're concerned with the entire range that we're going to be
7302 * doing DIO to, so we need to make sure there's no ordered
7303 * extents in this range.
7305 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7306 lockend - lockstart + 1);
7309 * We need to make sure there are no buffered pages in this
7310 * range either, we could have raced between the invalidate in
7311 * generic_file_direct_write and locking the extent. The
7312 * invalidate needs to happen so that reads after a write do not
7316 (!writing || !filemap_range_has_page(inode->i_mapping,
7317 lockstart, lockend)))
7320 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7325 * If we are doing a DIO read and the ordered extent we
7326 * found is for a buffered write, we can not wait for it
7327 * to complete and retry, because if we do so we can
7328 * deadlock with concurrent buffered writes on page
7329 * locks. This happens only if our DIO read covers more
7330 * than one extent map, if at this point has already
7331 * created an ordered extent for a previous extent map
7332 * and locked its range in the inode's io tree, and a
7333 * concurrent write against that previous extent map's
7334 * range and this range started (we unlock the ranges
7335 * in the io tree only when the bios complete and
7336 * buffered writes always lock pages before attempting
7337 * to lock range in the io tree).
7340 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7341 btrfs_start_ordered_extent(ordered, 1);
7344 btrfs_put_ordered_extent(ordered);
7347 * We could trigger writeback for this range (and wait
7348 * for it to complete) and then invalidate the pages for
7349 * this range (through invalidate_inode_pages2_range()),
7350 * but that can lead us to a deadlock with a concurrent
7351 * call to readahead (a buffered read or a defrag call
7352 * triggered a readahead) on a page lock due to an
7353 * ordered dio extent we created before but did not have
7354 * yet a corresponding bio submitted (whence it can not
7355 * complete), which makes readahead wait for that
7356 * ordered extent to complete while holding a lock on
7371 /* The callers of this must take lock_extent() */
7372 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7373 u64 len, u64 orig_start, u64 block_start,
7374 u64 block_len, u64 orig_block_len,
7375 u64 ram_bytes, int compress_type,
7378 struct extent_map_tree *em_tree;
7379 struct extent_map *em;
7382 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7383 type == BTRFS_ORDERED_COMPRESSED ||
7384 type == BTRFS_ORDERED_NOCOW ||
7385 type == BTRFS_ORDERED_REGULAR);
7387 em_tree = &inode->extent_tree;
7388 em = alloc_extent_map();
7390 return ERR_PTR(-ENOMEM);
7393 em->orig_start = orig_start;
7395 em->block_len = block_len;
7396 em->block_start = block_start;
7397 em->orig_block_len = orig_block_len;
7398 em->ram_bytes = ram_bytes;
7399 em->generation = -1;
7400 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7401 if (type == BTRFS_ORDERED_PREALLOC) {
7402 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7403 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7404 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7405 em->compress_type = compress_type;
7409 btrfs_drop_extent_cache(inode, em->start,
7410 em->start + em->len - 1, 0);
7411 write_lock(&em_tree->lock);
7412 ret = add_extent_mapping(em_tree, em, 1);
7413 write_unlock(&em_tree->lock);
7415 * The caller has taken lock_extent(), who could race with us
7418 } while (ret == -EEXIST);
7421 free_extent_map(em);
7422 return ERR_PTR(ret);
7425 /* em got 2 refs now, callers needs to do free_extent_map once. */
7430 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7431 struct inode *inode,
7432 struct btrfs_dio_data *dio_data,
7435 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7436 struct extent_map *em = *map;
7438 u64 block_start, orig_start, orig_block_len, ram_bytes;
7439 bool can_nocow = false;
7440 bool space_reserved = false;
7444 * We don't allocate a new extent in the following cases
7446 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7448 * 2) The extent is marked as PREALLOC. We're good to go here and can
7449 * just use the extent.
7452 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7453 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7454 em->block_start != EXTENT_MAP_HOLE)) {
7455 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7456 type = BTRFS_ORDERED_PREALLOC;
7458 type = BTRFS_ORDERED_NOCOW;
7459 len = min(len, em->len - (start - em->start));
7460 block_start = em->block_start + (start - em->start);
7462 if (can_nocow_extent(inode, start, &len, &orig_start,
7463 &orig_block_len, &ram_bytes, false) == 1 &&
7464 btrfs_inc_nocow_writers(fs_info, block_start))
7469 struct extent_map *em2;
7471 /* We can NOCOW, so only need to reserve metadata space. */
7472 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len);
7474 /* Our caller expects us to free the input extent map. */
7475 free_extent_map(em);
7477 btrfs_dec_nocow_writers(fs_info, block_start);
7480 space_reserved = true;
7482 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7483 orig_start, block_start,
7484 len, orig_block_len,
7486 btrfs_dec_nocow_writers(fs_info, block_start);
7487 if (type == BTRFS_ORDERED_PREALLOC) {
7488 free_extent_map(em);
7497 const u64 prev_len = len;
7499 /* Our caller expects us to free the input extent map. */
7500 free_extent_map(em);
7503 /* We have to COW, so need to reserve metadata and data space. */
7504 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7505 &dio_data->data_reserved,
7509 space_reserved = true;
7511 em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7517 len = min(len, em->len - (start - em->start));
7519 btrfs_delalloc_release_space(BTRFS_I(inode),
7520 dio_data->data_reserved,
7521 start + len, prev_len - len,
7526 * We have created our ordered extent, so we can now release our reservation
7527 * for an outstanding extent.
7529 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7532 * Need to update the i_size under the extent lock so buffered
7533 * readers will get the updated i_size when we unlock.
7535 if (start + len > i_size_read(inode))
7536 i_size_write(inode, start + len);
7538 if (ret && space_reserved) {
7539 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7541 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7543 btrfs_delalloc_release_space(BTRFS_I(inode),
7544 dio_data->data_reserved,
7546 extent_changeset_free(dio_data->data_reserved);
7547 dio_data->data_reserved = NULL;
7553 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7554 loff_t length, unsigned int flags, struct iomap *iomap,
7555 struct iomap *srcmap)
7557 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7558 struct extent_map *em;
7559 struct extent_state *cached_state = NULL;
7560 struct btrfs_dio_data *dio_data = NULL;
7561 u64 lockstart, lockend;
7562 const bool write = !!(flags & IOMAP_WRITE);
7565 bool unlock_extents = false;
7568 len = min_t(u64, len, fs_info->sectorsize);
7571 lockend = start + len - 1;
7574 * The generic stuff only does filemap_write_and_wait_range, which
7575 * isn't enough if we've written compressed pages to this area, so we
7576 * need to flush the dirty pages again to make absolutely sure that any
7577 * outstanding dirty pages are on disk.
7579 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7580 &BTRFS_I(inode)->runtime_flags)) {
7581 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7582 start + length - 1);
7587 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7591 iomap->private = dio_data;
7595 * If this errors out it's because we couldn't invalidate pagecache for
7596 * this range and we need to fallback to buffered.
7598 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7603 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7610 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7611 * io. INLINE is special, and we could probably kludge it in here, but
7612 * it's still buffered so for safety lets just fall back to the generic
7615 * For COMPRESSED we _have_ to read the entire extent in so we can
7616 * decompress it, so there will be buffering required no matter what we
7617 * do, so go ahead and fallback to buffered.
7619 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7620 * to buffered IO. Don't blame me, this is the price we pay for using
7623 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7624 em->block_start == EXTENT_MAP_INLINE) {
7625 free_extent_map(em);
7630 len = min(len, em->len - (start - em->start));
7633 * If we have a NOWAIT request and the range contains multiple extents
7634 * (or a mix of extents and holes), then we return -EAGAIN to make the
7635 * caller fallback to a context where it can do a blocking (without
7636 * NOWAIT) request. This way we avoid doing partial IO and returning
7637 * success to the caller, which is not optimal for writes and for reads
7638 * it can result in unexpected behaviour for an application.
7640 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7641 * iomap_dio_rw(), we can end up returning less data then what the caller
7642 * asked for, resulting in an unexpected, and incorrect, short read.
7643 * That is, the caller asked to read N bytes and we return less than that,
7644 * which is wrong unless we are crossing EOF. This happens if we get a
7645 * page fault error when trying to fault in pages for the buffer that is
7646 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7647 * have previously submitted bios for other extents in the range, in
7648 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7649 * those bios have completed by the time we get the page fault error,
7650 * which we return back to our caller - we should only return EIOCBQUEUED
7651 * after we have submitted bios for all the extents in the range.
7653 if ((flags & IOMAP_NOWAIT) && len < length) {
7654 free_extent_map(em);
7660 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7664 unlock_extents = true;
7665 /* Recalc len in case the new em is smaller than requested */
7666 len = min(len, em->len - (start - em->start));
7669 * We need to unlock only the end area that we aren't using.
7670 * The rest is going to be unlocked by the endio routine.
7672 lockstart = start + len;
7673 if (lockstart < lockend)
7674 unlock_extents = true;
7678 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7679 lockstart, lockend, &cached_state);
7681 free_extent_state(cached_state);
7684 * Translate extent map information to iomap.
7685 * We trim the extents (and move the addr) even though iomap code does
7686 * that, since we have locked only the parts we are performing I/O in.
7688 if ((em->block_start == EXTENT_MAP_HOLE) ||
7689 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7690 iomap->addr = IOMAP_NULL_ADDR;
7691 iomap->type = IOMAP_HOLE;
7693 iomap->addr = em->block_start + (start - em->start);
7694 iomap->type = IOMAP_MAPPED;
7696 iomap->offset = start;
7697 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7698 iomap->length = len;
7700 if (write && btrfs_use_zone_append(BTRFS_I(inode), em->block_start))
7701 iomap->flags |= IOMAP_F_ZONE_APPEND;
7703 free_extent_map(em);
7708 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7716 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7717 ssize_t written, unsigned int flags, struct iomap *iomap)
7720 struct btrfs_dio_data *dio_data = iomap->private;
7721 size_t submitted = dio_data->submitted;
7722 const bool write = !!(flags & IOMAP_WRITE);
7724 if (!write && (iomap->type == IOMAP_HOLE)) {
7725 /* If reading from a hole, unlock and return */
7726 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7730 if (submitted < length) {
7732 length -= submitted;
7734 __endio_write_update_ordered(BTRFS_I(inode), pos,
7737 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7743 extent_changeset_free(dio_data->data_reserved);
7746 iomap->private = NULL;
7751 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7754 * This implies a barrier so that stores to dio_bio->bi_status before
7755 * this and loads of dio_bio->bi_status after this are fully ordered.
7757 if (!refcount_dec_and_test(&dip->refs))
7760 if (btrfs_op(dip->dio_bio) == BTRFS_MAP_WRITE) {
7761 __endio_write_update_ordered(BTRFS_I(dip->inode),
7764 !dip->dio_bio->bi_status);
7766 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7768 dip->file_offset + dip->bytes - 1);
7771 bio_endio(dip->dio_bio);
7775 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7777 unsigned long bio_flags)
7779 struct btrfs_dio_private *dip = bio->bi_private;
7780 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7783 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7785 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7789 refcount_inc(&dip->refs);
7790 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7792 refcount_dec(&dip->refs);
7796 static blk_status_t btrfs_check_read_dio_bio(struct btrfs_dio_private *dip,
7797 struct btrfs_bio *bbio,
7798 const bool uptodate)
7800 struct inode *inode = dip->inode;
7801 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7802 const u32 sectorsize = fs_info->sectorsize;
7803 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7804 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7805 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7806 struct bio_vec bvec;
7807 struct bvec_iter iter;
7808 const u64 orig_file_offset = dip->file_offset;
7809 u64 start = orig_file_offset;
7811 blk_status_t err = BLK_STS_OK;
7813 __bio_for_each_segment(bvec, &bbio->bio, iter, bbio->iter) {
7814 unsigned int i, nr_sectors, pgoff;
7816 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7817 pgoff = bvec.bv_offset;
7818 for (i = 0; i < nr_sectors; i++) {
7819 ASSERT(pgoff < PAGE_SIZE);
7821 (!csum || !check_data_csum(inode, bbio,
7822 bio_offset, bvec.bv_page,
7824 clean_io_failure(fs_info, failure_tree, io_tree,
7825 start, bvec.bv_page,
7826 btrfs_ino(BTRFS_I(inode)),
7831 ASSERT((start - orig_file_offset) < UINT_MAX);
7832 ret = btrfs_repair_one_sector(inode,
7834 start - orig_file_offset,
7835 bvec.bv_page, pgoff,
7836 start, bbio->mirror_num,
7837 submit_dio_repair_bio);
7839 err = errno_to_blk_status(ret);
7841 start += sectorsize;
7842 ASSERT(bio_offset + sectorsize > bio_offset);
7843 bio_offset += sectorsize;
7844 pgoff += sectorsize;
7850 static void __endio_write_update_ordered(struct btrfs_inode *inode,
7851 const u64 offset, const u64 bytes,
7852 const bool uptodate)
7854 btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes,
7855 finish_ordered_fn, uptodate);
7858 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7860 u64 dio_file_offset)
7862 return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, false);
7865 static void btrfs_end_dio_bio(struct bio *bio)
7867 struct btrfs_dio_private *dip = bio->bi_private;
7868 blk_status_t err = bio->bi_status;
7871 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7872 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7873 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7874 bio->bi_opf, bio->bi_iter.bi_sector,
7875 bio->bi_iter.bi_size, err);
7877 if (bio_op(bio) == REQ_OP_READ)
7878 err = btrfs_check_read_dio_bio(dip, btrfs_bio(bio), !err);
7881 dip->dio_bio->bi_status = err;
7883 btrfs_record_physical_zoned(dip->inode, dip->file_offset, bio);
7886 btrfs_dio_private_put(dip);
7889 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7890 struct inode *inode, u64 file_offset, int async_submit)
7892 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7893 struct btrfs_dio_private *dip = bio->bi_private;
7894 bool write = btrfs_op(bio) == BTRFS_MAP_WRITE;
7897 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7899 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7902 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7907 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7910 if (write && async_submit) {
7911 ret = btrfs_wq_submit_bio(inode, bio, 0, 0, file_offset,
7912 btrfs_submit_bio_start_direct_io);
7916 * If we aren't doing async submit, calculate the csum of the
7919 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, false);
7925 csum_offset = file_offset - dip->file_offset;
7926 csum_offset >>= fs_info->sectorsize_bits;
7927 csum_offset *= fs_info->csum_size;
7928 btrfs_bio(bio)->csum = dip->csums + csum_offset;
7931 ret = btrfs_map_bio(fs_info, bio, 0);
7937 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7938 * or ordered extents whether or not we submit any bios.
7940 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7941 struct inode *inode,
7944 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
7945 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7947 struct btrfs_dio_private *dip;
7949 dip_size = sizeof(*dip);
7950 if (!write && csum) {
7951 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7954 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
7955 dip_size += fs_info->csum_size * nblocks;
7958 dip = kzalloc(dip_size, GFP_NOFS);
7963 dip->file_offset = file_offset;
7964 dip->bytes = dio_bio->bi_iter.bi_size;
7965 dip->disk_bytenr = dio_bio->bi_iter.bi_sector << 9;
7966 dip->dio_bio = dio_bio;
7967 refcount_set(&dip->refs, 1);
7971 static void btrfs_submit_direct(const struct iomap_iter *iter,
7972 struct bio *dio_bio, loff_t file_offset)
7974 struct inode *inode = iter->inode;
7975 const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
7976 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7977 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7978 BTRFS_BLOCK_GROUP_RAID56_MASK);
7979 struct btrfs_dio_private *dip;
7982 int async_submit = 0;
7984 u64 clone_offset = 0;
7988 blk_status_t status;
7989 struct btrfs_io_geometry geom;
7990 struct btrfs_dio_data *dio_data = iter->iomap.private;
7991 struct extent_map *em = NULL;
7993 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7996 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7997 file_offset + dio_bio->bi_iter.bi_size - 1);
7999 dio_bio->bi_status = BLK_STS_RESOURCE;
8006 * Load the csums up front to reduce csum tree searches and
8007 * contention when submitting bios.
8009 * If we have csums disabled this will do nothing.
8011 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8012 if (status != BLK_STS_OK)
8016 start_sector = dio_bio->bi_iter.bi_sector;
8017 submit_len = dio_bio->bi_iter.bi_size;
8020 logical = start_sector << 9;
8021 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8023 status = errno_to_blk_status(PTR_ERR(em));
8027 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8030 status = errno_to_blk_status(ret);
8034 clone_len = min(submit_len, geom.len);
8035 ASSERT(clone_len <= UINT_MAX);
8038 * This will never fail as it's passing GPF_NOFS and
8039 * the allocation is backed by btrfs_bioset.
8041 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
8042 bio->bi_private = dip;
8043 bio->bi_end_io = btrfs_end_dio_bio;
8045 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8046 status = extract_ordered_extent(BTRFS_I(inode), bio,
8054 ASSERT(submit_len >= clone_len);
8055 submit_len -= clone_len;
8058 * Increase the count before we submit the bio so we know
8059 * the end IO handler won't happen before we increase the
8060 * count. Otherwise, the dip might get freed before we're
8061 * done setting it up.
8063 * We transfer the initial reference to the last bio, so we
8064 * don't need to increment the reference count for the last one.
8066 if (submit_len > 0) {
8067 refcount_inc(&dip->refs);
8069 * If we are submitting more than one bio, submit them
8070 * all asynchronously. The exception is RAID 5 or 6, as
8071 * asynchronous checksums make it difficult to collect
8072 * full stripe writes.
8078 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8083 refcount_dec(&dip->refs);
8087 dio_data->submitted += clone_len;
8088 clone_offset += clone_len;
8089 start_sector += clone_len >> 9;
8090 file_offset += clone_len;
8092 free_extent_map(em);
8093 } while (submit_len > 0);
8097 free_extent_map(em);
8099 dip->dio_bio->bi_status = status;
8100 btrfs_dio_private_put(dip);
8103 const struct iomap_ops btrfs_dio_iomap_ops = {
8104 .iomap_begin = btrfs_dio_iomap_begin,
8105 .iomap_end = btrfs_dio_iomap_end,
8108 const struct iomap_dio_ops btrfs_dio_ops = {
8109 .submit_io = btrfs_submit_direct,
8112 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8117 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8121 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8124 int btrfs_readpage(struct file *file, struct page *page)
8126 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8127 u64 start = page_offset(page);
8128 u64 end = start + PAGE_SIZE - 1;
8129 struct btrfs_bio_ctrl bio_ctrl = { 0 };
8132 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8134 ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
8138 ret2 = submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.bio_flags);
8145 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8147 struct inode *inode = page->mapping->host;
8150 if (current->flags & PF_MEMALLOC) {
8151 redirty_page_for_writepage(wbc, page);
8157 * If we are under memory pressure we will call this directly from the
8158 * VM, we need to make sure we have the inode referenced for the ordered
8159 * extent. If not just return like we didn't do anything.
8161 if (!igrab(inode)) {
8162 redirty_page_for_writepage(wbc, page);
8163 return AOP_WRITEPAGE_ACTIVATE;
8165 ret = extent_write_full_page(page, wbc);
8166 btrfs_add_delayed_iput(inode);
8170 static int btrfs_writepages(struct address_space *mapping,
8171 struct writeback_control *wbc)
8173 return extent_writepages(mapping, wbc);
8176 static void btrfs_readahead(struct readahead_control *rac)
8178 extent_readahead(rac);
8182 * For releasepage() and invalidate_folio() we have a race window where
8183 * folio_end_writeback() is called but the subpage spinlock is not yet released.
8184 * If we continue to release/invalidate the page, we could cause use-after-free
8185 * for subpage spinlock. So this function is to spin and wait for subpage
8188 static void wait_subpage_spinlock(struct page *page)
8190 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
8191 struct btrfs_subpage *subpage;
8193 if (fs_info->sectorsize == PAGE_SIZE)
8196 ASSERT(PagePrivate(page) && page->private);
8197 subpage = (struct btrfs_subpage *)page->private;
8200 * This may look insane as we just acquire the spinlock and release it,
8201 * without doing anything. But we just want to make sure no one is
8202 * still holding the subpage spinlock.
8203 * And since the page is not dirty nor writeback, and we have page
8204 * locked, the only possible way to hold a spinlock is from the endio
8205 * function to clear page writeback.
8207 * Here we just acquire the spinlock so that all existing callers
8208 * should exit and we're safe to release/invalidate the page.
8210 spin_lock_irq(&subpage->lock);
8211 spin_unlock_irq(&subpage->lock);
8214 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8216 int ret = try_release_extent_mapping(page, gfp_flags);
8219 wait_subpage_spinlock(page);
8220 clear_page_extent_mapped(page);
8225 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8227 if (PageWriteback(page) || PageDirty(page))
8229 return __btrfs_releasepage(page, gfp_flags);
8232 #ifdef CONFIG_MIGRATION
8233 static int btrfs_migratepage(struct address_space *mapping,
8234 struct page *newpage, struct page *page,
8235 enum migrate_mode mode)
8239 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8240 if (ret != MIGRATEPAGE_SUCCESS)
8243 if (page_has_private(page))
8244 attach_page_private(newpage, detach_page_private(page));
8246 if (PageOrdered(page)) {
8247 ClearPageOrdered(page);
8248 SetPageOrdered(newpage);
8251 if (mode != MIGRATE_SYNC_NO_COPY)
8252 migrate_page_copy(newpage, page);
8254 migrate_page_states(newpage, page);
8255 return MIGRATEPAGE_SUCCESS;
8259 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
8262 struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
8263 struct btrfs_fs_info *fs_info = inode->root->fs_info;
8264 struct extent_io_tree *tree = &inode->io_tree;
8265 struct extent_state *cached_state = NULL;
8266 u64 page_start = folio_pos(folio);
8267 u64 page_end = page_start + folio_size(folio) - 1;
8269 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8272 * We have folio locked so no new ordered extent can be created on this
8273 * page, nor bio can be submitted for this folio.
8275 * But already submitted bio can still be finished on this folio.
8276 * Furthermore, endio function won't skip folio which has Ordered
8277 * (Private2) already cleared, so it's possible for endio and
8278 * invalidate_folio to do the same ordered extent accounting twice
8281 * So here we wait for any submitted bios to finish, so that we won't
8282 * do double ordered extent accounting on the same folio.
8284 folio_wait_writeback(folio);
8285 wait_subpage_spinlock(&folio->page);
8288 * For subpage case, we have call sites like
8289 * btrfs_punch_hole_lock_range() which passes range not aligned to
8291 * If the range doesn't cover the full folio, we don't need to and
8292 * shouldn't clear page extent mapped, as folio->private can still
8293 * record subpage dirty bits for other part of the range.
8295 * For cases that invalidate the full folio even the range doesn't
8296 * cover the full folio, like invalidating the last folio, we're
8297 * still safe to wait for ordered extent to finish.
8299 if (!(offset == 0 && length == PAGE_SIZE)) {
8300 btrfs_releasepage(&folio->page, GFP_NOFS);
8304 if (!inode_evicting)
8305 lock_extent_bits(tree, page_start, page_end, &cached_state);
8308 while (cur < page_end) {
8309 struct btrfs_ordered_extent *ordered;
8314 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8315 page_end + 1 - cur);
8317 range_end = page_end;
8319 * No ordered extent covering this range, we are safe
8320 * to delete all extent states in the range.
8322 delete_states = true;
8325 if (ordered->file_offset > cur) {
8327 * There is a range between [cur, oe->file_offset) not
8328 * covered by any ordered extent.
8329 * We are safe to delete all extent states, and handle
8330 * the ordered extent in the next iteration.
8332 range_end = ordered->file_offset - 1;
8333 delete_states = true;
8337 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8339 ASSERT(range_end + 1 - cur < U32_MAX);
8340 range_len = range_end + 1 - cur;
8341 if (!btrfs_page_test_ordered(fs_info, &folio->page, cur, range_len)) {
8343 * If Ordered (Private2) is cleared, it means endio has
8344 * already been executed for the range.
8345 * We can't delete the extent states as
8346 * btrfs_finish_ordered_io() may still use some of them.
8348 delete_states = false;
8351 btrfs_page_clear_ordered(fs_info, &folio->page, cur, range_len);
8354 * IO on this page will never be started, so we need to account
8355 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8356 * here, must leave that up for the ordered extent completion.
8358 * This will also unlock the range for incoming
8359 * btrfs_finish_ordered_io().
8361 if (!inode_evicting)
8362 clear_extent_bit(tree, cur, range_end,
8364 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8365 EXTENT_DEFRAG, 1, 0, &cached_state);
8367 spin_lock_irq(&inode->ordered_tree.lock);
8368 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8369 ordered->truncated_len = min(ordered->truncated_len,
8370 cur - ordered->file_offset);
8371 spin_unlock_irq(&inode->ordered_tree.lock);
8373 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8374 cur, range_end + 1 - cur)) {
8375 btrfs_finish_ordered_io(ordered);
8377 * The ordered extent has finished, now we're again
8378 * safe to delete all extent states of the range.
8380 delete_states = true;
8383 * btrfs_finish_ordered_io() will get executed by endio
8384 * of other pages, thus we can't delete extent states
8387 delete_states = false;
8391 btrfs_put_ordered_extent(ordered);
8393 * Qgroup reserved space handler
8394 * Sector(s) here will be either:
8396 * 1) Already written to disk or bio already finished
8397 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8398 * Qgroup will be handled by its qgroup_record then.
8399 * btrfs_qgroup_free_data() call will do nothing here.
8401 * 2) Not written to disk yet
8402 * Then btrfs_qgroup_free_data() call will clear the
8403 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8404 * reserved data space.
8405 * Since the IO will never happen for this page.
8407 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8408 if (!inode_evicting) {
8409 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8410 EXTENT_DELALLOC | EXTENT_UPTODATE |
8411 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1,
8412 delete_states, &cached_state);
8414 cur = range_end + 1;
8417 * We have iterated through all ordered extents of the page, the page
8418 * should not have Ordered (Private2) anymore, or the above iteration
8419 * did something wrong.
8421 ASSERT(!folio_test_ordered(folio));
8422 btrfs_page_clear_checked(fs_info, &folio->page, folio_pos(folio), folio_size(folio));
8423 if (!inode_evicting)
8424 __btrfs_releasepage(&folio->page, GFP_NOFS);
8425 clear_page_extent_mapped(&folio->page);
8429 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8430 * called from a page fault handler when a page is first dirtied. Hence we must
8431 * be careful to check for EOF conditions here. We set the page up correctly
8432 * for a written page which means we get ENOSPC checking when writing into
8433 * holes and correct delalloc and unwritten extent mapping on filesystems that
8434 * support these features.
8436 * We are not allowed to take the i_mutex here so we have to play games to
8437 * protect against truncate races as the page could now be beyond EOF. Because
8438 * truncate_setsize() writes the inode size before removing pages, once we have
8439 * the page lock we can determine safely if the page is beyond EOF. If it is not
8440 * beyond EOF, then the page is guaranteed safe against truncation until we
8443 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8445 struct page *page = vmf->page;
8446 struct inode *inode = file_inode(vmf->vma->vm_file);
8447 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8448 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8449 struct btrfs_ordered_extent *ordered;
8450 struct extent_state *cached_state = NULL;
8451 struct extent_changeset *data_reserved = NULL;
8452 unsigned long zero_start;
8462 reserved_space = PAGE_SIZE;
8464 sb_start_pagefault(inode->i_sb);
8465 page_start = page_offset(page);
8466 page_end = page_start + PAGE_SIZE - 1;
8470 * Reserving delalloc space after obtaining the page lock can lead to
8471 * deadlock. For example, if a dirty page is locked by this function
8472 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8473 * dirty page write out, then the btrfs_writepage() function could
8474 * end up waiting indefinitely to get a lock on the page currently
8475 * being processed by btrfs_page_mkwrite() function.
8477 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8478 page_start, reserved_space);
8480 ret2 = file_update_time(vmf->vma->vm_file);
8484 ret = vmf_error(ret2);
8490 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8492 down_read(&BTRFS_I(inode)->i_mmap_lock);
8494 size = i_size_read(inode);
8496 if ((page->mapping != inode->i_mapping) ||
8497 (page_start >= size)) {
8498 /* page got truncated out from underneath us */
8501 wait_on_page_writeback(page);
8503 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8504 ret2 = set_page_extent_mapped(page);
8506 ret = vmf_error(ret2);
8507 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8512 * we can't set the delalloc bits if there are pending ordered
8513 * extents. Drop our locks and wait for them to finish
8515 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8518 unlock_extent_cached(io_tree, page_start, page_end,
8521 up_read(&BTRFS_I(inode)->i_mmap_lock);
8522 btrfs_start_ordered_extent(ordered, 1);
8523 btrfs_put_ordered_extent(ordered);
8527 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8528 reserved_space = round_up(size - page_start,
8529 fs_info->sectorsize);
8530 if (reserved_space < PAGE_SIZE) {
8531 end = page_start + reserved_space - 1;
8532 btrfs_delalloc_release_space(BTRFS_I(inode),
8533 data_reserved, page_start,
8534 PAGE_SIZE - reserved_space, true);
8539 * page_mkwrite gets called when the page is firstly dirtied after it's
8540 * faulted in, but write(2) could also dirty a page and set delalloc
8541 * bits, thus in this case for space account reason, we still need to
8542 * clear any delalloc bits within this page range since we have to
8543 * reserve data&meta space before lock_page() (see above comments).
8545 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8546 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8547 EXTENT_DEFRAG, 0, 0, &cached_state);
8549 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8552 unlock_extent_cached(io_tree, page_start, page_end,
8554 ret = VM_FAULT_SIGBUS;
8558 /* page is wholly or partially inside EOF */
8559 if (page_start + PAGE_SIZE > size)
8560 zero_start = offset_in_page(size);
8562 zero_start = PAGE_SIZE;
8564 if (zero_start != PAGE_SIZE) {
8565 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8566 flush_dcache_page(page);
8568 btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
8569 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8570 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8572 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8574 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8575 up_read(&BTRFS_I(inode)->i_mmap_lock);
8577 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8578 sb_end_pagefault(inode->i_sb);
8579 extent_changeset_free(data_reserved);
8580 return VM_FAULT_LOCKED;
8584 up_read(&BTRFS_I(inode)->i_mmap_lock);
8586 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8587 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8588 reserved_space, (ret != 0));
8590 sb_end_pagefault(inode->i_sb);
8591 extent_changeset_free(data_reserved);
8595 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8597 struct btrfs_truncate_control control = {
8598 .inode = BTRFS_I(inode),
8599 .ino = btrfs_ino(BTRFS_I(inode)),
8600 .min_type = BTRFS_EXTENT_DATA_KEY,
8601 .clear_extent_range = true,
8603 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8604 struct btrfs_root *root = BTRFS_I(inode)->root;
8605 struct btrfs_block_rsv *rsv;
8607 struct btrfs_trans_handle *trans;
8608 u64 mask = fs_info->sectorsize - 1;
8609 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8611 if (!skip_writeback) {
8612 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8619 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8620 * things going on here:
8622 * 1) We need to reserve space to update our inode.
8624 * 2) We need to have something to cache all the space that is going to
8625 * be free'd up by the truncate operation, but also have some slack
8626 * space reserved in case it uses space during the truncate (thank you
8627 * very much snapshotting).
8629 * And we need these to be separate. The fact is we can use a lot of
8630 * space doing the truncate, and we have no earthly idea how much space
8631 * we will use, so we need the truncate reservation to be separate so it
8632 * doesn't end up using space reserved for updating the inode. We also
8633 * need to be able to stop the transaction and start a new one, which
8634 * means we need to be able to update the inode several times, and we
8635 * have no idea of knowing how many times that will be, so we can't just
8636 * reserve 1 item for the entirety of the operation, so that has to be
8637 * done separately as well.
8639 * So that leaves us with
8641 * 1) rsv - for the truncate reservation, which we will steal from the
8642 * transaction reservation.
8643 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8644 * updating the inode.
8646 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8649 rsv->size = min_size;
8653 * 1 for the truncate slack space
8654 * 1 for updating the inode.
8656 trans = btrfs_start_transaction(root, 2);
8657 if (IS_ERR(trans)) {
8658 ret = PTR_ERR(trans);
8662 /* Migrate the slack space for the truncate to our reserve */
8663 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8667 trans->block_rsv = rsv;
8670 struct extent_state *cached_state = NULL;
8671 const u64 new_size = inode->i_size;
8672 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8674 control.new_size = new_size;
8675 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
8678 * We want to drop from the next block forward in case this new
8679 * size is not block aligned since we will be keeping the last
8680 * block of the extent just the way it is.
8682 btrfs_drop_extent_cache(BTRFS_I(inode),
8683 ALIGN(new_size, fs_info->sectorsize),
8686 ret = btrfs_truncate_inode_items(trans, root, &control);
8688 inode_sub_bytes(inode, control.sub_bytes);
8689 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), control.last_size);
8691 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
8692 (u64)-1, &cached_state);
8694 trans->block_rsv = &fs_info->trans_block_rsv;
8695 if (ret != -ENOSPC && ret != -EAGAIN)
8698 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8702 btrfs_end_transaction(trans);
8703 btrfs_btree_balance_dirty(fs_info);
8705 trans = btrfs_start_transaction(root, 2);
8706 if (IS_ERR(trans)) {
8707 ret = PTR_ERR(trans);
8712 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8713 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8714 rsv, min_size, false);
8715 BUG_ON(ret); /* shouldn't happen */
8716 trans->block_rsv = rsv;
8720 * We can't call btrfs_truncate_block inside a trans handle as we could
8721 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8722 * know we've truncated everything except the last little bit, and can
8723 * do btrfs_truncate_block and then update the disk_i_size.
8725 if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8726 btrfs_end_transaction(trans);
8727 btrfs_btree_balance_dirty(fs_info);
8729 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8732 trans = btrfs_start_transaction(root, 1);
8733 if (IS_ERR(trans)) {
8734 ret = PTR_ERR(trans);
8737 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8743 trans->block_rsv = &fs_info->trans_block_rsv;
8744 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8748 ret2 = btrfs_end_transaction(trans);
8751 btrfs_btree_balance_dirty(fs_info);
8754 btrfs_free_block_rsv(fs_info, rsv);
8756 * So if we truncate and then write and fsync we normally would just
8757 * write the extents that changed, which is a problem if we need to
8758 * first truncate that entire inode. So set this flag so we write out
8759 * all of the extents in the inode to the sync log so we're completely
8762 * If no extents were dropped or trimmed we don't need to force the next
8763 * fsync to truncate all the inode's items from the log and re-log them
8764 * all. This means the truncate operation did not change the file size,
8765 * or changed it to a smaller size but there was only an implicit hole
8766 * between the old i_size and the new i_size, and there were no prealloc
8767 * extents beyond i_size to drop.
8769 if (control.extents_found > 0)
8770 btrfs_set_inode_full_sync(BTRFS_I(inode));
8776 * create a new subvolume directory/inode (helper for the ioctl).
8778 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8779 struct btrfs_root *new_root,
8780 struct btrfs_root *parent_root,
8781 struct user_namespace *mnt_userns)
8783 struct inode *inode;
8788 err = btrfs_get_free_objectid(new_root, &ino);
8792 inode = btrfs_new_inode(trans, new_root, mnt_userns, NULL, "..", 2,
8794 S_IFDIR | (~current_umask() & S_IRWXUGO),
8797 return PTR_ERR(inode);
8798 inode->i_op = &btrfs_dir_inode_operations;
8799 inode->i_fop = &btrfs_dir_file_operations;
8801 set_nlink(inode, 1);
8802 btrfs_i_size_write(BTRFS_I(inode), 0);
8803 unlock_new_inode(inode);
8805 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8807 btrfs_err(new_root->fs_info,
8808 "error inheriting subvolume %llu properties: %d",
8809 new_root->root_key.objectid, err);
8811 err = btrfs_update_inode(trans, new_root, BTRFS_I(inode));
8817 struct inode *btrfs_alloc_inode(struct super_block *sb)
8819 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8820 struct btrfs_inode *ei;
8821 struct inode *inode;
8823 ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8830 ei->last_sub_trans = 0;
8831 ei->logged_trans = 0;
8832 ei->delalloc_bytes = 0;
8833 ei->new_delalloc_bytes = 0;
8834 ei->defrag_bytes = 0;
8835 ei->disk_i_size = 0;
8839 ei->index_cnt = (u64)-1;
8841 ei->last_unlink_trans = 0;
8842 ei->last_reflink_trans = 0;
8843 ei->last_log_commit = 0;
8845 spin_lock_init(&ei->lock);
8846 ei->outstanding_extents = 0;
8847 if (sb->s_magic != BTRFS_TEST_MAGIC)
8848 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8849 BTRFS_BLOCK_RSV_DELALLOC);
8850 ei->runtime_flags = 0;
8851 ei->prop_compress = BTRFS_COMPRESS_NONE;
8852 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8854 ei->delayed_node = NULL;
8856 ei->i_otime.tv_sec = 0;
8857 ei->i_otime.tv_nsec = 0;
8859 inode = &ei->vfs_inode;
8860 extent_map_tree_init(&ei->extent_tree);
8861 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8862 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8863 IO_TREE_INODE_IO_FAILURE, inode);
8864 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8865 IO_TREE_INODE_FILE_EXTENT, inode);
8866 ei->io_tree.track_uptodate = true;
8867 ei->io_failure_tree.track_uptodate = true;
8868 atomic_set(&ei->sync_writers, 0);
8869 mutex_init(&ei->log_mutex);
8870 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8871 INIT_LIST_HEAD(&ei->delalloc_inodes);
8872 INIT_LIST_HEAD(&ei->delayed_iput);
8873 RB_CLEAR_NODE(&ei->rb_node);
8874 init_rwsem(&ei->i_mmap_lock);
8879 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8880 void btrfs_test_destroy_inode(struct inode *inode)
8882 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8883 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8887 void btrfs_free_inode(struct inode *inode)
8889 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8892 void btrfs_destroy_inode(struct inode *vfs_inode)
8894 struct btrfs_ordered_extent *ordered;
8895 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8896 struct btrfs_root *root = inode->root;
8898 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8899 WARN_ON(vfs_inode->i_data.nrpages);
8900 WARN_ON(inode->block_rsv.reserved);
8901 WARN_ON(inode->block_rsv.size);
8902 WARN_ON(inode->outstanding_extents);
8903 if (!S_ISDIR(vfs_inode->i_mode)) {
8904 WARN_ON(inode->delalloc_bytes);
8905 WARN_ON(inode->new_delalloc_bytes);
8907 WARN_ON(inode->csum_bytes);
8908 WARN_ON(inode->defrag_bytes);
8911 * This can happen where we create an inode, but somebody else also
8912 * created the same inode and we need to destroy the one we already
8919 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8923 btrfs_err(root->fs_info,
8924 "found ordered extent %llu %llu on inode cleanup",
8925 ordered->file_offset, ordered->num_bytes);
8926 btrfs_remove_ordered_extent(inode, ordered);
8927 btrfs_put_ordered_extent(ordered);
8928 btrfs_put_ordered_extent(ordered);
8931 btrfs_qgroup_check_reserved_leak(inode);
8932 inode_tree_del(inode);
8933 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8934 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8935 btrfs_put_root(inode->root);
8938 int btrfs_drop_inode(struct inode *inode)
8940 struct btrfs_root *root = BTRFS_I(inode)->root;
8945 /* the snap/subvol tree is on deleting */
8946 if (btrfs_root_refs(&root->root_item) == 0)
8949 return generic_drop_inode(inode);
8952 static void init_once(void *foo)
8954 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8956 inode_init_once(&ei->vfs_inode);
8959 void __cold btrfs_destroy_cachep(void)
8962 * Make sure all delayed rcu free inodes are flushed before we
8966 kmem_cache_destroy(btrfs_inode_cachep);
8967 kmem_cache_destroy(btrfs_trans_handle_cachep);
8968 kmem_cache_destroy(btrfs_path_cachep);
8969 kmem_cache_destroy(btrfs_free_space_cachep);
8970 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8973 int __init btrfs_init_cachep(void)
8975 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8976 sizeof(struct btrfs_inode), 0,
8977 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8979 if (!btrfs_inode_cachep)
8982 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8983 sizeof(struct btrfs_trans_handle), 0,
8984 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8985 if (!btrfs_trans_handle_cachep)
8988 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8989 sizeof(struct btrfs_path), 0,
8990 SLAB_MEM_SPREAD, NULL);
8991 if (!btrfs_path_cachep)
8994 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8995 sizeof(struct btrfs_free_space), 0,
8996 SLAB_MEM_SPREAD, NULL);
8997 if (!btrfs_free_space_cachep)
9000 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9001 PAGE_SIZE, PAGE_SIZE,
9002 SLAB_MEM_SPREAD, NULL);
9003 if (!btrfs_free_space_bitmap_cachep)
9008 btrfs_destroy_cachep();
9012 static int btrfs_getattr(struct user_namespace *mnt_userns,
9013 const struct path *path, struct kstat *stat,
9014 u32 request_mask, unsigned int flags)
9018 struct inode *inode = d_inode(path->dentry);
9019 u32 blocksize = inode->i_sb->s_blocksize;
9020 u32 bi_flags = BTRFS_I(inode)->flags;
9021 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
9023 stat->result_mask |= STATX_BTIME;
9024 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9025 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9026 if (bi_flags & BTRFS_INODE_APPEND)
9027 stat->attributes |= STATX_ATTR_APPEND;
9028 if (bi_flags & BTRFS_INODE_COMPRESS)
9029 stat->attributes |= STATX_ATTR_COMPRESSED;
9030 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9031 stat->attributes |= STATX_ATTR_IMMUTABLE;
9032 if (bi_flags & BTRFS_INODE_NODUMP)
9033 stat->attributes |= STATX_ATTR_NODUMP;
9034 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
9035 stat->attributes |= STATX_ATTR_VERITY;
9037 stat->attributes_mask |= (STATX_ATTR_APPEND |
9038 STATX_ATTR_COMPRESSED |
9039 STATX_ATTR_IMMUTABLE |
9042 generic_fillattr(mnt_userns, inode, stat);
9043 stat->dev = BTRFS_I(inode)->root->anon_dev;
9045 spin_lock(&BTRFS_I(inode)->lock);
9046 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9047 inode_bytes = inode_get_bytes(inode);
9048 spin_unlock(&BTRFS_I(inode)->lock);
9049 stat->blocks = (ALIGN(inode_bytes, blocksize) +
9050 ALIGN(delalloc_bytes, blocksize)) >> 9;
9054 static int btrfs_rename_exchange(struct inode *old_dir,
9055 struct dentry *old_dentry,
9056 struct inode *new_dir,
9057 struct dentry *new_dentry)
9059 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9060 struct btrfs_trans_handle *trans;
9061 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9062 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9063 struct inode *new_inode = new_dentry->d_inode;
9064 struct inode *old_inode = old_dentry->d_inode;
9065 struct timespec64 ctime = current_time(old_inode);
9066 struct btrfs_rename_ctx old_rename_ctx;
9067 struct btrfs_rename_ctx new_rename_ctx;
9068 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9069 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9074 bool need_abort = false;
9077 * For non-subvolumes allow exchange only within one subvolume, in the
9078 * same inode namespace. Two subvolumes (represented as directory) can
9079 * be exchanged as they're a logical link and have a fixed inode number.
9082 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
9083 new_ino != BTRFS_FIRST_FREE_OBJECTID))
9086 /* close the race window with snapshot create/destroy ioctl */
9087 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9088 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9089 down_read(&fs_info->subvol_sem);
9092 * We want to reserve the absolute worst case amount of items. So if
9093 * both inodes are subvols and we need to unlink them then that would
9094 * require 4 item modifications, but if they are both normal inodes it
9095 * would require 5 item modifications, so we'll assume their normal
9096 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9097 * should cover the worst case number of items we'll modify.
9099 trans = btrfs_start_transaction(root, 12);
9100 if (IS_ERR(trans)) {
9101 ret = PTR_ERR(trans);
9106 ret = btrfs_record_root_in_trans(trans, dest);
9112 * We need to find a free sequence number both in the source and
9113 * in the destination directory for the exchange.
9115 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9118 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9122 BTRFS_I(old_inode)->dir_index = 0ULL;
9123 BTRFS_I(new_inode)->dir_index = 0ULL;
9125 /* Reference for the source. */
9126 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9127 /* force full log commit if subvolume involved. */
9128 btrfs_set_log_full_commit(trans);
9130 ret = btrfs_insert_inode_ref(trans, dest,
9131 new_dentry->d_name.name,
9132 new_dentry->d_name.len,
9134 btrfs_ino(BTRFS_I(new_dir)),
9141 /* And now for the dest. */
9142 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9143 /* force full log commit if subvolume involved. */
9144 btrfs_set_log_full_commit(trans);
9146 ret = btrfs_insert_inode_ref(trans, root,
9147 old_dentry->d_name.name,
9148 old_dentry->d_name.len,
9150 btrfs_ino(BTRFS_I(old_dir)),
9154 btrfs_abort_transaction(trans, ret);
9159 /* Update inode version and ctime/mtime. */
9160 inode_inc_iversion(old_dir);
9161 inode_inc_iversion(new_dir);
9162 inode_inc_iversion(old_inode);
9163 inode_inc_iversion(new_inode);
9164 old_dir->i_ctime = old_dir->i_mtime = ctime;
9165 new_dir->i_ctime = new_dir->i_mtime = ctime;
9166 old_inode->i_ctime = ctime;
9167 new_inode->i_ctime = ctime;
9169 if (old_dentry->d_parent != new_dentry->d_parent) {
9170 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9171 BTRFS_I(old_inode), 1);
9172 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9173 BTRFS_I(new_inode), 1);
9176 /* src is a subvolume */
9177 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9178 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9179 } else { /* src is an inode */
9180 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9181 BTRFS_I(old_dentry->d_inode),
9182 old_dentry->d_name.name,
9183 old_dentry->d_name.len,
9186 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9189 btrfs_abort_transaction(trans, ret);
9193 /* dest is a subvolume */
9194 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9195 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9196 } else { /* dest is an inode */
9197 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9198 BTRFS_I(new_dentry->d_inode),
9199 new_dentry->d_name.name,
9200 new_dentry->d_name.len,
9203 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9206 btrfs_abort_transaction(trans, ret);
9210 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9211 new_dentry->d_name.name,
9212 new_dentry->d_name.len, 0, old_idx);
9214 btrfs_abort_transaction(trans, ret);
9218 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9219 old_dentry->d_name.name,
9220 old_dentry->d_name.len, 0, new_idx);
9222 btrfs_abort_transaction(trans, ret);
9226 if (old_inode->i_nlink == 1)
9227 BTRFS_I(old_inode)->dir_index = old_idx;
9228 if (new_inode->i_nlink == 1)
9229 BTRFS_I(new_inode)->dir_index = new_idx;
9232 * Now pin the logs of the roots. We do it to ensure that no other task
9233 * can sync the logs while we are in progress with the rename, because
9234 * that could result in an inconsistency in case any of the inodes that
9235 * are part of this rename operation were logged before.
9237 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9238 btrfs_pin_log_trans(root);
9239 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9240 btrfs_pin_log_trans(dest);
9242 /* Do the log updates for all inodes. */
9243 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9244 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9245 old_rename_ctx.index, new_dentry->d_parent);
9246 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9247 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
9248 new_rename_ctx.index, old_dentry->d_parent);
9250 /* Now unpin the logs. */
9251 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9252 btrfs_end_log_trans(root);
9253 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9254 btrfs_end_log_trans(dest);
9256 ret2 = btrfs_end_transaction(trans);
9257 ret = ret ? ret : ret2;
9259 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9260 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9261 up_read(&fs_info->subvol_sem);
9266 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9267 struct btrfs_root *root,
9268 struct user_namespace *mnt_userns,
9270 struct dentry *dentry)
9273 struct inode *inode;
9277 ret = btrfs_get_free_objectid(root, &objectid);
9281 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
9282 dentry->d_name.name,
9284 btrfs_ino(BTRFS_I(dir)),
9286 S_IFCHR | WHITEOUT_MODE,
9289 if (IS_ERR(inode)) {
9290 ret = PTR_ERR(inode);
9294 inode->i_op = &btrfs_special_inode_operations;
9295 init_special_inode(inode, inode->i_mode,
9298 ret = btrfs_init_inode_security(trans, inode, dir,
9303 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9304 BTRFS_I(inode), 0, index);
9308 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9310 unlock_new_inode(inode);
9312 inode_dec_link_count(inode);
9318 static int btrfs_rename(struct user_namespace *mnt_userns,
9319 struct inode *old_dir, struct dentry *old_dentry,
9320 struct inode *new_dir, struct dentry *new_dentry,
9323 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9324 struct btrfs_trans_handle *trans;
9325 unsigned int trans_num_items;
9326 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9327 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9328 struct inode *new_inode = d_inode(new_dentry);
9329 struct inode *old_inode = d_inode(old_dentry);
9330 struct btrfs_rename_ctx rename_ctx;
9334 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9336 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9339 /* we only allow rename subvolume link between subvolumes */
9340 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9343 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9344 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9347 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9348 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9352 /* check for collisions, even if the name isn't there */
9353 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9354 new_dentry->d_name.name,
9355 new_dentry->d_name.len);
9358 if (ret == -EEXIST) {
9360 * eexist without a new_inode */
9361 if (WARN_ON(!new_inode)) {
9365 /* maybe -EOVERFLOW */
9372 * we're using rename to replace one file with another. Start IO on it
9373 * now so we don't add too much work to the end of the transaction
9375 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9376 filemap_flush(old_inode->i_mapping);
9378 /* close the racy window with snapshot create/destroy ioctl */
9379 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9380 down_read(&fs_info->subvol_sem);
9382 * We want to reserve the absolute worst case amount of items. So if
9383 * both inodes are subvols and we need to unlink them then that would
9384 * require 4 item modifications, but if they are both normal inodes it
9385 * would require 5 item modifications, so we'll assume they are normal
9386 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9387 * should cover the worst case number of items we'll modify.
9388 * If our rename has the whiteout flag, we need more 5 units for the
9389 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9390 * when selinux is enabled).
9392 trans_num_items = 11;
9393 if (flags & RENAME_WHITEOUT)
9394 trans_num_items += 5;
9395 trans = btrfs_start_transaction(root, trans_num_items);
9396 if (IS_ERR(trans)) {
9397 ret = PTR_ERR(trans);
9402 ret = btrfs_record_root_in_trans(trans, dest);
9407 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9411 BTRFS_I(old_inode)->dir_index = 0ULL;
9412 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9413 /* force full log commit if subvolume involved. */
9414 btrfs_set_log_full_commit(trans);
9416 ret = btrfs_insert_inode_ref(trans, dest,
9417 new_dentry->d_name.name,
9418 new_dentry->d_name.len,
9420 btrfs_ino(BTRFS_I(new_dir)), index);
9425 inode_inc_iversion(old_dir);
9426 inode_inc_iversion(new_dir);
9427 inode_inc_iversion(old_inode);
9428 old_dir->i_ctime = old_dir->i_mtime =
9429 new_dir->i_ctime = new_dir->i_mtime =
9430 old_inode->i_ctime = current_time(old_dir);
9432 if (old_dentry->d_parent != new_dentry->d_parent)
9433 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9434 BTRFS_I(old_inode), 1);
9436 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9437 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9439 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9440 BTRFS_I(d_inode(old_dentry)),
9441 old_dentry->d_name.name,
9442 old_dentry->d_name.len,
9445 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9448 btrfs_abort_transaction(trans, ret);
9453 inode_inc_iversion(new_inode);
9454 new_inode->i_ctime = current_time(new_inode);
9455 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9456 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9457 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9458 BUG_ON(new_inode->i_nlink == 0);
9460 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9461 BTRFS_I(d_inode(new_dentry)),
9462 new_dentry->d_name.name,
9463 new_dentry->d_name.len);
9465 if (!ret && new_inode->i_nlink == 0)
9466 ret = btrfs_orphan_add(trans,
9467 BTRFS_I(d_inode(new_dentry)));
9469 btrfs_abort_transaction(trans, ret);
9474 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9475 new_dentry->d_name.name,
9476 new_dentry->d_name.len, 0, index);
9478 btrfs_abort_transaction(trans, ret);
9482 if (old_inode->i_nlink == 1)
9483 BTRFS_I(old_inode)->dir_index = index;
9485 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9486 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9487 rename_ctx.index, new_dentry->d_parent);
9489 if (flags & RENAME_WHITEOUT) {
9490 ret = btrfs_whiteout_for_rename(trans, root, mnt_userns,
9491 old_dir, old_dentry);
9494 btrfs_abort_transaction(trans, ret);
9499 ret2 = btrfs_end_transaction(trans);
9500 ret = ret ? ret : ret2;
9502 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9503 up_read(&fs_info->subvol_sem);
9508 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9509 struct dentry *old_dentry, struct inode *new_dir,
9510 struct dentry *new_dentry, unsigned int flags)
9512 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9515 if (flags & RENAME_EXCHANGE)
9516 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9519 return btrfs_rename(mnt_userns, old_dir, old_dentry, new_dir,
9523 struct btrfs_delalloc_work {
9524 struct inode *inode;
9525 struct completion completion;
9526 struct list_head list;
9527 struct btrfs_work work;
9530 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9532 struct btrfs_delalloc_work *delalloc_work;
9533 struct inode *inode;
9535 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9537 inode = delalloc_work->inode;
9538 filemap_flush(inode->i_mapping);
9539 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9540 &BTRFS_I(inode)->runtime_flags))
9541 filemap_flush(inode->i_mapping);
9544 complete(&delalloc_work->completion);
9547 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9549 struct btrfs_delalloc_work *work;
9551 work = kmalloc(sizeof(*work), GFP_NOFS);
9555 init_completion(&work->completion);
9556 INIT_LIST_HEAD(&work->list);
9557 work->inode = inode;
9558 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9564 * some fairly slow code that needs optimization. This walks the list
9565 * of all the inodes with pending delalloc and forces them to disk.
9567 static int start_delalloc_inodes(struct btrfs_root *root,
9568 struct writeback_control *wbc, bool snapshot,
9569 bool in_reclaim_context)
9571 struct btrfs_inode *binode;
9572 struct inode *inode;
9573 struct btrfs_delalloc_work *work, *next;
9574 struct list_head works;
9575 struct list_head splice;
9577 bool full_flush = wbc->nr_to_write == LONG_MAX;
9579 INIT_LIST_HEAD(&works);
9580 INIT_LIST_HEAD(&splice);
9582 mutex_lock(&root->delalloc_mutex);
9583 spin_lock(&root->delalloc_lock);
9584 list_splice_init(&root->delalloc_inodes, &splice);
9585 while (!list_empty(&splice)) {
9586 binode = list_entry(splice.next, struct btrfs_inode,
9589 list_move_tail(&binode->delalloc_inodes,
9590 &root->delalloc_inodes);
9592 if (in_reclaim_context &&
9593 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9596 inode = igrab(&binode->vfs_inode);
9598 cond_resched_lock(&root->delalloc_lock);
9601 spin_unlock(&root->delalloc_lock);
9604 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9605 &binode->runtime_flags);
9607 work = btrfs_alloc_delalloc_work(inode);
9613 list_add_tail(&work->list, &works);
9614 btrfs_queue_work(root->fs_info->flush_workers,
9617 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9618 btrfs_add_delayed_iput(inode);
9619 if (ret || wbc->nr_to_write <= 0)
9623 spin_lock(&root->delalloc_lock);
9625 spin_unlock(&root->delalloc_lock);
9628 list_for_each_entry_safe(work, next, &works, list) {
9629 list_del_init(&work->list);
9630 wait_for_completion(&work->completion);
9634 if (!list_empty(&splice)) {
9635 spin_lock(&root->delalloc_lock);
9636 list_splice_tail(&splice, &root->delalloc_inodes);
9637 spin_unlock(&root->delalloc_lock);
9639 mutex_unlock(&root->delalloc_mutex);
9643 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9645 struct writeback_control wbc = {
9646 .nr_to_write = LONG_MAX,
9647 .sync_mode = WB_SYNC_NONE,
9649 .range_end = LLONG_MAX,
9651 struct btrfs_fs_info *fs_info = root->fs_info;
9653 if (BTRFS_FS_ERROR(fs_info))
9656 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9659 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9660 bool in_reclaim_context)
9662 struct writeback_control wbc = {
9664 .sync_mode = WB_SYNC_NONE,
9666 .range_end = LLONG_MAX,
9668 struct btrfs_root *root;
9669 struct list_head splice;
9672 if (BTRFS_FS_ERROR(fs_info))
9675 INIT_LIST_HEAD(&splice);
9677 mutex_lock(&fs_info->delalloc_root_mutex);
9678 spin_lock(&fs_info->delalloc_root_lock);
9679 list_splice_init(&fs_info->delalloc_roots, &splice);
9680 while (!list_empty(&splice)) {
9682 * Reset nr_to_write here so we know that we're doing a full
9686 wbc.nr_to_write = LONG_MAX;
9688 root = list_first_entry(&splice, struct btrfs_root,
9690 root = btrfs_grab_root(root);
9692 list_move_tail(&root->delalloc_root,
9693 &fs_info->delalloc_roots);
9694 spin_unlock(&fs_info->delalloc_root_lock);
9696 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9697 btrfs_put_root(root);
9698 if (ret < 0 || wbc.nr_to_write <= 0)
9700 spin_lock(&fs_info->delalloc_root_lock);
9702 spin_unlock(&fs_info->delalloc_root_lock);
9706 if (!list_empty(&splice)) {
9707 spin_lock(&fs_info->delalloc_root_lock);
9708 list_splice_tail(&splice, &fs_info->delalloc_roots);
9709 spin_unlock(&fs_info->delalloc_root_lock);
9711 mutex_unlock(&fs_info->delalloc_root_mutex);
9715 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9716 struct dentry *dentry, const char *symname)
9718 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9719 struct btrfs_trans_handle *trans;
9720 struct btrfs_root *root = BTRFS_I(dir)->root;
9721 struct btrfs_path *path;
9722 struct btrfs_key key;
9723 struct inode *inode = NULL;
9730 struct btrfs_file_extent_item *ei;
9731 struct extent_buffer *leaf;
9733 name_len = strlen(symname);
9734 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9735 return -ENAMETOOLONG;
9738 * 2 items for inode item and ref
9739 * 2 items for dir items
9740 * 1 item for updating parent inode item
9741 * 1 item for the inline extent item
9742 * 1 item for xattr if selinux is on
9744 trans = btrfs_start_transaction(root, 7);
9746 return PTR_ERR(trans);
9748 err = btrfs_get_free_objectid(root, &objectid);
9752 inode = btrfs_new_inode(trans, root, mnt_userns, dir,
9753 dentry->d_name.name, dentry->d_name.len,
9754 btrfs_ino(BTRFS_I(dir)), objectid,
9755 S_IFLNK | S_IRWXUGO, &index);
9756 if (IS_ERR(inode)) {
9757 err = PTR_ERR(inode);
9763 * If the active LSM wants to access the inode during
9764 * d_instantiate it needs these. Smack checks to see
9765 * if the filesystem supports xattrs by looking at the
9768 inode->i_fop = &btrfs_file_operations;
9769 inode->i_op = &btrfs_file_inode_operations;
9770 inode->i_mapping->a_ops = &btrfs_aops;
9772 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9776 path = btrfs_alloc_path();
9781 key.objectid = btrfs_ino(BTRFS_I(inode));
9783 key.type = BTRFS_EXTENT_DATA_KEY;
9784 datasize = btrfs_file_extent_calc_inline_size(name_len);
9785 err = btrfs_insert_empty_item(trans, root, path, &key,
9788 btrfs_free_path(path);
9791 leaf = path->nodes[0];
9792 ei = btrfs_item_ptr(leaf, path->slots[0],
9793 struct btrfs_file_extent_item);
9794 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9795 btrfs_set_file_extent_type(leaf, ei,
9796 BTRFS_FILE_EXTENT_INLINE);
9797 btrfs_set_file_extent_encryption(leaf, ei, 0);
9798 btrfs_set_file_extent_compression(leaf, ei, 0);
9799 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9800 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9802 ptr = btrfs_file_extent_inline_start(ei);
9803 write_extent_buffer(leaf, symname, ptr, name_len);
9804 btrfs_mark_buffer_dirty(leaf);
9805 btrfs_free_path(path);
9807 inode->i_op = &btrfs_symlink_inode_operations;
9808 inode_nohighmem(inode);
9809 inode_set_bytes(inode, name_len);
9810 btrfs_i_size_write(BTRFS_I(inode), name_len);
9811 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
9813 * Last step, add directory indexes for our symlink inode. This is the
9814 * last step to avoid extra cleanup of these indexes if an error happens
9818 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9819 BTRFS_I(inode), 0, index);
9823 d_instantiate_new(dentry, inode);
9826 btrfs_end_transaction(trans);
9828 inode_dec_link_count(inode);
9829 discard_new_inode(inode);
9831 btrfs_btree_balance_dirty(fs_info);
9835 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9836 struct btrfs_trans_handle *trans_in,
9837 struct btrfs_inode *inode,
9838 struct btrfs_key *ins,
9841 struct btrfs_file_extent_item stack_fi;
9842 struct btrfs_replace_extent_info extent_info;
9843 struct btrfs_trans_handle *trans = trans_in;
9844 struct btrfs_path *path;
9845 u64 start = ins->objectid;
9846 u64 len = ins->offset;
9847 int qgroup_released;
9850 memset(&stack_fi, 0, sizeof(stack_fi));
9852 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9853 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9854 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9855 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9856 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9857 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9858 /* Encryption and other encoding is reserved and all 0 */
9860 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9861 if (qgroup_released < 0)
9862 return ERR_PTR(qgroup_released);
9865 ret = insert_reserved_file_extent(trans, inode,
9866 file_offset, &stack_fi,
9867 true, qgroup_released);
9873 extent_info.disk_offset = start;
9874 extent_info.disk_len = len;
9875 extent_info.data_offset = 0;
9876 extent_info.data_len = len;
9877 extent_info.file_offset = file_offset;
9878 extent_info.extent_buf = (char *)&stack_fi;
9879 extent_info.is_new_extent = true;
9880 extent_info.qgroup_reserved = qgroup_released;
9881 extent_info.insertions = 0;
9883 path = btrfs_alloc_path();
9889 ret = btrfs_replace_file_extents(inode, path, file_offset,
9890 file_offset + len - 1, &extent_info,
9892 btrfs_free_path(path);
9899 * We have released qgroup data range at the beginning of the function,
9900 * and normally qgroup_released bytes will be freed when committing
9902 * But if we error out early, we have to free what we have released
9903 * or we leak qgroup data reservation.
9905 btrfs_qgroup_free_refroot(inode->root->fs_info,
9906 inode->root->root_key.objectid, qgroup_released,
9907 BTRFS_QGROUP_RSV_DATA);
9908 return ERR_PTR(ret);
9911 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9912 u64 start, u64 num_bytes, u64 min_size,
9913 loff_t actual_len, u64 *alloc_hint,
9914 struct btrfs_trans_handle *trans)
9916 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9917 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9918 struct extent_map *em;
9919 struct btrfs_root *root = BTRFS_I(inode)->root;
9920 struct btrfs_key ins;
9921 u64 cur_offset = start;
9922 u64 clear_offset = start;
9925 u64 last_alloc = (u64)-1;
9927 bool own_trans = true;
9928 u64 end = start + num_bytes - 1;
9932 while (num_bytes > 0) {
9933 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9934 cur_bytes = max(cur_bytes, min_size);
9936 * If we are severely fragmented we could end up with really
9937 * small allocations, so if the allocator is returning small
9938 * chunks lets make its job easier by only searching for those
9941 cur_bytes = min(cur_bytes, last_alloc);
9942 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9943 min_size, 0, *alloc_hint, &ins, 1, 0);
9948 * We've reserved this space, and thus converted it from
9949 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9950 * from here on out we will only need to clear our reservation
9951 * for the remaining unreserved area, so advance our
9952 * clear_offset by our extent size.
9954 clear_offset += ins.offset;
9956 last_alloc = ins.offset;
9957 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9960 * Now that we inserted the prealloc extent we can finally
9961 * decrement the number of reservations in the block group.
9962 * If we did it before, we could race with relocation and have
9963 * relocation miss the reserved extent, making it fail later.
9965 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9966 if (IS_ERR(trans)) {
9967 ret = PTR_ERR(trans);
9968 btrfs_free_reserved_extent(fs_info, ins.objectid,
9973 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9974 cur_offset + ins.offset -1, 0);
9976 em = alloc_extent_map();
9978 btrfs_set_inode_full_sync(BTRFS_I(inode));
9982 em->start = cur_offset;
9983 em->orig_start = cur_offset;
9984 em->len = ins.offset;
9985 em->block_start = ins.objectid;
9986 em->block_len = ins.offset;
9987 em->orig_block_len = ins.offset;
9988 em->ram_bytes = ins.offset;
9989 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9990 em->generation = trans->transid;
9993 write_lock(&em_tree->lock);
9994 ret = add_extent_mapping(em_tree, em, 1);
9995 write_unlock(&em_tree->lock);
9998 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9999 cur_offset + ins.offset - 1,
10002 free_extent_map(em);
10004 num_bytes -= ins.offset;
10005 cur_offset += ins.offset;
10006 *alloc_hint = ins.objectid + ins.offset;
10008 inode_inc_iversion(inode);
10009 inode->i_ctime = current_time(inode);
10010 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10011 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10012 (actual_len > inode->i_size) &&
10013 (cur_offset > inode->i_size)) {
10014 if (cur_offset > actual_len)
10015 i_size = actual_len;
10017 i_size = cur_offset;
10018 i_size_write(inode, i_size);
10019 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10022 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10025 btrfs_abort_transaction(trans, ret);
10027 btrfs_end_transaction(trans);
10032 btrfs_end_transaction(trans);
10036 if (clear_offset < end)
10037 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10038 end - clear_offset + 1);
10042 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10043 u64 start, u64 num_bytes, u64 min_size,
10044 loff_t actual_len, u64 *alloc_hint)
10046 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10047 min_size, actual_len, alloc_hint,
10051 int btrfs_prealloc_file_range_trans(struct inode *inode,
10052 struct btrfs_trans_handle *trans, int mode,
10053 u64 start, u64 num_bytes, u64 min_size,
10054 loff_t actual_len, u64 *alloc_hint)
10056 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10057 min_size, actual_len, alloc_hint, trans);
10060 static int btrfs_permission(struct user_namespace *mnt_userns,
10061 struct inode *inode, int mask)
10063 struct btrfs_root *root = BTRFS_I(inode)->root;
10064 umode_t mode = inode->i_mode;
10066 if (mask & MAY_WRITE &&
10067 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10068 if (btrfs_root_readonly(root))
10070 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10073 return generic_permission(mnt_userns, inode, mask);
10076 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10077 struct dentry *dentry, umode_t mode)
10079 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10080 struct btrfs_trans_handle *trans;
10081 struct btrfs_root *root = BTRFS_I(dir)->root;
10082 struct inode *inode = NULL;
10088 * 5 units required for adding orphan entry
10090 trans = btrfs_start_transaction(root, 5);
10092 return PTR_ERR(trans);
10094 ret = btrfs_get_free_objectid(root, &objectid);
10098 inode = btrfs_new_inode(trans, root, mnt_userns, dir, NULL, 0,
10099 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10100 if (IS_ERR(inode)) {
10101 ret = PTR_ERR(inode);
10106 inode->i_fop = &btrfs_file_operations;
10107 inode->i_op = &btrfs_file_inode_operations;
10109 inode->i_mapping->a_ops = &btrfs_aops;
10111 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10115 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10118 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10123 * We set number of links to 0 in btrfs_new_inode(), and here we set
10124 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10127 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10129 set_nlink(inode, 1);
10130 d_tmpfile(dentry, inode);
10131 unlock_new_inode(inode);
10132 mark_inode_dirty(inode);
10134 btrfs_end_transaction(trans);
10136 discard_new_inode(inode);
10137 btrfs_btree_balance_dirty(fs_info);
10141 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
10143 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10144 unsigned long index = start >> PAGE_SHIFT;
10145 unsigned long end_index = end >> PAGE_SHIFT;
10149 ASSERT(end + 1 - start <= U32_MAX);
10150 len = end + 1 - start;
10151 while (index <= end_index) {
10152 page = find_get_page(inode->vfs_inode.i_mapping, index);
10153 ASSERT(page); /* Pages should be in the extent_io_tree */
10155 btrfs_page_set_writeback(fs_info, page, start, len);
10161 static int btrfs_encoded_io_compression_from_extent(
10162 struct btrfs_fs_info *fs_info,
10165 switch (compress_type) {
10166 case BTRFS_COMPRESS_NONE:
10167 return BTRFS_ENCODED_IO_COMPRESSION_NONE;
10168 case BTRFS_COMPRESS_ZLIB:
10169 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
10170 case BTRFS_COMPRESS_LZO:
10172 * The LZO format depends on the sector size. 64K is the maximum
10173 * sector size that we support.
10175 if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
10177 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
10178 (fs_info->sectorsize_bits - 12);
10179 case BTRFS_COMPRESS_ZSTD:
10180 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
10186 static ssize_t btrfs_encoded_read_inline(
10187 struct kiocb *iocb,
10188 struct iov_iter *iter, u64 start,
10190 struct extent_state **cached_state,
10191 u64 extent_start, size_t count,
10192 struct btrfs_ioctl_encoded_io_args *encoded,
10195 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10196 struct btrfs_root *root = inode->root;
10197 struct btrfs_fs_info *fs_info = root->fs_info;
10198 struct extent_io_tree *io_tree = &inode->io_tree;
10199 struct btrfs_path *path;
10200 struct extent_buffer *leaf;
10201 struct btrfs_file_extent_item *item;
10207 path = btrfs_alloc_path();
10212 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
10216 /* The extent item disappeared? */
10221 leaf = path->nodes[0];
10222 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10224 ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
10225 ptr = btrfs_file_extent_inline_start(item);
10227 encoded->len = min_t(u64, extent_start + ram_bytes,
10228 inode->vfs_inode.i_size) - iocb->ki_pos;
10229 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10230 btrfs_file_extent_compression(leaf, item));
10233 encoded->compression = ret;
10234 if (encoded->compression) {
10235 size_t inline_size;
10237 inline_size = btrfs_file_extent_inline_item_len(leaf,
10239 if (inline_size > count) {
10243 count = inline_size;
10244 encoded->unencoded_len = ram_bytes;
10245 encoded->unencoded_offset = iocb->ki_pos - extent_start;
10247 count = min_t(u64, count, encoded->len);
10248 encoded->len = count;
10249 encoded->unencoded_len = count;
10250 ptr += iocb->ki_pos - extent_start;
10253 tmp = kmalloc(count, GFP_NOFS);
10258 read_extent_buffer(leaf, tmp, ptr, count);
10259 btrfs_release_path(path);
10260 unlock_extent_cached(io_tree, start, lockend, cached_state);
10261 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10264 ret = copy_to_iter(tmp, count, iter);
10269 btrfs_free_path(path);
10273 struct btrfs_encoded_read_private {
10274 struct btrfs_inode *inode;
10276 wait_queue_head_t wait;
10278 blk_status_t status;
10282 static blk_status_t submit_encoded_read_bio(struct btrfs_inode *inode,
10283 struct bio *bio, int mirror_num)
10285 struct btrfs_encoded_read_private *priv = bio->bi_private;
10286 struct btrfs_bio *bbio = btrfs_bio(bio);
10287 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10290 if (!priv->skip_csum) {
10291 ret = btrfs_lookup_bio_sums(&inode->vfs_inode, bio, NULL);
10296 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
10298 btrfs_bio_free_csum(bbio);
10302 atomic_inc(&priv->pending);
10303 ret = btrfs_map_bio(fs_info, bio, mirror_num);
10305 atomic_dec(&priv->pending);
10306 btrfs_bio_free_csum(bbio);
10311 static blk_status_t btrfs_encoded_read_verify_csum(struct btrfs_bio *bbio)
10313 const bool uptodate = (bbio->bio.bi_status == BLK_STS_OK);
10314 struct btrfs_encoded_read_private *priv = bbio->bio.bi_private;
10315 struct btrfs_inode *inode = priv->inode;
10316 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10317 u32 sectorsize = fs_info->sectorsize;
10318 struct bio_vec *bvec;
10319 struct bvec_iter_all iter_all;
10320 u64 start = priv->file_offset;
10321 u32 bio_offset = 0;
10323 if (priv->skip_csum || !uptodate)
10324 return bbio->bio.bi_status;
10326 bio_for_each_segment_all(bvec, &bbio->bio, iter_all) {
10327 unsigned int i, nr_sectors, pgoff;
10329 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
10330 pgoff = bvec->bv_offset;
10331 for (i = 0; i < nr_sectors; i++) {
10332 ASSERT(pgoff < PAGE_SIZE);
10333 if (check_data_csum(&inode->vfs_inode, bbio, bio_offset,
10334 bvec->bv_page, pgoff, start))
10335 return BLK_STS_IOERR;
10336 start += sectorsize;
10337 bio_offset += sectorsize;
10338 pgoff += sectorsize;
10344 static void btrfs_encoded_read_endio(struct bio *bio)
10346 struct btrfs_encoded_read_private *priv = bio->bi_private;
10347 struct btrfs_bio *bbio = btrfs_bio(bio);
10348 blk_status_t status;
10350 status = btrfs_encoded_read_verify_csum(bbio);
10353 * The memory barrier implied by the atomic_dec_return() here
10354 * pairs with the memory barrier implied by the
10355 * atomic_dec_return() or io_wait_event() in
10356 * btrfs_encoded_read_regular_fill_pages() to ensure that this
10357 * write is observed before the load of status in
10358 * btrfs_encoded_read_regular_fill_pages().
10360 WRITE_ONCE(priv->status, status);
10362 if (!atomic_dec_return(&priv->pending))
10363 wake_up(&priv->wait);
10364 btrfs_bio_free_csum(bbio);
10368 static int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
10372 struct page **pages)
10374 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10375 struct btrfs_encoded_read_private priv = {
10377 .file_offset = file_offset,
10378 .pending = ATOMIC_INIT(1),
10379 .skip_csum = (inode->flags & BTRFS_INODE_NODATASUM),
10381 unsigned long i = 0;
10385 init_waitqueue_head(&priv.wait);
10387 * Submit bios for the extent, splitting due to bio or stripe limits as
10390 while (cur < disk_io_size) {
10391 struct extent_map *em;
10392 struct btrfs_io_geometry geom;
10393 struct bio *bio = NULL;
10396 em = btrfs_get_chunk_map(fs_info, disk_bytenr + cur,
10397 disk_io_size - cur);
10401 ret = btrfs_get_io_geometry(fs_info, em, BTRFS_MAP_READ,
10402 disk_bytenr + cur, &geom);
10403 free_extent_map(em);
10406 WRITE_ONCE(priv.status, errno_to_blk_status(ret));
10409 remaining = min(geom.len, disk_io_size - cur);
10410 while (bio || remaining) {
10411 size_t bytes = min_t(u64, remaining, PAGE_SIZE);
10414 bio = btrfs_bio_alloc(BIO_MAX_VECS);
10415 bio->bi_iter.bi_sector =
10416 (disk_bytenr + cur) >> SECTOR_SHIFT;
10417 bio->bi_end_io = btrfs_encoded_read_endio;
10418 bio->bi_private = &priv;
10419 bio->bi_opf = REQ_OP_READ;
10423 bio_add_page(bio, pages[i], bytes, 0) < bytes) {
10424 blk_status_t status;
10426 status = submit_encoded_read_bio(inode, bio, 0);
10428 WRITE_ONCE(priv.status, status);
10438 remaining -= bytes;
10443 if (atomic_dec_return(&priv.pending))
10444 io_wait_event(priv.wait, !atomic_read(&priv.pending));
10445 /* See btrfs_encoded_read_endio() for ordering. */
10446 return blk_status_to_errno(READ_ONCE(priv.status));
10449 static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
10450 struct iov_iter *iter,
10451 u64 start, u64 lockend,
10452 struct extent_state **cached_state,
10453 u64 disk_bytenr, u64 disk_io_size,
10454 size_t count, bool compressed,
10457 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10458 struct extent_io_tree *io_tree = &inode->io_tree;
10459 struct page **pages;
10460 unsigned long nr_pages, i;
10462 size_t page_offset;
10465 nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
10466 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
10469 for (i = 0; i < nr_pages; i++) {
10470 pages[i] = alloc_page(GFP_NOFS);
10477 ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
10478 disk_io_size, pages);
10482 unlock_extent_cached(io_tree, start, lockend, cached_state);
10483 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10490 i = (iocb->ki_pos - start) >> PAGE_SHIFT;
10491 page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
10494 while (cur < count) {
10495 size_t bytes = min_t(size_t, count - cur,
10496 PAGE_SIZE - page_offset);
10498 if (copy_page_to_iter(pages[i], page_offset, bytes,
10509 for (i = 0; i < nr_pages; i++) {
10511 __free_page(pages[i]);
10517 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
10518 struct btrfs_ioctl_encoded_io_args *encoded)
10520 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10521 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10522 struct extent_io_tree *io_tree = &inode->io_tree;
10524 size_t count = iov_iter_count(iter);
10525 u64 start, lockend, disk_bytenr, disk_io_size;
10526 struct extent_state *cached_state = NULL;
10527 struct extent_map *em;
10528 bool unlocked = false;
10530 file_accessed(iocb->ki_filp);
10532 btrfs_inode_lock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10534 if (iocb->ki_pos >= inode->vfs_inode.i_size) {
10535 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10538 start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
10540 * We don't know how long the extent containing iocb->ki_pos is, but if
10541 * it's compressed we know that it won't be longer than this.
10543 lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
10546 struct btrfs_ordered_extent *ordered;
10548 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
10549 lockend - start + 1);
10551 goto out_unlock_inode;
10552 lock_extent_bits(io_tree, start, lockend, &cached_state);
10553 ordered = btrfs_lookup_ordered_range(inode, start,
10554 lockend - start + 1);
10557 btrfs_put_ordered_extent(ordered);
10558 unlock_extent_cached(io_tree, start, lockend, &cached_state);
10562 em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
10565 goto out_unlock_extent;
10568 if (em->block_start == EXTENT_MAP_INLINE) {
10569 u64 extent_start = em->start;
10572 * For inline extents we get everything we need out of the
10575 free_extent_map(em);
10577 ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
10578 &cached_state, extent_start,
10579 count, encoded, &unlocked);
10584 * We only want to return up to EOF even if the extent extends beyond
10587 encoded->len = min_t(u64, extent_map_end(em),
10588 inode->vfs_inode.i_size) - iocb->ki_pos;
10589 if (em->block_start == EXTENT_MAP_HOLE ||
10590 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
10591 disk_bytenr = EXTENT_MAP_HOLE;
10592 count = min_t(u64, count, encoded->len);
10593 encoded->len = count;
10594 encoded->unencoded_len = count;
10595 } else if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10596 disk_bytenr = em->block_start;
10598 * Bail if the buffer isn't large enough to return the whole
10599 * compressed extent.
10601 if (em->block_len > count) {
10605 disk_io_size = count = em->block_len;
10606 encoded->unencoded_len = em->ram_bytes;
10607 encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
10608 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10609 em->compress_type);
10612 encoded->compression = ret;
10614 disk_bytenr = em->block_start + (start - em->start);
10615 if (encoded->len > count)
10616 encoded->len = count;
10618 * Don't read beyond what we locked. This also limits the page
10619 * allocations that we'll do.
10621 disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
10622 count = start + disk_io_size - iocb->ki_pos;
10623 encoded->len = count;
10624 encoded->unencoded_len = count;
10625 disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
10627 free_extent_map(em);
10630 if (disk_bytenr == EXTENT_MAP_HOLE) {
10631 unlock_extent_cached(io_tree, start, lockend, &cached_state);
10632 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10634 ret = iov_iter_zero(count, iter);
10638 ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
10639 &cached_state, disk_bytenr,
10640 disk_io_size, count,
10641 encoded->compression,
10647 iocb->ki_pos += encoded->len;
10649 free_extent_map(em);
10652 unlock_extent_cached(io_tree, start, lockend, &cached_state);
10655 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10659 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
10660 const struct btrfs_ioctl_encoded_io_args *encoded)
10662 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10663 struct btrfs_root *root = inode->root;
10664 struct btrfs_fs_info *fs_info = root->fs_info;
10665 struct extent_io_tree *io_tree = &inode->io_tree;
10666 struct extent_changeset *data_reserved = NULL;
10667 struct extent_state *cached_state = NULL;
10671 u64 num_bytes, ram_bytes, disk_num_bytes;
10672 unsigned long nr_pages, i;
10673 struct page **pages;
10674 struct btrfs_key ins;
10675 bool extent_reserved = false;
10676 struct extent_map *em;
10679 switch (encoded->compression) {
10680 case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
10681 compression = BTRFS_COMPRESS_ZLIB;
10683 case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
10684 compression = BTRFS_COMPRESS_ZSTD;
10686 case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
10687 case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
10688 case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
10689 case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
10690 case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
10691 /* The sector size must match for LZO. */
10692 if (encoded->compression -
10693 BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
10694 fs_info->sectorsize_bits)
10696 compression = BTRFS_COMPRESS_LZO;
10701 if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
10704 orig_count = iov_iter_count(from);
10706 /* The extent size must be sane. */
10707 if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
10708 orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
10712 * The compressed data must be smaller than the decompressed data.
10714 * It's of course possible for data to compress to larger or the same
10715 * size, but the buffered I/O path falls back to no compression for such
10716 * data, and we don't want to break any assumptions by creating these
10719 * Note that this is less strict than the current check we have that the
10720 * compressed data must be at least one sector smaller than the
10721 * decompressed data. We only want to enforce the weaker requirement
10722 * from old kernels that it is at least one byte smaller.
10724 if (orig_count >= encoded->unencoded_len)
10727 /* The extent must start on a sector boundary. */
10728 start = iocb->ki_pos;
10729 if (!IS_ALIGNED(start, fs_info->sectorsize))
10733 * The extent must end on a sector boundary. However, we allow a write
10734 * which ends at or extends i_size to have an unaligned length; we round
10735 * up the extent size and set i_size to the unaligned end.
10737 if (start + encoded->len < inode->vfs_inode.i_size &&
10738 !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
10741 /* Finally, the offset in the unencoded data must be sector-aligned. */
10742 if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
10745 num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10746 ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10747 end = start + num_bytes - 1;
10750 * If the extent cannot be inline, the compressed data on disk must be
10751 * sector-aligned. For convenience, we extend it with zeroes if it
10754 disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10755 nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
10756 pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
10759 for (i = 0; i < nr_pages; i++) {
10760 size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
10763 pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
10768 kaddr = kmap(pages[i]);
10769 if (copy_from_iter(kaddr, bytes, from) != bytes) {
10774 if (bytes < PAGE_SIZE)
10775 memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
10780 struct btrfs_ordered_extent *ordered;
10782 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
10785 ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10786 start >> PAGE_SHIFT,
10787 end >> PAGE_SHIFT);
10790 lock_extent_bits(io_tree, start, end, &cached_state);
10791 ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10793 !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10796 btrfs_put_ordered_extent(ordered);
10797 unlock_extent_cached(io_tree, start, end, &cached_state);
10802 * We don't use the higher-level delalloc space functions because our
10803 * num_bytes and disk_num_bytes are different.
10805 ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10808 ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10810 goto out_free_data_space;
10811 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes);
10813 goto out_qgroup_free_data;
10815 /* Try an inline extent first. */
10816 if (start == 0 && encoded->unencoded_len == encoded->len &&
10817 encoded->unencoded_offset == 0) {
10818 ret = cow_file_range_inline(inode, encoded->len, orig_count,
10819 compression, pages, true);
10823 goto out_delalloc_release;
10827 ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10828 disk_num_bytes, 0, 0, &ins, 1, 1);
10830 goto out_delalloc_release;
10831 extent_reserved = true;
10833 em = create_io_em(inode, start, num_bytes,
10834 start - encoded->unencoded_offset, ins.objectid,
10835 ins.offset, ins.offset, ram_bytes, compression,
10836 BTRFS_ORDERED_COMPRESSED);
10839 goto out_free_reserved;
10841 free_extent_map(em);
10843 ret = btrfs_add_ordered_extent(inode, start, num_bytes, ram_bytes,
10844 ins.objectid, ins.offset,
10845 encoded->unencoded_offset,
10846 (1 << BTRFS_ORDERED_ENCODED) |
10847 (1 << BTRFS_ORDERED_COMPRESSED),
10850 btrfs_drop_extent_cache(inode, start, end, 0);
10851 goto out_free_reserved;
10853 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10855 if (start + encoded->len > inode->vfs_inode.i_size)
10856 i_size_write(&inode->vfs_inode, start + encoded->len);
10858 unlock_extent_cached(io_tree, start, end, &cached_state);
10860 btrfs_delalloc_release_extents(inode, num_bytes);
10862 if (btrfs_submit_compressed_write(inode, start, num_bytes, ins.objectid,
10863 ins.offset, pages, nr_pages, 0, NULL,
10865 btrfs_writepage_endio_finish_ordered(inode, pages[0], start, end, 0);
10873 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10874 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
10875 out_delalloc_release:
10876 btrfs_delalloc_release_extents(inode, num_bytes);
10877 btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10878 out_qgroup_free_data:
10880 btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes);
10881 out_free_data_space:
10883 * If btrfs_reserve_extent() succeeded, then we already decremented
10886 if (!extent_reserved)
10887 btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
10889 unlock_extent_cached(io_tree, start, end, &cached_state);
10891 for (i = 0; i < nr_pages; i++) {
10893 __free_page(pages[i]);
10898 iocb->ki_pos += encoded->len;
10904 * Add an entry indicating a block group or device which is pinned by a
10905 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10906 * negative errno on failure.
10908 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10909 bool is_block_group)
10911 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10912 struct btrfs_swapfile_pin *sp, *entry;
10913 struct rb_node **p;
10914 struct rb_node *parent = NULL;
10916 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10921 sp->is_block_group = is_block_group;
10922 sp->bg_extent_count = 1;
10924 spin_lock(&fs_info->swapfile_pins_lock);
10925 p = &fs_info->swapfile_pins.rb_node;
10928 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10929 if (sp->ptr < entry->ptr ||
10930 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10931 p = &(*p)->rb_left;
10932 } else if (sp->ptr > entry->ptr ||
10933 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10934 p = &(*p)->rb_right;
10936 if (is_block_group)
10937 entry->bg_extent_count++;
10938 spin_unlock(&fs_info->swapfile_pins_lock);
10943 rb_link_node(&sp->node, parent, p);
10944 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10945 spin_unlock(&fs_info->swapfile_pins_lock);
10949 /* Free all of the entries pinned by this swapfile. */
10950 static void btrfs_free_swapfile_pins(struct inode *inode)
10952 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10953 struct btrfs_swapfile_pin *sp;
10954 struct rb_node *node, *next;
10956 spin_lock(&fs_info->swapfile_pins_lock);
10957 node = rb_first(&fs_info->swapfile_pins);
10959 next = rb_next(node);
10960 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10961 if (sp->inode == inode) {
10962 rb_erase(&sp->node, &fs_info->swapfile_pins);
10963 if (sp->is_block_group) {
10964 btrfs_dec_block_group_swap_extents(sp->ptr,
10965 sp->bg_extent_count);
10966 btrfs_put_block_group(sp->ptr);
10972 spin_unlock(&fs_info->swapfile_pins_lock);
10975 struct btrfs_swap_info {
10981 unsigned long nr_pages;
10985 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10986 struct btrfs_swap_info *bsi)
10988 unsigned long nr_pages;
10989 unsigned long max_pages;
10990 u64 first_ppage, first_ppage_reported, next_ppage;
10994 * Our swapfile may have had its size extended after the swap header was
10995 * written. In that case activating the swapfile should not go beyond
10996 * the max size set in the swap header.
10998 if (bsi->nr_pages >= sis->max)
11001 max_pages = sis->max - bsi->nr_pages;
11002 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
11003 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
11004 PAGE_SIZE) >> PAGE_SHIFT;
11006 if (first_ppage >= next_ppage)
11008 nr_pages = next_ppage - first_ppage;
11009 nr_pages = min(nr_pages, max_pages);
11011 first_ppage_reported = first_ppage;
11012 if (bsi->start == 0)
11013 first_ppage_reported++;
11014 if (bsi->lowest_ppage > first_ppage_reported)
11015 bsi->lowest_ppage = first_ppage_reported;
11016 if (bsi->highest_ppage < (next_ppage - 1))
11017 bsi->highest_ppage = next_ppage - 1;
11019 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
11022 bsi->nr_extents += ret;
11023 bsi->nr_pages += nr_pages;
11027 static void btrfs_swap_deactivate(struct file *file)
11029 struct inode *inode = file_inode(file);
11031 btrfs_free_swapfile_pins(inode);
11032 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
11035 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
11038 struct inode *inode = file_inode(file);
11039 struct btrfs_root *root = BTRFS_I(inode)->root;
11040 struct btrfs_fs_info *fs_info = root->fs_info;
11041 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
11042 struct extent_state *cached_state = NULL;
11043 struct extent_map *em = NULL;
11044 struct btrfs_device *device = NULL;
11045 struct btrfs_swap_info bsi = {
11046 .lowest_ppage = (sector_t)-1ULL,
11053 * If the swap file was just created, make sure delalloc is done. If the
11054 * file changes again after this, the user is doing something stupid and
11055 * we don't really care.
11057 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
11062 * The inode is locked, so these flags won't change after we check them.
11064 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
11065 btrfs_warn(fs_info, "swapfile must not be compressed");
11068 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
11069 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
11072 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
11073 btrfs_warn(fs_info, "swapfile must not be checksummed");
11078 * Balance or device remove/replace/resize can move stuff around from
11079 * under us. The exclop protection makes sure they aren't running/won't
11080 * run concurrently while we are mapping the swap extents, and
11081 * fs_info->swapfile_pins prevents them from running while the swap
11082 * file is active and moving the extents. Note that this also prevents
11083 * a concurrent device add which isn't actually necessary, but it's not
11084 * really worth the trouble to allow it.
11086 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
11087 btrfs_warn(fs_info,
11088 "cannot activate swapfile while exclusive operation is running");
11093 * Prevent snapshot creation while we are activating the swap file.
11094 * We do not want to race with snapshot creation. If snapshot creation
11095 * already started before we bumped nr_swapfiles from 0 to 1 and
11096 * completes before the first write into the swap file after it is
11097 * activated, than that write would fallback to COW.
11099 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
11100 btrfs_exclop_finish(fs_info);
11101 btrfs_warn(fs_info,
11102 "cannot activate swapfile because snapshot creation is in progress");
11106 * Snapshots can create extents which require COW even if NODATACOW is
11107 * set. We use this counter to prevent snapshots. We must increment it
11108 * before walking the extents because we don't want a concurrent
11109 * snapshot to run after we've already checked the extents.
11111 atomic_inc(&root->nr_swapfiles);
11113 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
11115 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
11117 while (start < isize) {
11118 u64 logical_block_start, physical_block_start;
11119 struct btrfs_block_group *bg;
11120 u64 len = isize - start;
11122 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
11128 if (em->block_start == EXTENT_MAP_HOLE) {
11129 btrfs_warn(fs_info, "swapfile must not have holes");
11133 if (em->block_start == EXTENT_MAP_INLINE) {
11135 * It's unlikely we'll ever actually find ourselves
11136 * here, as a file small enough to fit inline won't be
11137 * big enough to store more than the swap header, but in
11138 * case something changes in the future, let's catch it
11139 * here rather than later.
11141 btrfs_warn(fs_info, "swapfile must not be inline");
11145 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
11146 btrfs_warn(fs_info, "swapfile must not be compressed");
11151 logical_block_start = em->block_start + (start - em->start);
11152 len = min(len, em->len - (start - em->start));
11153 free_extent_map(em);
11156 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
11162 btrfs_warn(fs_info,
11163 "swapfile must not be copy-on-write");
11168 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
11174 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
11175 btrfs_warn(fs_info,
11176 "swapfile must have single data profile");
11181 if (device == NULL) {
11182 device = em->map_lookup->stripes[0].dev;
11183 ret = btrfs_add_swapfile_pin(inode, device, false);
11188 } else if (device != em->map_lookup->stripes[0].dev) {
11189 btrfs_warn(fs_info, "swapfile must be on one device");
11194 physical_block_start = (em->map_lookup->stripes[0].physical +
11195 (logical_block_start - em->start));
11196 len = min(len, em->len - (logical_block_start - em->start));
11197 free_extent_map(em);
11200 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
11202 btrfs_warn(fs_info,
11203 "could not find block group containing swapfile");
11208 if (!btrfs_inc_block_group_swap_extents(bg)) {
11209 btrfs_warn(fs_info,
11210 "block group for swapfile at %llu is read-only%s",
11212 atomic_read(&fs_info->scrubs_running) ?
11213 " (scrub running)" : "");
11214 btrfs_put_block_group(bg);
11219 ret = btrfs_add_swapfile_pin(inode, bg, true);
11221 btrfs_put_block_group(bg);
11228 if (bsi.block_len &&
11229 bsi.block_start + bsi.block_len == physical_block_start) {
11230 bsi.block_len += len;
11232 if (bsi.block_len) {
11233 ret = btrfs_add_swap_extent(sis, &bsi);
11238 bsi.block_start = physical_block_start;
11239 bsi.block_len = len;
11246 ret = btrfs_add_swap_extent(sis, &bsi);
11249 if (!IS_ERR_OR_NULL(em))
11250 free_extent_map(em);
11252 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
11255 btrfs_swap_deactivate(file);
11257 btrfs_drew_write_unlock(&root->snapshot_lock);
11259 btrfs_exclop_finish(fs_info);
11265 sis->bdev = device->bdev;
11266 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
11267 sis->max = bsi.nr_pages;
11268 sis->pages = bsi.nr_pages - 1;
11269 sis->highest_bit = bsi.nr_pages - 1;
11270 return bsi.nr_extents;
11273 static void btrfs_swap_deactivate(struct file *file)
11277 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
11280 return -EOPNOTSUPP;
11285 * Update the number of bytes used in the VFS' inode. When we replace extents in
11286 * a range (clone, dedupe, fallocate's zero range), we must update the number of
11287 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
11288 * always get a correct value.
11290 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
11291 const u64 add_bytes,
11292 const u64 del_bytes)
11294 if (add_bytes == del_bytes)
11297 spin_lock(&inode->lock);
11299 inode_sub_bytes(&inode->vfs_inode, del_bytes);
11301 inode_add_bytes(&inode->vfs_inode, add_bytes);
11302 spin_unlock(&inode->lock);
11305 static const struct inode_operations btrfs_dir_inode_operations = {
11306 .getattr = btrfs_getattr,
11307 .lookup = btrfs_lookup,
11308 .create = btrfs_create,
11309 .unlink = btrfs_unlink,
11310 .link = btrfs_link,
11311 .mkdir = btrfs_mkdir,
11312 .rmdir = btrfs_rmdir,
11313 .rename = btrfs_rename2,
11314 .symlink = btrfs_symlink,
11315 .setattr = btrfs_setattr,
11316 .mknod = btrfs_mknod,
11317 .listxattr = btrfs_listxattr,
11318 .permission = btrfs_permission,
11319 .get_acl = btrfs_get_acl,
11320 .set_acl = btrfs_set_acl,
11321 .update_time = btrfs_update_time,
11322 .tmpfile = btrfs_tmpfile,
11323 .fileattr_get = btrfs_fileattr_get,
11324 .fileattr_set = btrfs_fileattr_set,
11327 static const struct file_operations btrfs_dir_file_operations = {
11328 .llseek = generic_file_llseek,
11329 .read = generic_read_dir,
11330 .iterate_shared = btrfs_real_readdir,
11331 .open = btrfs_opendir,
11332 .unlocked_ioctl = btrfs_ioctl,
11333 #ifdef CONFIG_COMPAT
11334 .compat_ioctl = btrfs_compat_ioctl,
11336 .release = btrfs_release_file,
11337 .fsync = btrfs_sync_file,
11341 * btrfs doesn't support the bmap operation because swapfiles
11342 * use bmap to make a mapping of extents in the file. They assume
11343 * these extents won't change over the life of the file and they
11344 * use the bmap result to do IO directly to the drive.
11346 * the btrfs bmap call would return logical addresses that aren't
11347 * suitable for IO and they also will change frequently as COW
11348 * operations happen. So, swapfile + btrfs == corruption.
11350 * For now we're avoiding this by dropping bmap.
11352 static const struct address_space_operations btrfs_aops = {
11353 .readpage = btrfs_readpage,
11354 .writepage = btrfs_writepage,
11355 .writepages = btrfs_writepages,
11356 .readahead = btrfs_readahead,
11357 .direct_IO = noop_direct_IO,
11358 .invalidate_folio = btrfs_invalidate_folio,
11359 .releasepage = btrfs_releasepage,
11360 #ifdef CONFIG_MIGRATION
11361 .migratepage = btrfs_migratepage,
11363 .dirty_folio = filemap_dirty_folio,
11364 .error_remove_page = generic_error_remove_page,
11365 .swap_activate = btrfs_swap_activate,
11366 .swap_deactivate = btrfs_swap_deactivate,
11369 static const struct inode_operations btrfs_file_inode_operations = {
11370 .getattr = btrfs_getattr,
11371 .setattr = btrfs_setattr,
11372 .listxattr = btrfs_listxattr,
11373 .permission = btrfs_permission,
11374 .fiemap = btrfs_fiemap,
11375 .get_acl = btrfs_get_acl,
11376 .set_acl = btrfs_set_acl,
11377 .update_time = btrfs_update_time,
11378 .fileattr_get = btrfs_fileattr_get,
11379 .fileattr_set = btrfs_fileattr_set,
11381 static const struct inode_operations btrfs_special_inode_operations = {
11382 .getattr = btrfs_getattr,
11383 .setattr = btrfs_setattr,
11384 .permission = btrfs_permission,
11385 .listxattr = btrfs_listxattr,
11386 .get_acl = btrfs_get_acl,
11387 .set_acl = btrfs_set_acl,
11388 .update_time = btrfs_update_time,
11390 static const struct inode_operations btrfs_symlink_inode_operations = {
11391 .get_link = page_get_link,
11392 .getattr = btrfs_getattr,
11393 .setattr = btrfs_setattr,
11394 .permission = btrfs_permission,
11395 .listxattr = btrfs_listxattr,
11396 .update_time = btrfs_update_time,
11399 const struct dentry_operations btrfs_dentry_operations = {
11400 .d_delete = btrfs_dentry_delete,