1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <crypto/hash.h>
7 #include <linux/kernel.h>
9 #include <linux/blk-cgroup.h>
10 #include <linux/file.h>
12 #include <linux/pagemap.h>
13 #include <linux/highmem.h>
14 #include <linux/time.h>
15 #include <linux/init.h>
16 #include <linux/string.h>
17 #include <linux/backing-dev.h>
18 #include <linux/writeback.h>
19 #include <linux/compat.h>
20 #include <linux/xattr.h>
21 #include <linux/posix_acl.h>
22 #include <linux/falloc.h>
23 #include <linux/slab.h>
24 #include <linux/ratelimit.h>
25 #include <linux/btrfs.h>
26 #include <linux/blkdev.h>
27 #include <linux/posix_acl_xattr.h>
28 #include <linux/uio.h>
29 #include <linux/magic.h>
30 #include <linux/iversion.h>
31 #include <linux/swap.h>
32 #include <linux/migrate.h>
33 #include <linux/sched/mm.h>
34 #include <linux/iomap.h>
35 #include <asm/unaligned.h>
36 #include <linux/fsverity.h>
40 #include "transaction.h"
41 #include "btrfs_inode.h"
42 #include "print-tree.h"
43 #include "ordered-data.h"
47 #include "compression.h"
49 #include "free-space-cache.h"
52 #include "delalloc-space.h"
53 #include "block-group.h"
54 #include "space-info.h"
57 #include "inode-item.h"
59 #include "accessors.h"
60 #include "extent-tree.h"
61 #include "root-tree.h"
64 #include "file-item.h"
65 #include "uuid-tree.h"
69 #include "relocation.h"
74 struct btrfs_iget_args
{
76 struct btrfs_root
*root
;
79 struct btrfs_dio_data
{
81 struct extent_changeset
*data_reserved
;
82 struct btrfs_ordered_extent
*ordered
;
83 bool data_space_reserved
;
87 struct btrfs_dio_private
{
92 /* This must be last */
93 struct btrfs_bio bbio
;
96 static struct bio_set btrfs_dio_bioset
;
98 struct btrfs_rename_ctx
{
99 /* Output field. Stores the index number of the old directory entry. */
103 static const struct inode_operations btrfs_dir_inode_operations
;
104 static const struct inode_operations btrfs_symlink_inode_operations
;
105 static const struct inode_operations btrfs_special_inode_operations
;
106 static const struct inode_operations btrfs_file_inode_operations
;
107 static const struct address_space_operations btrfs_aops
;
108 static const struct file_operations btrfs_dir_file_operations
;
110 static struct kmem_cache
*btrfs_inode_cachep
;
112 static int btrfs_setsize(struct inode
*inode
, struct iattr
*attr
);
113 static int btrfs_truncate(struct btrfs_inode
*inode
, bool skip_writeback
);
114 static noinline
int cow_file_range(struct btrfs_inode
*inode
,
115 struct page
*locked_page
,
116 u64 start
, u64 end
, int *page_started
,
117 unsigned long *nr_written
, int unlock
,
119 static struct extent_map
*create_io_em(struct btrfs_inode
*inode
, u64 start
,
120 u64 len
, u64 orig_start
, u64 block_start
,
121 u64 block_len
, u64 orig_block_len
,
122 u64 ram_bytes
, int compress_type
,
125 static void __cold
btrfs_print_data_csum_error(struct btrfs_inode
*inode
,
126 u64 logical_start
, u8
*csum
, u8
*csum_expected
, int mirror_num
)
128 struct btrfs_root
*root
= inode
->root
;
129 const u32 csum_size
= root
->fs_info
->csum_size
;
131 /* Output without objectid, which is more meaningful */
132 if (root
->root_key
.objectid
>= BTRFS_LAST_FREE_OBJECTID
) {
133 btrfs_warn_rl(root
->fs_info
,
134 "csum failed root %lld ino %lld off %llu csum " CSUM_FMT
" expected csum " CSUM_FMT
" mirror %d",
135 root
->root_key
.objectid
, btrfs_ino(inode
),
137 CSUM_FMT_VALUE(csum_size
, csum
),
138 CSUM_FMT_VALUE(csum_size
, csum_expected
),
141 btrfs_warn_rl(root
->fs_info
,
142 "csum failed root %llu ino %llu off %llu csum " CSUM_FMT
" expected csum " CSUM_FMT
" mirror %d",
143 root
->root_key
.objectid
, btrfs_ino(inode
),
145 CSUM_FMT_VALUE(csum_size
, csum
),
146 CSUM_FMT_VALUE(csum_size
, csum_expected
),
152 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
154 * ilock_flags can have the following bit set:
156 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
157 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
159 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
161 int btrfs_inode_lock(struct btrfs_inode
*inode
, unsigned int ilock_flags
)
163 if (ilock_flags
& BTRFS_ILOCK_SHARED
) {
164 if (ilock_flags
& BTRFS_ILOCK_TRY
) {
165 if (!inode_trylock_shared(&inode
->vfs_inode
))
170 inode_lock_shared(&inode
->vfs_inode
);
172 if (ilock_flags
& BTRFS_ILOCK_TRY
) {
173 if (!inode_trylock(&inode
->vfs_inode
))
178 inode_lock(&inode
->vfs_inode
);
180 if (ilock_flags
& BTRFS_ILOCK_MMAP
)
181 down_write(&inode
->i_mmap_lock
);
186 * btrfs_inode_unlock - unock inode i_rwsem
188 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
189 * to decide whether the lock acquired is shared or exclusive.
191 void btrfs_inode_unlock(struct btrfs_inode
*inode
, unsigned int ilock_flags
)
193 if (ilock_flags
& BTRFS_ILOCK_MMAP
)
194 up_write(&inode
->i_mmap_lock
);
195 if (ilock_flags
& BTRFS_ILOCK_SHARED
)
196 inode_unlock_shared(&inode
->vfs_inode
);
198 inode_unlock(&inode
->vfs_inode
);
202 * Cleanup all submitted ordered extents in specified range to handle errors
203 * from the btrfs_run_delalloc_range() callback.
205 * NOTE: caller must ensure that when an error happens, it can not call
206 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
207 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
208 * to be released, which we want to happen only when finishing the ordered
209 * extent (btrfs_finish_ordered_io()).
211 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode
*inode
,
212 struct page
*locked_page
,
213 u64 offset
, u64 bytes
)
215 unsigned long index
= offset
>> PAGE_SHIFT
;
216 unsigned long end_index
= (offset
+ bytes
- 1) >> PAGE_SHIFT
;
217 u64 page_start
= 0, page_end
= 0;
221 page_start
= page_offset(locked_page
);
222 page_end
= page_start
+ PAGE_SIZE
- 1;
225 while (index
<= end_index
) {
227 * For locked page, we will call end_extent_writepage() on it
228 * in run_delalloc_range() for the error handling. That
229 * end_extent_writepage() function will call
230 * btrfs_mark_ordered_io_finished() to clear page Ordered and
231 * run the ordered extent accounting.
233 * Here we can't just clear the Ordered bit, or
234 * btrfs_mark_ordered_io_finished() would skip the accounting
235 * for the page range, and the ordered extent will never finish.
237 if (locked_page
&& index
== (page_start
>> PAGE_SHIFT
)) {
241 page
= find_get_page(inode
->vfs_inode
.i_mapping
, index
);
247 * Here we just clear all Ordered bits for every page in the
248 * range, then btrfs_mark_ordered_io_finished() will handle
249 * the ordered extent accounting for the range.
251 btrfs_page_clamp_clear_ordered(inode
->root
->fs_info
, page
,
257 /* The locked page covers the full range, nothing needs to be done */
258 if (bytes
+ offset
<= page_start
+ PAGE_SIZE
)
261 * In case this page belongs to the delalloc range being
262 * instantiated then skip it, since the first page of a range is
263 * going to be properly cleaned up by the caller of
266 if (page_start
>= offset
&& page_end
<= (offset
+ bytes
- 1)) {
267 bytes
= offset
+ bytes
- page_offset(locked_page
) - PAGE_SIZE
;
268 offset
= page_offset(locked_page
) + PAGE_SIZE
;
272 return btrfs_mark_ordered_io_finished(inode
, NULL
, offset
, bytes
, false);
275 static int btrfs_dirty_inode(struct btrfs_inode
*inode
);
277 static int btrfs_init_inode_security(struct btrfs_trans_handle
*trans
,
278 struct btrfs_new_inode_args
*args
)
282 if (args
->default_acl
) {
283 err
= __btrfs_set_acl(trans
, args
->inode
, args
->default_acl
,
289 err
= __btrfs_set_acl(trans
, args
->inode
, args
->acl
, ACL_TYPE_ACCESS
);
293 if (!args
->default_acl
&& !args
->acl
)
294 cache_no_acl(args
->inode
);
295 return btrfs_xattr_security_init(trans
, args
->inode
, args
->dir
,
296 &args
->dentry
->d_name
);
300 * this does all the hard work for inserting an inline extent into
301 * the btree. The caller should have done a btrfs_drop_extents so that
302 * no overlapping inline items exist in the btree
304 static int insert_inline_extent(struct btrfs_trans_handle
*trans
,
305 struct btrfs_path
*path
,
306 struct btrfs_inode
*inode
, bool extent_inserted
,
307 size_t size
, size_t compressed_size
,
309 struct page
**compressed_pages
,
312 struct btrfs_root
*root
= inode
->root
;
313 struct extent_buffer
*leaf
;
314 struct page
*page
= NULL
;
317 struct btrfs_file_extent_item
*ei
;
319 size_t cur_size
= size
;
322 ASSERT((compressed_size
> 0 && compressed_pages
) ||
323 (compressed_size
== 0 && !compressed_pages
));
325 if (compressed_size
&& compressed_pages
)
326 cur_size
= compressed_size
;
328 if (!extent_inserted
) {
329 struct btrfs_key key
;
332 key
.objectid
= btrfs_ino(inode
);
334 key
.type
= BTRFS_EXTENT_DATA_KEY
;
336 datasize
= btrfs_file_extent_calc_inline_size(cur_size
);
337 ret
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
342 leaf
= path
->nodes
[0];
343 ei
= btrfs_item_ptr(leaf
, path
->slots
[0],
344 struct btrfs_file_extent_item
);
345 btrfs_set_file_extent_generation(leaf
, ei
, trans
->transid
);
346 btrfs_set_file_extent_type(leaf
, ei
, BTRFS_FILE_EXTENT_INLINE
);
347 btrfs_set_file_extent_encryption(leaf
, ei
, 0);
348 btrfs_set_file_extent_other_encoding(leaf
, ei
, 0);
349 btrfs_set_file_extent_ram_bytes(leaf
, ei
, size
);
350 ptr
= btrfs_file_extent_inline_start(ei
);
352 if (compress_type
!= BTRFS_COMPRESS_NONE
) {
355 while (compressed_size
> 0) {
356 cpage
= compressed_pages
[i
];
357 cur_size
= min_t(unsigned long, compressed_size
,
360 kaddr
= kmap_local_page(cpage
);
361 write_extent_buffer(leaf
, kaddr
, ptr
, cur_size
);
366 compressed_size
-= cur_size
;
368 btrfs_set_file_extent_compression(leaf
, ei
,
371 page
= find_get_page(inode
->vfs_inode
.i_mapping
, 0);
372 btrfs_set_file_extent_compression(leaf
, ei
, 0);
373 kaddr
= kmap_local_page(page
);
374 write_extent_buffer(leaf
, kaddr
, ptr
, size
);
378 btrfs_mark_buffer_dirty(leaf
);
379 btrfs_release_path(path
);
382 * We align size to sectorsize for inline extents just for simplicity
385 ret
= btrfs_inode_set_file_extent_range(inode
, 0,
386 ALIGN(size
, root
->fs_info
->sectorsize
));
391 * We're an inline extent, so nobody can extend the file past i_size
392 * without locking a page we already have locked.
394 * We must do any i_size and inode updates before we unlock the pages.
395 * Otherwise we could end up racing with unlink.
397 i_size
= i_size_read(&inode
->vfs_inode
);
398 if (update_i_size
&& size
> i_size
) {
399 i_size_write(&inode
->vfs_inode
, size
);
402 inode
->disk_i_size
= i_size
;
410 * conditionally insert an inline extent into the file. This
411 * does the checks required to make sure the data is small enough
412 * to fit as an inline extent.
414 static noinline
int cow_file_range_inline(struct btrfs_inode
*inode
, u64 size
,
415 size_t compressed_size
,
417 struct page
**compressed_pages
,
420 struct btrfs_drop_extents_args drop_args
= { 0 };
421 struct btrfs_root
*root
= inode
->root
;
422 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
423 struct btrfs_trans_handle
*trans
;
424 u64 data_len
= (compressed_size
?: size
);
426 struct btrfs_path
*path
;
429 * We can create an inline extent if it ends at or beyond the current
430 * i_size, is no larger than a sector (decompressed), and the (possibly
431 * compressed) data fits in a leaf and the configured maximum inline
434 if (size
< i_size_read(&inode
->vfs_inode
) ||
435 size
> fs_info
->sectorsize
||
436 data_len
> BTRFS_MAX_INLINE_DATA_SIZE(fs_info
) ||
437 data_len
> fs_info
->max_inline
)
440 path
= btrfs_alloc_path();
444 trans
= btrfs_join_transaction(root
);
446 btrfs_free_path(path
);
447 return PTR_ERR(trans
);
449 trans
->block_rsv
= &inode
->block_rsv
;
451 drop_args
.path
= path
;
453 drop_args
.end
= fs_info
->sectorsize
;
454 drop_args
.drop_cache
= true;
455 drop_args
.replace_extent
= true;
456 drop_args
.extent_item_size
= btrfs_file_extent_calc_inline_size(data_len
);
457 ret
= btrfs_drop_extents(trans
, root
, inode
, &drop_args
);
459 btrfs_abort_transaction(trans
, ret
);
463 ret
= insert_inline_extent(trans
, path
, inode
, drop_args
.extent_inserted
,
464 size
, compressed_size
, compress_type
,
465 compressed_pages
, update_i_size
);
466 if (ret
&& ret
!= -ENOSPC
) {
467 btrfs_abort_transaction(trans
, ret
);
469 } else if (ret
== -ENOSPC
) {
474 btrfs_update_inode_bytes(inode
, size
, drop_args
.bytes_found
);
475 ret
= btrfs_update_inode(trans
, root
, inode
);
476 if (ret
&& ret
!= -ENOSPC
) {
477 btrfs_abort_transaction(trans
, ret
);
479 } else if (ret
== -ENOSPC
) {
484 btrfs_set_inode_full_sync(inode
);
487 * Don't forget to free the reserved space, as for inlined extent
488 * it won't count as data extent, free them directly here.
489 * And at reserve time, it's always aligned to page size, so
490 * just free one page here.
492 btrfs_qgroup_free_data(inode
, NULL
, 0, PAGE_SIZE
);
493 btrfs_free_path(path
);
494 btrfs_end_transaction(trans
);
498 struct async_extent
{
503 unsigned long nr_pages
;
505 struct list_head list
;
509 struct btrfs_inode
*inode
;
510 struct page
*locked_page
;
513 blk_opf_t write_flags
;
514 struct list_head extents
;
515 struct cgroup_subsys_state
*blkcg_css
;
516 struct btrfs_work work
;
517 struct async_cow
*async_cow
;
522 struct async_chunk chunks
[];
525 static noinline
int add_async_extent(struct async_chunk
*cow
,
526 u64 start
, u64 ram_size
,
529 unsigned long nr_pages
,
532 struct async_extent
*async_extent
;
534 async_extent
= kmalloc(sizeof(*async_extent
), GFP_NOFS
);
535 BUG_ON(!async_extent
); /* -ENOMEM */
536 async_extent
->start
= start
;
537 async_extent
->ram_size
= ram_size
;
538 async_extent
->compressed_size
= compressed_size
;
539 async_extent
->pages
= pages
;
540 async_extent
->nr_pages
= nr_pages
;
541 async_extent
->compress_type
= compress_type
;
542 list_add_tail(&async_extent
->list
, &cow
->extents
);
547 * Check if the inode needs to be submitted to compression, based on mount
548 * options, defragmentation, properties or heuristics.
550 static inline int inode_need_compress(struct btrfs_inode
*inode
, u64 start
,
553 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
555 if (!btrfs_inode_can_compress(inode
)) {
556 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG
),
557 KERN_ERR
"BTRFS: unexpected compression for ino %llu\n",
562 * Special check for subpage.
564 * We lock the full page then run each delalloc range in the page, thus
565 * for the following case, we will hit some subpage specific corner case:
568 * | |///////| |///////|
571 * In above case, both range A and range B will try to unlock the full
572 * page [0, 64K), causing the one finished later will have page
573 * unlocked already, triggering various page lock requirement BUG_ON()s.
575 * So here we add an artificial limit that subpage compression can only
576 * if the range is fully page aligned.
578 * In theory we only need to ensure the first page is fully covered, but
579 * the tailing partial page will be locked until the full compression
580 * finishes, delaying the write of other range.
582 * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
583 * first to prevent any submitted async extent to unlock the full page.
584 * By this, we can ensure for subpage case that only the last async_cow
585 * will unlock the full page.
587 if (fs_info
->sectorsize
< PAGE_SIZE
) {
588 if (!PAGE_ALIGNED(start
) ||
589 !PAGE_ALIGNED(end
+ 1))
594 if (btrfs_test_opt(fs_info
, FORCE_COMPRESS
))
597 if (inode
->defrag_compress
)
599 /* bad compression ratios */
600 if (inode
->flags
& BTRFS_INODE_NOCOMPRESS
)
602 if (btrfs_test_opt(fs_info
, COMPRESS
) ||
603 inode
->flags
& BTRFS_INODE_COMPRESS
||
604 inode
->prop_compress
)
605 return btrfs_compress_heuristic(&inode
->vfs_inode
, start
, end
);
609 static inline void inode_should_defrag(struct btrfs_inode
*inode
,
610 u64 start
, u64 end
, u64 num_bytes
, u32 small_write
)
612 /* If this is a small write inside eof, kick off a defrag */
613 if (num_bytes
< small_write
&&
614 (start
> 0 || end
+ 1 < inode
->disk_i_size
))
615 btrfs_add_inode_defrag(NULL
, inode
, small_write
);
619 * we create compressed extents in two phases. The first
620 * phase compresses a range of pages that have already been
621 * locked (both pages and state bits are locked).
623 * This is done inside an ordered work queue, and the compression
624 * is spread across many cpus. The actual IO submission is step
625 * two, and the ordered work queue takes care of making sure that
626 * happens in the same order things were put onto the queue by
627 * writepages and friends.
629 * If this code finds it can't get good compression, it puts an
630 * entry onto the work queue to write the uncompressed bytes. This
631 * makes sure that both compressed inodes and uncompressed inodes
632 * are written in the same order that the flusher thread sent them
635 static noinline
int compress_file_range(struct async_chunk
*async_chunk
)
637 struct btrfs_inode
*inode
= async_chunk
->inode
;
638 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
639 u64 blocksize
= fs_info
->sectorsize
;
640 u64 start
= async_chunk
->start
;
641 u64 end
= async_chunk
->end
;
645 struct page
**pages
= NULL
;
646 unsigned long nr_pages
;
647 unsigned long total_compressed
= 0;
648 unsigned long total_in
= 0;
651 int compress_type
= fs_info
->compress_type
;
652 int compressed_extents
= 0;
655 inode_should_defrag(inode
, start
, end
, end
- start
+ 1, SZ_16K
);
658 * We need to save i_size before now because it could change in between
659 * us evaluating the size and assigning it. This is because we lock and
660 * unlock the page in truncate and fallocate, and then modify the i_size
663 * The barriers are to emulate READ_ONCE, remove that once i_size_read
667 i_size
= i_size_read(&inode
->vfs_inode
);
669 actual_end
= min_t(u64
, i_size
, end
+ 1);
672 nr_pages
= (end
>> PAGE_SHIFT
) - (start
>> PAGE_SHIFT
) + 1;
673 nr_pages
= min_t(unsigned long, nr_pages
, BTRFS_MAX_COMPRESSED_PAGES
);
676 * we don't want to send crud past the end of i_size through
677 * compression, that's just a waste of CPU time. So, if the
678 * end of the file is before the start of our current
679 * requested range of bytes, we bail out to the uncompressed
680 * cleanup code that can deal with all of this.
682 * It isn't really the fastest way to fix things, but this is a
683 * very uncommon corner.
685 if (actual_end
<= start
)
686 goto cleanup_and_bail_uncompressed
;
688 total_compressed
= actual_end
- start
;
691 * Skip compression for a small file range(<=blocksize) that
692 * isn't an inline extent, since it doesn't save disk space at all.
694 if (total_compressed
<= blocksize
&&
695 (start
> 0 || end
+ 1 < inode
->disk_i_size
))
696 goto cleanup_and_bail_uncompressed
;
699 * For subpage case, we require full page alignment for the sector
701 * Thus we must also check against @actual_end, not just @end.
703 if (blocksize
< PAGE_SIZE
) {
704 if (!PAGE_ALIGNED(start
) ||
705 !PAGE_ALIGNED(round_up(actual_end
, blocksize
)))
706 goto cleanup_and_bail_uncompressed
;
709 total_compressed
= min_t(unsigned long, total_compressed
,
710 BTRFS_MAX_UNCOMPRESSED
);
715 * we do compression for mount -o compress and when the
716 * inode has not been flagged as nocompress. This flag can
717 * change at any time if we discover bad compression ratios.
719 if (inode_need_compress(inode
, start
, end
)) {
721 pages
= kcalloc(nr_pages
, sizeof(struct page
*), GFP_NOFS
);
723 /* just bail out to the uncompressed code */
728 if (inode
->defrag_compress
)
729 compress_type
= inode
->defrag_compress
;
730 else if (inode
->prop_compress
)
731 compress_type
= inode
->prop_compress
;
734 * we need to call clear_page_dirty_for_io on each
735 * page in the range. Otherwise applications with the file
736 * mmap'd can wander in and change the page contents while
737 * we are compressing them.
739 * If the compression fails for any reason, we set the pages
740 * dirty again later on.
742 * Note that the remaining part is redirtied, the start pointer
743 * has moved, the end is the original one.
746 extent_range_clear_dirty_for_io(&inode
->vfs_inode
, start
, end
);
750 /* Compression level is applied here and only here */
751 ret
= btrfs_compress_pages(
752 compress_type
| (fs_info
->compress_level
<< 4),
753 inode
->vfs_inode
.i_mapping
, start
,
760 unsigned long offset
= offset_in_page(total_compressed
);
761 struct page
*page
= pages
[nr_pages
- 1];
763 /* zero the tail end of the last page, we might be
764 * sending it down to disk
767 memzero_page(page
, offset
, PAGE_SIZE
- offset
);
773 * Check cow_file_range() for why we don't even try to create inline
774 * extent for subpage case.
776 if (start
== 0 && fs_info
->sectorsize
== PAGE_SIZE
) {
777 /* lets try to make an inline extent */
778 if (ret
|| total_in
< actual_end
) {
779 /* we didn't compress the entire range, try
780 * to make an uncompressed inline extent.
782 ret
= cow_file_range_inline(inode
, actual_end
,
783 0, BTRFS_COMPRESS_NONE
,
786 /* try making a compressed inline extent */
787 ret
= cow_file_range_inline(inode
, actual_end
,
789 compress_type
, pages
,
793 unsigned long clear_flags
= EXTENT_DELALLOC
|
794 EXTENT_DELALLOC_NEW
| EXTENT_DEFRAG
|
795 EXTENT_DO_ACCOUNTING
;
796 unsigned long page_error_op
;
798 page_error_op
= ret
< 0 ? PAGE_SET_ERROR
: 0;
801 * inline extent creation worked or returned error,
802 * we don't need to create any more async work items.
803 * Unlock and free up our temp pages.
805 * We use DO_ACCOUNTING here because we need the
806 * delalloc_release_metadata to be done _after_ we drop
807 * our outstanding extent for clearing delalloc for this
810 extent_clear_unlock_delalloc(inode
, start
, end
,
814 PAGE_START_WRITEBACK
|
819 * Ensure we only free the compressed pages if we have
820 * them allocated, as we can still reach here with
821 * inode_need_compress() == false.
824 for (i
= 0; i
< nr_pages
; i
++) {
825 WARN_ON(pages
[i
]->mapping
);
836 * we aren't doing an inline extent round the compressed size
837 * up to a block size boundary so the allocator does sane
840 total_compressed
= ALIGN(total_compressed
, blocksize
);
843 * one last check to make sure the compression is really a
844 * win, compare the page count read with the blocks on disk,
845 * compression must free at least one sector size
847 total_in
= round_up(total_in
, fs_info
->sectorsize
);
848 if (total_compressed
+ blocksize
<= total_in
) {
849 compressed_extents
++;
852 * The async work queues will take care of doing actual
853 * allocation on disk for these compressed pages, and
854 * will submit them to the elevator.
856 add_async_extent(async_chunk
, start
, total_in
,
857 total_compressed
, pages
, nr_pages
,
860 if (start
+ total_in
< end
) {
866 return compressed_extents
;
871 * the compression code ran but failed to make things smaller,
872 * free any pages it allocated and our page pointer array
874 for (i
= 0; i
< nr_pages
; i
++) {
875 WARN_ON(pages
[i
]->mapping
);
880 total_compressed
= 0;
883 /* flag the file so we don't compress in the future */
884 if (!btrfs_test_opt(fs_info
, FORCE_COMPRESS
) &&
885 !(inode
->prop_compress
)) {
886 inode
->flags
|= BTRFS_INODE_NOCOMPRESS
;
889 cleanup_and_bail_uncompressed
:
891 * No compression, but we still need to write the pages in the file
892 * we've been given so far. redirty the locked page if it corresponds
893 * to our extent and set things up for the async work queue to run
894 * cow_file_range to do the normal delalloc dance.
896 if (async_chunk
->locked_page
&&
897 (page_offset(async_chunk
->locked_page
) >= start
&&
898 page_offset(async_chunk
->locked_page
)) <= end
) {
899 __set_page_dirty_nobuffers(async_chunk
->locked_page
);
900 /* unlocked later on in the async handlers */
904 extent_range_redirty_for_io(&inode
->vfs_inode
, start
, end
);
905 add_async_extent(async_chunk
, start
, end
- start
+ 1, 0, NULL
, 0,
906 BTRFS_COMPRESS_NONE
);
907 compressed_extents
++;
909 return compressed_extents
;
912 static void free_async_extent_pages(struct async_extent
*async_extent
)
916 if (!async_extent
->pages
)
919 for (i
= 0; i
< async_extent
->nr_pages
; i
++) {
920 WARN_ON(async_extent
->pages
[i
]->mapping
);
921 put_page(async_extent
->pages
[i
]);
923 kfree(async_extent
->pages
);
924 async_extent
->nr_pages
= 0;
925 async_extent
->pages
= NULL
;
928 static int submit_uncompressed_range(struct btrfs_inode
*inode
,
929 struct async_extent
*async_extent
,
930 struct page
*locked_page
)
932 u64 start
= async_extent
->start
;
933 u64 end
= async_extent
->start
+ async_extent
->ram_size
- 1;
934 unsigned long nr_written
= 0;
935 int page_started
= 0;
939 * Call cow_file_range() to run the delalloc range directly, since we
940 * won't go to NOCOW or async path again.
942 * Also we call cow_file_range() with @unlock_page == 0, so that we
943 * can directly submit them without interruption.
945 ret
= cow_file_range(inode
, locked_page
, start
, end
, &page_started
,
946 &nr_written
, 0, NULL
);
947 /* Inline extent inserted, page gets unlocked and everything is done */
952 btrfs_cleanup_ordered_extents(inode
, locked_page
, start
, end
- start
+ 1);
954 const u64 page_start
= page_offset(locked_page
);
955 const u64 page_end
= page_start
+ PAGE_SIZE
- 1;
957 btrfs_page_set_error(inode
->root
->fs_info
, locked_page
,
958 page_start
, PAGE_SIZE
);
959 set_page_writeback(locked_page
);
960 end_page_writeback(locked_page
);
961 end_extent_writepage(locked_page
, ret
, page_start
, page_end
);
962 unlock_page(locked_page
);
967 /* All pages will be unlocked, including @locked_page */
968 return extent_write_locked_range(&inode
->vfs_inode
, start
, end
);
971 static int submit_one_async_extent(struct btrfs_inode
*inode
,
972 struct async_chunk
*async_chunk
,
973 struct async_extent
*async_extent
,
976 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
977 struct btrfs_root
*root
= inode
->root
;
978 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
979 struct btrfs_key ins
;
980 struct page
*locked_page
= NULL
;
981 struct extent_map
*em
;
983 u64 start
= async_extent
->start
;
984 u64 end
= async_extent
->start
+ async_extent
->ram_size
- 1;
986 if (async_chunk
->blkcg_css
)
987 kthread_associate_blkcg(async_chunk
->blkcg_css
);
990 * If async_chunk->locked_page is in the async_extent range, we need to
993 if (async_chunk
->locked_page
) {
994 u64 locked_page_start
= page_offset(async_chunk
->locked_page
);
995 u64 locked_page_end
= locked_page_start
+ PAGE_SIZE
- 1;
997 if (!(start
>= locked_page_end
|| end
<= locked_page_start
))
998 locked_page
= async_chunk
->locked_page
;
1000 lock_extent(io_tree
, start
, end
, NULL
);
1002 /* We have fall back to uncompressed write */
1003 if (!async_extent
->pages
) {
1004 ret
= submit_uncompressed_range(inode
, async_extent
, locked_page
);
1008 ret
= btrfs_reserve_extent(root
, async_extent
->ram_size
,
1009 async_extent
->compressed_size
,
1010 async_extent
->compressed_size
,
1011 0, *alloc_hint
, &ins
, 1, 1);
1013 free_async_extent_pages(async_extent
);
1015 * Here we used to try again by going back to non-compressed
1016 * path for ENOSPC. But we can't reserve space even for
1017 * compressed size, how could it work for uncompressed size
1018 * which requires larger size? So here we directly go error
1024 /* Here we're doing allocation and writeback of the compressed pages */
1025 em
= create_io_em(inode
, start
,
1026 async_extent
->ram_size
, /* len */
1027 start
, /* orig_start */
1028 ins
.objectid
, /* block_start */
1029 ins
.offset
, /* block_len */
1030 ins
.offset
, /* orig_block_len */
1031 async_extent
->ram_size
, /* ram_bytes */
1032 async_extent
->compress_type
,
1033 BTRFS_ORDERED_COMPRESSED
);
1036 goto out_free_reserve
;
1038 free_extent_map(em
);
1040 ret
= btrfs_add_ordered_extent(inode
, start
, /* file_offset */
1041 async_extent
->ram_size
, /* num_bytes */
1042 async_extent
->ram_size
, /* ram_bytes */
1043 ins
.objectid
, /* disk_bytenr */
1044 ins
.offset
, /* disk_num_bytes */
1046 1 << BTRFS_ORDERED_COMPRESSED
,
1047 async_extent
->compress_type
);
1049 btrfs_drop_extent_map_range(inode
, start
, end
, false);
1050 goto out_free_reserve
;
1052 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
1054 /* Clear dirty, set writeback and unlock the pages. */
1055 extent_clear_unlock_delalloc(inode
, start
, end
,
1056 NULL
, EXTENT_LOCKED
| EXTENT_DELALLOC
,
1057 PAGE_UNLOCK
| PAGE_START_WRITEBACK
);
1059 btrfs_submit_compressed_write(inode
, start
, /* file_offset */
1060 async_extent
->ram_size
, /* num_bytes */
1061 ins
.objectid
, /* disk_bytenr */
1062 ins
.offset
, /* compressed_len */
1063 async_extent
->pages
, /* compressed_pages */
1064 async_extent
->nr_pages
,
1065 async_chunk
->write_flags
, true);
1066 *alloc_hint
= ins
.objectid
+ ins
.offset
;
1068 if (async_chunk
->blkcg_css
)
1069 kthread_associate_blkcg(NULL
);
1070 kfree(async_extent
);
1074 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
1075 btrfs_free_reserved_extent(fs_info
, ins
.objectid
, ins
.offset
, 1);
1077 extent_clear_unlock_delalloc(inode
, start
, end
,
1078 NULL
, EXTENT_LOCKED
| EXTENT_DELALLOC
|
1079 EXTENT_DELALLOC_NEW
|
1080 EXTENT_DEFRAG
| EXTENT_DO_ACCOUNTING
,
1081 PAGE_UNLOCK
| PAGE_START_WRITEBACK
|
1082 PAGE_END_WRITEBACK
| PAGE_SET_ERROR
);
1083 free_async_extent_pages(async_extent
);
1088 * Phase two of compressed writeback. This is the ordered portion of the code,
1089 * which only gets called in the order the work was queued. We walk all the
1090 * async extents created by compress_file_range and send them down to the disk.
1092 static noinline
void submit_compressed_extents(struct async_chunk
*async_chunk
)
1094 struct btrfs_inode
*inode
= async_chunk
->inode
;
1095 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
1096 struct async_extent
*async_extent
;
1100 while (!list_empty(&async_chunk
->extents
)) {
1104 async_extent
= list_entry(async_chunk
->extents
.next
,
1105 struct async_extent
, list
);
1106 list_del(&async_extent
->list
);
1107 extent_start
= async_extent
->start
;
1108 ram_size
= async_extent
->ram_size
;
1110 ret
= submit_one_async_extent(inode
, async_chunk
, async_extent
,
1112 btrfs_debug(fs_info
,
1113 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1114 inode
->root
->root_key
.objectid
,
1115 btrfs_ino(inode
), extent_start
, ram_size
, ret
);
1119 static u64
get_extent_allocation_hint(struct btrfs_inode
*inode
, u64 start
,
1122 struct extent_map_tree
*em_tree
= &inode
->extent_tree
;
1123 struct extent_map
*em
;
1126 read_lock(&em_tree
->lock
);
1127 em
= search_extent_mapping(em_tree
, start
, num_bytes
);
1130 * if block start isn't an actual block number then find the
1131 * first block in this inode and use that as a hint. If that
1132 * block is also bogus then just don't worry about it.
1134 if (em
->block_start
>= EXTENT_MAP_LAST_BYTE
) {
1135 free_extent_map(em
);
1136 em
= search_extent_mapping(em_tree
, 0, 0);
1137 if (em
&& em
->block_start
< EXTENT_MAP_LAST_BYTE
)
1138 alloc_hint
= em
->block_start
;
1140 free_extent_map(em
);
1142 alloc_hint
= em
->block_start
;
1143 free_extent_map(em
);
1146 read_unlock(&em_tree
->lock
);
1152 * when extent_io.c finds a delayed allocation range in the file,
1153 * the call backs end up in this code. The basic idea is to
1154 * allocate extents on disk for the range, and create ordered data structs
1155 * in ram to track those extents.
1157 * locked_page is the page that writepage had locked already. We use
1158 * it to make sure we don't do extra locks or unlocks.
1160 * *page_started is set to one if we unlock locked_page and do everything
1161 * required to start IO on it. It may be clean and already done with
1162 * IO when we return.
1164 * When unlock == 1, we unlock the pages in successfully allocated regions.
1165 * When unlock == 0, we leave them locked for writing them out.
1167 * However, we unlock all the pages except @locked_page in case of failure.
1169 * In summary, page locking state will be as follow:
1171 * - page_started == 1 (return value)
1172 * - All the pages are unlocked. IO is started.
1173 * - Note that this can happen only on success
1175 * - All the pages except @locked_page are unlocked in any case
1177 * - On success, all the pages are locked for writing out them
1178 * - On failure, all the pages except @locked_page are unlocked
1180 * When a failure happens in the second or later iteration of the
1181 * while-loop, the ordered extents created in previous iterations are kept
1182 * intact. So, the caller must clean them up by calling
1183 * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
1186 static noinline
int cow_file_range(struct btrfs_inode
*inode
,
1187 struct page
*locked_page
,
1188 u64 start
, u64 end
, int *page_started
,
1189 unsigned long *nr_written
, int unlock
,
1192 struct btrfs_root
*root
= inode
->root
;
1193 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
1195 u64 orig_start
= start
;
1197 unsigned long ram_size
;
1198 u64 cur_alloc_size
= 0;
1200 u64 blocksize
= fs_info
->sectorsize
;
1201 struct btrfs_key ins
;
1202 struct extent_map
*em
;
1203 unsigned clear_bits
;
1204 unsigned long page_ops
;
1205 bool extent_reserved
= false;
1208 if (btrfs_is_free_space_inode(inode
)) {
1213 num_bytes
= ALIGN(end
- start
+ 1, blocksize
);
1214 num_bytes
= max(blocksize
, num_bytes
);
1215 ASSERT(num_bytes
<= btrfs_super_total_bytes(fs_info
->super_copy
));
1217 inode_should_defrag(inode
, start
, end
, num_bytes
, SZ_64K
);
1220 * Due to the page size limit, for subpage we can only trigger the
1221 * writeback for the dirty sectors of page, that means data writeback
1222 * is doing more writeback than what we want.
1224 * This is especially unexpected for some call sites like fallocate,
1225 * where we only increase i_size after everything is done.
1226 * This means we can trigger inline extent even if we didn't want to.
1227 * So here we skip inline extent creation completely.
1229 if (start
== 0 && fs_info
->sectorsize
== PAGE_SIZE
) {
1230 u64 actual_end
= min_t(u64
, i_size_read(&inode
->vfs_inode
),
1233 /* lets try to make an inline extent */
1234 ret
= cow_file_range_inline(inode
, actual_end
, 0,
1235 BTRFS_COMPRESS_NONE
, NULL
, false);
1238 * We use DO_ACCOUNTING here because we need the
1239 * delalloc_release_metadata to be run _after_ we drop
1240 * our outstanding extent for clearing delalloc for this
1243 extent_clear_unlock_delalloc(inode
, start
, end
,
1245 EXTENT_LOCKED
| EXTENT_DELALLOC
|
1246 EXTENT_DELALLOC_NEW
| EXTENT_DEFRAG
|
1247 EXTENT_DO_ACCOUNTING
, PAGE_UNLOCK
|
1248 PAGE_START_WRITEBACK
| PAGE_END_WRITEBACK
);
1249 *nr_written
= *nr_written
+
1250 (end
- start
+ PAGE_SIZE
) / PAGE_SIZE
;
1253 * locked_page is locked by the caller of
1254 * writepage_delalloc(), not locked by
1255 * __process_pages_contig().
1257 * We can't let __process_pages_contig() to unlock it,
1258 * as it doesn't have any subpage::writers recorded.
1260 * Here we manually unlock the page, since the caller
1261 * can't use page_started to determine if it's an
1262 * inline extent or a compressed extent.
1264 unlock_page(locked_page
);
1266 } else if (ret
< 0) {
1271 alloc_hint
= get_extent_allocation_hint(inode
, start
, num_bytes
);
1274 * Relocation relies on the relocated extents to have exactly the same
1275 * size as the original extents. Normally writeback for relocation data
1276 * extents follows a NOCOW path because relocation preallocates the
1277 * extents. However, due to an operation such as scrub turning a block
1278 * group to RO mode, it may fallback to COW mode, so we must make sure
1279 * an extent allocated during COW has exactly the requested size and can
1280 * not be split into smaller extents, otherwise relocation breaks and
1281 * fails during the stage where it updates the bytenr of file extent
1284 if (btrfs_is_data_reloc_root(root
))
1285 min_alloc_size
= num_bytes
;
1287 min_alloc_size
= fs_info
->sectorsize
;
1289 while (num_bytes
> 0) {
1290 cur_alloc_size
= num_bytes
;
1291 ret
= btrfs_reserve_extent(root
, cur_alloc_size
, cur_alloc_size
,
1292 min_alloc_size
, 0, alloc_hint
,
1296 cur_alloc_size
= ins
.offset
;
1297 extent_reserved
= true;
1299 ram_size
= ins
.offset
;
1300 em
= create_io_em(inode
, start
, ins
.offset
, /* len */
1301 start
, /* orig_start */
1302 ins
.objectid
, /* block_start */
1303 ins
.offset
, /* block_len */
1304 ins
.offset
, /* orig_block_len */
1305 ram_size
, /* ram_bytes */
1306 BTRFS_COMPRESS_NONE
, /* compress_type */
1307 BTRFS_ORDERED_REGULAR
/* type */);
1312 free_extent_map(em
);
1314 ret
= btrfs_add_ordered_extent(inode
, start
, ram_size
, ram_size
,
1315 ins
.objectid
, cur_alloc_size
, 0,
1316 1 << BTRFS_ORDERED_REGULAR
,
1317 BTRFS_COMPRESS_NONE
);
1319 goto out_drop_extent_cache
;
1321 if (btrfs_is_data_reloc_root(root
)) {
1322 ret
= btrfs_reloc_clone_csums(inode
, start
,
1325 * Only drop cache here, and process as normal.
1327 * We must not allow extent_clear_unlock_delalloc()
1328 * at out_unlock label to free meta of this ordered
1329 * extent, as its meta should be freed by
1330 * btrfs_finish_ordered_io().
1332 * So we must continue until @start is increased to
1333 * skip current ordered extent.
1336 btrfs_drop_extent_map_range(inode
, start
,
1337 start
+ ram_size
- 1,
1341 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
1344 * We're not doing compressed IO, don't unlock the first page
1345 * (which the caller expects to stay locked), don't clear any
1346 * dirty bits and don't set any writeback bits
1348 * Do set the Ordered (Private2) bit so we know this page was
1349 * properly setup for writepage.
1351 page_ops
= unlock
? PAGE_UNLOCK
: 0;
1352 page_ops
|= PAGE_SET_ORDERED
;
1354 extent_clear_unlock_delalloc(inode
, start
, start
+ ram_size
- 1,
1356 EXTENT_LOCKED
| EXTENT_DELALLOC
,
1358 if (num_bytes
< cur_alloc_size
)
1361 num_bytes
-= cur_alloc_size
;
1362 alloc_hint
= ins
.objectid
+ ins
.offset
;
1363 start
+= cur_alloc_size
;
1364 extent_reserved
= false;
1367 * btrfs_reloc_clone_csums() error, since start is increased
1368 * extent_clear_unlock_delalloc() at out_unlock label won't
1369 * free metadata of current ordered extent, we're OK to exit.
1377 out_drop_extent_cache
:
1378 btrfs_drop_extent_map_range(inode
, start
, start
+ ram_size
- 1, false);
1380 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
1381 btrfs_free_reserved_extent(fs_info
, ins
.objectid
, ins
.offset
, 1);
1384 * If done_offset is non-NULL and ret == -EAGAIN, we expect the
1385 * caller to write out the successfully allocated region and retry.
1387 if (done_offset
&& ret
== -EAGAIN
) {
1388 if (orig_start
< start
)
1389 *done_offset
= start
- 1;
1391 *done_offset
= start
;
1393 } else if (ret
== -EAGAIN
) {
1394 /* Convert to -ENOSPC since the caller cannot retry. */
1399 * Now, we have three regions to clean up:
1401 * |-------(1)----|---(2)---|-------------(3)----------|
1402 * `- orig_start `- start `- start + cur_alloc_size `- end
1404 * We process each region below.
1407 clear_bits
= EXTENT_LOCKED
| EXTENT_DELALLOC
| EXTENT_DELALLOC_NEW
|
1408 EXTENT_DEFRAG
| EXTENT_CLEAR_META_RESV
;
1409 page_ops
= PAGE_UNLOCK
| PAGE_START_WRITEBACK
| PAGE_END_WRITEBACK
;
1412 * For the range (1). We have already instantiated the ordered extents
1413 * for this region. They are cleaned up by
1414 * btrfs_cleanup_ordered_extents() in e.g,
1415 * btrfs_run_delalloc_range(). EXTENT_LOCKED | EXTENT_DELALLOC are
1416 * already cleared in the above loop. And, EXTENT_DELALLOC_NEW |
1417 * EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV are handled by the cleanup
1420 * However, in case of unlock == 0, we still need to unlock the pages
1421 * (except @locked_page) to ensure all the pages are unlocked.
1423 if (!unlock
&& orig_start
< start
) {
1425 mapping_set_error(inode
->vfs_inode
.i_mapping
, ret
);
1426 extent_clear_unlock_delalloc(inode
, orig_start
, start
- 1,
1427 locked_page
, 0, page_ops
);
1431 * For the range (2). If we reserved an extent for our delalloc range
1432 * (or a subrange) and failed to create the respective ordered extent,
1433 * then it means that when we reserved the extent we decremented the
1434 * extent's size from the data space_info's bytes_may_use counter and
1435 * incremented the space_info's bytes_reserved counter by the same
1436 * amount. We must make sure extent_clear_unlock_delalloc() does not try
1437 * to decrement again the data space_info's bytes_may_use counter,
1438 * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
1440 if (extent_reserved
) {
1441 extent_clear_unlock_delalloc(inode
, start
,
1442 start
+ cur_alloc_size
- 1,
1446 start
+= cur_alloc_size
;
1452 * For the range (3). We never touched the region. In addition to the
1453 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1454 * space_info's bytes_may_use counter, reserved in
1455 * btrfs_check_data_free_space().
1457 extent_clear_unlock_delalloc(inode
, start
, end
, locked_page
,
1458 clear_bits
| EXTENT_CLEAR_DATA_RESV
,
1464 * work queue call back to started compression on a file and pages
1466 static noinline
void async_cow_start(struct btrfs_work
*work
)
1468 struct async_chunk
*async_chunk
;
1469 int compressed_extents
;
1471 async_chunk
= container_of(work
, struct async_chunk
, work
);
1473 compressed_extents
= compress_file_range(async_chunk
);
1474 if (compressed_extents
== 0) {
1475 btrfs_add_delayed_iput(async_chunk
->inode
);
1476 async_chunk
->inode
= NULL
;
1481 * work queue call back to submit previously compressed pages
1483 static noinline
void async_cow_submit(struct btrfs_work
*work
)
1485 struct async_chunk
*async_chunk
= container_of(work
, struct async_chunk
,
1487 struct btrfs_fs_info
*fs_info
= btrfs_work_owner(work
);
1488 unsigned long nr_pages
;
1490 nr_pages
= (async_chunk
->end
- async_chunk
->start
+ PAGE_SIZE
) >>
1494 * ->inode could be NULL if async_chunk_start has failed to compress,
1495 * in which case we don't have anything to submit, yet we need to
1496 * always adjust ->async_delalloc_pages as its paired with the init
1497 * happening in cow_file_range_async
1499 if (async_chunk
->inode
)
1500 submit_compressed_extents(async_chunk
);
1502 /* atomic_sub_return implies a barrier */
1503 if (atomic_sub_return(nr_pages
, &fs_info
->async_delalloc_pages
) <
1505 cond_wake_up_nomb(&fs_info
->async_submit_wait
);
1508 static noinline
void async_cow_free(struct btrfs_work
*work
)
1510 struct async_chunk
*async_chunk
;
1511 struct async_cow
*async_cow
;
1513 async_chunk
= container_of(work
, struct async_chunk
, work
);
1514 if (async_chunk
->inode
)
1515 btrfs_add_delayed_iput(async_chunk
->inode
);
1516 if (async_chunk
->blkcg_css
)
1517 css_put(async_chunk
->blkcg_css
);
1519 async_cow
= async_chunk
->async_cow
;
1520 if (atomic_dec_and_test(&async_cow
->num_chunks
))
1524 static int cow_file_range_async(struct btrfs_inode
*inode
,
1525 struct writeback_control
*wbc
,
1526 struct page
*locked_page
,
1527 u64 start
, u64 end
, int *page_started
,
1528 unsigned long *nr_written
)
1530 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
1531 struct cgroup_subsys_state
*blkcg_css
= wbc_blkcg_css(wbc
);
1532 struct async_cow
*ctx
;
1533 struct async_chunk
*async_chunk
;
1534 unsigned long nr_pages
;
1536 u64 num_chunks
= DIV_ROUND_UP(end
- start
, SZ_512K
);
1538 bool should_compress
;
1540 const blk_opf_t write_flags
= wbc_to_write_flags(wbc
);
1542 unlock_extent(&inode
->io_tree
, start
, end
, NULL
);
1544 if (inode
->flags
& BTRFS_INODE_NOCOMPRESS
&&
1545 !btrfs_test_opt(fs_info
, FORCE_COMPRESS
)) {
1547 should_compress
= false;
1549 should_compress
= true;
1552 nofs_flag
= memalloc_nofs_save();
1553 ctx
= kvmalloc(struct_size(ctx
, chunks
, num_chunks
), GFP_KERNEL
);
1554 memalloc_nofs_restore(nofs_flag
);
1557 unsigned clear_bits
= EXTENT_LOCKED
| EXTENT_DELALLOC
|
1558 EXTENT_DELALLOC_NEW
| EXTENT_DEFRAG
|
1559 EXTENT_DO_ACCOUNTING
;
1560 unsigned long page_ops
= PAGE_UNLOCK
| PAGE_START_WRITEBACK
|
1561 PAGE_END_WRITEBACK
| PAGE_SET_ERROR
;
1563 extent_clear_unlock_delalloc(inode
, start
, end
, locked_page
,
1564 clear_bits
, page_ops
);
1568 async_chunk
= ctx
->chunks
;
1569 atomic_set(&ctx
->num_chunks
, num_chunks
);
1571 for (i
= 0; i
< num_chunks
; i
++) {
1572 if (should_compress
)
1573 cur_end
= min(end
, start
+ SZ_512K
- 1);
1578 * igrab is called higher up in the call chain, take only the
1579 * lightweight reference for the callback lifetime
1581 ihold(&inode
->vfs_inode
);
1582 async_chunk
[i
].async_cow
= ctx
;
1583 async_chunk
[i
].inode
= inode
;
1584 async_chunk
[i
].start
= start
;
1585 async_chunk
[i
].end
= cur_end
;
1586 async_chunk
[i
].write_flags
= write_flags
;
1587 INIT_LIST_HEAD(&async_chunk
[i
].extents
);
1590 * The locked_page comes all the way from writepage and its
1591 * the original page we were actually given. As we spread
1592 * this large delalloc region across multiple async_chunk
1593 * structs, only the first struct needs a pointer to locked_page
1595 * This way we don't need racey decisions about who is supposed
1600 * Depending on the compressibility, the pages might or
1601 * might not go through async. We want all of them to
1602 * be accounted against wbc once. Let's do it here
1603 * before the paths diverge. wbc accounting is used
1604 * only for foreign writeback detection and doesn't
1605 * need full accuracy. Just account the whole thing
1606 * against the first page.
1608 wbc_account_cgroup_owner(wbc
, locked_page
,
1610 async_chunk
[i
].locked_page
= locked_page
;
1613 async_chunk
[i
].locked_page
= NULL
;
1616 if (blkcg_css
!= blkcg_root_css
) {
1618 async_chunk
[i
].blkcg_css
= blkcg_css
;
1619 async_chunk
[i
].write_flags
|= REQ_BTRFS_CGROUP_PUNT
;
1621 async_chunk
[i
].blkcg_css
= NULL
;
1624 btrfs_init_work(&async_chunk
[i
].work
, async_cow_start
,
1625 async_cow_submit
, async_cow_free
);
1627 nr_pages
= DIV_ROUND_UP(cur_end
- start
, PAGE_SIZE
);
1628 atomic_add(nr_pages
, &fs_info
->async_delalloc_pages
);
1630 btrfs_queue_work(fs_info
->delalloc_workers
, &async_chunk
[i
].work
);
1632 *nr_written
+= nr_pages
;
1633 start
= cur_end
+ 1;
1639 static noinline
int run_delalloc_zoned(struct btrfs_inode
*inode
,
1640 struct page
*locked_page
, u64 start
,
1641 u64 end
, int *page_started
,
1642 unsigned long *nr_written
)
1644 u64 done_offset
= end
;
1646 bool locked_page_done
= false;
1648 while (start
<= end
) {
1649 ret
= cow_file_range(inode
, locked_page
, start
, end
, page_started
,
1650 nr_written
, 0, &done_offset
);
1651 if (ret
&& ret
!= -EAGAIN
)
1654 if (*page_started
) {
1662 if (done_offset
== start
) {
1663 wait_on_bit_io(&inode
->root
->fs_info
->flags
,
1664 BTRFS_FS_NEED_ZONE_FINISH
,
1665 TASK_UNINTERRUPTIBLE
);
1669 if (!locked_page_done
) {
1670 __set_page_dirty_nobuffers(locked_page
);
1671 account_page_redirty(locked_page
);
1673 locked_page_done
= true;
1674 extent_write_locked_range(&inode
->vfs_inode
, start
, done_offset
);
1676 start
= done_offset
+ 1;
1684 static noinline
int csum_exist_in_range(struct btrfs_fs_info
*fs_info
,
1685 u64 bytenr
, u64 num_bytes
, bool nowait
)
1687 struct btrfs_root
*csum_root
= btrfs_csum_root(fs_info
, bytenr
);
1688 struct btrfs_ordered_sum
*sums
;
1692 ret
= btrfs_lookup_csums_list(csum_root
, bytenr
, bytenr
+ num_bytes
- 1,
1694 if (ret
== 0 && list_empty(&list
))
1697 while (!list_empty(&list
)) {
1698 sums
= list_entry(list
.next
, struct btrfs_ordered_sum
, list
);
1699 list_del(&sums
->list
);
1707 static int fallback_to_cow(struct btrfs_inode
*inode
, struct page
*locked_page
,
1708 const u64 start
, const u64 end
,
1709 int *page_started
, unsigned long *nr_written
)
1711 const bool is_space_ino
= btrfs_is_free_space_inode(inode
);
1712 const bool is_reloc_ino
= btrfs_is_data_reloc_root(inode
->root
);
1713 const u64 range_bytes
= end
+ 1 - start
;
1714 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
1715 u64 range_start
= start
;
1719 * If EXTENT_NORESERVE is set it means that when the buffered write was
1720 * made we had not enough available data space and therefore we did not
1721 * reserve data space for it, since we though we could do NOCOW for the
1722 * respective file range (either there is prealloc extent or the inode
1723 * has the NOCOW bit set).
1725 * However when we need to fallback to COW mode (because for example the
1726 * block group for the corresponding extent was turned to RO mode by a
1727 * scrub or relocation) we need to do the following:
1729 * 1) We increment the bytes_may_use counter of the data space info.
1730 * If COW succeeds, it allocates a new data extent and after doing
1731 * that it decrements the space info's bytes_may_use counter and
1732 * increments its bytes_reserved counter by the same amount (we do
1733 * this at btrfs_add_reserved_bytes()). So we need to increment the
1734 * bytes_may_use counter to compensate (when space is reserved at
1735 * buffered write time, the bytes_may_use counter is incremented);
1737 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1738 * that if the COW path fails for any reason, it decrements (through
1739 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1740 * data space info, which we incremented in the step above.
1742 * If we need to fallback to cow and the inode corresponds to a free
1743 * space cache inode or an inode of the data relocation tree, we must
1744 * also increment bytes_may_use of the data space_info for the same
1745 * reason. Space caches and relocated data extents always get a prealloc
1746 * extent for them, however scrub or balance may have set the block
1747 * group that contains that extent to RO mode and therefore force COW
1748 * when starting writeback.
1750 count
= count_range_bits(io_tree
, &range_start
, end
, range_bytes
,
1751 EXTENT_NORESERVE
, 0, NULL
);
1752 if (count
> 0 || is_space_ino
|| is_reloc_ino
) {
1754 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
1755 struct btrfs_space_info
*sinfo
= fs_info
->data_sinfo
;
1757 if (is_space_ino
|| is_reloc_ino
)
1758 bytes
= range_bytes
;
1760 spin_lock(&sinfo
->lock
);
1761 btrfs_space_info_update_bytes_may_use(fs_info
, sinfo
, bytes
);
1762 spin_unlock(&sinfo
->lock
);
1765 clear_extent_bit(io_tree
, start
, end
, EXTENT_NORESERVE
,
1769 return cow_file_range(inode
, locked_page
, start
, end
, page_started
,
1770 nr_written
, 1, NULL
);
1773 struct can_nocow_file_extent_args
{
1776 /* Start file offset of the range we want to NOCOW. */
1778 /* End file offset (inclusive) of the range we want to NOCOW. */
1780 bool writeback_path
;
1783 * Free the path passed to can_nocow_file_extent() once it's not needed
1788 /* Output fields. Only set when can_nocow_file_extent() returns 1. */
1793 /* Number of bytes that can be written to in NOCOW mode. */
1798 * Check if we can NOCOW the file extent that the path points to.
1799 * This function may return with the path released, so the caller should check
1800 * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
1802 * Returns: < 0 on error
1803 * 0 if we can not NOCOW
1806 static int can_nocow_file_extent(struct btrfs_path
*path
,
1807 struct btrfs_key
*key
,
1808 struct btrfs_inode
*inode
,
1809 struct can_nocow_file_extent_args
*args
)
1811 const bool is_freespace_inode
= btrfs_is_free_space_inode(inode
);
1812 struct extent_buffer
*leaf
= path
->nodes
[0];
1813 struct btrfs_root
*root
= inode
->root
;
1814 struct btrfs_file_extent_item
*fi
;
1819 bool nowait
= path
->nowait
;
1821 fi
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_file_extent_item
);
1822 extent_type
= btrfs_file_extent_type(leaf
, fi
);
1824 if (extent_type
== BTRFS_FILE_EXTENT_INLINE
)
1827 /* Can't access these fields unless we know it's not an inline extent. */
1828 args
->disk_bytenr
= btrfs_file_extent_disk_bytenr(leaf
, fi
);
1829 args
->disk_num_bytes
= btrfs_file_extent_disk_num_bytes(leaf
, fi
);
1830 args
->extent_offset
= btrfs_file_extent_offset(leaf
, fi
);
1832 if (!(inode
->flags
& BTRFS_INODE_NODATACOW
) &&
1833 extent_type
== BTRFS_FILE_EXTENT_REG
)
1837 * If the extent was created before the generation where the last snapshot
1838 * for its subvolume was created, then this implies the extent is shared,
1839 * hence we must COW.
1841 if (!args
->strict
&&
1842 btrfs_file_extent_generation(leaf
, fi
) <=
1843 btrfs_root_last_snapshot(&root
->root_item
))
1846 /* An explicit hole, must COW. */
1847 if (args
->disk_bytenr
== 0)
1850 /* Compressed/encrypted/encoded extents must be COWed. */
1851 if (btrfs_file_extent_compression(leaf
, fi
) ||
1852 btrfs_file_extent_encryption(leaf
, fi
) ||
1853 btrfs_file_extent_other_encoding(leaf
, fi
))
1856 extent_end
= btrfs_file_extent_end(path
);
1859 * The following checks can be expensive, as they need to take other
1860 * locks and do btree or rbtree searches, so release the path to avoid
1861 * blocking other tasks for too long.
1863 btrfs_release_path(path
);
1865 ret
= btrfs_cross_ref_exist(root
, btrfs_ino(inode
),
1866 key
->offset
- args
->extent_offset
,
1867 args
->disk_bytenr
, false, path
);
1868 WARN_ON_ONCE(ret
> 0 && is_freespace_inode
);
1872 if (args
->free_path
) {
1874 * We don't need the path anymore, plus through the
1875 * csum_exist_in_range() call below we will end up allocating
1876 * another path. So free the path to avoid unnecessary extra
1879 btrfs_free_path(path
);
1883 /* If there are pending snapshots for this root, we must COW. */
1884 if (args
->writeback_path
&& !is_freespace_inode
&&
1885 atomic_read(&root
->snapshot_force_cow
))
1888 args
->disk_bytenr
+= args
->extent_offset
;
1889 args
->disk_bytenr
+= args
->start
- key
->offset
;
1890 args
->num_bytes
= min(args
->end
+ 1, extent_end
) - args
->start
;
1893 * Force COW if csums exist in the range. This ensures that csums for a
1894 * given extent are either valid or do not exist.
1896 ret
= csum_exist_in_range(root
->fs_info
, args
->disk_bytenr
, args
->num_bytes
,
1898 WARN_ON_ONCE(ret
> 0 && is_freespace_inode
);
1904 if (args
->free_path
&& path
)
1905 btrfs_free_path(path
);
1907 return ret
< 0 ? ret
: can_nocow
;
1911 * when nowcow writeback call back. This checks for snapshots or COW copies
1912 * of the extents that exist in the file, and COWs the file as required.
1914 * If no cow copies or snapshots exist, we write directly to the existing
1917 static noinline
int run_delalloc_nocow(struct btrfs_inode
*inode
,
1918 struct page
*locked_page
,
1919 const u64 start
, const u64 end
,
1921 unsigned long *nr_written
)
1923 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
1924 struct btrfs_root
*root
= inode
->root
;
1925 struct btrfs_path
*path
;
1926 u64 cow_start
= (u64
)-1;
1927 u64 cur_offset
= start
;
1929 bool check_prev
= true;
1930 u64 ino
= btrfs_ino(inode
);
1931 struct btrfs_block_group
*bg
;
1933 struct can_nocow_file_extent_args nocow_args
= { 0 };
1935 path
= btrfs_alloc_path();
1937 extent_clear_unlock_delalloc(inode
, start
, end
, locked_page
,
1938 EXTENT_LOCKED
| EXTENT_DELALLOC
|
1939 EXTENT_DO_ACCOUNTING
|
1940 EXTENT_DEFRAG
, PAGE_UNLOCK
|
1941 PAGE_START_WRITEBACK
|
1942 PAGE_END_WRITEBACK
);
1946 nocow_args
.end
= end
;
1947 nocow_args
.writeback_path
= true;
1950 struct btrfs_key found_key
;
1951 struct btrfs_file_extent_item
*fi
;
1952 struct extent_buffer
*leaf
;
1960 ret
= btrfs_lookup_file_extent(NULL
, root
, path
, ino
,
1966 * If there is no extent for our range when doing the initial
1967 * search, then go back to the previous slot as it will be the
1968 * one containing the search offset
1970 if (ret
> 0 && path
->slots
[0] > 0 && check_prev
) {
1971 leaf
= path
->nodes
[0];
1972 btrfs_item_key_to_cpu(leaf
, &found_key
,
1973 path
->slots
[0] - 1);
1974 if (found_key
.objectid
== ino
&&
1975 found_key
.type
== BTRFS_EXTENT_DATA_KEY
)
1980 /* Go to next leaf if we have exhausted the current one */
1981 leaf
= path
->nodes
[0];
1982 if (path
->slots
[0] >= btrfs_header_nritems(leaf
)) {
1983 ret
= btrfs_next_leaf(root
, path
);
1985 if (cow_start
!= (u64
)-1)
1986 cur_offset
= cow_start
;
1991 leaf
= path
->nodes
[0];
1994 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
1996 /* Didn't find anything for our INO */
1997 if (found_key
.objectid
> ino
)
2000 * Keep searching until we find an EXTENT_ITEM or there are no
2001 * more extents for this inode
2003 if (WARN_ON_ONCE(found_key
.objectid
< ino
) ||
2004 found_key
.type
< BTRFS_EXTENT_DATA_KEY
) {
2009 /* Found key is not EXTENT_DATA_KEY or starts after req range */
2010 if (found_key
.type
> BTRFS_EXTENT_DATA_KEY
||
2011 found_key
.offset
> end
)
2015 * If the found extent starts after requested offset, then
2016 * adjust extent_end to be right before this extent begins
2018 if (found_key
.offset
> cur_offset
) {
2019 extent_end
= found_key
.offset
;
2025 * Found extent which begins before our range and potentially
2028 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
2029 struct btrfs_file_extent_item
);
2030 extent_type
= btrfs_file_extent_type(leaf
, fi
);
2031 /* If this is triggered then we have a memory corruption. */
2032 ASSERT(extent_type
< BTRFS_NR_FILE_EXTENT_TYPES
);
2033 if (WARN_ON(extent_type
>= BTRFS_NR_FILE_EXTENT_TYPES
)) {
2037 ram_bytes
= btrfs_file_extent_ram_bytes(leaf
, fi
);
2038 extent_end
= btrfs_file_extent_end(path
);
2041 * If the extent we got ends before our current offset, skip to
2044 if (extent_end
<= cur_offset
) {
2049 nocow_args
.start
= cur_offset
;
2050 ret
= can_nocow_file_extent(path
, &found_key
, inode
, &nocow_args
);
2052 if (cow_start
!= (u64
)-1)
2053 cur_offset
= cow_start
;
2055 } else if (ret
== 0) {
2060 bg
= btrfs_inc_nocow_writers(fs_info
, nocow_args
.disk_bytenr
);
2065 * If nocow is false then record the beginning of the range
2066 * that needs to be COWed
2069 if (cow_start
== (u64
)-1)
2070 cow_start
= cur_offset
;
2071 cur_offset
= extent_end
;
2072 if (cur_offset
> end
)
2074 if (!path
->nodes
[0])
2081 * COW range from cow_start to found_key.offset - 1. As the key
2082 * will contain the beginning of the first extent that can be
2083 * NOCOW, following one which needs to be COW'ed
2085 if (cow_start
!= (u64
)-1) {
2086 ret
= fallback_to_cow(inode
, locked_page
,
2087 cow_start
, found_key
.offset
- 1,
2088 page_started
, nr_written
);
2091 cow_start
= (u64
)-1;
2094 nocow_end
= cur_offset
+ nocow_args
.num_bytes
- 1;
2096 if (extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
2097 u64 orig_start
= found_key
.offset
- nocow_args
.extent_offset
;
2098 struct extent_map
*em
;
2100 em
= create_io_em(inode
, cur_offset
, nocow_args
.num_bytes
,
2102 nocow_args
.disk_bytenr
, /* block_start */
2103 nocow_args
.num_bytes
, /* block_len */
2104 nocow_args
.disk_num_bytes
, /* orig_block_len */
2105 ram_bytes
, BTRFS_COMPRESS_NONE
,
2106 BTRFS_ORDERED_PREALLOC
);
2111 free_extent_map(em
);
2112 ret
= btrfs_add_ordered_extent(inode
,
2113 cur_offset
, nocow_args
.num_bytes
,
2114 nocow_args
.num_bytes
,
2115 nocow_args
.disk_bytenr
,
2116 nocow_args
.num_bytes
, 0,
2117 1 << BTRFS_ORDERED_PREALLOC
,
2118 BTRFS_COMPRESS_NONE
);
2120 btrfs_drop_extent_map_range(inode
, cur_offset
,
2125 ret
= btrfs_add_ordered_extent(inode
, cur_offset
,
2126 nocow_args
.num_bytes
,
2127 nocow_args
.num_bytes
,
2128 nocow_args
.disk_bytenr
,
2129 nocow_args
.num_bytes
,
2131 1 << BTRFS_ORDERED_NOCOW
,
2132 BTRFS_COMPRESS_NONE
);
2138 btrfs_dec_nocow_writers(bg
);
2142 if (btrfs_is_data_reloc_root(root
))
2144 * Error handled later, as we must prevent
2145 * extent_clear_unlock_delalloc() in error handler
2146 * from freeing metadata of created ordered extent.
2148 ret
= btrfs_reloc_clone_csums(inode
, cur_offset
,
2149 nocow_args
.num_bytes
);
2151 extent_clear_unlock_delalloc(inode
, cur_offset
, nocow_end
,
2152 locked_page
, EXTENT_LOCKED
|
2154 EXTENT_CLEAR_DATA_RESV
,
2155 PAGE_UNLOCK
| PAGE_SET_ORDERED
);
2157 cur_offset
= extent_end
;
2160 * btrfs_reloc_clone_csums() error, now we're OK to call error
2161 * handler, as metadata for created ordered extent will only
2162 * be freed by btrfs_finish_ordered_io().
2166 if (cur_offset
> end
)
2169 btrfs_release_path(path
);
2171 if (cur_offset
<= end
&& cow_start
== (u64
)-1)
2172 cow_start
= cur_offset
;
2174 if (cow_start
!= (u64
)-1) {
2176 ret
= fallback_to_cow(inode
, locked_page
, cow_start
, end
,
2177 page_started
, nr_written
);
2184 btrfs_dec_nocow_writers(bg
);
2186 if (ret
&& cur_offset
< end
)
2187 extent_clear_unlock_delalloc(inode
, cur_offset
, end
,
2188 locked_page
, EXTENT_LOCKED
|
2189 EXTENT_DELALLOC
| EXTENT_DEFRAG
|
2190 EXTENT_DO_ACCOUNTING
, PAGE_UNLOCK
|
2191 PAGE_START_WRITEBACK
|
2192 PAGE_END_WRITEBACK
);
2193 btrfs_free_path(path
);
2197 static bool should_nocow(struct btrfs_inode
*inode
, u64 start
, u64 end
)
2199 if (inode
->flags
& (BTRFS_INODE_NODATACOW
| BTRFS_INODE_PREALLOC
)) {
2200 if (inode
->defrag_bytes
&&
2201 test_range_bit(&inode
->io_tree
, start
, end
, EXTENT_DEFRAG
,
2210 * Function to process delayed allocation (create CoW) for ranges which are
2211 * being touched for the first time.
2213 int btrfs_run_delalloc_range(struct btrfs_inode
*inode
, struct page
*locked_page
,
2214 u64 start
, u64 end
, int *page_started
, unsigned long *nr_written
,
2215 struct writeback_control
*wbc
)
2218 const bool zoned
= btrfs_is_zoned(inode
->root
->fs_info
);
2221 * The range must cover part of the @locked_page, or the returned
2222 * @page_started can confuse the caller.
2224 ASSERT(!(end
<= page_offset(locked_page
) ||
2225 start
>= page_offset(locked_page
) + PAGE_SIZE
));
2227 if (should_nocow(inode
, start
, end
)) {
2229 * Normally on a zoned device we're only doing COW writes, but
2230 * in case of relocation on a zoned filesystem we have taken
2231 * precaution, that we're only writing sequentially. It's safe
2232 * to use run_delalloc_nocow() here, like for regular
2233 * preallocated inodes.
2235 ASSERT(!zoned
|| btrfs_is_data_reloc_root(inode
->root
));
2236 ret
= run_delalloc_nocow(inode
, locked_page
, start
, end
,
2237 page_started
, nr_written
);
2238 } else if (!btrfs_inode_can_compress(inode
) ||
2239 !inode_need_compress(inode
, start
, end
)) {
2241 ret
= run_delalloc_zoned(inode
, locked_page
, start
, end
,
2242 page_started
, nr_written
);
2244 ret
= cow_file_range(inode
, locked_page
, start
, end
,
2245 page_started
, nr_written
, 1, NULL
);
2247 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT
, &inode
->runtime_flags
);
2248 ret
= cow_file_range_async(inode
, wbc
, locked_page
, start
, end
,
2249 page_started
, nr_written
);
2253 btrfs_cleanup_ordered_extents(inode
, locked_page
, start
,
2258 void btrfs_split_delalloc_extent(struct btrfs_inode
*inode
,
2259 struct extent_state
*orig
, u64 split
)
2261 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
2264 /* not delalloc, ignore it */
2265 if (!(orig
->state
& EXTENT_DELALLOC
))
2268 size
= orig
->end
- orig
->start
+ 1;
2269 if (size
> fs_info
->max_extent_size
) {
2274 * See the explanation in btrfs_merge_delalloc_extent, the same
2275 * applies here, just in reverse.
2277 new_size
= orig
->end
- split
+ 1;
2278 num_extents
= count_max_extents(fs_info
, new_size
);
2279 new_size
= split
- orig
->start
;
2280 num_extents
+= count_max_extents(fs_info
, new_size
);
2281 if (count_max_extents(fs_info
, size
) >= num_extents
)
2285 spin_lock(&inode
->lock
);
2286 btrfs_mod_outstanding_extents(inode
, 1);
2287 spin_unlock(&inode
->lock
);
2291 * Handle merged delayed allocation extents so we can keep track of new extents
2292 * that are just merged onto old extents, such as when we are doing sequential
2293 * writes, so we can properly account for the metadata space we'll need.
2295 void btrfs_merge_delalloc_extent(struct btrfs_inode
*inode
, struct extent_state
*new,
2296 struct extent_state
*other
)
2298 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
2299 u64 new_size
, old_size
;
2302 /* not delalloc, ignore it */
2303 if (!(other
->state
& EXTENT_DELALLOC
))
2306 if (new->start
> other
->start
)
2307 new_size
= new->end
- other
->start
+ 1;
2309 new_size
= other
->end
- new->start
+ 1;
2311 /* we're not bigger than the max, unreserve the space and go */
2312 if (new_size
<= fs_info
->max_extent_size
) {
2313 spin_lock(&inode
->lock
);
2314 btrfs_mod_outstanding_extents(inode
, -1);
2315 spin_unlock(&inode
->lock
);
2320 * We have to add up either side to figure out how many extents were
2321 * accounted for before we merged into one big extent. If the number of
2322 * extents we accounted for is <= the amount we need for the new range
2323 * then we can return, otherwise drop. Think of it like this
2327 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2328 * need 2 outstanding extents, on one side we have 1 and the other side
2329 * we have 1 so they are == and we can return. But in this case
2331 * [MAX_SIZE+4k][MAX_SIZE+4k]
2333 * Each range on their own accounts for 2 extents, but merged together
2334 * they are only 3 extents worth of accounting, so we need to drop in
2337 old_size
= other
->end
- other
->start
+ 1;
2338 num_extents
= count_max_extents(fs_info
, old_size
);
2339 old_size
= new->end
- new->start
+ 1;
2340 num_extents
+= count_max_extents(fs_info
, old_size
);
2341 if (count_max_extents(fs_info
, new_size
) >= num_extents
)
2344 spin_lock(&inode
->lock
);
2345 btrfs_mod_outstanding_extents(inode
, -1);
2346 spin_unlock(&inode
->lock
);
2349 static void btrfs_add_delalloc_inodes(struct btrfs_root
*root
,
2350 struct btrfs_inode
*inode
)
2352 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
2354 spin_lock(&root
->delalloc_lock
);
2355 if (list_empty(&inode
->delalloc_inodes
)) {
2356 list_add_tail(&inode
->delalloc_inodes
, &root
->delalloc_inodes
);
2357 set_bit(BTRFS_INODE_IN_DELALLOC_LIST
, &inode
->runtime_flags
);
2358 root
->nr_delalloc_inodes
++;
2359 if (root
->nr_delalloc_inodes
== 1) {
2360 spin_lock(&fs_info
->delalloc_root_lock
);
2361 BUG_ON(!list_empty(&root
->delalloc_root
));
2362 list_add_tail(&root
->delalloc_root
,
2363 &fs_info
->delalloc_roots
);
2364 spin_unlock(&fs_info
->delalloc_root_lock
);
2367 spin_unlock(&root
->delalloc_lock
);
2370 void __btrfs_del_delalloc_inode(struct btrfs_root
*root
,
2371 struct btrfs_inode
*inode
)
2373 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
2375 if (!list_empty(&inode
->delalloc_inodes
)) {
2376 list_del_init(&inode
->delalloc_inodes
);
2377 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST
,
2378 &inode
->runtime_flags
);
2379 root
->nr_delalloc_inodes
--;
2380 if (!root
->nr_delalloc_inodes
) {
2381 ASSERT(list_empty(&root
->delalloc_inodes
));
2382 spin_lock(&fs_info
->delalloc_root_lock
);
2383 BUG_ON(list_empty(&root
->delalloc_root
));
2384 list_del_init(&root
->delalloc_root
);
2385 spin_unlock(&fs_info
->delalloc_root_lock
);
2390 static void btrfs_del_delalloc_inode(struct btrfs_root
*root
,
2391 struct btrfs_inode
*inode
)
2393 spin_lock(&root
->delalloc_lock
);
2394 __btrfs_del_delalloc_inode(root
, inode
);
2395 spin_unlock(&root
->delalloc_lock
);
2399 * Properly track delayed allocation bytes in the inode and to maintain the
2400 * list of inodes that have pending delalloc work to be done.
2402 void btrfs_set_delalloc_extent(struct btrfs_inode
*inode
, struct extent_state
*state
,
2405 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
2407 if ((bits
& EXTENT_DEFRAG
) && !(bits
& EXTENT_DELALLOC
))
2410 * set_bit and clear bit hooks normally require _irqsave/restore
2411 * but in this case, we are only testing for the DELALLOC
2412 * bit, which is only set or cleared with irqs on
2414 if (!(state
->state
& EXTENT_DELALLOC
) && (bits
& EXTENT_DELALLOC
)) {
2415 struct btrfs_root
*root
= inode
->root
;
2416 u64 len
= state
->end
+ 1 - state
->start
;
2417 u32 num_extents
= count_max_extents(fs_info
, len
);
2418 bool do_list
= !btrfs_is_free_space_inode(inode
);
2420 spin_lock(&inode
->lock
);
2421 btrfs_mod_outstanding_extents(inode
, num_extents
);
2422 spin_unlock(&inode
->lock
);
2424 /* For sanity tests */
2425 if (btrfs_is_testing(fs_info
))
2428 percpu_counter_add_batch(&fs_info
->delalloc_bytes
, len
,
2429 fs_info
->delalloc_batch
);
2430 spin_lock(&inode
->lock
);
2431 inode
->delalloc_bytes
+= len
;
2432 if (bits
& EXTENT_DEFRAG
)
2433 inode
->defrag_bytes
+= len
;
2434 if (do_list
&& !test_bit(BTRFS_INODE_IN_DELALLOC_LIST
,
2435 &inode
->runtime_flags
))
2436 btrfs_add_delalloc_inodes(root
, inode
);
2437 spin_unlock(&inode
->lock
);
2440 if (!(state
->state
& EXTENT_DELALLOC_NEW
) &&
2441 (bits
& EXTENT_DELALLOC_NEW
)) {
2442 spin_lock(&inode
->lock
);
2443 inode
->new_delalloc_bytes
+= state
->end
+ 1 - state
->start
;
2444 spin_unlock(&inode
->lock
);
2449 * Once a range is no longer delalloc this function ensures that proper
2450 * accounting happens.
2452 void btrfs_clear_delalloc_extent(struct btrfs_inode
*inode
,
2453 struct extent_state
*state
, u32 bits
)
2455 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
2456 u64 len
= state
->end
+ 1 - state
->start
;
2457 u32 num_extents
= count_max_extents(fs_info
, len
);
2459 if ((state
->state
& EXTENT_DEFRAG
) && (bits
& EXTENT_DEFRAG
)) {
2460 spin_lock(&inode
->lock
);
2461 inode
->defrag_bytes
-= len
;
2462 spin_unlock(&inode
->lock
);
2466 * set_bit and clear bit hooks normally require _irqsave/restore
2467 * but in this case, we are only testing for the DELALLOC
2468 * bit, which is only set or cleared with irqs on
2470 if ((state
->state
& EXTENT_DELALLOC
) && (bits
& EXTENT_DELALLOC
)) {
2471 struct btrfs_root
*root
= inode
->root
;
2472 bool do_list
= !btrfs_is_free_space_inode(inode
);
2474 spin_lock(&inode
->lock
);
2475 btrfs_mod_outstanding_extents(inode
, -num_extents
);
2476 spin_unlock(&inode
->lock
);
2479 * We don't reserve metadata space for space cache inodes so we
2480 * don't need to call delalloc_release_metadata if there is an
2483 if (bits
& EXTENT_CLEAR_META_RESV
&&
2484 root
!= fs_info
->tree_root
)
2485 btrfs_delalloc_release_metadata(inode
, len
, false);
2487 /* For sanity tests. */
2488 if (btrfs_is_testing(fs_info
))
2491 if (!btrfs_is_data_reloc_root(root
) &&
2492 do_list
&& !(state
->state
& EXTENT_NORESERVE
) &&
2493 (bits
& EXTENT_CLEAR_DATA_RESV
))
2494 btrfs_free_reserved_data_space_noquota(fs_info
, len
);
2496 percpu_counter_add_batch(&fs_info
->delalloc_bytes
, -len
,
2497 fs_info
->delalloc_batch
);
2498 spin_lock(&inode
->lock
);
2499 inode
->delalloc_bytes
-= len
;
2500 if (do_list
&& inode
->delalloc_bytes
== 0 &&
2501 test_bit(BTRFS_INODE_IN_DELALLOC_LIST
,
2502 &inode
->runtime_flags
))
2503 btrfs_del_delalloc_inode(root
, inode
);
2504 spin_unlock(&inode
->lock
);
2507 if ((state
->state
& EXTENT_DELALLOC_NEW
) &&
2508 (bits
& EXTENT_DELALLOC_NEW
)) {
2509 spin_lock(&inode
->lock
);
2510 ASSERT(inode
->new_delalloc_bytes
>= len
);
2511 inode
->new_delalloc_bytes
-= len
;
2512 if (bits
& EXTENT_ADD_INODE_BYTES
)
2513 inode_add_bytes(&inode
->vfs_inode
, len
);
2514 spin_unlock(&inode
->lock
);
2519 * Split off the first pre bytes from the extent_map at [start, start + len]
2521 * This function is intended to be used only for extract_ordered_extent().
2523 static int split_extent_map(struct btrfs_inode
*inode
, u64 start
, u64 len
, u64 pre
)
2525 struct extent_map_tree
*em_tree
= &inode
->extent_tree
;
2526 struct extent_map
*em
;
2527 struct extent_map
*split_pre
= NULL
;
2528 struct extent_map
*split_mid
= NULL
;
2530 unsigned long flags
;
2535 split_pre
= alloc_extent_map();
2538 split_mid
= alloc_extent_map();
2544 lock_extent(&inode
->io_tree
, start
, start
+ len
- 1, NULL
);
2545 write_lock(&em_tree
->lock
);
2546 em
= lookup_extent_mapping(em_tree
, start
, len
);
2552 ASSERT(em
->len
== len
);
2553 ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
));
2554 ASSERT(em
->block_start
< EXTENT_MAP_LAST_BYTE
);
2555 ASSERT(test_bit(EXTENT_FLAG_PINNED
, &em
->flags
));
2556 ASSERT(!test_bit(EXTENT_FLAG_LOGGING
, &em
->flags
));
2557 ASSERT(!list_empty(&em
->list
));
2560 clear_bit(EXTENT_FLAG_PINNED
, &em
->flags
);
2562 /* First, replace the em with a new extent_map starting from * em->start */
2563 split_pre
->start
= em
->start
;
2564 split_pre
->len
= pre
;
2565 split_pre
->orig_start
= split_pre
->start
;
2566 split_pre
->block_start
= em
->block_start
;
2567 split_pre
->block_len
= split_pre
->len
;
2568 split_pre
->orig_block_len
= split_pre
->block_len
;
2569 split_pre
->ram_bytes
= split_pre
->len
;
2570 split_pre
->flags
= flags
;
2571 split_pre
->compress_type
= em
->compress_type
;
2572 split_pre
->generation
= em
->generation
;
2574 replace_extent_mapping(em_tree
, em
, split_pre
, 1);
2577 * Now we only have an extent_map at:
2578 * [em->start, em->start + pre]
2581 /* Insert the middle extent_map. */
2582 split_mid
->start
= em
->start
+ pre
;
2583 split_mid
->len
= em
->len
- pre
;
2584 split_mid
->orig_start
= split_mid
->start
;
2585 split_mid
->block_start
= em
->block_start
+ pre
;
2586 split_mid
->block_len
= split_mid
->len
;
2587 split_mid
->orig_block_len
= split_mid
->block_len
;
2588 split_mid
->ram_bytes
= split_mid
->len
;
2589 split_mid
->flags
= flags
;
2590 split_mid
->compress_type
= em
->compress_type
;
2591 split_mid
->generation
= em
->generation
;
2592 add_extent_mapping(em_tree
, split_mid
, 1);
2595 free_extent_map(em
);
2596 /* Once for the tree */
2597 free_extent_map(em
);
2600 write_unlock(&em_tree
->lock
);
2601 unlock_extent(&inode
->io_tree
, start
, start
+ len
- 1, NULL
);
2602 free_extent_map(split_mid
);
2604 free_extent_map(split_pre
);
2608 int btrfs_extract_ordered_extent(struct btrfs_bio
*bbio
,
2609 struct btrfs_ordered_extent
*ordered
)
2611 u64 start
= (u64
)bbio
->bio
.bi_iter
.bi_sector
<< SECTOR_SHIFT
;
2612 u64 len
= bbio
->bio
.bi_iter
.bi_size
;
2613 struct btrfs_inode
*inode
= bbio
->inode
;
2614 u64 ordered_len
= ordered
->num_bytes
;
2617 /* Must always be called for the beginning of an ordered extent. */
2618 if (WARN_ON_ONCE(start
!= ordered
->disk_bytenr
))
2621 /* No need to split if the ordered extent covers the entire bio. */
2622 if (ordered
->disk_num_bytes
== len
)
2625 ret
= btrfs_split_ordered_extent(ordered
, len
);
2630 * Don't split the extent_map for NOCOW extents, as we're writing into
2631 * a pre-existing one.
2633 if (test_bit(BTRFS_ORDERED_NOCOW
, &ordered
->flags
))
2636 return split_extent_map(inode
, bbio
->file_offset
, ordered_len
, len
);
2640 * given a list of ordered sums record them in the inode. This happens
2641 * at IO completion time based on sums calculated at bio submission time.
2643 static int add_pending_csums(struct btrfs_trans_handle
*trans
,
2644 struct list_head
*list
)
2646 struct btrfs_ordered_sum
*sum
;
2647 struct btrfs_root
*csum_root
= NULL
;
2650 list_for_each_entry(sum
, list
, list
) {
2651 trans
->adding_csums
= true;
2653 csum_root
= btrfs_csum_root(trans
->fs_info
,
2655 ret
= btrfs_csum_file_blocks(trans
, csum_root
, sum
);
2656 trans
->adding_csums
= false;
2663 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode
*inode
,
2666 struct extent_state
**cached_state
)
2668 u64 search_start
= start
;
2669 const u64 end
= start
+ len
- 1;
2671 while (search_start
< end
) {
2672 const u64 search_len
= end
- search_start
+ 1;
2673 struct extent_map
*em
;
2677 em
= btrfs_get_extent(inode
, NULL
, 0, search_start
, search_len
);
2681 if (em
->block_start
!= EXTENT_MAP_HOLE
)
2685 if (em
->start
< search_start
)
2686 em_len
-= search_start
- em
->start
;
2687 if (em_len
> search_len
)
2688 em_len
= search_len
;
2690 ret
= set_extent_bit(&inode
->io_tree
, search_start
,
2691 search_start
+ em_len
- 1,
2692 EXTENT_DELALLOC_NEW
, cached_state
,
2695 search_start
= extent_map_end(em
);
2696 free_extent_map(em
);
2703 int btrfs_set_extent_delalloc(struct btrfs_inode
*inode
, u64 start
, u64 end
,
2704 unsigned int extra_bits
,
2705 struct extent_state
**cached_state
)
2707 WARN_ON(PAGE_ALIGNED(end
));
2709 if (start
>= i_size_read(&inode
->vfs_inode
) &&
2710 !(inode
->flags
& BTRFS_INODE_PREALLOC
)) {
2712 * There can't be any extents following eof in this case so just
2713 * set the delalloc new bit for the range directly.
2715 extra_bits
|= EXTENT_DELALLOC_NEW
;
2719 ret
= btrfs_find_new_delalloc_bytes(inode
, start
,
2726 return set_extent_delalloc(&inode
->io_tree
, start
, end
, extra_bits
,
2730 /* see btrfs_writepage_start_hook for details on why this is required */
2731 struct btrfs_writepage_fixup
{
2733 struct btrfs_inode
*inode
;
2734 struct btrfs_work work
;
2737 static void btrfs_writepage_fixup_worker(struct btrfs_work
*work
)
2739 struct btrfs_writepage_fixup
*fixup
;
2740 struct btrfs_ordered_extent
*ordered
;
2741 struct extent_state
*cached_state
= NULL
;
2742 struct extent_changeset
*data_reserved
= NULL
;
2744 struct btrfs_inode
*inode
;
2748 bool free_delalloc_space
= true;
2750 fixup
= container_of(work
, struct btrfs_writepage_fixup
, work
);
2752 inode
= fixup
->inode
;
2753 page_start
= page_offset(page
);
2754 page_end
= page_offset(page
) + PAGE_SIZE
- 1;
2757 * This is similar to page_mkwrite, we need to reserve the space before
2758 * we take the page lock.
2760 ret
= btrfs_delalloc_reserve_space(inode
, &data_reserved
, page_start
,
2766 * Before we queued this fixup, we took a reference on the page.
2767 * page->mapping may go NULL, but it shouldn't be moved to a different
2770 if (!page
->mapping
|| !PageDirty(page
) || !PageChecked(page
)) {
2772 * Unfortunately this is a little tricky, either
2774 * 1) We got here and our page had already been dealt with and
2775 * we reserved our space, thus ret == 0, so we need to just
2776 * drop our space reservation and bail. This can happen the
2777 * first time we come into the fixup worker, or could happen
2778 * while waiting for the ordered extent.
2779 * 2) Our page was already dealt with, but we happened to get an
2780 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2781 * this case we obviously don't have anything to release, but
2782 * because the page was already dealt with we don't want to
2783 * mark the page with an error, so make sure we're resetting
2784 * ret to 0. This is why we have this check _before_ the ret
2785 * check, because we do not want to have a surprise ENOSPC
2786 * when the page was already properly dealt with.
2789 btrfs_delalloc_release_extents(inode
, PAGE_SIZE
);
2790 btrfs_delalloc_release_space(inode
, data_reserved
,
2791 page_start
, PAGE_SIZE
,
2799 * We can't mess with the page state unless it is locked, so now that
2800 * it is locked bail if we failed to make our space reservation.
2805 lock_extent(&inode
->io_tree
, page_start
, page_end
, &cached_state
);
2807 /* already ordered? We're done */
2808 if (PageOrdered(page
))
2811 ordered
= btrfs_lookup_ordered_range(inode
, page_start
, PAGE_SIZE
);
2813 unlock_extent(&inode
->io_tree
, page_start
, page_end
,
2816 btrfs_start_ordered_extent(ordered
);
2817 btrfs_put_ordered_extent(ordered
);
2821 ret
= btrfs_set_extent_delalloc(inode
, page_start
, page_end
, 0,
2827 * Everything went as planned, we're now the owner of a dirty page with
2828 * delayed allocation bits set and space reserved for our COW
2831 * The page was dirty when we started, nothing should have cleaned it.
2833 BUG_ON(!PageDirty(page
));
2834 free_delalloc_space
= false;
2836 btrfs_delalloc_release_extents(inode
, PAGE_SIZE
);
2837 if (free_delalloc_space
)
2838 btrfs_delalloc_release_space(inode
, data_reserved
, page_start
,
2840 unlock_extent(&inode
->io_tree
, page_start
, page_end
, &cached_state
);
2844 * We hit ENOSPC or other errors. Update the mapping and page
2845 * to reflect the errors and clean the page.
2847 mapping_set_error(page
->mapping
, ret
);
2848 end_extent_writepage(page
, ret
, page_start
, page_end
);
2849 clear_page_dirty_for_io(page
);
2852 btrfs_page_clear_checked(inode
->root
->fs_info
, page
, page_start
, PAGE_SIZE
);
2856 extent_changeset_free(data_reserved
);
2858 * As a precaution, do a delayed iput in case it would be the last iput
2859 * that could need flushing space. Recursing back to fixup worker would
2862 btrfs_add_delayed_iput(inode
);
2866 * There are a few paths in the higher layers of the kernel that directly
2867 * set the page dirty bit without asking the filesystem if it is a
2868 * good idea. This causes problems because we want to make sure COW
2869 * properly happens and the data=ordered rules are followed.
2871 * In our case any range that doesn't have the ORDERED bit set
2872 * hasn't been properly setup for IO. We kick off an async process
2873 * to fix it up. The async helper will wait for ordered extents, set
2874 * the delalloc bit and make it safe to write the page.
2876 int btrfs_writepage_cow_fixup(struct page
*page
)
2878 struct inode
*inode
= page
->mapping
->host
;
2879 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2880 struct btrfs_writepage_fixup
*fixup
;
2882 /* This page has ordered extent covering it already */
2883 if (PageOrdered(page
))
2887 * PageChecked is set below when we create a fixup worker for this page,
2888 * don't try to create another one if we're already PageChecked()
2890 * The extent_io writepage code will redirty the page if we send back
2893 if (PageChecked(page
))
2896 fixup
= kzalloc(sizeof(*fixup
), GFP_NOFS
);
2901 * We are already holding a reference to this inode from
2902 * write_cache_pages. We need to hold it because the space reservation
2903 * takes place outside of the page lock, and we can't trust
2904 * page->mapping outside of the page lock.
2907 btrfs_page_set_checked(fs_info
, page
, page_offset(page
), PAGE_SIZE
);
2909 btrfs_init_work(&fixup
->work
, btrfs_writepage_fixup_worker
, NULL
, NULL
);
2911 fixup
->inode
= BTRFS_I(inode
);
2912 btrfs_queue_work(fs_info
->fixup_workers
, &fixup
->work
);
2917 static int insert_reserved_file_extent(struct btrfs_trans_handle
*trans
,
2918 struct btrfs_inode
*inode
, u64 file_pos
,
2919 struct btrfs_file_extent_item
*stack_fi
,
2920 const bool update_inode_bytes
,
2921 u64 qgroup_reserved
)
2923 struct btrfs_root
*root
= inode
->root
;
2924 const u64 sectorsize
= root
->fs_info
->sectorsize
;
2925 struct btrfs_path
*path
;
2926 struct extent_buffer
*leaf
;
2927 struct btrfs_key ins
;
2928 u64 disk_num_bytes
= btrfs_stack_file_extent_disk_num_bytes(stack_fi
);
2929 u64 disk_bytenr
= btrfs_stack_file_extent_disk_bytenr(stack_fi
);
2930 u64 offset
= btrfs_stack_file_extent_offset(stack_fi
);
2931 u64 num_bytes
= btrfs_stack_file_extent_num_bytes(stack_fi
);
2932 u64 ram_bytes
= btrfs_stack_file_extent_ram_bytes(stack_fi
);
2933 struct btrfs_drop_extents_args drop_args
= { 0 };
2936 path
= btrfs_alloc_path();
2941 * we may be replacing one extent in the tree with another.
2942 * The new extent is pinned in the extent map, and we don't want
2943 * to drop it from the cache until it is completely in the btree.
2945 * So, tell btrfs_drop_extents to leave this extent in the cache.
2946 * the caller is expected to unpin it and allow it to be merged
2949 drop_args
.path
= path
;
2950 drop_args
.start
= file_pos
;
2951 drop_args
.end
= file_pos
+ num_bytes
;
2952 drop_args
.replace_extent
= true;
2953 drop_args
.extent_item_size
= sizeof(*stack_fi
);
2954 ret
= btrfs_drop_extents(trans
, root
, inode
, &drop_args
);
2958 if (!drop_args
.extent_inserted
) {
2959 ins
.objectid
= btrfs_ino(inode
);
2960 ins
.offset
= file_pos
;
2961 ins
.type
= BTRFS_EXTENT_DATA_KEY
;
2963 ret
= btrfs_insert_empty_item(trans
, root
, path
, &ins
,
2968 leaf
= path
->nodes
[0];
2969 btrfs_set_stack_file_extent_generation(stack_fi
, trans
->transid
);
2970 write_extent_buffer(leaf
, stack_fi
,
2971 btrfs_item_ptr_offset(leaf
, path
->slots
[0]),
2972 sizeof(struct btrfs_file_extent_item
));
2974 btrfs_mark_buffer_dirty(leaf
);
2975 btrfs_release_path(path
);
2978 * If we dropped an inline extent here, we know the range where it is
2979 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2980 * number of bytes only for that range containing the inline extent.
2981 * The remaining of the range will be processed when clearning the
2982 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2984 if (file_pos
== 0 && !IS_ALIGNED(drop_args
.bytes_found
, sectorsize
)) {
2985 u64 inline_size
= round_down(drop_args
.bytes_found
, sectorsize
);
2987 inline_size
= drop_args
.bytes_found
- inline_size
;
2988 btrfs_update_inode_bytes(inode
, sectorsize
, inline_size
);
2989 drop_args
.bytes_found
-= inline_size
;
2990 num_bytes
-= sectorsize
;
2993 if (update_inode_bytes
)
2994 btrfs_update_inode_bytes(inode
, num_bytes
, drop_args
.bytes_found
);
2996 ins
.objectid
= disk_bytenr
;
2997 ins
.offset
= disk_num_bytes
;
2998 ins
.type
= BTRFS_EXTENT_ITEM_KEY
;
3000 ret
= btrfs_inode_set_file_extent_range(inode
, file_pos
, ram_bytes
);
3004 ret
= btrfs_alloc_reserved_file_extent(trans
, root
, btrfs_ino(inode
),
3006 qgroup_reserved
, &ins
);
3008 btrfs_free_path(path
);
3013 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info
*fs_info
,
3016 struct btrfs_block_group
*cache
;
3018 cache
= btrfs_lookup_block_group(fs_info
, start
);
3021 spin_lock(&cache
->lock
);
3022 cache
->delalloc_bytes
-= len
;
3023 spin_unlock(&cache
->lock
);
3025 btrfs_put_block_group(cache
);
3028 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle
*trans
,
3029 struct btrfs_ordered_extent
*oe
)
3031 struct btrfs_file_extent_item stack_fi
;
3032 bool update_inode_bytes
;
3033 u64 num_bytes
= oe
->num_bytes
;
3034 u64 ram_bytes
= oe
->ram_bytes
;
3036 memset(&stack_fi
, 0, sizeof(stack_fi
));
3037 btrfs_set_stack_file_extent_type(&stack_fi
, BTRFS_FILE_EXTENT_REG
);
3038 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi
, oe
->disk_bytenr
);
3039 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi
,
3040 oe
->disk_num_bytes
);
3041 btrfs_set_stack_file_extent_offset(&stack_fi
, oe
->offset
);
3042 if (test_bit(BTRFS_ORDERED_TRUNCATED
, &oe
->flags
)) {
3043 num_bytes
= oe
->truncated_len
;
3044 ram_bytes
= num_bytes
;
3046 btrfs_set_stack_file_extent_num_bytes(&stack_fi
, num_bytes
);
3047 btrfs_set_stack_file_extent_ram_bytes(&stack_fi
, ram_bytes
);
3048 btrfs_set_stack_file_extent_compression(&stack_fi
, oe
->compress_type
);
3049 /* Encryption and other encoding is reserved and all 0 */
3052 * For delalloc, when completing an ordered extent we update the inode's
3053 * bytes when clearing the range in the inode's io tree, so pass false
3054 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3055 * except if the ordered extent was truncated.
3057 update_inode_bytes
= test_bit(BTRFS_ORDERED_DIRECT
, &oe
->flags
) ||
3058 test_bit(BTRFS_ORDERED_ENCODED
, &oe
->flags
) ||
3059 test_bit(BTRFS_ORDERED_TRUNCATED
, &oe
->flags
);
3061 return insert_reserved_file_extent(trans
, BTRFS_I(oe
->inode
),
3062 oe
->file_offset
, &stack_fi
,
3063 update_inode_bytes
, oe
->qgroup_rsv
);
3067 * As ordered data IO finishes, this gets called so we can finish
3068 * an ordered extent if the range of bytes in the file it covers are
3071 int btrfs_finish_ordered_io(struct btrfs_ordered_extent
*ordered_extent
)
3073 struct btrfs_inode
*inode
= BTRFS_I(ordered_extent
->inode
);
3074 struct btrfs_root
*root
= inode
->root
;
3075 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
3076 struct btrfs_trans_handle
*trans
= NULL
;
3077 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
3078 struct extent_state
*cached_state
= NULL
;
3080 int compress_type
= 0;
3082 u64 logical_len
= ordered_extent
->num_bytes
;
3083 bool freespace_inode
;
3084 bool truncated
= false;
3085 bool clear_reserved_extent
= true;
3086 unsigned int clear_bits
= EXTENT_DEFRAG
;
3088 start
= ordered_extent
->file_offset
;
3089 end
= start
+ ordered_extent
->num_bytes
- 1;
3091 if (!test_bit(BTRFS_ORDERED_NOCOW
, &ordered_extent
->flags
) &&
3092 !test_bit(BTRFS_ORDERED_PREALLOC
, &ordered_extent
->flags
) &&
3093 !test_bit(BTRFS_ORDERED_DIRECT
, &ordered_extent
->flags
) &&
3094 !test_bit(BTRFS_ORDERED_ENCODED
, &ordered_extent
->flags
))
3095 clear_bits
|= EXTENT_DELALLOC_NEW
;
3097 freespace_inode
= btrfs_is_free_space_inode(inode
);
3098 if (!freespace_inode
)
3099 btrfs_lockdep_acquire(fs_info
, btrfs_ordered_extent
);
3101 if (test_bit(BTRFS_ORDERED_IOERR
, &ordered_extent
->flags
)) {
3106 /* A valid ->physical implies a write on a sequential zone. */
3107 if (ordered_extent
->physical
!= (u64
)-1) {
3108 btrfs_rewrite_logical_zoned(ordered_extent
);
3109 btrfs_zone_finish_endio(fs_info
, ordered_extent
->disk_bytenr
,
3110 ordered_extent
->disk_num_bytes
);
3111 } else if (btrfs_is_data_reloc_root(inode
->root
)) {
3112 btrfs_zone_finish_endio(fs_info
, ordered_extent
->disk_bytenr
,
3113 ordered_extent
->disk_num_bytes
);
3116 if (test_bit(BTRFS_ORDERED_TRUNCATED
, &ordered_extent
->flags
)) {
3118 logical_len
= ordered_extent
->truncated_len
;
3119 /* Truncated the entire extent, don't bother adding */
3124 if (test_bit(BTRFS_ORDERED_NOCOW
, &ordered_extent
->flags
)) {
3125 BUG_ON(!list_empty(&ordered_extent
->list
)); /* Logic error */
3127 btrfs_inode_safe_disk_i_size_write(inode
, 0);
3128 if (freespace_inode
)
3129 trans
= btrfs_join_transaction_spacecache(root
);
3131 trans
= btrfs_join_transaction(root
);
3132 if (IS_ERR(trans
)) {
3133 ret
= PTR_ERR(trans
);
3137 trans
->block_rsv
= &inode
->block_rsv
;
3138 ret
= btrfs_update_inode_fallback(trans
, root
, inode
);
3139 if (ret
) /* -ENOMEM or corruption */
3140 btrfs_abort_transaction(trans
, ret
);
3144 clear_bits
|= EXTENT_LOCKED
;
3145 lock_extent(io_tree
, start
, end
, &cached_state
);
3147 if (freespace_inode
)
3148 trans
= btrfs_join_transaction_spacecache(root
);
3150 trans
= btrfs_join_transaction(root
);
3151 if (IS_ERR(trans
)) {
3152 ret
= PTR_ERR(trans
);
3157 trans
->block_rsv
= &inode
->block_rsv
;
3159 if (test_bit(BTRFS_ORDERED_COMPRESSED
, &ordered_extent
->flags
))
3160 compress_type
= ordered_extent
->compress_type
;
3161 if (test_bit(BTRFS_ORDERED_PREALLOC
, &ordered_extent
->flags
)) {
3162 BUG_ON(compress_type
);
3163 ret
= btrfs_mark_extent_written(trans
, inode
,
3164 ordered_extent
->file_offset
,
3165 ordered_extent
->file_offset
+
3167 btrfs_zoned_release_data_reloc_bg(fs_info
, ordered_extent
->disk_bytenr
,
3168 ordered_extent
->disk_num_bytes
);
3170 BUG_ON(root
== fs_info
->tree_root
);
3171 ret
= insert_ordered_extent_file_extent(trans
, ordered_extent
);
3173 clear_reserved_extent
= false;
3174 btrfs_release_delalloc_bytes(fs_info
,
3175 ordered_extent
->disk_bytenr
,
3176 ordered_extent
->disk_num_bytes
);
3179 unpin_extent_cache(&inode
->extent_tree
, ordered_extent
->file_offset
,
3180 ordered_extent
->num_bytes
, trans
->transid
);
3182 btrfs_abort_transaction(trans
, ret
);
3186 ret
= add_pending_csums(trans
, &ordered_extent
->list
);
3188 btrfs_abort_transaction(trans
, ret
);
3193 * If this is a new delalloc range, clear its new delalloc flag to
3194 * update the inode's number of bytes. This needs to be done first
3195 * before updating the inode item.
3197 if ((clear_bits
& EXTENT_DELALLOC_NEW
) &&
3198 !test_bit(BTRFS_ORDERED_TRUNCATED
, &ordered_extent
->flags
))
3199 clear_extent_bit(&inode
->io_tree
, start
, end
,
3200 EXTENT_DELALLOC_NEW
| EXTENT_ADD_INODE_BYTES
,
3203 btrfs_inode_safe_disk_i_size_write(inode
, 0);
3204 ret
= btrfs_update_inode_fallback(trans
, root
, inode
);
3205 if (ret
) { /* -ENOMEM or corruption */
3206 btrfs_abort_transaction(trans
, ret
);
3211 clear_extent_bit(&inode
->io_tree
, start
, end
, clear_bits
,
3215 btrfs_end_transaction(trans
);
3217 if (ret
|| truncated
) {
3218 u64 unwritten_start
= start
;
3221 * If we failed to finish this ordered extent for any reason we
3222 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3223 * extent, and mark the inode with the error if it wasn't
3224 * already set. Any error during writeback would have already
3225 * set the mapping error, so we need to set it if we're the ones
3226 * marking this ordered extent as failed.
3228 if (ret
&& !test_and_set_bit(BTRFS_ORDERED_IOERR
,
3229 &ordered_extent
->flags
))
3230 mapping_set_error(ordered_extent
->inode
->i_mapping
, -EIO
);
3233 unwritten_start
+= logical_len
;
3234 clear_extent_uptodate(io_tree
, unwritten_start
, end
, NULL
);
3236 /* Drop extent maps for the part of the extent we didn't write. */
3237 btrfs_drop_extent_map_range(inode
, unwritten_start
, end
, false);
3240 * If the ordered extent had an IOERR or something else went
3241 * wrong we need to return the space for this ordered extent
3242 * back to the allocator. We only free the extent in the
3243 * truncated case if we didn't write out the extent at all.
3245 * If we made it past insert_reserved_file_extent before we
3246 * errored out then we don't need to do this as the accounting
3247 * has already been done.
3249 if ((ret
|| !logical_len
) &&
3250 clear_reserved_extent
&&
3251 !test_bit(BTRFS_ORDERED_NOCOW
, &ordered_extent
->flags
) &&
3252 !test_bit(BTRFS_ORDERED_PREALLOC
, &ordered_extent
->flags
)) {
3254 * Discard the range before returning it back to the
3257 if (ret
&& btrfs_test_opt(fs_info
, DISCARD_SYNC
))
3258 btrfs_discard_extent(fs_info
,
3259 ordered_extent
->disk_bytenr
,
3260 ordered_extent
->disk_num_bytes
,
3262 btrfs_free_reserved_extent(fs_info
,
3263 ordered_extent
->disk_bytenr
,
3264 ordered_extent
->disk_num_bytes
, 1);
3269 * This needs to be done to make sure anybody waiting knows we are done
3270 * updating everything for this ordered extent.
3272 btrfs_remove_ordered_extent(inode
, ordered_extent
);
3275 btrfs_put_ordered_extent(ordered_extent
);
3276 /* once for the tree */
3277 btrfs_put_ordered_extent(ordered_extent
);
3282 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode
*inode
,
3283 struct page
*page
, u64 start
,
3284 u64 end
, bool uptodate
)
3286 trace_btrfs_writepage_end_io_hook(inode
, start
, end
, uptodate
);
3288 btrfs_mark_ordered_io_finished(inode
, page
, start
, end
+ 1 - start
, uptodate
);
3292 * Verify the checksum for a single sector without any extra action that depend
3293 * on the type of I/O.
3295 int btrfs_check_sector_csum(struct btrfs_fs_info
*fs_info
, struct page
*page
,
3296 u32 pgoff
, u8
*csum
, const u8
* const csum_expected
)
3298 SHASH_DESC_ON_STACK(shash
, fs_info
->csum_shash
);
3301 ASSERT(pgoff
+ fs_info
->sectorsize
<= PAGE_SIZE
);
3303 shash
->tfm
= fs_info
->csum_shash
;
3305 kaddr
= kmap_local_page(page
) + pgoff
;
3306 crypto_shash_digest(shash
, kaddr
, fs_info
->sectorsize
, csum
);
3307 kunmap_local(kaddr
);
3309 if (memcmp(csum
, csum_expected
, fs_info
->csum_size
))
3315 * Verify the checksum of a single data sector.
3317 * @bbio: btrfs_io_bio which contains the csum
3318 * @dev: device the sector is on
3319 * @bio_offset: offset to the beginning of the bio (in bytes)
3320 * @bv: bio_vec to check
3322 * Check if the checksum on a data block is valid. When a checksum mismatch is
3323 * detected, report the error and fill the corrupted range with zero.
3325 * Return %true if the sector is ok or had no checksum to start with, else %false.
3327 bool btrfs_data_csum_ok(struct btrfs_bio
*bbio
, struct btrfs_device
*dev
,
3328 u32 bio_offset
, struct bio_vec
*bv
)
3330 struct btrfs_inode
*inode
= bbio
->inode
;
3331 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
3332 u64 file_offset
= bbio
->file_offset
+ bio_offset
;
3333 u64 end
= file_offset
+ bv
->bv_len
- 1;
3335 u8 csum
[BTRFS_CSUM_SIZE
];
3337 ASSERT(bv
->bv_len
== fs_info
->sectorsize
);
3342 if (btrfs_is_data_reloc_root(inode
->root
) &&
3343 test_range_bit(&inode
->io_tree
, file_offset
, end
, EXTENT_NODATASUM
,
3345 /* Skip the range without csum for data reloc inode */
3346 clear_extent_bits(&inode
->io_tree
, file_offset
, end
,
3351 csum_expected
= bbio
->csum
+ (bio_offset
>> fs_info
->sectorsize_bits
) *
3353 if (btrfs_check_sector_csum(fs_info
, bv
->bv_page
, bv
->bv_offset
, csum
,
3359 btrfs_print_data_csum_error(inode
, file_offset
, csum
, csum_expected
,
3362 btrfs_dev_stat_inc_and_print(dev
, BTRFS_DEV_STAT_CORRUPTION_ERRS
);
3368 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3370 * @inode: The inode we want to perform iput on
3372 * This function uses the generic vfs_inode::i_count to track whether we should
3373 * just decrement it (in case it's > 1) or if this is the last iput then link
3374 * the inode to the delayed iput machinery. Delayed iputs are processed at
3375 * transaction commit time/superblock commit/cleaner kthread.
3377 void btrfs_add_delayed_iput(struct btrfs_inode
*inode
)
3379 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
3381 if (atomic_add_unless(&inode
->vfs_inode
.i_count
, -1, 1))
3384 atomic_inc(&fs_info
->nr_delayed_iputs
);
3385 spin_lock(&fs_info
->delayed_iput_lock
);
3386 ASSERT(list_empty(&inode
->delayed_iput
));
3387 list_add_tail(&inode
->delayed_iput
, &fs_info
->delayed_iputs
);
3388 spin_unlock(&fs_info
->delayed_iput_lock
);
3389 if (!test_bit(BTRFS_FS_CLEANER_RUNNING
, &fs_info
->flags
))
3390 wake_up_process(fs_info
->cleaner_kthread
);
3393 static void run_delayed_iput_locked(struct btrfs_fs_info
*fs_info
,
3394 struct btrfs_inode
*inode
)
3396 list_del_init(&inode
->delayed_iput
);
3397 spin_unlock(&fs_info
->delayed_iput_lock
);
3398 iput(&inode
->vfs_inode
);
3399 if (atomic_dec_and_test(&fs_info
->nr_delayed_iputs
))
3400 wake_up(&fs_info
->delayed_iputs_wait
);
3401 spin_lock(&fs_info
->delayed_iput_lock
);
3404 static void btrfs_run_delayed_iput(struct btrfs_fs_info
*fs_info
,
3405 struct btrfs_inode
*inode
)
3407 if (!list_empty(&inode
->delayed_iput
)) {
3408 spin_lock(&fs_info
->delayed_iput_lock
);
3409 if (!list_empty(&inode
->delayed_iput
))
3410 run_delayed_iput_locked(fs_info
, inode
);
3411 spin_unlock(&fs_info
->delayed_iput_lock
);
3415 void btrfs_run_delayed_iputs(struct btrfs_fs_info
*fs_info
)
3418 spin_lock(&fs_info
->delayed_iput_lock
);
3419 while (!list_empty(&fs_info
->delayed_iputs
)) {
3420 struct btrfs_inode
*inode
;
3422 inode
= list_first_entry(&fs_info
->delayed_iputs
,
3423 struct btrfs_inode
, delayed_iput
);
3424 run_delayed_iput_locked(fs_info
, inode
);
3425 cond_resched_lock(&fs_info
->delayed_iput_lock
);
3427 spin_unlock(&fs_info
->delayed_iput_lock
);
3431 * Wait for flushing all delayed iputs
3433 * @fs_info: the filesystem
3435 * This will wait on any delayed iputs that are currently running with KILLABLE
3436 * set. Once they are all done running we will return, unless we are killed in
3437 * which case we return EINTR. This helps in user operations like fallocate etc
3438 * that might get blocked on the iputs.
3440 * Return EINTR if we were killed, 0 if nothing's pending
3442 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info
*fs_info
)
3444 int ret
= wait_event_killable(fs_info
->delayed_iputs_wait
,
3445 atomic_read(&fs_info
->nr_delayed_iputs
) == 0);
3452 * This creates an orphan entry for the given inode in case something goes wrong
3453 * in the middle of an unlink.
3455 int btrfs_orphan_add(struct btrfs_trans_handle
*trans
,
3456 struct btrfs_inode
*inode
)
3460 ret
= btrfs_insert_orphan_item(trans
, inode
->root
, btrfs_ino(inode
));
3461 if (ret
&& ret
!= -EEXIST
) {
3462 btrfs_abort_transaction(trans
, ret
);
3470 * We have done the delete so we can go ahead and remove the orphan item for
3471 * this particular inode.
3473 static int btrfs_orphan_del(struct btrfs_trans_handle
*trans
,
3474 struct btrfs_inode
*inode
)
3476 return btrfs_del_orphan_item(trans
, inode
->root
, btrfs_ino(inode
));
3480 * this cleans up any orphans that may be left on the list from the last use
3483 int btrfs_orphan_cleanup(struct btrfs_root
*root
)
3485 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
3486 struct btrfs_path
*path
;
3487 struct extent_buffer
*leaf
;
3488 struct btrfs_key key
, found_key
;
3489 struct btrfs_trans_handle
*trans
;
3490 struct inode
*inode
;
3491 u64 last_objectid
= 0;
3492 int ret
= 0, nr_unlink
= 0;
3494 if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP
, &root
->state
))
3497 path
= btrfs_alloc_path();
3502 path
->reada
= READA_BACK
;
3504 key
.objectid
= BTRFS_ORPHAN_OBJECTID
;
3505 key
.type
= BTRFS_ORPHAN_ITEM_KEY
;
3506 key
.offset
= (u64
)-1;
3509 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
3514 * if ret == 0 means we found what we were searching for, which
3515 * is weird, but possible, so only screw with path if we didn't
3516 * find the key and see if we have stuff that matches
3520 if (path
->slots
[0] == 0)
3525 /* pull out the item */
3526 leaf
= path
->nodes
[0];
3527 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
3529 /* make sure the item matches what we want */
3530 if (found_key
.objectid
!= BTRFS_ORPHAN_OBJECTID
)
3532 if (found_key
.type
!= BTRFS_ORPHAN_ITEM_KEY
)
3535 /* release the path since we're done with it */
3536 btrfs_release_path(path
);
3539 * this is where we are basically btrfs_lookup, without the
3540 * crossing root thing. we store the inode number in the
3541 * offset of the orphan item.
3544 if (found_key
.offset
== last_objectid
) {
3546 "Error removing orphan entry, stopping orphan cleanup");
3551 last_objectid
= found_key
.offset
;
3553 found_key
.objectid
= found_key
.offset
;
3554 found_key
.type
= BTRFS_INODE_ITEM_KEY
;
3555 found_key
.offset
= 0;
3556 inode
= btrfs_iget(fs_info
->sb
, last_objectid
, root
);
3557 ret
= PTR_ERR_OR_ZERO(inode
);
3558 if (ret
&& ret
!= -ENOENT
)
3561 if (ret
== -ENOENT
&& root
== fs_info
->tree_root
) {
3562 struct btrfs_root
*dead_root
;
3563 int is_dead_root
= 0;
3566 * This is an orphan in the tree root. Currently these
3567 * could come from 2 sources:
3568 * a) a root (snapshot/subvolume) deletion in progress
3569 * b) a free space cache inode
3570 * We need to distinguish those two, as the orphan item
3571 * for a root must not get deleted before the deletion
3572 * of the snapshot/subvolume's tree completes.
3574 * btrfs_find_orphan_roots() ran before us, which has
3575 * found all deleted roots and loaded them into
3576 * fs_info->fs_roots_radix. So here we can find if an
3577 * orphan item corresponds to a deleted root by looking
3578 * up the root from that radix tree.
3581 spin_lock(&fs_info
->fs_roots_radix_lock
);
3582 dead_root
= radix_tree_lookup(&fs_info
->fs_roots_radix
,
3583 (unsigned long)found_key
.objectid
);
3584 if (dead_root
&& btrfs_root_refs(&dead_root
->root_item
) == 0)
3586 spin_unlock(&fs_info
->fs_roots_radix_lock
);
3589 /* prevent this orphan from being found again */
3590 key
.offset
= found_key
.objectid
- 1;
3597 * If we have an inode with links, there are a couple of
3600 * 1. We were halfway through creating fsverity metadata for the
3601 * file. In that case, the orphan item represents incomplete
3602 * fsverity metadata which must be cleaned up with
3603 * btrfs_drop_verity_items and deleting the orphan item.
3605 * 2. Old kernels (before v3.12) used to create an
3606 * orphan item for truncate indicating that there were possibly
3607 * extent items past i_size that needed to be deleted. In v3.12,
3608 * truncate was changed to update i_size in sync with the extent
3609 * items, but the (useless) orphan item was still created. Since
3610 * v4.18, we don't create the orphan item for truncate at all.
3612 * So, this item could mean that we need to do a truncate, but
3613 * only if this filesystem was last used on a pre-v3.12 kernel
3614 * and was not cleanly unmounted. The odds of that are quite
3615 * slim, and it's a pain to do the truncate now, so just delete
3618 * It's also possible that this orphan item was supposed to be
3619 * deleted but wasn't. The inode number may have been reused,
3620 * but either way, we can delete the orphan item.
3622 if (ret
== -ENOENT
|| inode
->i_nlink
) {
3624 ret
= btrfs_drop_verity_items(BTRFS_I(inode
));
3629 trans
= btrfs_start_transaction(root
, 1);
3630 if (IS_ERR(trans
)) {
3631 ret
= PTR_ERR(trans
);
3635 btrfs_debug(fs_info
, "auto deleting %Lu",
3636 found_key
.objectid
);
3637 ret
= btrfs_del_orphan_item(trans
, root
,
3638 found_key
.objectid
);
3639 btrfs_end_transaction(trans
);
3649 /* this will do delete_inode and everything for us */
3652 /* release the path since we're done with it */
3653 btrfs_release_path(path
);
3655 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED
, &root
->state
)) {
3656 trans
= btrfs_join_transaction(root
);
3658 btrfs_end_transaction(trans
);
3662 btrfs_debug(fs_info
, "unlinked %d orphans", nr_unlink
);
3666 btrfs_err(fs_info
, "could not do orphan cleanup %d", ret
);
3667 btrfs_free_path(path
);
3672 * very simple check to peek ahead in the leaf looking for xattrs. If we
3673 * don't find any xattrs, we know there can't be any acls.
3675 * slot is the slot the inode is in, objectid is the objectid of the inode
3677 static noinline
int acls_after_inode_item(struct extent_buffer
*leaf
,
3678 int slot
, u64 objectid
,
3679 int *first_xattr_slot
)
3681 u32 nritems
= btrfs_header_nritems(leaf
);
3682 struct btrfs_key found_key
;
3683 static u64 xattr_access
= 0;
3684 static u64 xattr_default
= 0;
3687 if (!xattr_access
) {
3688 xattr_access
= btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS
,
3689 strlen(XATTR_NAME_POSIX_ACL_ACCESS
));
3690 xattr_default
= btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT
,
3691 strlen(XATTR_NAME_POSIX_ACL_DEFAULT
));
3695 *first_xattr_slot
= -1;
3696 while (slot
< nritems
) {
3697 btrfs_item_key_to_cpu(leaf
, &found_key
, slot
);
3699 /* we found a different objectid, there must not be acls */
3700 if (found_key
.objectid
!= objectid
)
3703 /* we found an xattr, assume we've got an acl */
3704 if (found_key
.type
== BTRFS_XATTR_ITEM_KEY
) {
3705 if (*first_xattr_slot
== -1)
3706 *first_xattr_slot
= slot
;
3707 if (found_key
.offset
== xattr_access
||
3708 found_key
.offset
== xattr_default
)
3713 * we found a key greater than an xattr key, there can't
3714 * be any acls later on
3716 if (found_key
.type
> BTRFS_XATTR_ITEM_KEY
)
3723 * it goes inode, inode backrefs, xattrs, extents,
3724 * so if there are a ton of hard links to an inode there can
3725 * be a lot of backrefs. Don't waste time searching too hard,
3726 * this is just an optimization
3731 /* we hit the end of the leaf before we found an xattr or
3732 * something larger than an xattr. We have to assume the inode
3735 if (*first_xattr_slot
== -1)
3736 *first_xattr_slot
= slot
;
3741 * read an inode from the btree into the in-memory inode
3743 static int btrfs_read_locked_inode(struct inode
*inode
,
3744 struct btrfs_path
*in_path
)
3746 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
3747 struct btrfs_path
*path
= in_path
;
3748 struct extent_buffer
*leaf
;
3749 struct btrfs_inode_item
*inode_item
;
3750 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
3751 struct btrfs_key location
;
3756 bool filled
= false;
3757 int first_xattr_slot
;
3759 ret
= btrfs_fill_inode(inode
, &rdev
);
3764 path
= btrfs_alloc_path();
3769 memcpy(&location
, &BTRFS_I(inode
)->location
, sizeof(location
));
3771 ret
= btrfs_lookup_inode(NULL
, root
, path
, &location
, 0);
3773 if (path
!= in_path
)
3774 btrfs_free_path(path
);
3778 leaf
= path
->nodes
[0];
3783 inode_item
= btrfs_item_ptr(leaf
, path
->slots
[0],
3784 struct btrfs_inode_item
);
3785 inode
->i_mode
= btrfs_inode_mode(leaf
, inode_item
);
3786 set_nlink(inode
, btrfs_inode_nlink(leaf
, inode_item
));
3787 i_uid_write(inode
, btrfs_inode_uid(leaf
, inode_item
));
3788 i_gid_write(inode
, btrfs_inode_gid(leaf
, inode_item
));
3789 btrfs_i_size_write(BTRFS_I(inode
), btrfs_inode_size(leaf
, inode_item
));
3790 btrfs_inode_set_file_extent_range(BTRFS_I(inode
), 0,
3791 round_up(i_size_read(inode
), fs_info
->sectorsize
));
3793 inode
->i_atime
.tv_sec
= btrfs_timespec_sec(leaf
, &inode_item
->atime
);
3794 inode
->i_atime
.tv_nsec
= btrfs_timespec_nsec(leaf
, &inode_item
->atime
);
3796 inode
->i_mtime
.tv_sec
= btrfs_timespec_sec(leaf
, &inode_item
->mtime
);
3797 inode
->i_mtime
.tv_nsec
= btrfs_timespec_nsec(leaf
, &inode_item
->mtime
);
3799 inode
->i_ctime
.tv_sec
= btrfs_timespec_sec(leaf
, &inode_item
->ctime
);
3800 inode
->i_ctime
.tv_nsec
= btrfs_timespec_nsec(leaf
, &inode_item
->ctime
);
3802 BTRFS_I(inode
)->i_otime
.tv_sec
=
3803 btrfs_timespec_sec(leaf
, &inode_item
->otime
);
3804 BTRFS_I(inode
)->i_otime
.tv_nsec
=
3805 btrfs_timespec_nsec(leaf
, &inode_item
->otime
);
3807 inode_set_bytes(inode
, btrfs_inode_nbytes(leaf
, inode_item
));
3808 BTRFS_I(inode
)->generation
= btrfs_inode_generation(leaf
, inode_item
);
3809 BTRFS_I(inode
)->last_trans
= btrfs_inode_transid(leaf
, inode_item
);
3811 inode_set_iversion_queried(inode
,
3812 btrfs_inode_sequence(leaf
, inode_item
));
3813 inode
->i_generation
= BTRFS_I(inode
)->generation
;
3815 rdev
= btrfs_inode_rdev(leaf
, inode_item
);
3817 BTRFS_I(inode
)->index_cnt
= (u64
)-1;
3818 btrfs_inode_split_flags(btrfs_inode_flags(leaf
, inode_item
),
3819 &BTRFS_I(inode
)->flags
, &BTRFS_I(inode
)->ro_flags
);
3823 * If we were modified in the current generation and evicted from memory
3824 * and then re-read we need to do a full sync since we don't have any
3825 * idea about which extents were modified before we were evicted from
3828 * This is required for both inode re-read from disk and delayed inode
3829 * in delayed_nodes_tree.
3831 if (BTRFS_I(inode
)->last_trans
== fs_info
->generation
)
3832 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
3833 &BTRFS_I(inode
)->runtime_flags
);
3836 * We don't persist the id of the transaction where an unlink operation
3837 * against the inode was last made. So here we assume the inode might
3838 * have been evicted, and therefore the exact value of last_unlink_trans
3839 * lost, and set it to last_trans to avoid metadata inconsistencies
3840 * between the inode and its parent if the inode is fsync'ed and the log
3841 * replayed. For example, in the scenario:
3844 * ln mydir/foo mydir/bar
3847 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3848 * xfs_io -c fsync mydir/foo
3850 * mount fs, triggers fsync log replay
3852 * We must make sure that when we fsync our inode foo we also log its
3853 * parent inode, otherwise after log replay the parent still has the
3854 * dentry with the "bar" name but our inode foo has a link count of 1
3855 * and doesn't have an inode ref with the name "bar" anymore.
3857 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3858 * but it guarantees correctness at the expense of occasional full
3859 * transaction commits on fsync if our inode is a directory, or if our
3860 * inode is not a directory, logging its parent unnecessarily.
3862 BTRFS_I(inode
)->last_unlink_trans
= BTRFS_I(inode
)->last_trans
;
3865 * Same logic as for last_unlink_trans. We don't persist the generation
3866 * of the last transaction where this inode was used for a reflink
3867 * operation, so after eviction and reloading the inode we must be
3868 * pessimistic and assume the last transaction that modified the inode.
3870 BTRFS_I(inode
)->last_reflink_trans
= BTRFS_I(inode
)->last_trans
;
3873 if (inode
->i_nlink
!= 1 ||
3874 path
->slots
[0] >= btrfs_header_nritems(leaf
))
3877 btrfs_item_key_to_cpu(leaf
, &location
, path
->slots
[0]);
3878 if (location
.objectid
!= btrfs_ino(BTRFS_I(inode
)))
3881 ptr
= btrfs_item_ptr_offset(leaf
, path
->slots
[0]);
3882 if (location
.type
== BTRFS_INODE_REF_KEY
) {
3883 struct btrfs_inode_ref
*ref
;
3885 ref
= (struct btrfs_inode_ref
*)ptr
;
3886 BTRFS_I(inode
)->dir_index
= btrfs_inode_ref_index(leaf
, ref
);
3887 } else if (location
.type
== BTRFS_INODE_EXTREF_KEY
) {
3888 struct btrfs_inode_extref
*extref
;
3890 extref
= (struct btrfs_inode_extref
*)ptr
;
3891 BTRFS_I(inode
)->dir_index
= btrfs_inode_extref_index(leaf
,
3896 * try to precache a NULL acl entry for files that don't have
3897 * any xattrs or acls
3899 maybe_acls
= acls_after_inode_item(leaf
, path
->slots
[0],
3900 btrfs_ino(BTRFS_I(inode
)), &first_xattr_slot
);
3901 if (first_xattr_slot
!= -1) {
3902 path
->slots
[0] = first_xattr_slot
;
3903 ret
= btrfs_load_inode_props(inode
, path
);
3906 "error loading props for ino %llu (root %llu): %d",
3907 btrfs_ino(BTRFS_I(inode
)),
3908 root
->root_key
.objectid
, ret
);
3910 if (path
!= in_path
)
3911 btrfs_free_path(path
);
3914 cache_no_acl(inode
);
3916 switch (inode
->i_mode
& S_IFMT
) {
3918 inode
->i_mapping
->a_ops
= &btrfs_aops
;
3919 inode
->i_fop
= &btrfs_file_operations
;
3920 inode
->i_op
= &btrfs_file_inode_operations
;
3923 inode
->i_fop
= &btrfs_dir_file_operations
;
3924 inode
->i_op
= &btrfs_dir_inode_operations
;
3927 inode
->i_op
= &btrfs_symlink_inode_operations
;
3928 inode_nohighmem(inode
);
3929 inode
->i_mapping
->a_ops
= &btrfs_aops
;
3932 inode
->i_op
= &btrfs_special_inode_operations
;
3933 init_special_inode(inode
, inode
->i_mode
, rdev
);
3937 btrfs_sync_inode_flags_to_i_flags(inode
);
3942 * given a leaf and an inode, copy the inode fields into the leaf
3944 static void fill_inode_item(struct btrfs_trans_handle
*trans
,
3945 struct extent_buffer
*leaf
,
3946 struct btrfs_inode_item
*item
,
3947 struct inode
*inode
)
3949 struct btrfs_map_token token
;
3952 btrfs_init_map_token(&token
, leaf
);
3954 btrfs_set_token_inode_uid(&token
, item
, i_uid_read(inode
));
3955 btrfs_set_token_inode_gid(&token
, item
, i_gid_read(inode
));
3956 btrfs_set_token_inode_size(&token
, item
, BTRFS_I(inode
)->disk_i_size
);
3957 btrfs_set_token_inode_mode(&token
, item
, inode
->i_mode
);
3958 btrfs_set_token_inode_nlink(&token
, item
, inode
->i_nlink
);
3960 btrfs_set_token_timespec_sec(&token
, &item
->atime
,
3961 inode
->i_atime
.tv_sec
);
3962 btrfs_set_token_timespec_nsec(&token
, &item
->atime
,
3963 inode
->i_atime
.tv_nsec
);
3965 btrfs_set_token_timespec_sec(&token
, &item
->mtime
,
3966 inode
->i_mtime
.tv_sec
);
3967 btrfs_set_token_timespec_nsec(&token
, &item
->mtime
,
3968 inode
->i_mtime
.tv_nsec
);
3970 btrfs_set_token_timespec_sec(&token
, &item
->ctime
,
3971 inode
->i_ctime
.tv_sec
);
3972 btrfs_set_token_timespec_nsec(&token
, &item
->ctime
,
3973 inode
->i_ctime
.tv_nsec
);
3975 btrfs_set_token_timespec_sec(&token
, &item
->otime
,
3976 BTRFS_I(inode
)->i_otime
.tv_sec
);
3977 btrfs_set_token_timespec_nsec(&token
, &item
->otime
,
3978 BTRFS_I(inode
)->i_otime
.tv_nsec
);
3980 btrfs_set_token_inode_nbytes(&token
, item
, inode_get_bytes(inode
));
3981 btrfs_set_token_inode_generation(&token
, item
,
3982 BTRFS_I(inode
)->generation
);
3983 btrfs_set_token_inode_sequence(&token
, item
, inode_peek_iversion(inode
));
3984 btrfs_set_token_inode_transid(&token
, item
, trans
->transid
);
3985 btrfs_set_token_inode_rdev(&token
, item
, inode
->i_rdev
);
3986 flags
= btrfs_inode_combine_flags(BTRFS_I(inode
)->flags
,
3987 BTRFS_I(inode
)->ro_flags
);
3988 btrfs_set_token_inode_flags(&token
, item
, flags
);
3989 btrfs_set_token_inode_block_group(&token
, item
, 0);
3993 * copy everything in the in-memory inode into the btree.
3995 static noinline
int btrfs_update_inode_item(struct btrfs_trans_handle
*trans
,
3996 struct btrfs_root
*root
,
3997 struct btrfs_inode
*inode
)
3999 struct btrfs_inode_item
*inode_item
;
4000 struct btrfs_path
*path
;
4001 struct extent_buffer
*leaf
;
4004 path
= btrfs_alloc_path();
4008 ret
= btrfs_lookup_inode(trans
, root
, path
, &inode
->location
, 1);
4015 leaf
= path
->nodes
[0];
4016 inode_item
= btrfs_item_ptr(leaf
, path
->slots
[0],
4017 struct btrfs_inode_item
);
4019 fill_inode_item(trans
, leaf
, inode_item
, &inode
->vfs_inode
);
4020 btrfs_mark_buffer_dirty(leaf
);
4021 btrfs_set_inode_last_trans(trans
, inode
);
4024 btrfs_free_path(path
);
4029 * copy everything in the in-memory inode into the btree.
4031 noinline
int btrfs_update_inode(struct btrfs_trans_handle
*trans
,
4032 struct btrfs_root
*root
,
4033 struct btrfs_inode
*inode
)
4035 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4039 * If the inode is a free space inode, we can deadlock during commit
4040 * if we put it into the delayed code.
4042 * The data relocation inode should also be directly updated
4045 if (!btrfs_is_free_space_inode(inode
)
4046 && !btrfs_is_data_reloc_root(root
)
4047 && !test_bit(BTRFS_FS_LOG_RECOVERING
, &fs_info
->flags
)) {
4048 btrfs_update_root_times(trans
, root
);
4050 ret
= btrfs_delayed_update_inode(trans
, root
, inode
);
4052 btrfs_set_inode_last_trans(trans
, inode
);
4056 return btrfs_update_inode_item(trans
, root
, inode
);
4059 int btrfs_update_inode_fallback(struct btrfs_trans_handle
*trans
,
4060 struct btrfs_root
*root
, struct btrfs_inode
*inode
)
4064 ret
= btrfs_update_inode(trans
, root
, inode
);
4066 return btrfs_update_inode_item(trans
, root
, inode
);
4071 * unlink helper that gets used here in inode.c and in the tree logging
4072 * recovery code. It remove a link in a directory with a given name, and
4073 * also drops the back refs in the inode to the directory
4075 static int __btrfs_unlink_inode(struct btrfs_trans_handle
*trans
,
4076 struct btrfs_inode
*dir
,
4077 struct btrfs_inode
*inode
,
4078 const struct fscrypt_str
*name
,
4079 struct btrfs_rename_ctx
*rename_ctx
)
4081 struct btrfs_root
*root
= dir
->root
;
4082 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4083 struct btrfs_path
*path
;
4085 struct btrfs_dir_item
*di
;
4087 u64 ino
= btrfs_ino(inode
);
4088 u64 dir_ino
= btrfs_ino(dir
);
4090 path
= btrfs_alloc_path();
4096 di
= btrfs_lookup_dir_item(trans
, root
, path
, dir_ino
, name
, -1);
4097 if (IS_ERR_OR_NULL(di
)) {
4098 ret
= di
? PTR_ERR(di
) : -ENOENT
;
4101 ret
= btrfs_delete_one_dir_name(trans
, root
, path
, di
);
4104 btrfs_release_path(path
);
4107 * If we don't have dir index, we have to get it by looking up
4108 * the inode ref, since we get the inode ref, remove it directly,
4109 * it is unnecessary to do delayed deletion.
4111 * But if we have dir index, needn't search inode ref to get it.
4112 * Since the inode ref is close to the inode item, it is better
4113 * that we delay to delete it, and just do this deletion when
4114 * we update the inode item.
4116 if (inode
->dir_index
) {
4117 ret
= btrfs_delayed_delete_inode_ref(inode
);
4119 index
= inode
->dir_index
;
4124 ret
= btrfs_del_inode_ref(trans
, root
, name
, ino
, dir_ino
, &index
);
4127 "failed to delete reference to %.*s, inode %llu parent %llu",
4128 name
->len
, name
->name
, ino
, dir_ino
);
4129 btrfs_abort_transaction(trans
, ret
);
4134 rename_ctx
->index
= index
;
4136 ret
= btrfs_delete_delayed_dir_index(trans
, dir
, index
);
4138 btrfs_abort_transaction(trans
, ret
);
4143 * If we are in a rename context, we don't need to update anything in the
4144 * log. That will be done later during the rename by btrfs_log_new_name().
4145 * Besides that, doing it here would only cause extra unnecessary btree
4146 * operations on the log tree, increasing latency for applications.
4149 btrfs_del_inode_ref_in_log(trans
, root
, name
, inode
, dir_ino
);
4150 btrfs_del_dir_entries_in_log(trans
, root
, name
, dir
, index
);
4154 * If we have a pending delayed iput we could end up with the final iput
4155 * being run in btrfs-cleaner context. If we have enough of these built
4156 * up we can end up burning a lot of time in btrfs-cleaner without any
4157 * way to throttle the unlinks. Since we're currently holding a ref on
4158 * the inode we can run the delayed iput here without any issues as the
4159 * final iput won't be done until after we drop the ref we're currently
4162 btrfs_run_delayed_iput(fs_info
, inode
);
4164 btrfs_free_path(path
);
4168 btrfs_i_size_write(dir
, dir
->vfs_inode
.i_size
- name
->len
* 2);
4169 inode_inc_iversion(&inode
->vfs_inode
);
4170 inode_inc_iversion(&dir
->vfs_inode
);
4171 inode
->vfs_inode
.i_ctime
= current_time(&inode
->vfs_inode
);
4172 dir
->vfs_inode
.i_mtime
= inode
->vfs_inode
.i_ctime
;
4173 dir
->vfs_inode
.i_ctime
= inode
->vfs_inode
.i_ctime
;
4174 ret
= btrfs_update_inode(trans
, root
, dir
);
4179 int btrfs_unlink_inode(struct btrfs_trans_handle
*trans
,
4180 struct btrfs_inode
*dir
, struct btrfs_inode
*inode
,
4181 const struct fscrypt_str
*name
)
4185 ret
= __btrfs_unlink_inode(trans
, dir
, inode
, name
, NULL
);
4187 drop_nlink(&inode
->vfs_inode
);
4188 ret
= btrfs_update_inode(trans
, inode
->root
, inode
);
4194 * helper to start transaction for unlink and rmdir.
4196 * unlink and rmdir are special in btrfs, they do not always free space, so
4197 * if we cannot make our reservations the normal way try and see if there is
4198 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4199 * allow the unlink to occur.
4201 static struct btrfs_trans_handle
*__unlink_start_trans(struct btrfs_inode
*dir
)
4203 struct btrfs_root
*root
= dir
->root
;
4205 return btrfs_start_transaction_fallback_global_rsv(root
,
4206 BTRFS_UNLINK_METADATA_UNITS
);
4209 static int btrfs_unlink(struct inode
*dir
, struct dentry
*dentry
)
4211 struct btrfs_trans_handle
*trans
;
4212 struct inode
*inode
= d_inode(dentry
);
4214 struct fscrypt_name fname
;
4216 ret
= fscrypt_setup_filename(dir
, &dentry
->d_name
, 1, &fname
);
4220 /* This needs to handle no-key deletions later on */
4222 trans
= __unlink_start_trans(BTRFS_I(dir
));
4223 if (IS_ERR(trans
)) {
4224 ret
= PTR_ERR(trans
);
4228 btrfs_record_unlink_dir(trans
, BTRFS_I(dir
), BTRFS_I(d_inode(dentry
)),
4231 ret
= btrfs_unlink_inode(trans
, BTRFS_I(dir
), BTRFS_I(d_inode(dentry
)),
4236 if (inode
->i_nlink
== 0) {
4237 ret
= btrfs_orphan_add(trans
, BTRFS_I(inode
));
4243 btrfs_end_transaction(trans
);
4244 btrfs_btree_balance_dirty(BTRFS_I(dir
)->root
->fs_info
);
4246 fscrypt_free_filename(&fname
);
4250 static int btrfs_unlink_subvol(struct btrfs_trans_handle
*trans
,
4251 struct btrfs_inode
*dir
, struct dentry
*dentry
)
4253 struct btrfs_root
*root
= 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
;
4262 u64 dir_ino
= btrfs_ino(dir
);
4263 struct fscrypt_name fname
;
4265 ret
= fscrypt_setup_filename(&dir
->vfs_inode
, &dentry
->d_name
, 1, &fname
);
4269 /* This needs to handle no-key deletions later on */
4271 if (btrfs_ino(inode
) == BTRFS_FIRST_FREE_OBJECTID
) {
4272 objectid
= inode
->root
->root_key
.objectid
;
4273 } else if (btrfs_ino(inode
) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
) {
4274 objectid
= inode
->location
.objectid
;
4277 fscrypt_free_filename(&fname
);
4281 path
= btrfs_alloc_path();
4287 di
= btrfs_lookup_dir_item(trans
, root
, path
, dir_ino
,
4288 &fname
.disk_name
, -1);
4289 if (IS_ERR_OR_NULL(di
)) {
4290 ret
= di
? PTR_ERR(di
) : -ENOENT
;
4294 leaf
= path
->nodes
[0];
4295 btrfs_dir_item_key_to_cpu(leaf
, di
, &key
);
4296 WARN_ON(key
.type
!= BTRFS_ROOT_ITEM_KEY
|| key
.objectid
!= objectid
);
4297 ret
= btrfs_delete_one_dir_name(trans
, root
, path
, di
);
4299 btrfs_abort_transaction(trans
, ret
);
4302 btrfs_release_path(path
);
4305 * This is a placeholder inode for a subvolume we didn't have a
4306 * reference to at the time of the snapshot creation. In the meantime
4307 * we could have renamed the real subvol link into our snapshot, so
4308 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4309 * Instead simply lookup the dir_index_item for this entry so we can
4310 * remove it. Otherwise we know we have a ref to the root and we can
4311 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4313 if (btrfs_ino(inode
) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
) {
4314 di
= btrfs_search_dir_index_item(root
, path
, dir_ino
, &fname
.disk_name
);
4315 if (IS_ERR_OR_NULL(di
)) {
4320 btrfs_abort_transaction(trans
, ret
);
4324 leaf
= path
->nodes
[0];
4325 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
4327 btrfs_release_path(path
);
4329 ret
= btrfs_del_root_ref(trans
, objectid
,
4330 root
->root_key
.objectid
, dir_ino
,
4331 &index
, &fname
.disk_name
);
4333 btrfs_abort_transaction(trans
, ret
);
4338 ret
= btrfs_delete_delayed_dir_index(trans
, dir
, index
);
4340 btrfs_abort_transaction(trans
, ret
);
4344 btrfs_i_size_write(dir
, dir
->vfs_inode
.i_size
- fname
.disk_name
.len
* 2);
4345 inode_inc_iversion(&dir
->vfs_inode
);
4346 dir
->vfs_inode
.i_mtime
= current_time(&dir
->vfs_inode
);
4347 dir
->vfs_inode
.i_ctime
= dir
->vfs_inode
.i_mtime
;
4348 ret
= btrfs_update_inode_fallback(trans
, root
, dir
);
4350 btrfs_abort_transaction(trans
, ret
);
4352 btrfs_free_path(path
);
4353 fscrypt_free_filename(&fname
);
4358 * Helper to check if the subvolume references other subvolumes or if it's
4361 static noinline
int may_destroy_subvol(struct btrfs_root
*root
)
4363 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4364 struct btrfs_path
*path
;
4365 struct btrfs_dir_item
*di
;
4366 struct btrfs_key key
;
4367 struct fscrypt_str name
= FSTR_INIT("default", 7);
4371 path
= btrfs_alloc_path();
4375 /* Make sure this root isn't set as the default subvol */
4376 dir_id
= btrfs_super_root_dir(fs_info
->super_copy
);
4377 di
= btrfs_lookup_dir_item(NULL
, fs_info
->tree_root
, path
,
4379 if (di
&& !IS_ERR(di
)) {
4380 btrfs_dir_item_key_to_cpu(path
->nodes
[0], di
, &key
);
4381 if (key
.objectid
== root
->root_key
.objectid
) {
4384 "deleting default subvolume %llu is not allowed",
4388 btrfs_release_path(path
);
4391 key
.objectid
= root
->root_key
.objectid
;
4392 key
.type
= BTRFS_ROOT_REF_KEY
;
4393 key
.offset
= (u64
)-1;
4395 ret
= btrfs_search_slot(NULL
, fs_info
->tree_root
, &key
, path
, 0, 0);
4401 if (path
->slots
[0] > 0) {
4403 btrfs_item_key_to_cpu(path
->nodes
[0], &key
, path
->slots
[0]);
4404 if (key
.objectid
== root
->root_key
.objectid
&&
4405 key
.type
== BTRFS_ROOT_REF_KEY
)
4409 btrfs_free_path(path
);
4413 /* Delete all dentries for inodes belonging to the root */
4414 static void btrfs_prune_dentries(struct btrfs_root
*root
)
4416 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4417 struct rb_node
*node
;
4418 struct rb_node
*prev
;
4419 struct btrfs_inode
*entry
;
4420 struct inode
*inode
;
4423 if (!BTRFS_FS_ERROR(fs_info
))
4424 WARN_ON(btrfs_root_refs(&root
->root_item
) != 0);
4426 spin_lock(&root
->inode_lock
);
4428 node
= root
->inode_tree
.rb_node
;
4432 entry
= rb_entry(node
, struct btrfs_inode
, rb_node
);
4434 if (objectid
< btrfs_ino(entry
))
4435 node
= node
->rb_left
;
4436 else if (objectid
> btrfs_ino(entry
))
4437 node
= node
->rb_right
;
4443 entry
= rb_entry(prev
, struct btrfs_inode
, rb_node
);
4444 if (objectid
<= btrfs_ino(entry
)) {
4448 prev
= rb_next(prev
);
4452 entry
= rb_entry(node
, struct btrfs_inode
, rb_node
);
4453 objectid
= btrfs_ino(entry
) + 1;
4454 inode
= igrab(&entry
->vfs_inode
);
4456 spin_unlock(&root
->inode_lock
);
4457 if (atomic_read(&inode
->i_count
) > 1)
4458 d_prune_aliases(inode
);
4460 * btrfs_drop_inode will have it removed from the inode
4461 * cache when its usage count hits zero.
4465 spin_lock(&root
->inode_lock
);
4469 if (cond_resched_lock(&root
->inode_lock
))
4472 node
= rb_next(node
);
4474 spin_unlock(&root
->inode_lock
);
4477 int btrfs_delete_subvolume(struct btrfs_inode
*dir
, struct dentry
*dentry
)
4479 struct btrfs_fs_info
*fs_info
= btrfs_sb(dentry
->d_sb
);
4480 struct btrfs_root
*root
= dir
->root
;
4481 struct inode
*inode
= d_inode(dentry
);
4482 struct btrfs_root
*dest
= BTRFS_I(inode
)->root
;
4483 struct btrfs_trans_handle
*trans
;
4484 struct btrfs_block_rsv block_rsv
;
4489 * Don't allow to delete a subvolume with send in progress. This is
4490 * inside the inode lock so the error handling that has to drop the bit
4491 * again is not run concurrently.
4493 spin_lock(&dest
->root_item_lock
);
4494 if (dest
->send_in_progress
) {
4495 spin_unlock(&dest
->root_item_lock
);
4497 "attempt to delete subvolume %llu during send",
4498 dest
->root_key
.objectid
);
4501 if (atomic_read(&dest
->nr_swapfiles
)) {
4502 spin_unlock(&dest
->root_item_lock
);
4504 "attempt to delete subvolume %llu with active swapfile",
4505 root
->root_key
.objectid
);
4508 root_flags
= btrfs_root_flags(&dest
->root_item
);
4509 btrfs_set_root_flags(&dest
->root_item
,
4510 root_flags
| BTRFS_ROOT_SUBVOL_DEAD
);
4511 spin_unlock(&dest
->root_item_lock
);
4513 down_write(&fs_info
->subvol_sem
);
4515 ret
= may_destroy_subvol(dest
);
4519 btrfs_init_block_rsv(&block_rsv
, BTRFS_BLOCK_RSV_TEMP
);
4521 * One for dir inode,
4522 * two for dir entries,
4523 * two for root ref/backref.
4525 ret
= btrfs_subvolume_reserve_metadata(root
, &block_rsv
, 5, true);
4529 trans
= btrfs_start_transaction(root
, 0);
4530 if (IS_ERR(trans
)) {
4531 ret
= PTR_ERR(trans
);
4534 trans
->block_rsv
= &block_rsv
;
4535 trans
->bytes_reserved
= block_rsv
.size
;
4537 btrfs_record_snapshot_destroy(trans
, dir
);
4539 ret
= btrfs_unlink_subvol(trans
, dir
, dentry
);
4541 btrfs_abort_transaction(trans
, ret
);
4545 ret
= btrfs_record_root_in_trans(trans
, dest
);
4547 btrfs_abort_transaction(trans
, ret
);
4551 memset(&dest
->root_item
.drop_progress
, 0,
4552 sizeof(dest
->root_item
.drop_progress
));
4553 btrfs_set_root_drop_level(&dest
->root_item
, 0);
4554 btrfs_set_root_refs(&dest
->root_item
, 0);
4556 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED
, &dest
->state
)) {
4557 ret
= btrfs_insert_orphan_item(trans
,
4559 dest
->root_key
.objectid
);
4561 btrfs_abort_transaction(trans
, ret
);
4566 ret
= btrfs_uuid_tree_remove(trans
, dest
->root_item
.uuid
,
4567 BTRFS_UUID_KEY_SUBVOL
,
4568 dest
->root_key
.objectid
);
4569 if (ret
&& ret
!= -ENOENT
) {
4570 btrfs_abort_transaction(trans
, ret
);
4573 if (!btrfs_is_empty_uuid(dest
->root_item
.received_uuid
)) {
4574 ret
= btrfs_uuid_tree_remove(trans
,
4575 dest
->root_item
.received_uuid
,
4576 BTRFS_UUID_KEY_RECEIVED_SUBVOL
,
4577 dest
->root_key
.objectid
);
4578 if (ret
&& ret
!= -ENOENT
) {
4579 btrfs_abort_transaction(trans
, ret
);
4584 free_anon_bdev(dest
->anon_dev
);
4587 trans
->block_rsv
= NULL
;
4588 trans
->bytes_reserved
= 0;
4589 ret
= btrfs_end_transaction(trans
);
4590 inode
->i_flags
|= S_DEAD
;
4592 btrfs_subvolume_release_metadata(root
, &block_rsv
);
4594 up_write(&fs_info
->subvol_sem
);
4596 spin_lock(&dest
->root_item_lock
);
4597 root_flags
= btrfs_root_flags(&dest
->root_item
);
4598 btrfs_set_root_flags(&dest
->root_item
,
4599 root_flags
& ~BTRFS_ROOT_SUBVOL_DEAD
);
4600 spin_unlock(&dest
->root_item_lock
);
4602 d_invalidate(dentry
);
4603 btrfs_prune_dentries(dest
);
4604 ASSERT(dest
->send_in_progress
== 0);
4610 static int btrfs_rmdir(struct inode
*dir
, struct dentry
*dentry
)
4612 struct inode
*inode
= d_inode(dentry
);
4613 struct btrfs_fs_info
*fs_info
= BTRFS_I(inode
)->root
->fs_info
;
4615 struct btrfs_trans_handle
*trans
;
4616 u64 last_unlink_trans
;
4617 struct fscrypt_name fname
;
4619 if (inode
->i_size
> BTRFS_EMPTY_DIR_SIZE
)
4621 if (btrfs_ino(BTRFS_I(inode
)) == BTRFS_FIRST_FREE_OBJECTID
) {
4622 if (unlikely(btrfs_fs_incompat(fs_info
, EXTENT_TREE_V2
))) {
4624 "extent tree v2 doesn't support snapshot deletion yet");
4627 return btrfs_delete_subvolume(BTRFS_I(dir
), dentry
);
4630 err
= fscrypt_setup_filename(dir
, &dentry
->d_name
, 1, &fname
);
4634 /* This needs to handle no-key deletions later on */
4636 trans
= __unlink_start_trans(BTRFS_I(dir
));
4637 if (IS_ERR(trans
)) {
4638 err
= PTR_ERR(trans
);
4642 if (unlikely(btrfs_ino(BTRFS_I(inode
)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
)) {
4643 err
= btrfs_unlink_subvol(trans
, BTRFS_I(dir
), dentry
);
4647 err
= btrfs_orphan_add(trans
, BTRFS_I(inode
));
4651 last_unlink_trans
= BTRFS_I(inode
)->last_unlink_trans
;
4653 /* now the directory is empty */
4654 err
= btrfs_unlink_inode(trans
, BTRFS_I(dir
), BTRFS_I(d_inode(dentry
)),
4657 btrfs_i_size_write(BTRFS_I(inode
), 0);
4659 * Propagate the last_unlink_trans value of the deleted dir to
4660 * its parent directory. This is to prevent an unrecoverable
4661 * log tree in the case we do something like this:
4663 * 2) create snapshot under dir foo
4664 * 3) delete the snapshot
4667 * 6) fsync foo or some file inside foo
4669 if (last_unlink_trans
>= trans
->transid
)
4670 BTRFS_I(dir
)->last_unlink_trans
= last_unlink_trans
;
4673 btrfs_end_transaction(trans
);
4675 btrfs_btree_balance_dirty(fs_info
);
4676 fscrypt_free_filename(&fname
);
4682 * btrfs_truncate_block - read, zero a chunk and write a block
4683 * @inode - inode that we're zeroing
4684 * @from - the offset to start zeroing
4685 * @len - the length to zero, 0 to zero the entire range respective to the
4687 * @front - zero up to the offset instead of from the offset on
4689 * This will find the block for the "from" offset and cow the block and zero the
4690 * part we want to zero. This is used with truncate and hole punching.
4692 int btrfs_truncate_block(struct btrfs_inode
*inode
, loff_t from
, loff_t len
,
4695 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
4696 struct address_space
*mapping
= inode
->vfs_inode
.i_mapping
;
4697 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
4698 struct btrfs_ordered_extent
*ordered
;
4699 struct extent_state
*cached_state
= NULL
;
4700 struct extent_changeset
*data_reserved
= NULL
;
4701 bool only_release_metadata
= false;
4702 u32 blocksize
= fs_info
->sectorsize
;
4703 pgoff_t index
= from
>> PAGE_SHIFT
;
4704 unsigned offset
= from
& (blocksize
- 1);
4706 gfp_t mask
= btrfs_alloc_write_mask(mapping
);
4707 size_t write_bytes
= blocksize
;
4712 if (IS_ALIGNED(offset
, blocksize
) &&
4713 (!len
|| IS_ALIGNED(len
, blocksize
)))
4716 block_start
= round_down(from
, blocksize
);
4717 block_end
= block_start
+ blocksize
- 1;
4719 ret
= btrfs_check_data_free_space(inode
, &data_reserved
, block_start
,
4722 if (btrfs_check_nocow_lock(inode
, block_start
, &write_bytes
, false) > 0) {
4723 /* For nocow case, no need to reserve data space */
4724 only_release_metadata
= true;
4729 ret
= btrfs_delalloc_reserve_metadata(inode
, blocksize
, blocksize
, false);
4731 if (!only_release_metadata
)
4732 btrfs_free_reserved_data_space(inode
, data_reserved
,
4733 block_start
, blocksize
);
4737 page
= find_or_create_page(mapping
, index
, mask
);
4739 btrfs_delalloc_release_space(inode
, data_reserved
, block_start
,
4741 btrfs_delalloc_release_extents(inode
, blocksize
);
4745 ret
= set_page_extent_mapped(page
);
4749 if (!PageUptodate(page
)) {
4750 ret
= btrfs_read_folio(NULL
, page_folio(page
));
4752 if (page
->mapping
!= mapping
) {
4757 if (!PageUptodate(page
)) {
4762 wait_on_page_writeback(page
);
4764 lock_extent(io_tree
, block_start
, block_end
, &cached_state
);
4766 ordered
= btrfs_lookup_ordered_extent(inode
, block_start
);
4768 unlock_extent(io_tree
, block_start
, block_end
, &cached_state
);
4771 btrfs_start_ordered_extent(ordered
);
4772 btrfs_put_ordered_extent(ordered
);
4776 clear_extent_bit(&inode
->io_tree
, block_start
, block_end
,
4777 EXTENT_DELALLOC
| EXTENT_DO_ACCOUNTING
| EXTENT_DEFRAG
,
4780 ret
= btrfs_set_extent_delalloc(inode
, block_start
, block_end
, 0,
4783 unlock_extent(io_tree
, block_start
, block_end
, &cached_state
);
4787 if (offset
!= blocksize
) {
4789 len
= blocksize
- offset
;
4791 memzero_page(page
, (block_start
- page_offset(page
)),
4794 memzero_page(page
, (block_start
- page_offset(page
)) + offset
,
4797 btrfs_page_clear_checked(fs_info
, page
, block_start
,
4798 block_end
+ 1 - block_start
);
4799 btrfs_page_set_dirty(fs_info
, page
, block_start
, block_end
+ 1 - block_start
);
4800 unlock_extent(io_tree
, block_start
, block_end
, &cached_state
);
4802 if (only_release_metadata
)
4803 set_extent_bit(&inode
->io_tree
, block_start
, block_end
,
4804 EXTENT_NORESERVE
, NULL
, GFP_NOFS
);
4808 if (only_release_metadata
)
4809 btrfs_delalloc_release_metadata(inode
, blocksize
, true);
4811 btrfs_delalloc_release_space(inode
, data_reserved
,
4812 block_start
, blocksize
, true);
4814 btrfs_delalloc_release_extents(inode
, blocksize
);
4818 if (only_release_metadata
)
4819 btrfs_check_nocow_unlock(inode
);
4820 extent_changeset_free(data_reserved
);
4824 static int maybe_insert_hole(struct btrfs_root
*root
, struct btrfs_inode
*inode
,
4825 u64 offset
, u64 len
)
4827 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4828 struct btrfs_trans_handle
*trans
;
4829 struct btrfs_drop_extents_args drop_args
= { 0 };
4833 * If NO_HOLES is enabled, we don't need to do anything.
4834 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
4835 * or btrfs_update_inode() will be called, which guarantee that the next
4836 * fsync will know this inode was changed and needs to be logged.
4838 if (btrfs_fs_incompat(fs_info
, NO_HOLES
))
4842 * 1 - for the one we're dropping
4843 * 1 - for the one we're adding
4844 * 1 - for updating the inode.
4846 trans
= btrfs_start_transaction(root
, 3);
4848 return PTR_ERR(trans
);
4850 drop_args
.start
= offset
;
4851 drop_args
.end
= offset
+ len
;
4852 drop_args
.drop_cache
= true;
4854 ret
= btrfs_drop_extents(trans
, root
, inode
, &drop_args
);
4856 btrfs_abort_transaction(trans
, ret
);
4857 btrfs_end_transaction(trans
);
4861 ret
= btrfs_insert_hole_extent(trans
, root
, btrfs_ino(inode
), offset
, len
);
4863 btrfs_abort_transaction(trans
, ret
);
4865 btrfs_update_inode_bytes(inode
, 0, drop_args
.bytes_found
);
4866 btrfs_update_inode(trans
, root
, inode
);
4868 btrfs_end_transaction(trans
);
4873 * This function puts in dummy file extents for the area we're creating a hole
4874 * for. So if we are truncating this file to a larger size we need to insert
4875 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4876 * the range between oldsize and size
4878 int btrfs_cont_expand(struct btrfs_inode
*inode
, loff_t oldsize
, loff_t size
)
4880 struct btrfs_root
*root
= inode
->root
;
4881 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4882 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
4883 struct extent_map
*em
= NULL
;
4884 struct extent_state
*cached_state
= NULL
;
4885 u64 hole_start
= ALIGN(oldsize
, fs_info
->sectorsize
);
4886 u64 block_end
= ALIGN(size
, fs_info
->sectorsize
);
4893 * If our size started in the middle of a block we need to zero out the
4894 * rest of the block before we expand the i_size, otherwise we could
4895 * expose stale data.
4897 err
= btrfs_truncate_block(inode
, oldsize
, 0, 0);
4901 if (size
<= hole_start
)
4904 btrfs_lock_and_flush_ordered_range(inode
, hole_start
, block_end
- 1,
4906 cur_offset
= hole_start
;
4908 em
= btrfs_get_extent(inode
, NULL
, 0, cur_offset
,
4909 block_end
- cur_offset
);
4915 last_byte
= min(extent_map_end(em
), block_end
);
4916 last_byte
= ALIGN(last_byte
, fs_info
->sectorsize
);
4917 hole_size
= last_byte
- cur_offset
;
4919 if (!test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)) {
4920 struct extent_map
*hole_em
;
4922 err
= maybe_insert_hole(root
, inode
, cur_offset
,
4927 err
= btrfs_inode_set_file_extent_range(inode
,
4928 cur_offset
, hole_size
);
4932 hole_em
= alloc_extent_map();
4934 btrfs_drop_extent_map_range(inode
, cur_offset
,
4935 cur_offset
+ hole_size
- 1,
4937 btrfs_set_inode_full_sync(inode
);
4940 hole_em
->start
= cur_offset
;
4941 hole_em
->len
= hole_size
;
4942 hole_em
->orig_start
= cur_offset
;
4944 hole_em
->block_start
= EXTENT_MAP_HOLE
;
4945 hole_em
->block_len
= 0;
4946 hole_em
->orig_block_len
= 0;
4947 hole_em
->ram_bytes
= hole_size
;
4948 hole_em
->compress_type
= BTRFS_COMPRESS_NONE
;
4949 hole_em
->generation
= fs_info
->generation
;
4951 err
= btrfs_replace_extent_map_range(inode
, hole_em
, true);
4952 free_extent_map(hole_em
);
4954 err
= btrfs_inode_set_file_extent_range(inode
,
4955 cur_offset
, hole_size
);
4960 free_extent_map(em
);
4962 cur_offset
= last_byte
;
4963 if (cur_offset
>= block_end
)
4966 free_extent_map(em
);
4967 unlock_extent(io_tree
, hole_start
, block_end
- 1, &cached_state
);
4971 static int btrfs_setsize(struct inode
*inode
, struct iattr
*attr
)
4973 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
4974 struct btrfs_trans_handle
*trans
;
4975 loff_t oldsize
= i_size_read(inode
);
4976 loff_t newsize
= attr
->ia_size
;
4977 int mask
= attr
->ia_valid
;
4981 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4982 * special case where we need to update the times despite not having
4983 * these flags set. For all other operations the VFS set these flags
4984 * explicitly if it wants a timestamp update.
4986 if (newsize
!= oldsize
) {
4987 inode_inc_iversion(inode
);
4988 if (!(mask
& (ATTR_CTIME
| ATTR_MTIME
))) {
4989 inode
->i_mtime
= current_time(inode
);
4990 inode
->i_ctime
= inode
->i_mtime
;
4994 if (newsize
> oldsize
) {
4996 * Don't do an expanding truncate while snapshotting is ongoing.
4997 * This is to ensure the snapshot captures a fully consistent
4998 * state of this file - if the snapshot captures this expanding
4999 * truncation, it must capture all writes that happened before
5002 btrfs_drew_write_lock(&root
->snapshot_lock
);
5003 ret
= btrfs_cont_expand(BTRFS_I(inode
), oldsize
, newsize
);
5005 btrfs_drew_write_unlock(&root
->snapshot_lock
);
5009 trans
= btrfs_start_transaction(root
, 1);
5010 if (IS_ERR(trans
)) {
5011 btrfs_drew_write_unlock(&root
->snapshot_lock
);
5012 return PTR_ERR(trans
);
5015 i_size_write(inode
, newsize
);
5016 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode
), 0);
5017 pagecache_isize_extended(inode
, oldsize
, newsize
);
5018 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(inode
));
5019 btrfs_drew_write_unlock(&root
->snapshot_lock
);
5020 btrfs_end_transaction(trans
);
5022 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
5024 if (btrfs_is_zoned(fs_info
)) {
5025 ret
= btrfs_wait_ordered_range(inode
,
5026 ALIGN(newsize
, fs_info
->sectorsize
),
5033 * We're truncating a file that used to have good data down to
5034 * zero. Make sure any new writes to the file get on disk
5038 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE
,
5039 &BTRFS_I(inode
)->runtime_flags
);
5041 truncate_setsize(inode
, newsize
);
5043 inode_dio_wait(inode
);
5045 ret
= btrfs_truncate(BTRFS_I(inode
), newsize
== oldsize
);
5046 if (ret
&& inode
->i_nlink
) {
5050 * Truncate failed, so fix up the in-memory size. We
5051 * adjusted disk_i_size down as we removed extents, so
5052 * wait for disk_i_size to be stable and then update the
5053 * in-memory size to match.
5055 err
= btrfs_wait_ordered_range(inode
, 0, (u64
)-1);
5058 i_size_write(inode
, BTRFS_I(inode
)->disk_i_size
);
5065 static int btrfs_setattr(struct mnt_idmap
*idmap
, struct dentry
*dentry
,
5068 struct inode
*inode
= d_inode(dentry
);
5069 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5072 if (btrfs_root_readonly(root
))
5075 err
= setattr_prepare(idmap
, dentry
, attr
);
5079 if (S_ISREG(inode
->i_mode
) && (attr
->ia_valid
& ATTR_SIZE
)) {
5080 err
= btrfs_setsize(inode
, attr
);
5085 if (attr
->ia_valid
) {
5086 setattr_copy(idmap
, inode
, attr
);
5087 inode_inc_iversion(inode
);
5088 err
= btrfs_dirty_inode(BTRFS_I(inode
));
5090 if (!err
&& attr
->ia_valid
& ATTR_MODE
)
5091 err
= posix_acl_chmod(idmap
, dentry
, inode
->i_mode
);
5098 * While truncating the inode pages during eviction, we get the VFS
5099 * calling btrfs_invalidate_folio() against each folio of the inode. This
5100 * is slow because the calls to btrfs_invalidate_folio() result in a
5101 * huge amount of calls to lock_extent() and clear_extent_bit(),
5102 * which keep merging and splitting extent_state structures over and over,
5103 * wasting lots of time.
5105 * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5106 * skip all those expensive operations on a per folio basis and do only
5107 * the ordered io finishing, while we release here the extent_map and
5108 * extent_state structures, without the excessive merging and splitting.
5110 static void evict_inode_truncate_pages(struct inode
*inode
)
5112 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
5113 struct rb_node
*node
;
5115 ASSERT(inode
->i_state
& I_FREEING
);
5116 truncate_inode_pages_final(&inode
->i_data
);
5118 btrfs_drop_extent_map_range(BTRFS_I(inode
), 0, (u64
)-1, false);
5121 * Keep looping until we have no more ranges in the io tree.
5122 * We can have ongoing bios started by readahead that have
5123 * their endio callback (extent_io.c:end_bio_extent_readpage)
5124 * still in progress (unlocked the pages in the bio but did not yet
5125 * unlocked the ranges in the io tree). Therefore this means some
5126 * ranges can still be locked and eviction started because before
5127 * submitting those bios, which are executed by a separate task (work
5128 * queue kthread), inode references (inode->i_count) were not taken
5129 * (which would be dropped in the end io callback of each bio).
5130 * Therefore here we effectively end up waiting for those bios and
5131 * anyone else holding locked ranges without having bumped the inode's
5132 * reference count - if we don't do it, when they access the inode's
5133 * io_tree to unlock a range it may be too late, leading to an
5134 * use-after-free issue.
5136 spin_lock(&io_tree
->lock
);
5137 while (!RB_EMPTY_ROOT(&io_tree
->state
)) {
5138 struct extent_state
*state
;
5139 struct extent_state
*cached_state
= NULL
;
5142 unsigned state_flags
;
5144 node
= rb_first(&io_tree
->state
);
5145 state
= rb_entry(node
, struct extent_state
, rb_node
);
5146 start
= state
->start
;
5148 state_flags
= state
->state
;
5149 spin_unlock(&io_tree
->lock
);
5151 lock_extent(io_tree
, start
, end
, &cached_state
);
5154 * If still has DELALLOC flag, the extent didn't reach disk,
5155 * and its reserved space won't be freed by delayed_ref.
5156 * So we need to free its reserved space here.
5157 * (Refer to comment in btrfs_invalidate_folio, case 2)
5159 * Note, end is the bytenr of last byte, so we need + 1 here.
5161 if (state_flags
& EXTENT_DELALLOC
)
5162 btrfs_qgroup_free_data(BTRFS_I(inode
), NULL
, start
,
5165 clear_extent_bit(io_tree
, start
, end
,
5166 EXTENT_CLEAR_ALL_BITS
| EXTENT_DO_ACCOUNTING
,
5170 spin_lock(&io_tree
->lock
);
5172 spin_unlock(&io_tree
->lock
);
5175 static struct btrfs_trans_handle
*evict_refill_and_join(struct btrfs_root
*root
,
5176 struct btrfs_block_rsv
*rsv
)
5178 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
5179 struct btrfs_trans_handle
*trans
;
5180 u64 delayed_refs_extra
= btrfs_calc_delayed_ref_bytes(fs_info
, 1);
5184 * Eviction should be taking place at some place safe because of our
5185 * delayed iputs. However the normal flushing code will run delayed
5186 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5188 * We reserve the delayed_refs_extra here again because we can't use
5189 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5190 * above. We reserve our extra bit here because we generate a ton of
5191 * delayed refs activity by truncating.
5193 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5194 * if we fail to make this reservation we can re-try without the
5195 * delayed_refs_extra so we can make some forward progress.
5197 ret
= btrfs_block_rsv_refill(fs_info
, rsv
, rsv
->size
+ delayed_refs_extra
,
5198 BTRFS_RESERVE_FLUSH_EVICT
);
5200 ret
= btrfs_block_rsv_refill(fs_info
, rsv
, rsv
->size
,
5201 BTRFS_RESERVE_FLUSH_EVICT
);
5204 "could not allocate space for delete; will truncate on mount");
5205 return ERR_PTR(-ENOSPC
);
5207 delayed_refs_extra
= 0;
5210 trans
= btrfs_join_transaction(root
);
5214 if (delayed_refs_extra
) {
5215 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
5216 trans
->bytes_reserved
= delayed_refs_extra
;
5217 btrfs_block_rsv_migrate(rsv
, trans
->block_rsv
,
5218 delayed_refs_extra
, true);
5223 void btrfs_evict_inode(struct inode
*inode
)
5225 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
5226 struct btrfs_trans_handle
*trans
;
5227 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5228 struct btrfs_block_rsv
*rsv
= NULL
;
5231 trace_btrfs_inode_evict(inode
);
5234 fsverity_cleanup_inode(inode
);
5239 evict_inode_truncate_pages(inode
);
5241 if (inode
->i_nlink
&&
5242 ((btrfs_root_refs(&root
->root_item
) != 0 &&
5243 root
->root_key
.objectid
!= BTRFS_ROOT_TREE_OBJECTID
) ||
5244 btrfs_is_free_space_inode(BTRFS_I(inode
))))
5247 if (is_bad_inode(inode
))
5250 if (test_bit(BTRFS_FS_LOG_RECOVERING
, &fs_info
->flags
))
5253 if (inode
->i_nlink
> 0) {
5254 BUG_ON(btrfs_root_refs(&root
->root_item
) != 0 &&
5255 root
->root_key
.objectid
!= BTRFS_ROOT_TREE_OBJECTID
);
5260 * This makes sure the inode item in tree is uptodate and the space for
5261 * the inode update is released.
5263 ret
= btrfs_commit_inode_delayed_inode(BTRFS_I(inode
));
5268 * This drops any pending insert or delete operations we have for this
5269 * inode. We could have a delayed dir index deletion queued up, but
5270 * we're removing the inode completely so that'll be taken care of in
5273 btrfs_kill_delayed_inode_items(BTRFS_I(inode
));
5275 rsv
= btrfs_alloc_block_rsv(fs_info
, BTRFS_BLOCK_RSV_TEMP
);
5278 rsv
->size
= btrfs_calc_metadata_size(fs_info
, 1);
5279 rsv
->failfast
= true;
5281 btrfs_i_size_write(BTRFS_I(inode
), 0);
5284 struct btrfs_truncate_control control
= {
5285 .inode
= BTRFS_I(inode
),
5286 .ino
= btrfs_ino(BTRFS_I(inode
)),
5291 trans
= evict_refill_and_join(root
, rsv
);
5295 trans
->block_rsv
= rsv
;
5297 ret
= btrfs_truncate_inode_items(trans
, root
, &control
);
5298 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
5299 btrfs_end_transaction(trans
);
5301 * We have not added new delayed items for our inode after we
5302 * have flushed its delayed items, so no need to throttle on
5303 * delayed items. However we have modified extent buffers.
5305 btrfs_btree_balance_dirty_nodelay(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
);
5332 * If we didn't successfully delete, the orphan item will still be in
5333 * the tree and we'll retry on the next mount. Again, we might also want
5334 * to retry these periodically in the future.
5336 btrfs_remove_delayed_node(BTRFS_I(inode
));
5337 fsverity_cleanup_inode(inode
);
5342 * Return the key found in the dir entry in the location pointer, fill @type
5343 * with BTRFS_FT_*, and return 0.
5345 * If no dir entries were found, returns -ENOENT.
5346 * If found a corrupted location in dir entry, returns -EUCLEAN.
5348 static int btrfs_inode_by_name(struct btrfs_inode
*dir
, struct dentry
*dentry
,
5349 struct btrfs_key
*location
, u8
*type
)
5351 struct btrfs_dir_item
*di
;
5352 struct btrfs_path
*path
;
5353 struct btrfs_root
*root
= dir
->root
;
5355 struct fscrypt_name fname
;
5357 path
= btrfs_alloc_path();
5361 ret
= fscrypt_setup_filename(&dir
->vfs_inode
, &dentry
->d_name
, 1, &fname
);
5365 * fscrypt_setup_filename() should never return a positive value, but
5366 * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
5370 /* This needs to handle no-key deletions later on */
5372 di
= btrfs_lookup_dir_item(NULL
, root
, path
, btrfs_ino(dir
),
5373 &fname
.disk_name
, 0);
5374 if (IS_ERR_OR_NULL(di
)) {
5375 ret
= di
? PTR_ERR(di
) : -ENOENT
;
5379 btrfs_dir_item_key_to_cpu(path
->nodes
[0], di
, location
);
5380 if (location
->type
!= BTRFS_INODE_ITEM_KEY
&&
5381 location
->type
!= BTRFS_ROOT_ITEM_KEY
) {
5383 btrfs_warn(root
->fs_info
,
5384 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5385 __func__
, fname
.disk_name
.name
, btrfs_ino(dir
),
5386 location
->objectid
, location
->type
, location
->offset
);
5389 *type
= btrfs_dir_ftype(path
->nodes
[0], di
);
5391 fscrypt_free_filename(&fname
);
5392 btrfs_free_path(path
);
5397 * when we hit a tree root in a directory, the btrfs part of the inode
5398 * needs to be changed to reflect the root directory of the tree root. This
5399 * is kind of like crossing a mount point.
5401 static int fixup_tree_root_location(struct btrfs_fs_info
*fs_info
,
5402 struct btrfs_inode
*dir
,
5403 struct dentry
*dentry
,
5404 struct btrfs_key
*location
,
5405 struct btrfs_root
**sub_root
)
5407 struct btrfs_path
*path
;
5408 struct btrfs_root
*new_root
;
5409 struct btrfs_root_ref
*ref
;
5410 struct extent_buffer
*leaf
;
5411 struct btrfs_key key
;
5414 struct fscrypt_name fname
;
5416 ret
= fscrypt_setup_filename(&dir
->vfs_inode
, &dentry
->d_name
, 0, &fname
);
5420 path
= btrfs_alloc_path();
5427 key
.objectid
= dir
->root
->root_key
.objectid
;
5428 key
.type
= BTRFS_ROOT_REF_KEY
;
5429 key
.offset
= location
->objectid
;
5431 ret
= btrfs_search_slot(NULL
, fs_info
->tree_root
, &key
, path
, 0, 0);
5438 leaf
= path
->nodes
[0];
5439 ref
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_root_ref
);
5440 if (btrfs_root_ref_dirid(leaf
, ref
) != btrfs_ino(dir
) ||
5441 btrfs_root_ref_name_len(leaf
, ref
) != fname
.disk_name
.len
)
5444 ret
= memcmp_extent_buffer(leaf
, fname
.disk_name
.name
,
5445 (unsigned long)(ref
+ 1), fname
.disk_name
.len
);
5449 btrfs_release_path(path
);
5451 new_root
= btrfs_get_fs_root(fs_info
, location
->objectid
, true);
5452 if (IS_ERR(new_root
)) {
5453 err
= PTR_ERR(new_root
);
5457 *sub_root
= new_root
;
5458 location
->objectid
= btrfs_root_dirid(&new_root
->root_item
);
5459 location
->type
= BTRFS_INODE_ITEM_KEY
;
5460 location
->offset
= 0;
5463 btrfs_free_path(path
);
5464 fscrypt_free_filename(&fname
);
5468 static void inode_tree_add(struct btrfs_inode
*inode
)
5470 struct btrfs_root
*root
= inode
->root
;
5471 struct btrfs_inode
*entry
;
5473 struct rb_node
*parent
;
5474 struct rb_node
*new = &inode
->rb_node
;
5475 u64 ino
= btrfs_ino(inode
);
5477 if (inode_unhashed(&inode
->vfs_inode
))
5480 spin_lock(&root
->inode_lock
);
5481 p
= &root
->inode_tree
.rb_node
;
5484 entry
= rb_entry(parent
, struct btrfs_inode
, rb_node
);
5486 if (ino
< btrfs_ino(entry
))
5487 p
= &parent
->rb_left
;
5488 else if (ino
> btrfs_ino(entry
))
5489 p
= &parent
->rb_right
;
5491 WARN_ON(!(entry
->vfs_inode
.i_state
&
5492 (I_WILL_FREE
| I_FREEING
)));
5493 rb_replace_node(parent
, new, &root
->inode_tree
);
5494 RB_CLEAR_NODE(parent
);
5495 spin_unlock(&root
->inode_lock
);
5499 rb_link_node(new, parent
, p
);
5500 rb_insert_color(new, &root
->inode_tree
);
5501 spin_unlock(&root
->inode_lock
);
5504 static void inode_tree_del(struct btrfs_inode
*inode
)
5506 struct btrfs_root
*root
= inode
->root
;
5509 spin_lock(&root
->inode_lock
);
5510 if (!RB_EMPTY_NODE(&inode
->rb_node
)) {
5511 rb_erase(&inode
->rb_node
, &root
->inode_tree
);
5512 RB_CLEAR_NODE(&inode
->rb_node
);
5513 empty
= RB_EMPTY_ROOT(&root
->inode_tree
);
5515 spin_unlock(&root
->inode_lock
);
5517 if (empty
&& btrfs_root_refs(&root
->root_item
) == 0) {
5518 spin_lock(&root
->inode_lock
);
5519 empty
= RB_EMPTY_ROOT(&root
->inode_tree
);
5520 spin_unlock(&root
->inode_lock
);
5522 btrfs_add_dead_root(root
);
5527 static int btrfs_init_locked_inode(struct inode
*inode
, void *p
)
5529 struct btrfs_iget_args
*args
= p
;
5531 inode
->i_ino
= args
->ino
;
5532 BTRFS_I(inode
)->location
.objectid
= args
->ino
;
5533 BTRFS_I(inode
)->location
.type
= BTRFS_INODE_ITEM_KEY
;
5534 BTRFS_I(inode
)->location
.offset
= 0;
5535 BTRFS_I(inode
)->root
= btrfs_grab_root(args
->root
);
5536 BUG_ON(args
->root
&& !BTRFS_I(inode
)->root
);
5538 if (args
->root
&& args
->root
== args
->root
->fs_info
->tree_root
&&
5539 args
->ino
!= BTRFS_BTREE_INODE_OBJECTID
)
5540 set_bit(BTRFS_INODE_FREE_SPACE_INODE
,
5541 &BTRFS_I(inode
)->runtime_flags
);
5545 static int btrfs_find_actor(struct inode
*inode
, void *opaque
)
5547 struct btrfs_iget_args
*args
= opaque
;
5549 return args
->ino
== BTRFS_I(inode
)->location
.objectid
&&
5550 args
->root
== BTRFS_I(inode
)->root
;
5553 static struct inode
*btrfs_iget_locked(struct super_block
*s
, u64 ino
,
5554 struct btrfs_root
*root
)
5556 struct inode
*inode
;
5557 struct btrfs_iget_args args
;
5558 unsigned long hashval
= btrfs_inode_hash(ino
, root
);
5563 inode
= iget5_locked(s
, hashval
, btrfs_find_actor
,
5564 btrfs_init_locked_inode
,
5570 * Get an inode object given its inode number and corresponding root.
5571 * Path can be preallocated to prevent recursing back to iget through
5572 * allocator. NULL is also valid but may require an additional allocation
5575 struct inode
*btrfs_iget_path(struct super_block
*s
, u64 ino
,
5576 struct btrfs_root
*root
, struct btrfs_path
*path
)
5578 struct inode
*inode
;
5580 inode
= btrfs_iget_locked(s
, ino
, root
);
5582 return ERR_PTR(-ENOMEM
);
5584 if (inode
->i_state
& I_NEW
) {
5587 ret
= btrfs_read_locked_inode(inode
, path
);
5589 inode_tree_add(BTRFS_I(inode
));
5590 unlock_new_inode(inode
);
5594 * ret > 0 can come from btrfs_search_slot called by
5595 * btrfs_read_locked_inode, this means the inode item
5600 inode
= ERR_PTR(ret
);
5607 struct inode
*btrfs_iget(struct super_block
*s
, u64 ino
, struct btrfs_root
*root
)
5609 return btrfs_iget_path(s
, ino
, root
, NULL
);
5612 static struct inode
*new_simple_dir(struct super_block
*s
,
5613 struct btrfs_key
*key
,
5614 struct btrfs_root
*root
)
5616 struct inode
*inode
= new_inode(s
);
5619 return ERR_PTR(-ENOMEM
);
5621 BTRFS_I(inode
)->root
= btrfs_grab_root(root
);
5622 memcpy(&BTRFS_I(inode
)->location
, key
, sizeof(*key
));
5623 set_bit(BTRFS_INODE_DUMMY
, &BTRFS_I(inode
)->runtime_flags
);
5625 inode
->i_ino
= BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
;
5627 * We only need lookup, the rest is read-only and there's no inode
5628 * associated with the dentry
5630 inode
->i_op
= &simple_dir_inode_operations
;
5631 inode
->i_opflags
&= ~IOP_XATTR
;
5632 inode
->i_fop
= &simple_dir_operations
;
5633 inode
->i_mode
= S_IFDIR
| S_IRUGO
| S_IWUSR
| S_IXUGO
;
5634 inode
->i_mtime
= current_time(inode
);
5635 inode
->i_atime
= inode
->i_mtime
;
5636 inode
->i_ctime
= inode
->i_mtime
;
5637 BTRFS_I(inode
)->i_otime
= inode
->i_mtime
;
5642 static_assert(BTRFS_FT_UNKNOWN
== FT_UNKNOWN
);
5643 static_assert(BTRFS_FT_REG_FILE
== FT_REG_FILE
);
5644 static_assert(BTRFS_FT_DIR
== FT_DIR
);
5645 static_assert(BTRFS_FT_CHRDEV
== FT_CHRDEV
);
5646 static_assert(BTRFS_FT_BLKDEV
== FT_BLKDEV
);
5647 static_assert(BTRFS_FT_FIFO
== FT_FIFO
);
5648 static_assert(BTRFS_FT_SOCK
== FT_SOCK
);
5649 static_assert(BTRFS_FT_SYMLINK
== FT_SYMLINK
);
5651 static inline u8
btrfs_inode_type(struct inode
*inode
)
5653 return fs_umode_to_ftype(inode
->i_mode
);
5656 struct inode
*btrfs_lookup_dentry(struct inode
*dir
, struct dentry
*dentry
)
5658 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
5659 struct inode
*inode
;
5660 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
5661 struct btrfs_root
*sub_root
= root
;
5662 struct btrfs_key location
;
5666 if (dentry
->d_name
.len
> BTRFS_NAME_LEN
)
5667 return ERR_PTR(-ENAMETOOLONG
);
5669 ret
= btrfs_inode_by_name(BTRFS_I(dir
), dentry
, &location
, &di_type
);
5671 return ERR_PTR(ret
);
5673 if (location
.type
== BTRFS_INODE_ITEM_KEY
) {
5674 inode
= btrfs_iget(dir
->i_sb
, location
.objectid
, root
);
5678 /* Do extra check against inode mode with di_type */
5679 if (btrfs_inode_type(inode
) != di_type
) {
5681 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5682 inode
->i_mode
, btrfs_inode_type(inode
),
5685 return ERR_PTR(-EUCLEAN
);
5690 ret
= fixup_tree_root_location(fs_info
, BTRFS_I(dir
), dentry
,
5691 &location
, &sub_root
);
5694 inode
= ERR_PTR(ret
);
5696 inode
= new_simple_dir(dir
->i_sb
, &location
, root
);
5698 inode
= btrfs_iget(dir
->i_sb
, location
.objectid
, sub_root
);
5699 btrfs_put_root(sub_root
);
5704 down_read(&fs_info
->cleanup_work_sem
);
5705 if (!sb_rdonly(inode
->i_sb
))
5706 ret
= btrfs_orphan_cleanup(sub_root
);
5707 up_read(&fs_info
->cleanup_work_sem
);
5710 inode
= ERR_PTR(ret
);
5717 static int btrfs_dentry_delete(const struct dentry
*dentry
)
5719 struct btrfs_root
*root
;
5720 struct inode
*inode
= d_inode(dentry
);
5722 if (!inode
&& !IS_ROOT(dentry
))
5723 inode
= d_inode(dentry
->d_parent
);
5726 root
= BTRFS_I(inode
)->root
;
5727 if (btrfs_root_refs(&root
->root_item
) == 0)
5730 if (btrfs_ino(BTRFS_I(inode
)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
)
5736 static struct dentry
*btrfs_lookup(struct inode
*dir
, struct dentry
*dentry
,
5739 struct inode
*inode
= btrfs_lookup_dentry(dir
, dentry
);
5741 if (inode
== ERR_PTR(-ENOENT
))
5743 return d_splice_alias(inode
, dentry
);
5747 * All this infrastructure exists because dir_emit can fault, and we are holding
5748 * the tree lock when doing readdir. For now just allocate a buffer and copy
5749 * our information into that, and then dir_emit from the buffer. This is
5750 * similar to what NFS does, only we don't keep the buffer around in pagecache
5751 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5752 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5755 static int btrfs_opendir(struct inode
*inode
, struct file
*file
)
5757 struct btrfs_file_private
*private;
5759 private = kzalloc(sizeof(struct btrfs_file_private
), GFP_KERNEL
);
5762 private->filldir_buf
= kzalloc(PAGE_SIZE
, GFP_KERNEL
);
5763 if (!private->filldir_buf
) {
5767 file
->private_data
= private;
5778 static int btrfs_filldir(void *addr
, int entries
, struct dir_context
*ctx
)
5781 struct dir_entry
*entry
= addr
;
5782 char *name
= (char *)(entry
+ 1);
5784 ctx
->pos
= get_unaligned(&entry
->offset
);
5785 if (!dir_emit(ctx
, name
, get_unaligned(&entry
->name_len
),
5786 get_unaligned(&entry
->ino
),
5787 get_unaligned(&entry
->type
)))
5789 addr
+= sizeof(struct dir_entry
) +
5790 get_unaligned(&entry
->name_len
);
5796 static int btrfs_real_readdir(struct file
*file
, struct dir_context
*ctx
)
5798 struct inode
*inode
= file_inode(file
);
5799 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5800 struct btrfs_file_private
*private = file
->private_data
;
5801 struct btrfs_dir_item
*di
;
5802 struct btrfs_key key
;
5803 struct btrfs_key found_key
;
5804 struct btrfs_path
*path
;
5806 struct list_head ins_list
;
5807 struct list_head del_list
;
5814 struct btrfs_key location
;
5816 if (!dir_emit_dots(file
, ctx
))
5819 path
= btrfs_alloc_path();
5823 addr
= private->filldir_buf
;
5824 path
->reada
= READA_FORWARD
;
5826 INIT_LIST_HEAD(&ins_list
);
5827 INIT_LIST_HEAD(&del_list
);
5828 put
= btrfs_readdir_get_delayed_items(inode
, &ins_list
, &del_list
);
5831 key
.type
= BTRFS_DIR_INDEX_KEY
;
5832 key
.offset
= ctx
->pos
;
5833 key
.objectid
= btrfs_ino(BTRFS_I(inode
));
5835 btrfs_for_each_slot(root
, &key
, &found_key
, path
, ret
) {
5836 struct dir_entry
*entry
;
5837 struct extent_buffer
*leaf
= path
->nodes
[0];
5840 if (found_key
.objectid
!= key
.objectid
)
5842 if (found_key
.type
!= BTRFS_DIR_INDEX_KEY
)
5844 if (found_key
.offset
< ctx
->pos
)
5846 if (btrfs_should_delete_dir_index(&del_list
, found_key
.offset
))
5848 di
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_dir_item
);
5849 name_len
= btrfs_dir_name_len(leaf
, di
);
5850 if ((total_len
+ sizeof(struct dir_entry
) + name_len
) >=
5852 btrfs_release_path(path
);
5853 ret
= btrfs_filldir(private->filldir_buf
, entries
, ctx
);
5856 addr
= private->filldir_buf
;
5862 ftype
= btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf
, di
));
5864 name_ptr
= (char *)(entry
+ 1);
5865 read_extent_buffer(leaf
, name_ptr
,
5866 (unsigned long)(di
+ 1), name_len
);
5867 put_unaligned(name_len
, &entry
->name_len
);
5868 put_unaligned(fs_ftype_to_dtype(ftype
), &entry
->type
);
5869 btrfs_dir_item_key_to_cpu(leaf
, di
, &location
);
5870 put_unaligned(location
.objectid
, &entry
->ino
);
5871 put_unaligned(found_key
.offset
, &entry
->offset
);
5873 addr
+= sizeof(struct dir_entry
) + name_len
;
5874 total_len
+= sizeof(struct dir_entry
) + name_len
;
5876 /* Catch error encountered during iteration */
5880 btrfs_release_path(path
);
5882 ret
= btrfs_filldir(private->filldir_buf
, entries
, ctx
);
5886 ret
= btrfs_readdir_delayed_dir_index(ctx
, &ins_list
);
5891 * Stop new entries from being returned after we return the last
5894 * New directory entries are assigned a strictly increasing
5895 * offset. This means that new entries created during readdir
5896 * are *guaranteed* to be seen in the future by that readdir.
5897 * This has broken buggy programs which operate on names as
5898 * they're returned by readdir. Until we re-use freed offsets
5899 * we have this hack to stop new entries from being returned
5900 * under the assumption that they'll never reach this huge
5903 * This is being careful not to overflow 32bit loff_t unless the
5904 * last entry requires it because doing so has broken 32bit apps
5907 if (ctx
->pos
>= INT_MAX
)
5908 ctx
->pos
= LLONG_MAX
;
5915 btrfs_readdir_put_delayed_items(inode
, &ins_list
, &del_list
);
5916 btrfs_free_path(path
);
5921 * This is somewhat expensive, updating the tree every time the
5922 * inode changes. But, it is most likely to find the inode in cache.
5923 * FIXME, needs more benchmarking...there are no reasons other than performance
5924 * to keep or drop this code.
5926 static int btrfs_dirty_inode(struct btrfs_inode
*inode
)
5928 struct btrfs_root
*root
= inode
->root
;
5929 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
5930 struct btrfs_trans_handle
*trans
;
5933 if (test_bit(BTRFS_INODE_DUMMY
, &inode
->runtime_flags
))
5936 trans
= btrfs_join_transaction(root
);
5938 return PTR_ERR(trans
);
5940 ret
= btrfs_update_inode(trans
, root
, inode
);
5941 if (ret
&& (ret
== -ENOSPC
|| ret
== -EDQUOT
)) {
5942 /* whoops, lets try again with the full transaction */
5943 btrfs_end_transaction(trans
);
5944 trans
= btrfs_start_transaction(root
, 1);
5946 return PTR_ERR(trans
);
5948 ret
= btrfs_update_inode(trans
, root
, inode
);
5950 btrfs_end_transaction(trans
);
5951 if (inode
->delayed_node
)
5952 btrfs_balance_delayed_items(fs_info
);
5958 * This is a copy of file_update_time. We need this so we can return error on
5959 * ENOSPC for updating the inode in the case of file write and mmap writes.
5961 static int btrfs_update_time(struct inode
*inode
, struct timespec64
*now
,
5964 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5965 bool dirty
= flags
& ~S_VERSION
;
5967 if (btrfs_root_readonly(root
))
5970 if (flags
& S_VERSION
)
5971 dirty
|= inode_maybe_inc_iversion(inode
, dirty
);
5972 if (flags
& S_CTIME
)
5973 inode
->i_ctime
= *now
;
5974 if (flags
& S_MTIME
)
5975 inode
->i_mtime
= *now
;
5976 if (flags
& S_ATIME
)
5977 inode
->i_atime
= *now
;
5978 return dirty
? btrfs_dirty_inode(BTRFS_I(inode
)) : 0;
5982 * find the highest existing sequence number in a directory
5983 * and then set the in-memory index_cnt variable to reflect
5984 * free sequence numbers
5986 static int btrfs_set_inode_index_count(struct btrfs_inode
*inode
)
5988 struct btrfs_root
*root
= inode
->root
;
5989 struct btrfs_key key
, found_key
;
5990 struct btrfs_path
*path
;
5991 struct extent_buffer
*leaf
;
5994 key
.objectid
= btrfs_ino(inode
);
5995 key
.type
= BTRFS_DIR_INDEX_KEY
;
5996 key
.offset
= (u64
)-1;
5998 path
= btrfs_alloc_path();
6002 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
6005 /* FIXME: we should be able to handle this */
6010 if (path
->slots
[0] == 0) {
6011 inode
->index_cnt
= BTRFS_DIR_START_INDEX
;
6017 leaf
= path
->nodes
[0];
6018 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
6020 if (found_key
.objectid
!= btrfs_ino(inode
) ||
6021 found_key
.type
!= BTRFS_DIR_INDEX_KEY
) {
6022 inode
->index_cnt
= BTRFS_DIR_START_INDEX
;
6026 inode
->index_cnt
= found_key
.offset
+ 1;
6028 btrfs_free_path(path
);
6033 * helper to find a free sequence number in a given directory. This current
6034 * code is very simple, later versions will do smarter things in the btree
6036 int btrfs_set_inode_index(struct btrfs_inode
*dir
, u64
*index
)
6040 if (dir
->index_cnt
== (u64
)-1) {
6041 ret
= btrfs_inode_delayed_dir_index_count(dir
);
6043 ret
= btrfs_set_inode_index_count(dir
);
6049 *index
= dir
->index_cnt
;
6055 static int btrfs_insert_inode_locked(struct inode
*inode
)
6057 struct btrfs_iget_args args
;
6059 args
.ino
= BTRFS_I(inode
)->location
.objectid
;
6060 args
.root
= BTRFS_I(inode
)->root
;
6062 return insert_inode_locked4(inode
,
6063 btrfs_inode_hash(inode
->i_ino
, BTRFS_I(inode
)->root
),
6064 btrfs_find_actor
, &args
);
6067 int btrfs_new_inode_prepare(struct btrfs_new_inode_args
*args
,
6068 unsigned int *trans_num_items
)
6070 struct inode
*dir
= args
->dir
;
6071 struct inode
*inode
= args
->inode
;
6074 if (!args
->orphan
) {
6075 ret
= fscrypt_setup_filename(dir
, &args
->dentry
->d_name
, 0,
6081 ret
= posix_acl_create(dir
, &inode
->i_mode
, &args
->default_acl
, &args
->acl
);
6083 fscrypt_free_filename(&args
->fname
);
6087 /* 1 to add inode item */
6088 *trans_num_items
= 1;
6089 /* 1 to add compression property */
6090 if (BTRFS_I(dir
)->prop_compress
)
6091 (*trans_num_items
)++;
6092 /* 1 to add default ACL xattr */
6093 if (args
->default_acl
)
6094 (*trans_num_items
)++;
6095 /* 1 to add access ACL xattr */
6097 (*trans_num_items
)++;
6098 #ifdef CONFIG_SECURITY
6099 /* 1 to add LSM xattr */
6100 if (dir
->i_security
)
6101 (*trans_num_items
)++;
6104 /* 1 to add orphan item */
6105 (*trans_num_items
)++;
6109 * 1 to add dir index
6110 * 1 to update parent inode item
6112 * No need for 1 unit for the inode ref item because it is
6113 * inserted in a batch together with the inode item at
6114 * btrfs_create_new_inode().
6116 *trans_num_items
+= 3;
6121 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args
*args
)
6123 posix_acl_release(args
->acl
);
6124 posix_acl_release(args
->default_acl
);
6125 fscrypt_free_filename(&args
->fname
);
6129 * Inherit flags from the parent inode.
6131 * Currently only the compression flags and the cow flags are inherited.
6133 static void btrfs_inherit_iflags(struct btrfs_inode
*inode
, struct btrfs_inode
*dir
)
6139 if (flags
& BTRFS_INODE_NOCOMPRESS
) {
6140 inode
->flags
&= ~BTRFS_INODE_COMPRESS
;
6141 inode
->flags
|= BTRFS_INODE_NOCOMPRESS
;
6142 } else if (flags
& BTRFS_INODE_COMPRESS
) {
6143 inode
->flags
&= ~BTRFS_INODE_NOCOMPRESS
;
6144 inode
->flags
|= BTRFS_INODE_COMPRESS
;
6147 if (flags
& BTRFS_INODE_NODATACOW
) {
6148 inode
->flags
|= BTRFS_INODE_NODATACOW
;
6149 if (S_ISREG(inode
->vfs_inode
.i_mode
))
6150 inode
->flags
|= BTRFS_INODE_NODATASUM
;
6153 btrfs_sync_inode_flags_to_i_flags(&inode
->vfs_inode
);
6156 int btrfs_create_new_inode(struct btrfs_trans_handle
*trans
,
6157 struct btrfs_new_inode_args
*args
)
6159 struct inode
*dir
= args
->dir
;
6160 struct inode
*inode
= args
->inode
;
6161 const struct fscrypt_str
*name
= args
->orphan
? NULL
: &args
->fname
.disk_name
;
6162 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
6163 struct btrfs_root
*root
;
6164 struct btrfs_inode_item
*inode_item
;
6165 struct btrfs_key
*location
;
6166 struct btrfs_path
*path
;
6168 struct btrfs_inode_ref
*ref
;
6169 struct btrfs_key key
[2];
6171 struct btrfs_item_batch batch
;
6175 path
= btrfs_alloc_path();
6180 BTRFS_I(inode
)->root
= btrfs_grab_root(BTRFS_I(dir
)->root
);
6181 root
= BTRFS_I(inode
)->root
;
6183 ret
= btrfs_get_free_objectid(root
, &objectid
);
6186 inode
->i_ino
= objectid
;
6190 * O_TMPFILE, set link count to 0, so that after this point, we
6191 * fill in an inode item with the correct link count.
6193 set_nlink(inode
, 0);
6195 trace_btrfs_inode_request(dir
);
6197 ret
= btrfs_set_inode_index(BTRFS_I(dir
), &BTRFS_I(inode
)->dir_index
);
6201 /* index_cnt is ignored for everything but a dir. */
6202 BTRFS_I(inode
)->index_cnt
= BTRFS_DIR_START_INDEX
;
6203 BTRFS_I(inode
)->generation
= trans
->transid
;
6204 inode
->i_generation
= BTRFS_I(inode
)->generation
;
6207 * Subvolumes don't inherit flags from their parent directory.
6208 * Originally this was probably by accident, but we probably can't
6209 * change it now without compatibility issues.
6212 btrfs_inherit_iflags(BTRFS_I(inode
), BTRFS_I(dir
));
6214 if (S_ISREG(inode
->i_mode
)) {
6215 if (btrfs_test_opt(fs_info
, NODATASUM
))
6216 BTRFS_I(inode
)->flags
|= BTRFS_INODE_NODATASUM
;
6217 if (btrfs_test_opt(fs_info
, NODATACOW
))
6218 BTRFS_I(inode
)->flags
|= BTRFS_INODE_NODATACOW
|
6219 BTRFS_INODE_NODATASUM
;
6222 location
= &BTRFS_I(inode
)->location
;
6223 location
->objectid
= objectid
;
6224 location
->offset
= 0;
6225 location
->type
= BTRFS_INODE_ITEM_KEY
;
6227 ret
= btrfs_insert_inode_locked(inode
);
6230 BTRFS_I(dir
)->index_cnt
--;
6235 * We could have gotten an inode number from somebody who was fsynced
6236 * and then removed in this same transaction, so let's just set full
6237 * sync since it will be a full sync anyway and this will blow away the
6238 * old info in the log.
6240 btrfs_set_inode_full_sync(BTRFS_I(inode
));
6242 key
[0].objectid
= objectid
;
6243 key
[0].type
= BTRFS_INODE_ITEM_KEY
;
6246 sizes
[0] = sizeof(struct btrfs_inode_item
);
6248 if (!args
->orphan
) {
6250 * Start new inodes with an inode_ref. This is slightly more
6251 * efficient for small numbers of hard links since they will
6252 * be packed into one item. Extended refs will kick in if we
6253 * add more hard links than can fit in the ref item.
6255 key
[1].objectid
= objectid
;
6256 key
[1].type
= BTRFS_INODE_REF_KEY
;
6258 key
[1].offset
= objectid
;
6259 sizes
[1] = 2 + sizeof(*ref
);
6261 key
[1].offset
= btrfs_ino(BTRFS_I(dir
));
6262 sizes
[1] = name
->len
+ sizeof(*ref
);
6266 batch
.keys
= &key
[0];
6267 batch
.data_sizes
= &sizes
[0];
6268 batch
.total_data_size
= sizes
[0] + (args
->orphan
? 0 : sizes
[1]);
6269 batch
.nr
= args
->orphan
? 1 : 2;
6270 ret
= btrfs_insert_empty_items(trans
, root
, path
, &batch
);
6272 btrfs_abort_transaction(trans
, ret
);
6276 inode
->i_mtime
= current_time(inode
);
6277 inode
->i_atime
= inode
->i_mtime
;
6278 inode
->i_ctime
= inode
->i_mtime
;
6279 BTRFS_I(inode
)->i_otime
= inode
->i_mtime
;
6282 * We're going to fill the inode item now, so at this point the inode
6283 * must be fully initialized.
6286 inode_item
= btrfs_item_ptr(path
->nodes
[0], path
->slots
[0],
6287 struct btrfs_inode_item
);
6288 memzero_extent_buffer(path
->nodes
[0], (unsigned long)inode_item
,
6289 sizeof(*inode_item
));
6290 fill_inode_item(trans
, path
->nodes
[0], inode_item
, inode
);
6292 if (!args
->orphan
) {
6293 ref
= btrfs_item_ptr(path
->nodes
[0], path
->slots
[0] + 1,
6294 struct btrfs_inode_ref
);
6295 ptr
= (unsigned long)(ref
+ 1);
6297 btrfs_set_inode_ref_name_len(path
->nodes
[0], ref
, 2);
6298 btrfs_set_inode_ref_index(path
->nodes
[0], ref
, 0);
6299 write_extent_buffer(path
->nodes
[0], "..", ptr
, 2);
6301 btrfs_set_inode_ref_name_len(path
->nodes
[0], ref
,
6303 btrfs_set_inode_ref_index(path
->nodes
[0], ref
,
6304 BTRFS_I(inode
)->dir_index
);
6305 write_extent_buffer(path
->nodes
[0], name
->name
, ptr
,
6310 btrfs_mark_buffer_dirty(path
->nodes
[0]);
6312 * We don't need the path anymore, plus inheriting properties, adding
6313 * ACLs, security xattrs, orphan item or adding the link, will result in
6314 * allocating yet another path. So just free our path.
6316 btrfs_free_path(path
);
6320 struct inode
*parent
;
6323 * Subvolumes inherit properties from their parent subvolume,
6324 * not the directory they were created in.
6326 parent
= btrfs_iget(fs_info
->sb
, BTRFS_FIRST_FREE_OBJECTID
,
6327 BTRFS_I(dir
)->root
);
6328 if (IS_ERR(parent
)) {
6329 ret
= PTR_ERR(parent
);
6331 ret
= btrfs_inode_inherit_props(trans
, inode
, parent
);
6335 ret
= btrfs_inode_inherit_props(trans
, inode
, dir
);
6339 "error inheriting props for ino %llu (root %llu): %d",
6340 btrfs_ino(BTRFS_I(inode
)), root
->root_key
.objectid
,
6345 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6348 if (!args
->subvol
) {
6349 ret
= btrfs_init_inode_security(trans
, args
);
6351 btrfs_abort_transaction(trans
, ret
);
6356 inode_tree_add(BTRFS_I(inode
));
6358 trace_btrfs_inode_new(inode
);
6359 btrfs_set_inode_last_trans(trans
, BTRFS_I(inode
));
6361 btrfs_update_root_times(trans
, root
);
6364 ret
= btrfs_orphan_add(trans
, BTRFS_I(inode
));
6366 ret
= btrfs_add_link(trans
, BTRFS_I(dir
), BTRFS_I(inode
), name
,
6367 0, BTRFS_I(inode
)->dir_index
);
6370 btrfs_abort_transaction(trans
, ret
);
6378 * discard_new_inode() calls iput(), but the caller owns the reference
6382 discard_new_inode(inode
);
6384 btrfs_free_path(path
);
6389 * utility function to add 'inode' into 'parent_inode' with
6390 * a give name and a given sequence number.
6391 * if 'add_backref' is true, also insert a backref from the
6392 * inode to the parent directory.
6394 int btrfs_add_link(struct btrfs_trans_handle
*trans
,
6395 struct btrfs_inode
*parent_inode
, struct btrfs_inode
*inode
,
6396 const struct fscrypt_str
*name
, int add_backref
, u64 index
)
6399 struct btrfs_key key
;
6400 struct btrfs_root
*root
= parent_inode
->root
;
6401 u64 ino
= btrfs_ino(inode
);
6402 u64 parent_ino
= btrfs_ino(parent_inode
);
6404 if (unlikely(ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
6405 memcpy(&key
, &inode
->root
->root_key
, sizeof(key
));
6408 key
.type
= BTRFS_INODE_ITEM_KEY
;
6412 if (unlikely(ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
6413 ret
= btrfs_add_root_ref(trans
, key
.objectid
,
6414 root
->root_key
.objectid
, parent_ino
,
6416 } else if (add_backref
) {
6417 ret
= btrfs_insert_inode_ref(trans
, root
, name
,
6418 ino
, parent_ino
, index
);
6421 /* Nothing to clean up yet */
6425 ret
= btrfs_insert_dir_item(trans
, name
, parent_inode
, &key
,
6426 btrfs_inode_type(&inode
->vfs_inode
), index
);
6427 if (ret
== -EEXIST
|| ret
== -EOVERFLOW
)
6430 btrfs_abort_transaction(trans
, ret
);
6434 btrfs_i_size_write(parent_inode
, parent_inode
->vfs_inode
.i_size
+
6436 inode_inc_iversion(&parent_inode
->vfs_inode
);
6438 * If we are replaying a log tree, we do not want to update the mtime
6439 * and ctime of the parent directory with the current time, since the
6440 * log replay procedure is responsible for setting them to their correct
6441 * values (the ones it had when the fsync was done).
6443 if (!test_bit(BTRFS_FS_LOG_RECOVERING
, &root
->fs_info
->flags
)) {
6444 struct timespec64 now
= current_time(&parent_inode
->vfs_inode
);
6446 parent_inode
->vfs_inode
.i_mtime
= now
;
6447 parent_inode
->vfs_inode
.i_ctime
= now
;
6449 ret
= btrfs_update_inode(trans
, root
, parent_inode
);
6451 btrfs_abort_transaction(trans
, ret
);
6455 if (unlikely(ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
6458 err
= btrfs_del_root_ref(trans
, key
.objectid
,
6459 root
->root_key
.objectid
, parent_ino
,
6460 &local_index
, name
);
6462 btrfs_abort_transaction(trans
, err
);
6463 } else if (add_backref
) {
6467 err
= btrfs_del_inode_ref(trans
, root
, name
, ino
, parent_ino
,
6470 btrfs_abort_transaction(trans
, err
);
6473 /* Return the original error code */
6477 static int btrfs_create_common(struct inode
*dir
, struct dentry
*dentry
,
6478 struct inode
*inode
)
6480 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
6481 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
6482 struct btrfs_new_inode_args new_inode_args
= {
6487 unsigned int trans_num_items
;
6488 struct btrfs_trans_handle
*trans
;
6491 err
= btrfs_new_inode_prepare(&new_inode_args
, &trans_num_items
);
6495 trans
= btrfs_start_transaction(root
, trans_num_items
);
6496 if (IS_ERR(trans
)) {
6497 err
= PTR_ERR(trans
);
6498 goto out_new_inode_args
;
6501 err
= btrfs_create_new_inode(trans
, &new_inode_args
);
6503 d_instantiate_new(dentry
, inode
);
6505 btrfs_end_transaction(trans
);
6506 btrfs_btree_balance_dirty(fs_info
);
6508 btrfs_new_inode_args_destroy(&new_inode_args
);
6515 static int btrfs_mknod(struct mnt_idmap
*idmap
, struct inode
*dir
,
6516 struct dentry
*dentry
, umode_t mode
, dev_t rdev
)
6518 struct inode
*inode
;
6520 inode
= new_inode(dir
->i_sb
);
6523 inode_init_owner(idmap
, inode
, dir
, mode
);
6524 inode
->i_op
= &btrfs_special_inode_operations
;
6525 init_special_inode(inode
, inode
->i_mode
, rdev
);
6526 return btrfs_create_common(dir
, dentry
, inode
);
6529 static int btrfs_create(struct mnt_idmap
*idmap
, struct inode
*dir
,
6530 struct dentry
*dentry
, umode_t mode
, bool excl
)
6532 struct inode
*inode
;
6534 inode
= new_inode(dir
->i_sb
);
6537 inode_init_owner(idmap
, inode
, dir
, mode
);
6538 inode
->i_fop
= &btrfs_file_operations
;
6539 inode
->i_op
= &btrfs_file_inode_operations
;
6540 inode
->i_mapping
->a_ops
= &btrfs_aops
;
6541 return btrfs_create_common(dir
, dentry
, inode
);
6544 static int btrfs_link(struct dentry
*old_dentry
, struct inode
*dir
,
6545 struct dentry
*dentry
)
6547 struct btrfs_trans_handle
*trans
= NULL
;
6548 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
6549 struct inode
*inode
= d_inode(old_dentry
);
6550 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
6551 struct fscrypt_name fname
;
6556 /* do not allow sys_link's with other subvols of the same device */
6557 if (root
->root_key
.objectid
!= BTRFS_I(inode
)->root
->root_key
.objectid
)
6560 if (inode
->i_nlink
>= BTRFS_LINK_MAX
)
6563 err
= fscrypt_setup_filename(dir
, &dentry
->d_name
, 0, &fname
);
6567 err
= btrfs_set_inode_index(BTRFS_I(dir
), &index
);
6572 * 2 items for inode and inode ref
6573 * 2 items for dir items
6574 * 1 item for parent inode
6575 * 1 item for orphan item deletion if O_TMPFILE
6577 trans
= btrfs_start_transaction(root
, inode
->i_nlink
? 5 : 6);
6578 if (IS_ERR(trans
)) {
6579 err
= PTR_ERR(trans
);
6584 /* There are several dir indexes for this inode, clear the cache. */
6585 BTRFS_I(inode
)->dir_index
= 0ULL;
6587 inode_inc_iversion(inode
);
6588 inode
->i_ctime
= current_time(inode
);
6590 set_bit(BTRFS_INODE_COPY_EVERYTHING
, &BTRFS_I(inode
)->runtime_flags
);
6592 err
= btrfs_add_link(trans
, BTRFS_I(dir
), BTRFS_I(inode
),
6593 &fname
.disk_name
, 1, index
);
6598 struct dentry
*parent
= dentry
->d_parent
;
6600 err
= btrfs_update_inode(trans
, root
, BTRFS_I(inode
));
6603 if (inode
->i_nlink
== 1) {
6605 * If new hard link count is 1, it's a file created
6606 * with open(2) O_TMPFILE flag.
6608 err
= btrfs_orphan_del(trans
, BTRFS_I(inode
));
6612 d_instantiate(dentry
, inode
);
6613 btrfs_log_new_name(trans
, old_dentry
, NULL
, 0, parent
);
6617 fscrypt_free_filename(&fname
);
6619 btrfs_end_transaction(trans
);
6621 inode_dec_link_count(inode
);
6624 btrfs_btree_balance_dirty(fs_info
);
6628 static int btrfs_mkdir(struct mnt_idmap
*idmap
, struct inode
*dir
,
6629 struct dentry
*dentry
, umode_t mode
)
6631 struct inode
*inode
;
6633 inode
= new_inode(dir
->i_sb
);
6636 inode_init_owner(idmap
, inode
, dir
, S_IFDIR
| mode
);
6637 inode
->i_op
= &btrfs_dir_inode_operations
;
6638 inode
->i_fop
= &btrfs_dir_file_operations
;
6639 return btrfs_create_common(dir
, dentry
, inode
);
6642 static noinline
int uncompress_inline(struct btrfs_path
*path
,
6644 struct btrfs_file_extent_item
*item
)
6647 struct extent_buffer
*leaf
= path
->nodes
[0];
6650 unsigned long inline_size
;
6654 compress_type
= btrfs_file_extent_compression(leaf
, item
);
6655 max_size
= btrfs_file_extent_ram_bytes(leaf
, item
);
6656 inline_size
= btrfs_file_extent_inline_item_len(leaf
, path
->slots
[0]);
6657 tmp
= kmalloc(inline_size
, GFP_NOFS
);
6660 ptr
= btrfs_file_extent_inline_start(item
);
6662 read_extent_buffer(leaf
, tmp
, ptr
, inline_size
);
6664 max_size
= min_t(unsigned long, PAGE_SIZE
, max_size
);
6665 ret
= btrfs_decompress(compress_type
, tmp
, page
, 0, inline_size
, max_size
);
6668 * decompression code contains a memset to fill in any space between the end
6669 * of the uncompressed data and the end of max_size in case the decompressed
6670 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6671 * the end of an inline extent and the beginning of the next block, so we
6672 * cover that region here.
6675 if (max_size
< PAGE_SIZE
)
6676 memzero_page(page
, max_size
, PAGE_SIZE
- max_size
);
6681 static int read_inline_extent(struct btrfs_inode
*inode
, struct btrfs_path
*path
,
6684 struct btrfs_file_extent_item
*fi
;
6688 if (!page
|| PageUptodate(page
))
6691 ASSERT(page_offset(page
) == 0);
6693 fi
= btrfs_item_ptr(path
->nodes
[0], path
->slots
[0],
6694 struct btrfs_file_extent_item
);
6695 if (btrfs_file_extent_compression(path
->nodes
[0], fi
) != BTRFS_COMPRESS_NONE
)
6696 return uncompress_inline(path
, page
, fi
);
6698 copy_size
= min_t(u64
, PAGE_SIZE
,
6699 btrfs_file_extent_ram_bytes(path
->nodes
[0], fi
));
6700 kaddr
= kmap_local_page(page
);
6701 read_extent_buffer(path
->nodes
[0], kaddr
,
6702 btrfs_file_extent_inline_start(fi
), copy_size
);
6703 kunmap_local(kaddr
);
6704 if (copy_size
< PAGE_SIZE
)
6705 memzero_page(page
, copy_size
, PAGE_SIZE
- copy_size
);
6710 * Lookup the first extent overlapping a range in a file.
6712 * @inode: file to search in
6713 * @page: page to read extent data into if the extent is inline
6714 * @pg_offset: offset into @page to copy to
6715 * @start: file offset
6716 * @len: length of range starting at @start
6718 * Return the first &struct extent_map which overlaps the given range, reading
6719 * it from the B-tree and caching it if necessary. Note that there may be more
6720 * extents which overlap the given range after the returned extent_map.
6722 * If @page is not NULL and the extent is inline, this also reads the extent
6723 * data directly into the page and marks the extent up to date in the io_tree.
6725 * Return: ERR_PTR on error, non-NULL extent_map on success.
6727 struct extent_map
*btrfs_get_extent(struct btrfs_inode
*inode
,
6728 struct page
*page
, size_t pg_offset
,
6731 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
6733 u64 extent_start
= 0;
6735 u64 objectid
= btrfs_ino(inode
);
6736 int extent_type
= -1;
6737 struct btrfs_path
*path
= NULL
;
6738 struct btrfs_root
*root
= inode
->root
;
6739 struct btrfs_file_extent_item
*item
;
6740 struct extent_buffer
*leaf
;
6741 struct btrfs_key found_key
;
6742 struct extent_map
*em
= NULL
;
6743 struct extent_map_tree
*em_tree
= &inode
->extent_tree
;
6745 read_lock(&em_tree
->lock
);
6746 em
= lookup_extent_mapping(em_tree
, start
, len
);
6747 read_unlock(&em_tree
->lock
);
6750 if (em
->start
> start
|| em
->start
+ em
->len
<= start
)
6751 free_extent_map(em
);
6752 else if (em
->block_start
== EXTENT_MAP_INLINE
&& page
)
6753 free_extent_map(em
);
6757 em
= alloc_extent_map();
6762 em
->start
= EXTENT_MAP_HOLE
;
6763 em
->orig_start
= EXTENT_MAP_HOLE
;
6765 em
->block_len
= (u64
)-1;
6767 path
= btrfs_alloc_path();
6773 /* Chances are we'll be called again, so go ahead and do readahead */
6774 path
->reada
= READA_FORWARD
;
6777 * The same explanation in load_free_space_cache applies here as well,
6778 * we only read when we're loading the free space cache, and at that
6779 * point the commit_root has everything we need.
6781 if (btrfs_is_free_space_inode(inode
)) {
6782 path
->search_commit_root
= 1;
6783 path
->skip_locking
= 1;
6786 ret
= btrfs_lookup_file_extent(NULL
, root
, path
, objectid
, start
, 0);
6789 } else if (ret
> 0) {
6790 if (path
->slots
[0] == 0)
6796 leaf
= path
->nodes
[0];
6797 item
= btrfs_item_ptr(leaf
, path
->slots
[0],
6798 struct btrfs_file_extent_item
);
6799 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
6800 if (found_key
.objectid
!= objectid
||
6801 found_key
.type
!= BTRFS_EXTENT_DATA_KEY
) {
6803 * If we backup past the first extent we want to move forward
6804 * and see if there is an extent in front of us, otherwise we'll
6805 * say there is a hole for our whole search range which can
6812 extent_type
= btrfs_file_extent_type(leaf
, item
);
6813 extent_start
= found_key
.offset
;
6814 extent_end
= btrfs_file_extent_end(path
);
6815 if (extent_type
== BTRFS_FILE_EXTENT_REG
||
6816 extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
6817 /* Only regular file could have regular/prealloc extent */
6818 if (!S_ISREG(inode
->vfs_inode
.i_mode
)) {
6821 "regular/prealloc extent found for non-regular inode %llu",
6825 trace_btrfs_get_extent_show_fi_regular(inode
, leaf
, item
,
6827 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
6828 trace_btrfs_get_extent_show_fi_inline(inode
, leaf
, item
,
6833 if (start
>= extent_end
) {
6835 if (path
->slots
[0] >= btrfs_header_nritems(leaf
)) {
6836 ret
= btrfs_next_leaf(root
, path
);
6842 leaf
= path
->nodes
[0];
6844 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
6845 if (found_key
.objectid
!= objectid
||
6846 found_key
.type
!= BTRFS_EXTENT_DATA_KEY
)
6848 if (start
+ len
<= found_key
.offset
)
6850 if (start
> found_key
.offset
)
6853 /* New extent overlaps with existing one */
6855 em
->orig_start
= start
;
6856 em
->len
= found_key
.offset
- start
;
6857 em
->block_start
= EXTENT_MAP_HOLE
;
6861 btrfs_extent_item_to_extent_map(inode
, path
, item
, em
);
6863 if (extent_type
== BTRFS_FILE_EXTENT_REG
||
6864 extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
6866 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
6868 * Inline extent can only exist at file offset 0. This is
6869 * ensured by tree-checker and inline extent creation path.
6870 * Thus all members representing file offsets should be zero.
6872 ASSERT(pg_offset
== 0);
6873 ASSERT(extent_start
== 0);
6874 ASSERT(em
->start
== 0);
6877 * btrfs_extent_item_to_extent_map() should have properly
6878 * initialized em members already.
6880 * Other members are not utilized for inline extents.
6882 ASSERT(em
->block_start
== EXTENT_MAP_INLINE
);
6883 ASSERT(em
->len
== fs_info
->sectorsize
);
6885 ret
= read_inline_extent(inode
, path
, page
);
6892 em
->orig_start
= start
;
6894 em
->block_start
= EXTENT_MAP_HOLE
;
6897 btrfs_release_path(path
);
6898 if (em
->start
> start
|| extent_map_end(em
) <= start
) {
6900 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6901 em
->start
, em
->len
, start
, len
);
6906 write_lock(&em_tree
->lock
);
6907 ret
= btrfs_add_extent_mapping(fs_info
, em_tree
, &em
, start
, len
);
6908 write_unlock(&em_tree
->lock
);
6910 btrfs_free_path(path
);
6912 trace_btrfs_get_extent(root
, inode
, em
);
6915 free_extent_map(em
);
6916 return ERR_PTR(ret
);
6921 static struct extent_map
*btrfs_create_dio_extent(struct btrfs_inode
*inode
,
6922 struct btrfs_dio_data
*dio_data
,
6925 const u64 orig_start
,
6926 const u64 block_start
,
6927 const u64 block_len
,
6928 const u64 orig_block_len
,
6929 const u64 ram_bytes
,
6932 struct extent_map
*em
= NULL
;
6933 struct btrfs_ordered_extent
*ordered
;
6935 if (type
!= BTRFS_ORDERED_NOCOW
) {
6936 em
= create_io_em(inode
, start
, len
, orig_start
, block_start
,
6937 block_len
, orig_block_len
, ram_bytes
,
6938 BTRFS_COMPRESS_NONE
, /* compress_type */
6943 ordered
= btrfs_alloc_ordered_extent(inode
, start
, len
, len
,
6944 block_start
, block_len
, 0,
6946 (1 << BTRFS_ORDERED_DIRECT
),
6947 BTRFS_COMPRESS_NONE
);
6948 if (IS_ERR(ordered
)) {
6950 free_extent_map(em
);
6951 btrfs_drop_extent_map_range(inode
, start
,
6952 start
+ len
- 1, false);
6954 em
= ERR_CAST(ordered
);
6956 ASSERT(!dio_data
->ordered
);
6957 dio_data
->ordered
= ordered
;
6964 static struct extent_map
*btrfs_new_extent_direct(struct btrfs_inode
*inode
,
6965 struct btrfs_dio_data
*dio_data
,
6968 struct btrfs_root
*root
= inode
->root
;
6969 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
6970 struct extent_map
*em
;
6971 struct btrfs_key ins
;
6975 alloc_hint
= get_extent_allocation_hint(inode
, start
, len
);
6976 ret
= btrfs_reserve_extent(root
, len
, len
, fs_info
->sectorsize
,
6977 0, alloc_hint
, &ins
, 1, 1);
6979 return ERR_PTR(ret
);
6981 em
= btrfs_create_dio_extent(inode
, dio_data
, start
, ins
.offset
, start
,
6982 ins
.objectid
, ins
.offset
, ins
.offset
,
6983 ins
.offset
, BTRFS_ORDERED_REGULAR
);
6984 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
6986 btrfs_free_reserved_extent(fs_info
, ins
.objectid
, ins
.offset
,
6992 static bool btrfs_extent_readonly(struct btrfs_fs_info
*fs_info
, u64 bytenr
)
6994 struct btrfs_block_group
*block_group
;
6995 bool readonly
= false;
6997 block_group
= btrfs_lookup_block_group(fs_info
, bytenr
);
6998 if (!block_group
|| block_group
->ro
)
7001 btrfs_put_block_group(block_group
);
7006 * Check if we can do nocow write into the range [@offset, @offset + @len)
7008 * @offset: File offset
7009 * @len: The length to write, will be updated to the nocow writeable
7011 * @orig_start: (optional) Return the original file offset of the file extent
7012 * @orig_len: (optional) Return the original on-disk length of the file extent
7013 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7014 * @strict: if true, omit optimizations that might force us into unnecessary
7015 * cow. e.g., don't trust generation number.
7018 * >0 and update @len if we can do nocow write
7019 * 0 if we can't do nocow write
7020 * <0 if error happened
7022 * NOTE: This only checks the file extents, caller is responsible to wait for
7023 * any ordered extents.
7025 noinline
int can_nocow_extent(struct inode
*inode
, u64 offset
, u64
*len
,
7026 u64
*orig_start
, u64
*orig_block_len
,
7027 u64
*ram_bytes
, bool nowait
, bool strict
)
7029 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7030 struct can_nocow_file_extent_args nocow_args
= { 0 };
7031 struct btrfs_path
*path
;
7033 struct extent_buffer
*leaf
;
7034 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
7035 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
7036 struct btrfs_file_extent_item
*fi
;
7037 struct btrfs_key key
;
7040 path
= btrfs_alloc_path();
7043 path
->nowait
= nowait
;
7045 ret
= btrfs_lookup_file_extent(NULL
, root
, path
,
7046 btrfs_ino(BTRFS_I(inode
)), offset
, 0);
7051 if (path
->slots
[0] == 0) {
7052 /* can't find the item, must cow */
7059 leaf
= path
->nodes
[0];
7060 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
7061 if (key
.objectid
!= btrfs_ino(BTRFS_I(inode
)) ||
7062 key
.type
!= BTRFS_EXTENT_DATA_KEY
) {
7063 /* not our file or wrong item type, must cow */
7067 if (key
.offset
> offset
) {
7068 /* Wrong offset, must cow */
7072 if (btrfs_file_extent_end(path
) <= offset
)
7075 fi
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_file_extent_item
);
7076 found_type
= btrfs_file_extent_type(leaf
, fi
);
7078 *ram_bytes
= btrfs_file_extent_ram_bytes(leaf
, fi
);
7080 nocow_args
.start
= offset
;
7081 nocow_args
.end
= offset
+ *len
- 1;
7082 nocow_args
.strict
= strict
;
7083 nocow_args
.free_path
= true;
7085 ret
= can_nocow_file_extent(path
, &key
, BTRFS_I(inode
), &nocow_args
);
7086 /* can_nocow_file_extent() has freed the path. */
7090 /* Treat errors as not being able to NOCOW. */
7096 if (btrfs_extent_readonly(fs_info
, nocow_args
.disk_bytenr
))
7099 if (!(BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
) &&
7100 found_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
7103 range_end
= round_up(offset
+ nocow_args
.num_bytes
,
7104 root
->fs_info
->sectorsize
) - 1;
7105 ret
= test_range_bit(io_tree
, offset
, range_end
,
7106 EXTENT_DELALLOC
, 0, NULL
);
7114 *orig_start
= key
.offset
- nocow_args
.extent_offset
;
7116 *orig_block_len
= nocow_args
.disk_num_bytes
;
7118 *len
= nocow_args
.num_bytes
;
7121 btrfs_free_path(path
);
7125 static int lock_extent_direct(struct inode
*inode
, u64 lockstart
, u64 lockend
,
7126 struct extent_state
**cached_state
,
7127 unsigned int iomap_flags
)
7129 const bool writing
= (iomap_flags
& IOMAP_WRITE
);
7130 const bool nowait
= (iomap_flags
& IOMAP_NOWAIT
);
7131 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
7132 struct btrfs_ordered_extent
*ordered
;
7137 if (!try_lock_extent(io_tree
, lockstart
, lockend
,
7141 lock_extent(io_tree
, lockstart
, lockend
, cached_state
);
7144 * We're concerned with the entire range that we're going to be
7145 * doing DIO to, so we need to make sure there's no ordered
7146 * extents in this range.
7148 ordered
= btrfs_lookup_ordered_range(BTRFS_I(inode
), lockstart
,
7149 lockend
- lockstart
+ 1);
7152 * We need to make sure there are no buffered pages in this
7153 * range either, we could have raced between the invalidate in
7154 * generic_file_direct_write and locking the extent. The
7155 * invalidate needs to happen so that reads after a write do not
7159 (!writing
|| !filemap_range_has_page(inode
->i_mapping
,
7160 lockstart
, lockend
)))
7163 unlock_extent(io_tree
, lockstart
, lockend
, cached_state
);
7167 btrfs_put_ordered_extent(ordered
);
7172 * If we are doing a DIO read and the ordered extent we
7173 * found is for a buffered write, we can not wait for it
7174 * to complete and retry, because if we do so we can
7175 * deadlock with concurrent buffered writes on page
7176 * locks. This happens only if our DIO read covers more
7177 * than one extent map, if at this point has already
7178 * created an ordered extent for a previous extent map
7179 * and locked its range in the inode's io tree, and a
7180 * concurrent write against that previous extent map's
7181 * range and this range started (we unlock the ranges
7182 * in the io tree only when the bios complete and
7183 * buffered writes always lock pages before attempting
7184 * to lock range in the io tree).
7187 test_bit(BTRFS_ORDERED_DIRECT
, &ordered
->flags
))
7188 btrfs_start_ordered_extent(ordered
);
7190 ret
= nowait
? -EAGAIN
: -ENOTBLK
;
7191 btrfs_put_ordered_extent(ordered
);
7194 * We could trigger writeback for this range (and wait
7195 * for it to complete) and then invalidate the pages for
7196 * this range (through invalidate_inode_pages2_range()),
7197 * but that can lead us to a deadlock with a concurrent
7198 * call to readahead (a buffered read or a defrag call
7199 * triggered a readahead) on a page lock due to an
7200 * ordered dio extent we created before but did not have
7201 * yet a corresponding bio submitted (whence it can not
7202 * complete), which makes readahead wait for that
7203 * ordered extent to complete while holding a lock on
7206 ret
= nowait
? -EAGAIN
: -ENOTBLK
;
7218 /* The callers of this must take lock_extent() */
7219 static struct extent_map
*create_io_em(struct btrfs_inode
*inode
, u64 start
,
7220 u64 len
, u64 orig_start
, u64 block_start
,
7221 u64 block_len
, u64 orig_block_len
,
7222 u64 ram_bytes
, int compress_type
,
7225 struct extent_map
*em
;
7228 ASSERT(type
== BTRFS_ORDERED_PREALLOC
||
7229 type
== BTRFS_ORDERED_COMPRESSED
||
7230 type
== BTRFS_ORDERED_NOCOW
||
7231 type
== BTRFS_ORDERED_REGULAR
);
7233 em
= alloc_extent_map();
7235 return ERR_PTR(-ENOMEM
);
7238 em
->orig_start
= orig_start
;
7240 em
->block_len
= block_len
;
7241 em
->block_start
= block_start
;
7242 em
->orig_block_len
= orig_block_len
;
7243 em
->ram_bytes
= ram_bytes
;
7244 em
->generation
= -1;
7245 set_bit(EXTENT_FLAG_PINNED
, &em
->flags
);
7246 if (type
== BTRFS_ORDERED_PREALLOC
) {
7247 set_bit(EXTENT_FLAG_FILLING
, &em
->flags
);
7248 } else if (type
== BTRFS_ORDERED_COMPRESSED
) {
7249 set_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
);
7250 em
->compress_type
= compress_type
;
7253 ret
= btrfs_replace_extent_map_range(inode
, em
, true);
7255 free_extent_map(em
);
7256 return ERR_PTR(ret
);
7259 /* em got 2 refs now, callers needs to do free_extent_map once. */
7264 static int btrfs_get_blocks_direct_write(struct extent_map
**map
,
7265 struct inode
*inode
,
7266 struct btrfs_dio_data
*dio_data
,
7268 unsigned int iomap_flags
)
7270 const bool nowait
= (iomap_flags
& IOMAP_NOWAIT
);
7271 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7272 struct extent_map
*em
= *map
;
7274 u64 block_start
, orig_start
, orig_block_len
, ram_bytes
;
7275 struct btrfs_block_group
*bg
;
7276 bool can_nocow
= false;
7277 bool space_reserved
= false;
7282 * We don't allocate a new extent in the following cases
7284 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7286 * 2) The extent is marked as PREALLOC. We're good to go here and can
7287 * just use the extent.
7290 if (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
) ||
7291 ((BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
) &&
7292 em
->block_start
!= EXTENT_MAP_HOLE
)) {
7293 if (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))
7294 type
= BTRFS_ORDERED_PREALLOC
;
7296 type
= BTRFS_ORDERED_NOCOW
;
7297 len
= min(len
, em
->len
- (start
- em
->start
));
7298 block_start
= em
->block_start
+ (start
- em
->start
);
7300 if (can_nocow_extent(inode
, start
, &len
, &orig_start
,
7301 &orig_block_len
, &ram_bytes
, false, false) == 1) {
7302 bg
= btrfs_inc_nocow_writers(fs_info
, block_start
);
7310 struct extent_map
*em2
;
7312 /* We can NOCOW, so only need to reserve metadata space. */
7313 ret
= btrfs_delalloc_reserve_metadata(BTRFS_I(inode
), len
, len
,
7316 /* Our caller expects us to free the input extent map. */
7317 free_extent_map(em
);
7319 btrfs_dec_nocow_writers(bg
);
7320 if (nowait
&& (ret
== -ENOSPC
|| ret
== -EDQUOT
))
7324 space_reserved
= true;
7326 em2
= btrfs_create_dio_extent(BTRFS_I(inode
), dio_data
, start
, len
,
7327 orig_start
, block_start
,
7328 len
, orig_block_len
,
7330 btrfs_dec_nocow_writers(bg
);
7331 if (type
== BTRFS_ORDERED_PREALLOC
) {
7332 free_extent_map(em
);
7342 dio_data
->nocow_done
= true;
7344 /* Our caller expects us to free the input extent map. */
7345 free_extent_map(em
);
7352 * If we could not allocate data space before locking the file
7353 * range and we can't do a NOCOW write, then we have to fail.
7355 if (!dio_data
->data_space_reserved
)
7359 * We have to COW and we have already reserved data space before,
7360 * so now we reserve only metadata.
7362 ret
= btrfs_delalloc_reserve_metadata(BTRFS_I(inode
), len
, len
,
7366 space_reserved
= true;
7368 em
= btrfs_new_extent_direct(BTRFS_I(inode
), dio_data
, start
, len
);
7374 len
= min(len
, em
->len
- (start
- em
->start
));
7376 btrfs_delalloc_release_metadata(BTRFS_I(inode
),
7377 prev_len
- len
, true);
7381 * We have created our ordered extent, so we can now release our reservation
7382 * for an outstanding extent.
7384 btrfs_delalloc_release_extents(BTRFS_I(inode
), prev_len
);
7387 * Need to update the i_size under the extent lock so buffered
7388 * readers will get the updated i_size when we unlock.
7390 if (start
+ len
> i_size_read(inode
))
7391 i_size_write(inode
, start
+ len
);
7393 if (ret
&& space_reserved
) {
7394 btrfs_delalloc_release_extents(BTRFS_I(inode
), len
);
7395 btrfs_delalloc_release_metadata(BTRFS_I(inode
), len
, true);
7400 static int btrfs_dio_iomap_begin(struct inode
*inode
, loff_t start
,
7401 loff_t length
, unsigned int flags
, struct iomap
*iomap
,
7402 struct iomap
*srcmap
)
7404 struct iomap_iter
*iter
= container_of(iomap
, struct iomap_iter
, iomap
);
7405 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7406 struct extent_map
*em
;
7407 struct extent_state
*cached_state
= NULL
;
7408 struct btrfs_dio_data
*dio_data
= iter
->private;
7409 u64 lockstart
, lockend
;
7410 const bool write
= !!(flags
& IOMAP_WRITE
);
7413 const u64 data_alloc_len
= length
;
7414 bool unlock_extents
= false;
7417 * We could potentially fault if we have a buffer > PAGE_SIZE, and if
7418 * we're NOWAIT we may submit a bio for a partial range and return
7419 * EIOCBQUEUED, which would result in an errant short read.
7421 * The best way to handle this would be to allow for partial completions
7422 * of iocb's, so we could submit the partial bio, return and fault in
7423 * the rest of the pages, and then submit the io for the rest of the
7424 * range. However we don't have that currently, so simply return
7425 * -EAGAIN at this point so that the normal path is used.
7427 if (!write
&& (flags
& IOMAP_NOWAIT
) && length
> PAGE_SIZE
)
7431 * Cap the size of reads to that usually seen in buffered I/O as we need
7432 * to allocate a contiguous array for the checksums.
7435 len
= min_t(u64
, len
, fs_info
->sectorsize
* BTRFS_MAX_BIO_SECTORS
);
7438 lockend
= start
+ len
- 1;
7441 * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
7442 * enough if we've written compressed pages to this area, so we need to
7443 * flush the dirty pages again to make absolutely sure that any
7444 * outstanding dirty pages are on disk - the first flush only starts
7445 * compression on the data, while keeping the pages locked, so by the
7446 * time the second flush returns we know bios for the compressed pages
7447 * were submitted and finished, and the pages no longer under writeback.
7449 * If we have a NOWAIT request and we have any pages in the range that
7450 * are locked, likely due to compression still in progress, we don't want
7451 * to block on page locks. We also don't want to block on pages marked as
7452 * dirty or under writeback (same as for the non-compression case).
7453 * iomap_dio_rw() did the same check, but after that and before we got
7454 * here, mmap'ed writes may have happened or buffered reads started
7455 * (readpage() and readahead(), which lock pages), as we haven't locked
7456 * the file range yet.
7458 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT
,
7459 &BTRFS_I(inode
)->runtime_flags
)) {
7460 if (flags
& IOMAP_NOWAIT
) {
7461 if (filemap_range_needs_writeback(inode
->i_mapping
,
7462 lockstart
, lockend
))
7465 ret
= filemap_fdatawrite_range(inode
->i_mapping
, start
,
7466 start
+ length
- 1);
7472 memset(dio_data
, 0, sizeof(*dio_data
));
7475 * We always try to allocate data space and must do it before locking
7476 * the file range, to avoid deadlocks with concurrent writes to the same
7477 * range if the range has several extents and the writes don't expand the
7478 * current i_size (the inode lock is taken in shared mode). If we fail to
7479 * allocate data space here we continue and later, after locking the
7480 * file range, we fail with ENOSPC only if we figure out we can not do a
7483 if (write
&& !(flags
& IOMAP_NOWAIT
)) {
7484 ret
= btrfs_check_data_free_space(BTRFS_I(inode
),
7485 &dio_data
->data_reserved
,
7486 start
, data_alloc_len
, false);
7488 dio_data
->data_space_reserved
= true;
7489 else if (ret
&& !(BTRFS_I(inode
)->flags
&
7490 (BTRFS_INODE_NODATACOW
| BTRFS_INODE_PREALLOC
)))
7495 * If this errors out it's because we couldn't invalidate pagecache for
7496 * this range and we need to fallback to buffered IO, or we are doing a
7497 * NOWAIT read/write and we need to block.
7499 ret
= lock_extent_direct(inode
, lockstart
, lockend
, &cached_state
, flags
);
7503 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, start
, len
);
7510 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7511 * io. INLINE is special, and we could probably kludge it in here, but
7512 * it's still buffered so for safety lets just fall back to the generic
7515 * For COMPRESSED we _have_ to read the entire extent in so we can
7516 * decompress it, so there will be buffering required no matter what we
7517 * do, so go ahead and fallback to buffered.
7519 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7520 * to buffered IO. Don't blame me, this is the price we pay for using
7523 if (test_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
) ||
7524 em
->block_start
== EXTENT_MAP_INLINE
) {
7525 free_extent_map(em
);
7527 * If we are in a NOWAIT context, return -EAGAIN in order to
7528 * fallback to buffered IO. This is not only because we can
7529 * block with buffered IO (no support for NOWAIT semantics at
7530 * the moment) but also to avoid returning short reads to user
7531 * space - this happens if we were able to read some data from
7532 * previous non-compressed extents and then when we fallback to
7533 * buffered IO, at btrfs_file_read_iter() by calling
7534 * filemap_read(), we fail to fault in pages for the read buffer,
7535 * in which case filemap_read() returns a short read (the number
7536 * of bytes previously read is > 0, so it does not return -EFAULT).
7538 ret
= (flags
& IOMAP_NOWAIT
) ? -EAGAIN
: -ENOTBLK
;
7542 len
= min(len
, em
->len
- (start
- em
->start
));
7545 * If we have a NOWAIT request and the range contains multiple extents
7546 * (or a mix of extents and holes), then we return -EAGAIN to make the
7547 * caller fallback to a context where it can do a blocking (without
7548 * NOWAIT) request. This way we avoid doing partial IO and returning
7549 * success to the caller, which is not optimal for writes and for reads
7550 * it can result in unexpected behaviour for an application.
7552 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7553 * iomap_dio_rw(), we can end up returning less data then what the caller
7554 * asked for, resulting in an unexpected, and incorrect, short read.
7555 * That is, the caller asked to read N bytes and we return less than that,
7556 * which is wrong unless we are crossing EOF. This happens if we get a
7557 * page fault error when trying to fault in pages for the buffer that is
7558 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7559 * have previously submitted bios for other extents in the range, in
7560 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7561 * those bios have completed by the time we get the page fault error,
7562 * which we return back to our caller - we should only return EIOCBQUEUED
7563 * after we have submitted bios for all the extents in the range.
7565 if ((flags
& IOMAP_NOWAIT
) && len
< length
) {
7566 free_extent_map(em
);
7572 ret
= btrfs_get_blocks_direct_write(&em
, inode
, dio_data
,
7576 unlock_extents
= true;
7577 /* Recalc len in case the new em is smaller than requested */
7578 len
= min(len
, em
->len
- (start
- em
->start
));
7579 if (dio_data
->data_space_reserved
) {
7581 u64 release_len
= 0;
7583 if (dio_data
->nocow_done
) {
7584 release_offset
= start
;
7585 release_len
= data_alloc_len
;
7586 } else if (len
< data_alloc_len
) {
7587 release_offset
= start
+ len
;
7588 release_len
= data_alloc_len
- len
;
7591 if (release_len
> 0)
7592 btrfs_free_reserved_data_space(BTRFS_I(inode
),
7593 dio_data
->data_reserved
,
7599 * We need to unlock only the end area that we aren't using.
7600 * The rest is going to be unlocked by the endio routine.
7602 lockstart
= start
+ len
;
7603 if (lockstart
< lockend
)
7604 unlock_extents
= true;
7608 unlock_extent(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
7611 free_extent_state(cached_state
);
7614 * Translate extent map information to iomap.
7615 * We trim the extents (and move the addr) even though iomap code does
7616 * that, since we have locked only the parts we are performing I/O in.
7618 if ((em
->block_start
== EXTENT_MAP_HOLE
) ||
7619 (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
) && !write
)) {
7620 iomap
->addr
= IOMAP_NULL_ADDR
;
7621 iomap
->type
= IOMAP_HOLE
;
7623 iomap
->addr
= em
->block_start
+ (start
- em
->start
);
7624 iomap
->type
= IOMAP_MAPPED
;
7626 iomap
->offset
= start
;
7627 iomap
->bdev
= fs_info
->fs_devices
->latest_dev
->bdev
;
7628 iomap
->length
= len
;
7629 free_extent_map(em
);
7634 unlock_extent(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
7637 if (dio_data
->data_space_reserved
) {
7638 btrfs_free_reserved_data_space(BTRFS_I(inode
),
7639 dio_data
->data_reserved
,
7640 start
, data_alloc_len
);
7641 extent_changeset_free(dio_data
->data_reserved
);
7647 static int btrfs_dio_iomap_end(struct inode
*inode
, loff_t pos
, loff_t length
,
7648 ssize_t written
, unsigned int flags
, struct iomap
*iomap
)
7650 struct iomap_iter
*iter
= container_of(iomap
, struct iomap_iter
, iomap
);
7651 struct btrfs_dio_data
*dio_data
= iter
->private;
7652 size_t submitted
= dio_data
->submitted
;
7653 const bool write
= !!(flags
& IOMAP_WRITE
);
7656 if (!write
&& (iomap
->type
== IOMAP_HOLE
)) {
7657 /* If reading from a hole, unlock and return */
7658 unlock_extent(&BTRFS_I(inode
)->io_tree
, pos
, pos
+ length
- 1,
7663 if (submitted
< length
) {
7665 length
-= submitted
;
7667 btrfs_mark_ordered_io_finished(BTRFS_I(inode
), NULL
,
7668 pos
, length
, false);
7670 unlock_extent(&BTRFS_I(inode
)->io_tree
, pos
,
7671 pos
+ length
- 1, NULL
);
7675 btrfs_put_ordered_extent(dio_data
->ordered
);
7676 dio_data
->ordered
= NULL
;
7680 extent_changeset_free(dio_data
->data_reserved
);
7684 static void btrfs_dio_end_io(struct btrfs_bio
*bbio
)
7686 struct btrfs_dio_private
*dip
=
7687 container_of(bbio
, struct btrfs_dio_private
, bbio
);
7688 struct btrfs_inode
*inode
= bbio
->inode
;
7689 struct bio
*bio
= &bbio
->bio
;
7691 if (bio
->bi_status
) {
7692 btrfs_warn(inode
->root
->fs_info
,
7693 "direct IO failed ino %llu op 0x%0x offset %#llx len %u err no %d",
7694 btrfs_ino(inode
), bio
->bi_opf
,
7695 dip
->file_offset
, dip
->bytes
, bio
->bi_status
);
7698 if (btrfs_op(bio
) == BTRFS_MAP_WRITE
)
7699 btrfs_mark_ordered_io_finished(inode
, NULL
, dip
->file_offset
,
7700 dip
->bytes
, !bio
->bi_status
);
7702 unlock_extent(&inode
->io_tree
, dip
->file_offset
,
7703 dip
->file_offset
+ dip
->bytes
- 1, NULL
);
7705 bbio
->bio
.bi_private
= bbio
->private;
7706 iomap_dio_bio_end_io(bio
);
7709 static void btrfs_dio_submit_io(const struct iomap_iter
*iter
, struct bio
*bio
,
7712 struct btrfs_bio
*bbio
= btrfs_bio(bio
);
7713 struct btrfs_dio_private
*dip
=
7714 container_of(bbio
, struct btrfs_dio_private
, bbio
);
7715 struct btrfs_dio_data
*dio_data
= iter
->private;
7717 btrfs_bio_init(bbio
, BTRFS_I(iter
->inode
)->root
->fs_info
,
7718 btrfs_dio_end_io
, bio
->bi_private
);
7719 bbio
->inode
= BTRFS_I(iter
->inode
);
7720 bbio
->file_offset
= file_offset
;
7722 dip
->file_offset
= file_offset
;
7723 dip
->bytes
= bio
->bi_iter
.bi_size
;
7725 dio_data
->submitted
+= bio
->bi_iter
.bi_size
;
7728 * Check if we are doing a partial write. If we are, we need to split
7729 * the ordered extent to match the submitted bio. Hang on to the
7730 * remaining unfinishable ordered_extent in dio_data so that it can be
7731 * cancelled in iomap_end to avoid a deadlock wherein faulting the
7732 * remaining pages is blocked on the outstanding ordered extent.
7734 if (iter
->flags
& IOMAP_WRITE
) {
7737 ret
= btrfs_extract_ordered_extent(bbio
, dio_data
->ordered
);
7739 btrfs_bio_end_io(bbio
, errno_to_blk_status(ret
));
7744 btrfs_submit_bio(bbio
, 0);
7747 static const struct iomap_ops btrfs_dio_iomap_ops
= {
7748 .iomap_begin
= btrfs_dio_iomap_begin
,
7749 .iomap_end
= btrfs_dio_iomap_end
,
7752 static const struct iomap_dio_ops btrfs_dio_ops
= {
7753 .submit_io
= btrfs_dio_submit_io
,
7754 .bio_set
= &btrfs_dio_bioset
,
7757 ssize_t
btrfs_dio_read(struct kiocb
*iocb
, struct iov_iter
*iter
, size_t done_before
)
7759 struct btrfs_dio_data data
= { 0 };
7761 return iomap_dio_rw(iocb
, iter
, &btrfs_dio_iomap_ops
, &btrfs_dio_ops
,
7762 IOMAP_DIO_PARTIAL
, &data
, done_before
);
7765 struct iomap_dio
*btrfs_dio_write(struct kiocb
*iocb
, struct iov_iter
*iter
,
7768 struct btrfs_dio_data data
= { 0 };
7770 return __iomap_dio_rw(iocb
, iter
, &btrfs_dio_iomap_ops
, &btrfs_dio_ops
,
7771 IOMAP_DIO_PARTIAL
, &data
, done_before
);
7774 static int btrfs_fiemap(struct inode
*inode
, struct fiemap_extent_info
*fieinfo
,
7779 ret
= fiemap_prep(inode
, fieinfo
, start
, &len
, 0);
7784 * fiemap_prep() called filemap_write_and_wait() for the whole possible
7785 * file range (0 to LLONG_MAX), but that is not enough if we have
7786 * compression enabled. The first filemap_fdatawrite_range() only kicks
7787 * in the compression of data (in an async thread) and will return
7788 * before the compression is done and writeback is started. A second
7789 * filemap_fdatawrite_range() is needed to wait for the compression to
7790 * complete and writeback to start. We also need to wait for ordered
7791 * extents to complete, because our fiemap implementation uses mainly
7792 * file extent items to list the extents, searching for extent maps
7793 * only for file ranges with holes or prealloc extents to figure out
7794 * if we have delalloc in those ranges.
7796 if (fieinfo
->fi_flags
& FIEMAP_FLAG_SYNC
) {
7797 ret
= btrfs_wait_ordered_range(inode
, 0, LLONG_MAX
);
7802 return extent_fiemap(BTRFS_I(inode
), fieinfo
, start
, len
);
7805 static int btrfs_writepages(struct address_space
*mapping
,
7806 struct writeback_control
*wbc
)
7808 return extent_writepages(mapping
, wbc
);
7811 static void btrfs_readahead(struct readahead_control
*rac
)
7813 extent_readahead(rac
);
7817 * For release_folio() and invalidate_folio() we have a race window where
7818 * folio_end_writeback() is called but the subpage spinlock is not yet released.
7819 * If we continue to release/invalidate the page, we could cause use-after-free
7820 * for subpage spinlock. So this function is to spin and wait for subpage
7823 static void wait_subpage_spinlock(struct page
*page
)
7825 struct btrfs_fs_info
*fs_info
= btrfs_sb(page
->mapping
->host
->i_sb
);
7826 struct btrfs_subpage
*subpage
;
7828 if (!btrfs_is_subpage(fs_info
, page
))
7831 ASSERT(PagePrivate(page
) && page
->private);
7832 subpage
= (struct btrfs_subpage
*)page
->private;
7835 * This may look insane as we just acquire the spinlock and release it,
7836 * without doing anything. But we just want to make sure no one is
7837 * still holding the subpage spinlock.
7838 * And since the page is not dirty nor writeback, and we have page
7839 * locked, the only possible way to hold a spinlock is from the endio
7840 * function to clear page writeback.
7842 * Here we just acquire the spinlock so that all existing callers
7843 * should exit and we're safe to release/invalidate the page.
7845 spin_lock_irq(&subpage
->lock
);
7846 spin_unlock_irq(&subpage
->lock
);
7849 static bool __btrfs_release_folio(struct folio
*folio
, gfp_t gfp_flags
)
7851 int ret
= try_release_extent_mapping(&folio
->page
, gfp_flags
);
7854 wait_subpage_spinlock(&folio
->page
);
7855 clear_page_extent_mapped(&folio
->page
);
7860 static bool btrfs_release_folio(struct folio
*folio
, gfp_t gfp_flags
)
7862 if (folio_test_writeback(folio
) || folio_test_dirty(folio
))
7864 return __btrfs_release_folio(folio
, gfp_flags
);
7867 #ifdef CONFIG_MIGRATION
7868 static int btrfs_migrate_folio(struct address_space
*mapping
,
7869 struct folio
*dst
, struct folio
*src
,
7870 enum migrate_mode mode
)
7872 int ret
= filemap_migrate_folio(mapping
, dst
, src
, mode
);
7874 if (ret
!= MIGRATEPAGE_SUCCESS
)
7877 if (folio_test_ordered(src
)) {
7878 folio_clear_ordered(src
);
7879 folio_set_ordered(dst
);
7882 return MIGRATEPAGE_SUCCESS
;
7885 #define btrfs_migrate_folio NULL
7888 static void btrfs_invalidate_folio(struct folio
*folio
, size_t offset
,
7891 struct btrfs_inode
*inode
= BTRFS_I(folio
->mapping
->host
);
7892 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
7893 struct extent_io_tree
*tree
= &inode
->io_tree
;
7894 struct extent_state
*cached_state
= NULL
;
7895 u64 page_start
= folio_pos(folio
);
7896 u64 page_end
= page_start
+ folio_size(folio
) - 1;
7898 int inode_evicting
= inode
->vfs_inode
.i_state
& I_FREEING
;
7901 * We have folio locked so no new ordered extent can be created on this
7902 * page, nor bio can be submitted for this folio.
7904 * But already submitted bio can still be finished on this folio.
7905 * Furthermore, endio function won't skip folio which has Ordered
7906 * (Private2) already cleared, so it's possible for endio and
7907 * invalidate_folio to do the same ordered extent accounting twice
7910 * So here we wait for any submitted bios to finish, so that we won't
7911 * do double ordered extent accounting on the same folio.
7913 folio_wait_writeback(folio
);
7914 wait_subpage_spinlock(&folio
->page
);
7917 * For subpage case, we have call sites like
7918 * btrfs_punch_hole_lock_range() which passes range not aligned to
7920 * If the range doesn't cover the full folio, we don't need to and
7921 * shouldn't clear page extent mapped, as folio->private can still
7922 * record subpage dirty bits for other part of the range.
7924 * For cases that invalidate the full folio even the range doesn't
7925 * cover the full folio, like invalidating the last folio, we're
7926 * still safe to wait for ordered extent to finish.
7928 if (!(offset
== 0 && length
== folio_size(folio
))) {
7929 btrfs_release_folio(folio
, GFP_NOFS
);
7933 if (!inode_evicting
)
7934 lock_extent(tree
, page_start
, page_end
, &cached_state
);
7937 while (cur
< page_end
) {
7938 struct btrfs_ordered_extent
*ordered
;
7941 u32 extra_flags
= 0;
7943 ordered
= btrfs_lookup_first_ordered_range(inode
, cur
,
7944 page_end
+ 1 - cur
);
7946 range_end
= page_end
;
7948 * No ordered extent covering this range, we are safe
7949 * to delete all extent states in the range.
7951 extra_flags
= EXTENT_CLEAR_ALL_BITS
;
7954 if (ordered
->file_offset
> cur
) {
7956 * There is a range between [cur, oe->file_offset) not
7957 * covered by any ordered extent.
7958 * We are safe to delete all extent states, and handle
7959 * the ordered extent in the next iteration.
7961 range_end
= ordered
->file_offset
- 1;
7962 extra_flags
= EXTENT_CLEAR_ALL_BITS
;
7966 range_end
= min(ordered
->file_offset
+ ordered
->num_bytes
- 1,
7968 ASSERT(range_end
+ 1 - cur
< U32_MAX
);
7969 range_len
= range_end
+ 1 - cur
;
7970 if (!btrfs_page_test_ordered(fs_info
, &folio
->page
, cur
, range_len
)) {
7972 * If Ordered (Private2) is cleared, it means endio has
7973 * already been executed for the range.
7974 * We can't delete the extent states as
7975 * btrfs_finish_ordered_io() may still use some of them.
7979 btrfs_page_clear_ordered(fs_info
, &folio
->page
, cur
, range_len
);
7982 * IO on this page will never be started, so we need to account
7983 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
7984 * here, must leave that up for the ordered extent completion.
7986 * This will also unlock the range for incoming
7987 * btrfs_finish_ordered_io().
7989 if (!inode_evicting
)
7990 clear_extent_bit(tree
, cur
, range_end
,
7992 EXTENT_LOCKED
| EXTENT_DO_ACCOUNTING
|
7993 EXTENT_DEFRAG
, &cached_state
);
7995 spin_lock_irq(&inode
->ordered_tree
.lock
);
7996 set_bit(BTRFS_ORDERED_TRUNCATED
, &ordered
->flags
);
7997 ordered
->truncated_len
= min(ordered
->truncated_len
,
7998 cur
- ordered
->file_offset
);
7999 spin_unlock_irq(&inode
->ordered_tree
.lock
);
8002 * If the ordered extent has finished, we're safe to delete all
8003 * the extent states of the range, otherwise
8004 * btrfs_finish_ordered_io() will get executed by endio for
8005 * other pages, so we can't delete extent states.
8007 if (btrfs_dec_test_ordered_pending(inode
, &ordered
,
8008 cur
, range_end
+ 1 - cur
)) {
8009 btrfs_finish_ordered_io(ordered
);
8011 * The ordered extent has finished, now we're again
8012 * safe to delete all extent states of the range.
8014 extra_flags
= EXTENT_CLEAR_ALL_BITS
;
8018 btrfs_put_ordered_extent(ordered
);
8020 * Qgroup reserved space handler
8021 * Sector(s) here will be either:
8023 * 1) Already written to disk or bio already finished
8024 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8025 * Qgroup will be handled by its qgroup_record then.
8026 * btrfs_qgroup_free_data() call will do nothing here.
8028 * 2) Not written to disk yet
8029 * Then btrfs_qgroup_free_data() call will clear the
8030 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8031 * reserved data space.
8032 * Since the IO will never happen for this page.
8034 btrfs_qgroup_free_data(inode
, NULL
, cur
, range_end
+ 1 - cur
);
8035 if (!inode_evicting
) {
8036 clear_extent_bit(tree
, cur
, range_end
, EXTENT_LOCKED
|
8037 EXTENT_DELALLOC
| EXTENT_UPTODATE
|
8038 EXTENT_DO_ACCOUNTING
| EXTENT_DEFRAG
|
8039 extra_flags
, &cached_state
);
8041 cur
= range_end
+ 1;
8044 * We have iterated through all ordered extents of the page, the page
8045 * should not have Ordered (Private2) anymore, or the above iteration
8046 * did something wrong.
8048 ASSERT(!folio_test_ordered(folio
));
8049 btrfs_page_clear_checked(fs_info
, &folio
->page
, folio_pos(folio
), folio_size(folio
));
8050 if (!inode_evicting
)
8051 __btrfs_release_folio(folio
, GFP_NOFS
);
8052 clear_page_extent_mapped(&folio
->page
);
8056 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8057 * called from a page fault handler when a page is first dirtied. Hence we must
8058 * be careful to check for EOF conditions here. We set the page up correctly
8059 * for a written page which means we get ENOSPC checking when writing into
8060 * holes and correct delalloc and unwritten extent mapping on filesystems that
8061 * support these features.
8063 * We are not allowed to take the i_mutex here so we have to play games to
8064 * protect against truncate races as the page could now be beyond EOF. Because
8065 * truncate_setsize() writes the inode size before removing pages, once we have
8066 * the page lock we can determine safely if the page is beyond EOF. If it is not
8067 * beyond EOF, then the page is guaranteed safe against truncation until we
8070 vm_fault_t
btrfs_page_mkwrite(struct vm_fault
*vmf
)
8072 struct page
*page
= vmf
->page
;
8073 struct inode
*inode
= file_inode(vmf
->vma
->vm_file
);
8074 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
8075 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
8076 struct btrfs_ordered_extent
*ordered
;
8077 struct extent_state
*cached_state
= NULL
;
8078 struct extent_changeset
*data_reserved
= NULL
;
8079 unsigned long zero_start
;
8089 reserved_space
= PAGE_SIZE
;
8091 sb_start_pagefault(inode
->i_sb
);
8092 page_start
= page_offset(page
);
8093 page_end
= page_start
+ PAGE_SIZE
- 1;
8097 * Reserving delalloc space after obtaining the page lock can lead to
8098 * deadlock. For example, if a dirty page is locked by this function
8099 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8100 * dirty page write out, then the btrfs_writepages() function could
8101 * end up waiting indefinitely to get a lock on the page currently
8102 * being processed by btrfs_page_mkwrite() function.
8104 ret2
= btrfs_delalloc_reserve_space(BTRFS_I(inode
), &data_reserved
,
8105 page_start
, reserved_space
);
8107 ret2
= file_update_time(vmf
->vma
->vm_file
);
8111 ret
= vmf_error(ret2
);
8117 ret
= VM_FAULT_NOPAGE
; /* make the VM retry the fault */
8119 down_read(&BTRFS_I(inode
)->i_mmap_lock
);
8121 size
= i_size_read(inode
);
8123 if ((page
->mapping
!= inode
->i_mapping
) ||
8124 (page_start
>= size
)) {
8125 /* page got truncated out from underneath us */
8128 wait_on_page_writeback(page
);
8130 lock_extent(io_tree
, page_start
, page_end
, &cached_state
);
8131 ret2
= set_page_extent_mapped(page
);
8133 ret
= vmf_error(ret2
);
8134 unlock_extent(io_tree
, page_start
, page_end
, &cached_state
);
8139 * we can't set the delalloc bits if there are pending ordered
8140 * extents. Drop our locks and wait for them to finish
8142 ordered
= btrfs_lookup_ordered_range(BTRFS_I(inode
), page_start
,
8145 unlock_extent(io_tree
, page_start
, page_end
, &cached_state
);
8147 up_read(&BTRFS_I(inode
)->i_mmap_lock
);
8148 btrfs_start_ordered_extent(ordered
);
8149 btrfs_put_ordered_extent(ordered
);
8153 if (page
->index
== ((size
- 1) >> PAGE_SHIFT
)) {
8154 reserved_space
= round_up(size
- page_start
,
8155 fs_info
->sectorsize
);
8156 if (reserved_space
< PAGE_SIZE
) {
8157 end
= page_start
+ reserved_space
- 1;
8158 btrfs_delalloc_release_space(BTRFS_I(inode
),
8159 data_reserved
, page_start
,
8160 PAGE_SIZE
- reserved_space
, true);
8165 * page_mkwrite gets called when the page is firstly dirtied after it's
8166 * faulted in, but write(2) could also dirty a page and set delalloc
8167 * bits, thus in this case for space account reason, we still need to
8168 * clear any delalloc bits within this page range since we have to
8169 * reserve data&meta space before lock_page() (see above comments).
8171 clear_extent_bit(&BTRFS_I(inode
)->io_tree
, page_start
, end
,
8172 EXTENT_DELALLOC
| EXTENT_DO_ACCOUNTING
|
8173 EXTENT_DEFRAG
, &cached_state
);
8175 ret2
= btrfs_set_extent_delalloc(BTRFS_I(inode
), page_start
, end
, 0,
8178 unlock_extent(io_tree
, page_start
, page_end
, &cached_state
);
8179 ret
= VM_FAULT_SIGBUS
;
8183 /* page is wholly or partially inside EOF */
8184 if (page_start
+ PAGE_SIZE
> size
)
8185 zero_start
= offset_in_page(size
);
8187 zero_start
= PAGE_SIZE
;
8189 if (zero_start
!= PAGE_SIZE
)
8190 memzero_page(page
, zero_start
, PAGE_SIZE
- zero_start
);
8192 btrfs_page_clear_checked(fs_info
, page
, page_start
, PAGE_SIZE
);
8193 btrfs_page_set_dirty(fs_info
, page
, page_start
, end
+ 1 - page_start
);
8194 btrfs_page_set_uptodate(fs_info
, page
, page_start
, end
+ 1 - page_start
);
8196 btrfs_set_inode_last_sub_trans(BTRFS_I(inode
));
8198 unlock_extent(io_tree
, page_start
, page_end
, &cached_state
);
8199 up_read(&BTRFS_I(inode
)->i_mmap_lock
);
8201 btrfs_delalloc_release_extents(BTRFS_I(inode
), PAGE_SIZE
);
8202 sb_end_pagefault(inode
->i_sb
);
8203 extent_changeset_free(data_reserved
);
8204 return VM_FAULT_LOCKED
;
8208 up_read(&BTRFS_I(inode
)->i_mmap_lock
);
8210 btrfs_delalloc_release_extents(BTRFS_I(inode
), PAGE_SIZE
);
8211 btrfs_delalloc_release_space(BTRFS_I(inode
), data_reserved
, page_start
,
8212 reserved_space
, (ret
!= 0));
8214 sb_end_pagefault(inode
->i_sb
);
8215 extent_changeset_free(data_reserved
);
8219 static int btrfs_truncate(struct btrfs_inode
*inode
, bool skip_writeback
)
8221 struct btrfs_truncate_control control
= {
8223 .ino
= btrfs_ino(inode
),
8224 .min_type
= BTRFS_EXTENT_DATA_KEY
,
8225 .clear_extent_range
= true,
8227 struct btrfs_root
*root
= inode
->root
;
8228 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
8229 struct btrfs_block_rsv
*rsv
;
8231 struct btrfs_trans_handle
*trans
;
8232 u64 mask
= fs_info
->sectorsize
- 1;
8233 u64 min_size
= btrfs_calc_metadata_size(fs_info
, 1);
8235 if (!skip_writeback
) {
8236 ret
= btrfs_wait_ordered_range(&inode
->vfs_inode
,
8237 inode
->vfs_inode
.i_size
& (~mask
),
8244 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8245 * things going on here:
8247 * 1) We need to reserve space to update our inode.
8249 * 2) We need to have something to cache all the space that is going to
8250 * be free'd up by the truncate operation, but also have some slack
8251 * space reserved in case it uses space during the truncate (thank you
8252 * very much snapshotting).
8254 * And we need these to be separate. The fact is we can use a lot of
8255 * space doing the truncate, and we have no earthly idea how much space
8256 * we will use, so we need the truncate reservation to be separate so it
8257 * doesn't end up using space reserved for updating the inode. We also
8258 * need to be able to stop the transaction and start a new one, which
8259 * means we need to be able to update the inode several times, and we
8260 * have no idea of knowing how many times that will be, so we can't just
8261 * reserve 1 item for the entirety of the operation, so that has to be
8262 * done separately as well.
8264 * So that leaves us with
8266 * 1) rsv - for the truncate reservation, which we will steal from the
8267 * transaction reservation.
8268 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8269 * updating the inode.
8271 rsv
= btrfs_alloc_block_rsv(fs_info
, BTRFS_BLOCK_RSV_TEMP
);
8274 rsv
->size
= min_size
;
8275 rsv
->failfast
= true;
8278 * 1 for the truncate slack space
8279 * 1 for updating the inode.
8281 trans
= btrfs_start_transaction(root
, 2);
8282 if (IS_ERR(trans
)) {
8283 ret
= PTR_ERR(trans
);
8287 /* Migrate the slack space for the truncate to our reserve */
8288 ret
= btrfs_block_rsv_migrate(&fs_info
->trans_block_rsv
, rsv
,
8292 trans
->block_rsv
= rsv
;
8295 struct extent_state
*cached_state
= NULL
;
8296 const u64 new_size
= inode
->vfs_inode
.i_size
;
8297 const u64 lock_start
= ALIGN_DOWN(new_size
, fs_info
->sectorsize
);
8299 control
.new_size
= new_size
;
8300 lock_extent(&inode
->io_tree
, lock_start
, (u64
)-1, &cached_state
);
8302 * We want to drop from the next block forward in case this new
8303 * size is not block aligned since we will be keeping the last
8304 * block of the extent just the way it is.
8306 btrfs_drop_extent_map_range(inode
,
8307 ALIGN(new_size
, fs_info
->sectorsize
),
8310 ret
= btrfs_truncate_inode_items(trans
, root
, &control
);
8312 inode_sub_bytes(&inode
->vfs_inode
, control
.sub_bytes
);
8313 btrfs_inode_safe_disk_i_size_write(inode
, control
.last_size
);
8315 unlock_extent(&inode
->io_tree
, lock_start
, (u64
)-1, &cached_state
);
8317 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
8318 if (ret
!= -ENOSPC
&& ret
!= -EAGAIN
)
8321 ret
= btrfs_update_inode(trans
, root
, inode
);
8325 btrfs_end_transaction(trans
);
8326 btrfs_btree_balance_dirty(fs_info
);
8328 trans
= btrfs_start_transaction(root
, 2);
8329 if (IS_ERR(trans
)) {
8330 ret
= PTR_ERR(trans
);
8335 btrfs_block_rsv_release(fs_info
, rsv
, -1, NULL
);
8336 ret
= btrfs_block_rsv_migrate(&fs_info
->trans_block_rsv
,
8337 rsv
, min_size
, false);
8338 BUG_ON(ret
); /* shouldn't happen */
8339 trans
->block_rsv
= rsv
;
8343 * We can't call btrfs_truncate_block inside a trans handle as we could
8344 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8345 * know we've truncated everything except the last little bit, and can
8346 * do btrfs_truncate_block and then update the disk_i_size.
8348 if (ret
== BTRFS_NEED_TRUNCATE_BLOCK
) {
8349 btrfs_end_transaction(trans
);
8350 btrfs_btree_balance_dirty(fs_info
);
8352 ret
= btrfs_truncate_block(inode
, inode
->vfs_inode
.i_size
, 0, 0);
8355 trans
= btrfs_start_transaction(root
, 1);
8356 if (IS_ERR(trans
)) {
8357 ret
= PTR_ERR(trans
);
8360 btrfs_inode_safe_disk_i_size_write(inode
, 0);
8366 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
8367 ret2
= btrfs_update_inode(trans
, root
, inode
);
8371 ret2
= btrfs_end_transaction(trans
);
8374 btrfs_btree_balance_dirty(fs_info
);
8377 btrfs_free_block_rsv(fs_info
, rsv
);
8379 * So if we truncate and then write and fsync we normally would just
8380 * write the extents that changed, which is a problem if we need to
8381 * first truncate that entire inode. So set this flag so we write out
8382 * all of the extents in the inode to the sync log so we're completely
8385 * If no extents were dropped or trimmed we don't need to force the next
8386 * fsync to truncate all the inode's items from the log and re-log them
8387 * all. This means the truncate operation did not change the file size,
8388 * or changed it to a smaller size but there was only an implicit hole
8389 * between the old i_size and the new i_size, and there were no prealloc
8390 * extents beyond i_size to drop.
8392 if (control
.extents_found
> 0)
8393 btrfs_set_inode_full_sync(inode
);
8398 struct inode
*btrfs_new_subvol_inode(struct mnt_idmap
*idmap
,
8401 struct inode
*inode
;
8403 inode
= new_inode(dir
->i_sb
);
8406 * Subvolumes don't inherit the sgid bit or the parent's gid if
8407 * the parent's sgid bit is set. This is probably a bug.
8409 inode_init_owner(idmap
, inode
, NULL
,
8410 S_IFDIR
| (~current_umask() & S_IRWXUGO
));
8411 inode
->i_op
= &btrfs_dir_inode_operations
;
8412 inode
->i_fop
= &btrfs_dir_file_operations
;
8417 struct inode
*btrfs_alloc_inode(struct super_block
*sb
)
8419 struct btrfs_fs_info
*fs_info
= btrfs_sb(sb
);
8420 struct btrfs_inode
*ei
;
8421 struct inode
*inode
;
8423 ei
= alloc_inode_sb(sb
, btrfs_inode_cachep
, GFP_KERNEL
);
8430 ei
->last_sub_trans
= 0;
8431 ei
->logged_trans
= 0;
8432 ei
->delalloc_bytes
= 0;
8433 ei
->new_delalloc_bytes
= 0;
8434 ei
->defrag_bytes
= 0;
8435 ei
->disk_i_size
= 0;
8439 ei
->index_cnt
= (u64
)-1;
8441 ei
->last_unlink_trans
= 0;
8442 ei
->last_reflink_trans
= 0;
8443 ei
->last_log_commit
= 0;
8445 spin_lock_init(&ei
->lock
);
8446 ei
->outstanding_extents
= 0;
8447 if (sb
->s_magic
!= BTRFS_TEST_MAGIC
)
8448 btrfs_init_metadata_block_rsv(fs_info
, &ei
->block_rsv
,
8449 BTRFS_BLOCK_RSV_DELALLOC
);
8450 ei
->runtime_flags
= 0;
8451 ei
->prop_compress
= BTRFS_COMPRESS_NONE
;
8452 ei
->defrag_compress
= BTRFS_COMPRESS_NONE
;
8454 ei
->delayed_node
= NULL
;
8456 ei
->i_otime
.tv_sec
= 0;
8457 ei
->i_otime
.tv_nsec
= 0;
8459 inode
= &ei
->vfs_inode
;
8460 extent_map_tree_init(&ei
->extent_tree
);
8461 extent_io_tree_init(fs_info
, &ei
->io_tree
, IO_TREE_INODE_IO
);
8462 ei
->io_tree
.inode
= ei
;
8463 extent_io_tree_init(fs_info
, &ei
->file_extent_tree
,
8464 IO_TREE_INODE_FILE_EXTENT
);
8465 atomic_set(&ei
->sync_writers
, 0);
8466 mutex_init(&ei
->log_mutex
);
8467 btrfs_ordered_inode_tree_init(&ei
->ordered_tree
);
8468 INIT_LIST_HEAD(&ei
->delalloc_inodes
);
8469 INIT_LIST_HEAD(&ei
->delayed_iput
);
8470 RB_CLEAR_NODE(&ei
->rb_node
);
8471 init_rwsem(&ei
->i_mmap_lock
);
8476 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8477 void btrfs_test_destroy_inode(struct inode
*inode
)
8479 btrfs_drop_extent_map_range(BTRFS_I(inode
), 0, (u64
)-1, false);
8480 kmem_cache_free(btrfs_inode_cachep
, BTRFS_I(inode
));
8484 void btrfs_free_inode(struct inode
*inode
)
8486 kmem_cache_free(btrfs_inode_cachep
, BTRFS_I(inode
));
8489 void btrfs_destroy_inode(struct inode
*vfs_inode
)
8491 struct btrfs_ordered_extent
*ordered
;
8492 struct btrfs_inode
*inode
= BTRFS_I(vfs_inode
);
8493 struct btrfs_root
*root
= inode
->root
;
8494 bool freespace_inode
;
8496 WARN_ON(!hlist_empty(&vfs_inode
->i_dentry
));
8497 WARN_ON(vfs_inode
->i_data
.nrpages
);
8498 WARN_ON(inode
->block_rsv
.reserved
);
8499 WARN_ON(inode
->block_rsv
.size
);
8500 WARN_ON(inode
->outstanding_extents
);
8501 if (!S_ISDIR(vfs_inode
->i_mode
)) {
8502 WARN_ON(inode
->delalloc_bytes
);
8503 WARN_ON(inode
->new_delalloc_bytes
);
8505 WARN_ON(inode
->csum_bytes
);
8506 WARN_ON(inode
->defrag_bytes
);
8509 * This can happen where we create an inode, but somebody else also
8510 * created the same inode and we need to destroy the one we already
8517 * If this is a free space inode do not take the ordered extents lockdep
8520 freespace_inode
= btrfs_is_free_space_inode(inode
);
8523 ordered
= btrfs_lookup_first_ordered_extent(inode
, (u64
)-1);
8527 btrfs_err(root
->fs_info
,
8528 "found ordered extent %llu %llu on inode cleanup",
8529 ordered
->file_offset
, ordered
->num_bytes
);
8531 if (!freespace_inode
)
8532 btrfs_lockdep_acquire(root
->fs_info
, btrfs_ordered_extent
);
8534 btrfs_remove_ordered_extent(inode
, ordered
);
8535 btrfs_put_ordered_extent(ordered
);
8536 btrfs_put_ordered_extent(ordered
);
8539 btrfs_qgroup_check_reserved_leak(inode
);
8540 inode_tree_del(inode
);
8541 btrfs_drop_extent_map_range(inode
, 0, (u64
)-1, false);
8542 btrfs_inode_clear_file_extent_range(inode
, 0, (u64
)-1);
8543 btrfs_put_root(inode
->root
);
8546 int btrfs_drop_inode(struct inode
*inode
)
8548 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
8553 /* the snap/subvol tree is on deleting */
8554 if (btrfs_root_refs(&root
->root_item
) == 0)
8557 return generic_drop_inode(inode
);
8560 static void init_once(void *foo
)
8562 struct btrfs_inode
*ei
= foo
;
8564 inode_init_once(&ei
->vfs_inode
);
8567 void __cold
btrfs_destroy_cachep(void)
8570 * Make sure all delayed rcu free inodes are flushed before we
8574 bioset_exit(&btrfs_dio_bioset
);
8575 kmem_cache_destroy(btrfs_inode_cachep
);
8578 int __init
btrfs_init_cachep(void)
8580 btrfs_inode_cachep
= kmem_cache_create("btrfs_inode",
8581 sizeof(struct btrfs_inode
), 0,
8582 SLAB_RECLAIM_ACCOUNT
| SLAB_MEM_SPREAD
| SLAB_ACCOUNT
,
8584 if (!btrfs_inode_cachep
)
8587 if (bioset_init(&btrfs_dio_bioset
, BIO_POOL_SIZE
,
8588 offsetof(struct btrfs_dio_private
, bbio
.bio
),
8594 btrfs_destroy_cachep();
8598 static int btrfs_getattr(struct mnt_idmap
*idmap
,
8599 const struct path
*path
, struct kstat
*stat
,
8600 u32 request_mask
, unsigned int flags
)
8604 struct inode
*inode
= d_inode(path
->dentry
);
8605 u32 blocksize
= inode
->i_sb
->s_blocksize
;
8606 u32 bi_flags
= BTRFS_I(inode
)->flags
;
8607 u32 bi_ro_flags
= BTRFS_I(inode
)->ro_flags
;
8609 stat
->result_mask
|= STATX_BTIME
;
8610 stat
->btime
.tv_sec
= BTRFS_I(inode
)->i_otime
.tv_sec
;
8611 stat
->btime
.tv_nsec
= BTRFS_I(inode
)->i_otime
.tv_nsec
;
8612 if (bi_flags
& BTRFS_INODE_APPEND
)
8613 stat
->attributes
|= STATX_ATTR_APPEND
;
8614 if (bi_flags
& BTRFS_INODE_COMPRESS
)
8615 stat
->attributes
|= STATX_ATTR_COMPRESSED
;
8616 if (bi_flags
& BTRFS_INODE_IMMUTABLE
)
8617 stat
->attributes
|= STATX_ATTR_IMMUTABLE
;
8618 if (bi_flags
& BTRFS_INODE_NODUMP
)
8619 stat
->attributes
|= STATX_ATTR_NODUMP
;
8620 if (bi_ro_flags
& BTRFS_INODE_RO_VERITY
)
8621 stat
->attributes
|= STATX_ATTR_VERITY
;
8623 stat
->attributes_mask
|= (STATX_ATTR_APPEND
|
8624 STATX_ATTR_COMPRESSED
|
8625 STATX_ATTR_IMMUTABLE
|
8628 generic_fillattr(idmap
, inode
, stat
);
8629 stat
->dev
= BTRFS_I(inode
)->root
->anon_dev
;
8631 spin_lock(&BTRFS_I(inode
)->lock
);
8632 delalloc_bytes
= BTRFS_I(inode
)->new_delalloc_bytes
;
8633 inode_bytes
= inode_get_bytes(inode
);
8634 spin_unlock(&BTRFS_I(inode
)->lock
);
8635 stat
->blocks
= (ALIGN(inode_bytes
, blocksize
) +
8636 ALIGN(delalloc_bytes
, blocksize
)) >> 9;
8640 static int btrfs_rename_exchange(struct inode
*old_dir
,
8641 struct dentry
*old_dentry
,
8642 struct inode
*new_dir
,
8643 struct dentry
*new_dentry
)
8645 struct btrfs_fs_info
*fs_info
= btrfs_sb(old_dir
->i_sb
);
8646 struct btrfs_trans_handle
*trans
;
8647 unsigned int trans_num_items
;
8648 struct btrfs_root
*root
= BTRFS_I(old_dir
)->root
;
8649 struct btrfs_root
*dest
= BTRFS_I(new_dir
)->root
;
8650 struct inode
*new_inode
= new_dentry
->d_inode
;
8651 struct inode
*old_inode
= old_dentry
->d_inode
;
8652 struct timespec64 ctime
= current_time(old_inode
);
8653 struct btrfs_rename_ctx old_rename_ctx
;
8654 struct btrfs_rename_ctx new_rename_ctx
;
8655 u64 old_ino
= btrfs_ino(BTRFS_I(old_inode
));
8656 u64 new_ino
= btrfs_ino(BTRFS_I(new_inode
));
8661 bool need_abort
= false;
8662 struct fscrypt_name old_fname
, new_fname
;
8663 struct fscrypt_str
*old_name
, *new_name
;
8666 * For non-subvolumes allow exchange only within one subvolume, in the
8667 * same inode namespace. Two subvolumes (represented as directory) can
8668 * be exchanged as they're a logical link and have a fixed inode number.
8671 (old_ino
!= BTRFS_FIRST_FREE_OBJECTID
||
8672 new_ino
!= BTRFS_FIRST_FREE_OBJECTID
))
8675 ret
= fscrypt_setup_filename(old_dir
, &old_dentry
->d_name
, 0, &old_fname
);
8679 ret
= fscrypt_setup_filename(new_dir
, &new_dentry
->d_name
, 0, &new_fname
);
8681 fscrypt_free_filename(&old_fname
);
8685 old_name
= &old_fname
.disk_name
;
8686 new_name
= &new_fname
.disk_name
;
8688 /* close the race window with snapshot create/destroy ioctl */
8689 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
||
8690 new_ino
== BTRFS_FIRST_FREE_OBJECTID
)
8691 down_read(&fs_info
->subvol_sem
);
8695 * 1 to remove old dir item
8696 * 1 to remove old dir index
8697 * 1 to add new dir item
8698 * 1 to add new dir index
8699 * 1 to update parent inode
8701 * If the parents are the same, we only need to account for one
8703 trans_num_items
= (old_dir
== new_dir
? 9 : 10);
8704 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
8706 * 1 to remove old root ref
8707 * 1 to remove old root backref
8708 * 1 to add new root ref
8709 * 1 to add new root backref
8711 trans_num_items
+= 4;
8714 * 1 to update inode item
8715 * 1 to remove old inode ref
8716 * 1 to add new inode ref
8718 trans_num_items
+= 3;
8720 if (new_ino
== BTRFS_FIRST_FREE_OBJECTID
)
8721 trans_num_items
+= 4;
8723 trans_num_items
+= 3;
8724 trans
= btrfs_start_transaction(root
, trans_num_items
);
8725 if (IS_ERR(trans
)) {
8726 ret
= PTR_ERR(trans
);
8731 ret
= btrfs_record_root_in_trans(trans
, dest
);
8737 * We need to find a free sequence number both in the source and
8738 * in the destination directory for the exchange.
8740 ret
= btrfs_set_inode_index(BTRFS_I(new_dir
), &old_idx
);
8743 ret
= btrfs_set_inode_index(BTRFS_I(old_dir
), &new_idx
);
8747 BTRFS_I(old_inode
)->dir_index
= 0ULL;
8748 BTRFS_I(new_inode
)->dir_index
= 0ULL;
8750 /* Reference for the source. */
8751 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
8752 /* force full log commit if subvolume involved. */
8753 btrfs_set_log_full_commit(trans
);
8755 ret
= btrfs_insert_inode_ref(trans
, dest
, new_name
, old_ino
,
8756 btrfs_ino(BTRFS_I(new_dir
)),
8763 /* And now for the dest. */
8764 if (new_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
8765 /* force full log commit if subvolume involved. */
8766 btrfs_set_log_full_commit(trans
);
8768 ret
= btrfs_insert_inode_ref(trans
, root
, old_name
, new_ino
,
8769 btrfs_ino(BTRFS_I(old_dir
)),
8773 btrfs_abort_transaction(trans
, ret
);
8778 /* Update inode version and ctime/mtime. */
8779 inode_inc_iversion(old_dir
);
8780 inode_inc_iversion(new_dir
);
8781 inode_inc_iversion(old_inode
);
8782 inode_inc_iversion(new_inode
);
8783 old_dir
->i_mtime
= ctime
;
8784 old_dir
->i_ctime
= ctime
;
8785 new_dir
->i_mtime
= ctime
;
8786 new_dir
->i_ctime
= ctime
;
8787 old_inode
->i_ctime
= ctime
;
8788 new_inode
->i_ctime
= ctime
;
8790 if (old_dentry
->d_parent
!= new_dentry
->d_parent
) {
8791 btrfs_record_unlink_dir(trans
, BTRFS_I(old_dir
),
8792 BTRFS_I(old_inode
), 1);
8793 btrfs_record_unlink_dir(trans
, BTRFS_I(new_dir
),
8794 BTRFS_I(new_inode
), 1);
8797 /* src is a subvolume */
8798 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
8799 ret
= btrfs_unlink_subvol(trans
, BTRFS_I(old_dir
), old_dentry
);
8800 } else { /* src is an inode */
8801 ret
= __btrfs_unlink_inode(trans
, BTRFS_I(old_dir
),
8802 BTRFS_I(old_dentry
->d_inode
),
8803 old_name
, &old_rename_ctx
);
8805 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(old_inode
));
8808 btrfs_abort_transaction(trans
, ret
);
8812 /* dest is a subvolume */
8813 if (new_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
8814 ret
= btrfs_unlink_subvol(trans
, BTRFS_I(new_dir
), new_dentry
);
8815 } else { /* dest is an inode */
8816 ret
= __btrfs_unlink_inode(trans
, BTRFS_I(new_dir
),
8817 BTRFS_I(new_dentry
->d_inode
),
8818 new_name
, &new_rename_ctx
);
8820 ret
= btrfs_update_inode(trans
, dest
, BTRFS_I(new_inode
));
8823 btrfs_abort_transaction(trans
, ret
);
8827 ret
= btrfs_add_link(trans
, BTRFS_I(new_dir
), BTRFS_I(old_inode
),
8828 new_name
, 0, old_idx
);
8830 btrfs_abort_transaction(trans
, ret
);
8834 ret
= btrfs_add_link(trans
, BTRFS_I(old_dir
), BTRFS_I(new_inode
),
8835 old_name
, 0, new_idx
);
8837 btrfs_abort_transaction(trans
, ret
);
8841 if (old_inode
->i_nlink
== 1)
8842 BTRFS_I(old_inode
)->dir_index
= old_idx
;
8843 if (new_inode
->i_nlink
== 1)
8844 BTRFS_I(new_inode
)->dir_index
= new_idx
;
8847 * Now pin the logs of the roots. We do it to ensure that no other task
8848 * can sync the logs while we are in progress with the rename, because
8849 * that could result in an inconsistency in case any of the inodes that
8850 * are part of this rename operation were logged before.
8852 if (old_ino
!= BTRFS_FIRST_FREE_OBJECTID
)
8853 btrfs_pin_log_trans(root
);
8854 if (new_ino
!= BTRFS_FIRST_FREE_OBJECTID
)
8855 btrfs_pin_log_trans(dest
);
8857 /* Do the log updates for all inodes. */
8858 if (old_ino
!= BTRFS_FIRST_FREE_OBJECTID
)
8859 btrfs_log_new_name(trans
, old_dentry
, BTRFS_I(old_dir
),
8860 old_rename_ctx
.index
, new_dentry
->d_parent
);
8861 if (new_ino
!= BTRFS_FIRST_FREE_OBJECTID
)
8862 btrfs_log_new_name(trans
, new_dentry
, BTRFS_I(new_dir
),
8863 new_rename_ctx
.index
, old_dentry
->d_parent
);
8865 /* Now unpin the logs. */
8866 if (old_ino
!= BTRFS_FIRST_FREE_OBJECTID
)
8867 btrfs_end_log_trans(root
);
8868 if (new_ino
!= BTRFS_FIRST_FREE_OBJECTID
)
8869 btrfs_end_log_trans(dest
);
8871 ret2
= btrfs_end_transaction(trans
);
8872 ret
= ret
? ret
: ret2
;
8874 if (new_ino
== BTRFS_FIRST_FREE_OBJECTID
||
8875 old_ino
== BTRFS_FIRST_FREE_OBJECTID
)
8876 up_read(&fs_info
->subvol_sem
);
8878 fscrypt_free_filename(&new_fname
);
8879 fscrypt_free_filename(&old_fname
);
8883 static struct inode
*new_whiteout_inode(struct mnt_idmap
*idmap
,
8886 struct inode
*inode
;
8888 inode
= new_inode(dir
->i_sb
);
8890 inode_init_owner(idmap
, inode
, dir
,
8891 S_IFCHR
| WHITEOUT_MODE
);
8892 inode
->i_op
= &btrfs_special_inode_operations
;
8893 init_special_inode(inode
, inode
->i_mode
, WHITEOUT_DEV
);
8898 static int btrfs_rename(struct mnt_idmap
*idmap
,
8899 struct inode
*old_dir
, struct dentry
*old_dentry
,
8900 struct inode
*new_dir
, struct dentry
*new_dentry
,
8903 struct btrfs_fs_info
*fs_info
= btrfs_sb(old_dir
->i_sb
);
8904 struct btrfs_new_inode_args whiteout_args
= {
8906 .dentry
= old_dentry
,
8908 struct btrfs_trans_handle
*trans
;
8909 unsigned int trans_num_items
;
8910 struct btrfs_root
*root
= BTRFS_I(old_dir
)->root
;
8911 struct btrfs_root
*dest
= BTRFS_I(new_dir
)->root
;
8912 struct inode
*new_inode
= d_inode(new_dentry
);
8913 struct inode
*old_inode
= d_inode(old_dentry
);
8914 struct btrfs_rename_ctx rename_ctx
;
8918 u64 old_ino
= btrfs_ino(BTRFS_I(old_inode
));
8919 struct fscrypt_name old_fname
, new_fname
;
8921 if (btrfs_ino(BTRFS_I(new_dir
)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
)
8924 /* we only allow rename subvolume link between subvolumes */
8925 if (old_ino
!= BTRFS_FIRST_FREE_OBJECTID
&& root
!= dest
)
8928 if (old_ino
== BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
||
8929 (new_inode
&& btrfs_ino(BTRFS_I(new_inode
)) == BTRFS_FIRST_FREE_OBJECTID
))
8932 if (S_ISDIR(old_inode
->i_mode
) && new_inode
&&
8933 new_inode
->i_size
> BTRFS_EMPTY_DIR_SIZE
)
8936 ret
= fscrypt_setup_filename(old_dir
, &old_dentry
->d_name
, 0, &old_fname
);
8940 ret
= fscrypt_setup_filename(new_dir
, &new_dentry
->d_name
, 0, &new_fname
);
8942 fscrypt_free_filename(&old_fname
);
8946 /* check for collisions, even if the name isn't there */
8947 ret
= btrfs_check_dir_item_collision(dest
, new_dir
->i_ino
, &new_fname
.disk_name
);
8949 if (ret
== -EEXIST
) {
8951 * eexist without a new_inode */
8952 if (WARN_ON(!new_inode
)) {
8953 goto out_fscrypt_names
;
8956 /* maybe -EOVERFLOW */
8957 goto out_fscrypt_names
;
8963 * we're using rename to replace one file with another. Start IO on it
8964 * now so we don't add too much work to the end of the transaction
8966 if (new_inode
&& S_ISREG(old_inode
->i_mode
) && new_inode
->i_size
)
8967 filemap_flush(old_inode
->i_mapping
);
8969 if (flags
& RENAME_WHITEOUT
) {
8970 whiteout_args
.inode
= new_whiteout_inode(idmap
, old_dir
);
8971 if (!whiteout_args
.inode
) {
8973 goto out_fscrypt_names
;
8975 ret
= btrfs_new_inode_prepare(&whiteout_args
, &trans_num_items
);
8977 goto out_whiteout_inode
;
8979 /* 1 to update the old parent inode. */
8980 trans_num_items
= 1;
8983 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
8984 /* Close the race window with snapshot create/destroy ioctl */
8985 down_read(&fs_info
->subvol_sem
);
8987 * 1 to remove old root ref
8988 * 1 to remove old root backref
8989 * 1 to add new root ref
8990 * 1 to add new root backref
8992 trans_num_items
+= 4;
8996 * 1 to remove old inode ref
8997 * 1 to add new inode ref
8999 trans_num_items
+= 3;
9002 * 1 to remove old dir item
9003 * 1 to remove old dir index
9004 * 1 to add new dir item
9005 * 1 to add new dir index
9007 trans_num_items
+= 4;
9008 /* 1 to update new parent inode if it's not the same as the old parent */
9009 if (new_dir
!= old_dir
)
9014 * 1 to remove inode ref
9015 * 1 to remove dir item
9016 * 1 to remove dir index
9017 * 1 to possibly add orphan item
9019 trans_num_items
+= 5;
9021 trans
= btrfs_start_transaction(root
, trans_num_items
);
9022 if (IS_ERR(trans
)) {
9023 ret
= PTR_ERR(trans
);
9028 ret
= btrfs_record_root_in_trans(trans
, dest
);
9033 ret
= btrfs_set_inode_index(BTRFS_I(new_dir
), &index
);
9037 BTRFS_I(old_inode
)->dir_index
= 0ULL;
9038 if (unlikely(old_ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
9039 /* force full log commit if subvolume involved. */
9040 btrfs_set_log_full_commit(trans
);
9042 ret
= btrfs_insert_inode_ref(trans
, dest
, &new_fname
.disk_name
,
9043 old_ino
, btrfs_ino(BTRFS_I(new_dir
)),
9049 inode_inc_iversion(old_dir
);
9050 inode_inc_iversion(new_dir
);
9051 inode_inc_iversion(old_inode
);
9052 old_dir
->i_mtime
= current_time(old_dir
);
9053 old_dir
->i_ctime
= old_dir
->i_mtime
;
9054 new_dir
->i_mtime
= old_dir
->i_mtime
;
9055 new_dir
->i_ctime
= old_dir
->i_mtime
;
9056 old_inode
->i_ctime
= old_dir
->i_mtime
;
9058 if (old_dentry
->d_parent
!= new_dentry
->d_parent
)
9059 btrfs_record_unlink_dir(trans
, BTRFS_I(old_dir
),
9060 BTRFS_I(old_inode
), 1);
9062 if (unlikely(old_ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
9063 ret
= btrfs_unlink_subvol(trans
, BTRFS_I(old_dir
), old_dentry
);
9065 ret
= __btrfs_unlink_inode(trans
, BTRFS_I(old_dir
),
9066 BTRFS_I(d_inode(old_dentry
)),
9067 &old_fname
.disk_name
, &rename_ctx
);
9069 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(old_inode
));
9072 btrfs_abort_transaction(trans
, ret
);
9077 inode_inc_iversion(new_inode
);
9078 new_inode
->i_ctime
= current_time(new_inode
);
9079 if (unlikely(btrfs_ino(BTRFS_I(new_inode
)) ==
9080 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
)) {
9081 ret
= btrfs_unlink_subvol(trans
, BTRFS_I(new_dir
), new_dentry
);
9082 BUG_ON(new_inode
->i_nlink
== 0);
9084 ret
= btrfs_unlink_inode(trans
, BTRFS_I(new_dir
),
9085 BTRFS_I(d_inode(new_dentry
)),
9086 &new_fname
.disk_name
);
9088 if (!ret
&& new_inode
->i_nlink
== 0)
9089 ret
= btrfs_orphan_add(trans
,
9090 BTRFS_I(d_inode(new_dentry
)));
9092 btrfs_abort_transaction(trans
, ret
);
9097 ret
= btrfs_add_link(trans
, BTRFS_I(new_dir
), BTRFS_I(old_inode
),
9098 &new_fname
.disk_name
, 0, index
);
9100 btrfs_abort_transaction(trans
, ret
);
9104 if (old_inode
->i_nlink
== 1)
9105 BTRFS_I(old_inode
)->dir_index
= index
;
9107 if (old_ino
!= BTRFS_FIRST_FREE_OBJECTID
)
9108 btrfs_log_new_name(trans
, old_dentry
, BTRFS_I(old_dir
),
9109 rename_ctx
.index
, new_dentry
->d_parent
);
9111 if (flags
& RENAME_WHITEOUT
) {
9112 ret
= btrfs_create_new_inode(trans
, &whiteout_args
);
9114 btrfs_abort_transaction(trans
, ret
);
9117 unlock_new_inode(whiteout_args
.inode
);
9118 iput(whiteout_args
.inode
);
9119 whiteout_args
.inode
= NULL
;
9123 ret2
= btrfs_end_transaction(trans
);
9124 ret
= ret
? ret
: ret2
;
9126 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
)
9127 up_read(&fs_info
->subvol_sem
);
9128 if (flags
& RENAME_WHITEOUT
)
9129 btrfs_new_inode_args_destroy(&whiteout_args
);
9131 if (flags
& RENAME_WHITEOUT
)
9132 iput(whiteout_args
.inode
);
9134 fscrypt_free_filename(&old_fname
);
9135 fscrypt_free_filename(&new_fname
);
9139 static int btrfs_rename2(struct mnt_idmap
*idmap
, struct inode
*old_dir
,
9140 struct dentry
*old_dentry
, struct inode
*new_dir
,
9141 struct dentry
*new_dentry
, unsigned int flags
)
9145 if (flags
& ~(RENAME_NOREPLACE
| RENAME_EXCHANGE
| RENAME_WHITEOUT
))
9148 if (flags
& RENAME_EXCHANGE
)
9149 ret
= btrfs_rename_exchange(old_dir
, old_dentry
, new_dir
,
9152 ret
= btrfs_rename(idmap
, old_dir
, old_dentry
, new_dir
,
9155 btrfs_btree_balance_dirty(BTRFS_I(new_dir
)->root
->fs_info
);
9160 struct btrfs_delalloc_work
{
9161 struct inode
*inode
;
9162 struct completion completion
;
9163 struct list_head list
;
9164 struct btrfs_work work
;
9167 static void btrfs_run_delalloc_work(struct btrfs_work
*work
)
9169 struct btrfs_delalloc_work
*delalloc_work
;
9170 struct inode
*inode
;
9172 delalloc_work
= container_of(work
, struct btrfs_delalloc_work
,
9174 inode
= delalloc_work
->inode
;
9175 filemap_flush(inode
->i_mapping
);
9176 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT
,
9177 &BTRFS_I(inode
)->runtime_flags
))
9178 filemap_flush(inode
->i_mapping
);
9181 complete(&delalloc_work
->completion
);
9184 static struct btrfs_delalloc_work
*btrfs_alloc_delalloc_work(struct inode
*inode
)
9186 struct btrfs_delalloc_work
*work
;
9188 work
= kmalloc(sizeof(*work
), GFP_NOFS
);
9192 init_completion(&work
->completion
);
9193 INIT_LIST_HEAD(&work
->list
);
9194 work
->inode
= inode
;
9195 btrfs_init_work(&work
->work
, btrfs_run_delalloc_work
, NULL
, NULL
);
9201 * some fairly slow code that needs optimization. This walks the list
9202 * of all the inodes with pending delalloc and forces them to disk.
9204 static int start_delalloc_inodes(struct btrfs_root
*root
,
9205 struct writeback_control
*wbc
, bool snapshot
,
9206 bool in_reclaim_context
)
9208 struct btrfs_inode
*binode
;
9209 struct inode
*inode
;
9210 struct btrfs_delalloc_work
*work
, *next
;
9211 struct list_head works
;
9212 struct list_head splice
;
9214 bool full_flush
= wbc
->nr_to_write
== LONG_MAX
;
9216 INIT_LIST_HEAD(&works
);
9217 INIT_LIST_HEAD(&splice
);
9219 mutex_lock(&root
->delalloc_mutex
);
9220 spin_lock(&root
->delalloc_lock
);
9221 list_splice_init(&root
->delalloc_inodes
, &splice
);
9222 while (!list_empty(&splice
)) {
9223 binode
= list_entry(splice
.next
, struct btrfs_inode
,
9226 list_move_tail(&binode
->delalloc_inodes
,
9227 &root
->delalloc_inodes
);
9229 if (in_reclaim_context
&&
9230 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH
, &binode
->runtime_flags
))
9233 inode
= igrab(&binode
->vfs_inode
);
9235 cond_resched_lock(&root
->delalloc_lock
);
9238 spin_unlock(&root
->delalloc_lock
);
9241 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH
,
9242 &binode
->runtime_flags
);
9244 work
= btrfs_alloc_delalloc_work(inode
);
9250 list_add_tail(&work
->list
, &works
);
9251 btrfs_queue_work(root
->fs_info
->flush_workers
,
9254 ret
= filemap_fdatawrite_wbc(inode
->i_mapping
, wbc
);
9255 btrfs_add_delayed_iput(BTRFS_I(inode
));
9256 if (ret
|| wbc
->nr_to_write
<= 0)
9260 spin_lock(&root
->delalloc_lock
);
9262 spin_unlock(&root
->delalloc_lock
);
9265 list_for_each_entry_safe(work
, next
, &works
, list
) {
9266 list_del_init(&work
->list
);
9267 wait_for_completion(&work
->completion
);
9271 if (!list_empty(&splice
)) {
9272 spin_lock(&root
->delalloc_lock
);
9273 list_splice_tail(&splice
, &root
->delalloc_inodes
);
9274 spin_unlock(&root
->delalloc_lock
);
9276 mutex_unlock(&root
->delalloc_mutex
);
9280 int btrfs_start_delalloc_snapshot(struct btrfs_root
*root
, bool in_reclaim_context
)
9282 struct writeback_control wbc
= {
9283 .nr_to_write
= LONG_MAX
,
9284 .sync_mode
= WB_SYNC_NONE
,
9286 .range_end
= LLONG_MAX
,
9288 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
9290 if (BTRFS_FS_ERROR(fs_info
))
9293 return start_delalloc_inodes(root
, &wbc
, true, in_reclaim_context
);
9296 int btrfs_start_delalloc_roots(struct btrfs_fs_info
*fs_info
, long nr
,
9297 bool in_reclaim_context
)
9299 struct writeback_control wbc
= {
9301 .sync_mode
= WB_SYNC_NONE
,
9303 .range_end
= LLONG_MAX
,
9305 struct btrfs_root
*root
;
9306 struct list_head splice
;
9309 if (BTRFS_FS_ERROR(fs_info
))
9312 INIT_LIST_HEAD(&splice
);
9314 mutex_lock(&fs_info
->delalloc_root_mutex
);
9315 spin_lock(&fs_info
->delalloc_root_lock
);
9316 list_splice_init(&fs_info
->delalloc_roots
, &splice
);
9317 while (!list_empty(&splice
)) {
9319 * Reset nr_to_write here so we know that we're doing a full
9323 wbc
.nr_to_write
= LONG_MAX
;
9325 root
= list_first_entry(&splice
, struct btrfs_root
,
9327 root
= btrfs_grab_root(root
);
9329 list_move_tail(&root
->delalloc_root
,
9330 &fs_info
->delalloc_roots
);
9331 spin_unlock(&fs_info
->delalloc_root_lock
);
9333 ret
= start_delalloc_inodes(root
, &wbc
, false, in_reclaim_context
);
9334 btrfs_put_root(root
);
9335 if (ret
< 0 || wbc
.nr_to_write
<= 0)
9337 spin_lock(&fs_info
->delalloc_root_lock
);
9339 spin_unlock(&fs_info
->delalloc_root_lock
);
9343 if (!list_empty(&splice
)) {
9344 spin_lock(&fs_info
->delalloc_root_lock
);
9345 list_splice_tail(&splice
, &fs_info
->delalloc_roots
);
9346 spin_unlock(&fs_info
->delalloc_root_lock
);
9348 mutex_unlock(&fs_info
->delalloc_root_mutex
);
9352 static int btrfs_symlink(struct mnt_idmap
*idmap
, struct inode
*dir
,
9353 struct dentry
*dentry
, const char *symname
)
9355 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
9356 struct btrfs_trans_handle
*trans
;
9357 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
9358 struct btrfs_path
*path
;
9359 struct btrfs_key key
;
9360 struct inode
*inode
;
9361 struct btrfs_new_inode_args new_inode_args
= {
9365 unsigned int trans_num_items
;
9370 struct btrfs_file_extent_item
*ei
;
9371 struct extent_buffer
*leaf
;
9373 name_len
= strlen(symname
);
9374 if (name_len
> BTRFS_MAX_INLINE_DATA_SIZE(fs_info
))
9375 return -ENAMETOOLONG
;
9377 inode
= new_inode(dir
->i_sb
);
9380 inode_init_owner(idmap
, inode
, dir
, S_IFLNK
| S_IRWXUGO
);
9381 inode
->i_op
= &btrfs_symlink_inode_operations
;
9382 inode_nohighmem(inode
);
9383 inode
->i_mapping
->a_ops
= &btrfs_aops
;
9384 btrfs_i_size_write(BTRFS_I(inode
), name_len
);
9385 inode_set_bytes(inode
, name_len
);
9387 new_inode_args
.inode
= inode
;
9388 err
= btrfs_new_inode_prepare(&new_inode_args
, &trans_num_items
);
9391 /* 1 additional item for the inline extent */
9394 trans
= btrfs_start_transaction(root
, trans_num_items
);
9395 if (IS_ERR(trans
)) {
9396 err
= PTR_ERR(trans
);
9397 goto out_new_inode_args
;
9400 err
= btrfs_create_new_inode(trans
, &new_inode_args
);
9404 path
= btrfs_alloc_path();
9407 btrfs_abort_transaction(trans
, err
);
9408 discard_new_inode(inode
);
9412 key
.objectid
= btrfs_ino(BTRFS_I(inode
));
9414 key
.type
= BTRFS_EXTENT_DATA_KEY
;
9415 datasize
= btrfs_file_extent_calc_inline_size(name_len
);
9416 err
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
9419 btrfs_abort_transaction(trans
, err
);
9420 btrfs_free_path(path
);
9421 discard_new_inode(inode
);
9425 leaf
= path
->nodes
[0];
9426 ei
= btrfs_item_ptr(leaf
, path
->slots
[0],
9427 struct btrfs_file_extent_item
);
9428 btrfs_set_file_extent_generation(leaf
, ei
, trans
->transid
);
9429 btrfs_set_file_extent_type(leaf
, ei
,
9430 BTRFS_FILE_EXTENT_INLINE
);
9431 btrfs_set_file_extent_encryption(leaf
, ei
, 0);
9432 btrfs_set_file_extent_compression(leaf
, ei
, 0);
9433 btrfs_set_file_extent_other_encoding(leaf
, ei
, 0);
9434 btrfs_set_file_extent_ram_bytes(leaf
, ei
, name_len
);
9436 ptr
= btrfs_file_extent_inline_start(ei
);
9437 write_extent_buffer(leaf
, symname
, ptr
, name_len
);
9438 btrfs_mark_buffer_dirty(leaf
);
9439 btrfs_free_path(path
);
9441 d_instantiate_new(dentry
, inode
);
9444 btrfs_end_transaction(trans
);
9445 btrfs_btree_balance_dirty(fs_info
);
9447 btrfs_new_inode_args_destroy(&new_inode_args
);
9454 static struct btrfs_trans_handle
*insert_prealloc_file_extent(
9455 struct btrfs_trans_handle
*trans_in
,
9456 struct btrfs_inode
*inode
,
9457 struct btrfs_key
*ins
,
9460 struct btrfs_file_extent_item stack_fi
;
9461 struct btrfs_replace_extent_info extent_info
;
9462 struct btrfs_trans_handle
*trans
= trans_in
;
9463 struct btrfs_path
*path
;
9464 u64 start
= ins
->objectid
;
9465 u64 len
= ins
->offset
;
9466 int qgroup_released
;
9469 memset(&stack_fi
, 0, sizeof(stack_fi
));
9471 btrfs_set_stack_file_extent_type(&stack_fi
, BTRFS_FILE_EXTENT_PREALLOC
);
9472 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi
, start
);
9473 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi
, len
);
9474 btrfs_set_stack_file_extent_num_bytes(&stack_fi
, len
);
9475 btrfs_set_stack_file_extent_ram_bytes(&stack_fi
, len
);
9476 btrfs_set_stack_file_extent_compression(&stack_fi
, BTRFS_COMPRESS_NONE
);
9477 /* Encryption and other encoding is reserved and all 0 */
9479 qgroup_released
= btrfs_qgroup_release_data(inode
, file_offset
, len
);
9480 if (qgroup_released
< 0)
9481 return ERR_PTR(qgroup_released
);
9484 ret
= insert_reserved_file_extent(trans
, inode
,
9485 file_offset
, &stack_fi
,
9486 true, qgroup_released
);
9492 extent_info
.disk_offset
= start
;
9493 extent_info
.disk_len
= len
;
9494 extent_info
.data_offset
= 0;
9495 extent_info
.data_len
= len
;
9496 extent_info
.file_offset
= file_offset
;
9497 extent_info
.extent_buf
= (char *)&stack_fi
;
9498 extent_info
.is_new_extent
= true;
9499 extent_info
.update_times
= true;
9500 extent_info
.qgroup_reserved
= qgroup_released
;
9501 extent_info
.insertions
= 0;
9503 path
= btrfs_alloc_path();
9509 ret
= btrfs_replace_file_extents(inode
, path
, file_offset
,
9510 file_offset
+ len
- 1, &extent_info
,
9512 btrfs_free_path(path
);
9519 * We have released qgroup data range at the beginning of the function,
9520 * and normally qgroup_released bytes will be freed when committing
9522 * But if we error out early, we have to free what we have released
9523 * or we leak qgroup data reservation.
9525 btrfs_qgroup_free_refroot(inode
->root
->fs_info
,
9526 inode
->root
->root_key
.objectid
, qgroup_released
,
9527 BTRFS_QGROUP_RSV_DATA
);
9528 return ERR_PTR(ret
);
9531 static int __btrfs_prealloc_file_range(struct inode
*inode
, int mode
,
9532 u64 start
, u64 num_bytes
, u64 min_size
,
9533 loff_t actual_len
, u64
*alloc_hint
,
9534 struct btrfs_trans_handle
*trans
)
9536 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
9537 struct extent_map
*em
;
9538 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
9539 struct btrfs_key ins
;
9540 u64 cur_offset
= start
;
9541 u64 clear_offset
= start
;
9544 u64 last_alloc
= (u64
)-1;
9546 bool own_trans
= true;
9547 u64 end
= start
+ num_bytes
- 1;
9551 while (num_bytes
> 0) {
9552 cur_bytes
= min_t(u64
, num_bytes
, SZ_256M
);
9553 cur_bytes
= max(cur_bytes
, min_size
);
9555 * If we are severely fragmented we could end up with really
9556 * small allocations, so if the allocator is returning small
9557 * chunks lets make its job easier by only searching for those
9560 cur_bytes
= min(cur_bytes
, last_alloc
);
9561 ret
= btrfs_reserve_extent(root
, cur_bytes
, cur_bytes
,
9562 min_size
, 0, *alloc_hint
, &ins
, 1, 0);
9567 * We've reserved this space, and thus converted it from
9568 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9569 * from here on out we will only need to clear our reservation
9570 * for the remaining unreserved area, so advance our
9571 * clear_offset by our extent size.
9573 clear_offset
+= ins
.offset
;
9575 last_alloc
= ins
.offset
;
9576 trans
= insert_prealloc_file_extent(trans
, BTRFS_I(inode
),
9579 * Now that we inserted the prealloc extent we can finally
9580 * decrement the number of reservations in the block group.
9581 * If we did it before, we could race with relocation and have
9582 * relocation miss the reserved extent, making it fail later.
9584 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
9585 if (IS_ERR(trans
)) {
9586 ret
= PTR_ERR(trans
);
9587 btrfs_free_reserved_extent(fs_info
, ins
.objectid
,
9592 em
= alloc_extent_map();
9594 btrfs_drop_extent_map_range(BTRFS_I(inode
), cur_offset
,
9595 cur_offset
+ ins
.offset
- 1, false);
9596 btrfs_set_inode_full_sync(BTRFS_I(inode
));
9600 em
->start
= cur_offset
;
9601 em
->orig_start
= cur_offset
;
9602 em
->len
= ins
.offset
;
9603 em
->block_start
= ins
.objectid
;
9604 em
->block_len
= ins
.offset
;
9605 em
->orig_block_len
= ins
.offset
;
9606 em
->ram_bytes
= ins
.offset
;
9607 set_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
);
9608 em
->generation
= trans
->transid
;
9610 ret
= btrfs_replace_extent_map_range(BTRFS_I(inode
), em
, true);
9611 free_extent_map(em
);
9613 num_bytes
-= ins
.offset
;
9614 cur_offset
+= ins
.offset
;
9615 *alloc_hint
= ins
.objectid
+ ins
.offset
;
9617 inode_inc_iversion(inode
);
9618 inode
->i_ctime
= current_time(inode
);
9619 BTRFS_I(inode
)->flags
|= BTRFS_INODE_PREALLOC
;
9620 if (!(mode
& FALLOC_FL_KEEP_SIZE
) &&
9621 (actual_len
> inode
->i_size
) &&
9622 (cur_offset
> inode
->i_size
)) {
9623 if (cur_offset
> actual_len
)
9624 i_size
= actual_len
;
9626 i_size
= cur_offset
;
9627 i_size_write(inode
, i_size
);
9628 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode
), 0);
9631 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(inode
));
9634 btrfs_abort_transaction(trans
, ret
);
9636 btrfs_end_transaction(trans
);
9641 btrfs_end_transaction(trans
);
9645 if (clear_offset
< end
)
9646 btrfs_free_reserved_data_space(BTRFS_I(inode
), NULL
, clear_offset
,
9647 end
- clear_offset
+ 1);
9651 int btrfs_prealloc_file_range(struct inode
*inode
, int mode
,
9652 u64 start
, u64 num_bytes
, u64 min_size
,
9653 loff_t actual_len
, u64
*alloc_hint
)
9655 return __btrfs_prealloc_file_range(inode
, mode
, start
, num_bytes
,
9656 min_size
, actual_len
, alloc_hint
,
9660 int btrfs_prealloc_file_range_trans(struct inode
*inode
,
9661 struct btrfs_trans_handle
*trans
, int mode
,
9662 u64 start
, u64 num_bytes
, u64 min_size
,
9663 loff_t actual_len
, u64
*alloc_hint
)
9665 return __btrfs_prealloc_file_range(inode
, mode
, start
, num_bytes
,
9666 min_size
, actual_len
, alloc_hint
, trans
);
9669 static int btrfs_permission(struct mnt_idmap
*idmap
,
9670 struct inode
*inode
, int mask
)
9672 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
9673 umode_t mode
= inode
->i_mode
;
9675 if (mask
& MAY_WRITE
&&
9676 (S_ISREG(mode
) || S_ISDIR(mode
) || S_ISLNK(mode
))) {
9677 if (btrfs_root_readonly(root
))
9679 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_READONLY
)
9682 return generic_permission(idmap
, inode
, mask
);
9685 static int btrfs_tmpfile(struct mnt_idmap
*idmap
, struct inode
*dir
,
9686 struct file
*file
, umode_t mode
)
9688 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
9689 struct btrfs_trans_handle
*trans
;
9690 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
9691 struct inode
*inode
;
9692 struct btrfs_new_inode_args new_inode_args
= {
9694 .dentry
= file
->f_path
.dentry
,
9697 unsigned int trans_num_items
;
9700 inode
= new_inode(dir
->i_sb
);
9703 inode_init_owner(idmap
, inode
, dir
, mode
);
9704 inode
->i_fop
= &btrfs_file_operations
;
9705 inode
->i_op
= &btrfs_file_inode_operations
;
9706 inode
->i_mapping
->a_ops
= &btrfs_aops
;
9708 new_inode_args
.inode
= inode
;
9709 ret
= btrfs_new_inode_prepare(&new_inode_args
, &trans_num_items
);
9713 trans
= btrfs_start_transaction(root
, trans_num_items
);
9714 if (IS_ERR(trans
)) {
9715 ret
= PTR_ERR(trans
);
9716 goto out_new_inode_args
;
9719 ret
= btrfs_create_new_inode(trans
, &new_inode_args
);
9722 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9723 * set it to 1 because d_tmpfile() will issue a warning if the count is
9726 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9728 set_nlink(inode
, 1);
9731 d_tmpfile(file
, inode
);
9732 unlock_new_inode(inode
);
9733 mark_inode_dirty(inode
);
9736 btrfs_end_transaction(trans
);
9737 btrfs_btree_balance_dirty(fs_info
);
9739 btrfs_new_inode_args_destroy(&new_inode_args
);
9743 return finish_open_simple(file
, ret
);
9746 void btrfs_set_range_writeback(struct btrfs_inode
*inode
, u64 start
, u64 end
)
9748 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
9749 unsigned long index
= start
>> PAGE_SHIFT
;
9750 unsigned long end_index
= end
>> PAGE_SHIFT
;
9754 ASSERT(end
+ 1 - start
<= U32_MAX
);
9755 len
= end
+ 1 - start
;
9756 while (index
<= end_index
) {
9757 page
= find_get_page(inode
->vfs_inode
.i_mapping
, index
);
9758 ASSERT(page
); /* Pages should be in the extent_io_tree */
9760 btrfs_page_set_writeback(fs_info
, page
, start
, len
);
9766 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info
*fs_info
,
9769 switch (compress_type
) {
9770 case BTRFS_COMPRESS_NONE
:
9771 return BTRFS_ENCODED_IO_COMPRESSION_NONE
;
9772 case BTRFS_COMPRESS_ZLIB
:
9773 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB
;
9774 case BTRFS_COMPRESS_LZO
:
9776 * The LZO format depends on the sector size. 64K is the maximum
9777 * sector size that we support.
9779 if (fs_info
->sectorsize
< SZ_4K
|| fs_info
->sectorsize
> SZ_64K
)
9781 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K
+
9782 (fs_info
->sectorsize_bits
- 12);
9783 case BTRFS_COMPRESS_ZSTD
:
9784 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD
;
9790 static ssize_t
btrfs_encoded_read_inline(
9792 struct iov_iter
*iter
, u64 start
,
9794 struct extent_state
**cached_state
,
9795 u64 extent_start
, size_t count
,
9796 struct btrfs_ioctl_encoded_io_args
*encoded
,
9799 struct btrfs_inode
*inode
= BTRFS_I(file_inode(iocb
->ki_filp
));
9800 struct btrfs_root
*root
= inode
->root
;
9801 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
9802 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
9803 struct btrfs_path
*path
;
9804 struct extent_buffer
*leaf
;
9805 struct btrfs_file_extent_item
*item
;
9811 path
= btrfs_alloc_path();
9816 ret
= btrfs_lookup_file_extent(NULL
, root
, path
, btrfs_ino(inode
),
9820 /* The extent item disappeared? */
9825 leaf
= path
->nodes
[0];
9826 item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_file_extent_item
);
9828 ram_bytes
= btrfs_file_extent_ram_bytes(leaf
, item
);
9829 ptr
= btrfs_file_extent_inline_start(item
);
9831 encoded
->len
= min_t(u64
, extent_start
+ ram_bytes
,
9832 inode
->vfs_inode
.i_size
) - iocb
->ki_pos
;
9833 ret
= btrfs_encoded_io_compression_from_extent(fs_info
,
9834 btrfs_file_extent_compression(leaf
, item
));
9837 encoded
->compression
= ret
;
9838 if (encoded
->compression
) {
9841 inline_size
= btrfs_file_extent_inline_item_len(leaf
,
9843 if (inline_size
> count
) {
9847 count
= inline_size
;
9848 encoded
->unencoded_len
= ram_bytes
;
9849 encoded
->unencoded_offset
= iocb
->ki_pos
- extent_start
;
9851 count
= min_t(u64
, count
, encoded
->len
);
9852 encoded
->len
= count
;
9853 encoded
->unencoded_len
= count
;
9854 ptr
+= iocb
->ki_pos
- extent_start
;
9857 tmp
= kmalloc(count
, GFP_NOFS
);
9862 read_extent_buffer(leaf
, tmp
, ptr
, count
);
9863 btrfs_release_path(path
);
9864 unlock_extent(io_tree
, start
, lockend
, cached_state
);
9865 btrfs_inode_unlock(inode
, BTRFS_ILOCK_SHARED
);
9868 ret
= copy_to_iter(tmp
, count
, iter
);
9873 btrfs_free_path(path
);
9877 struct btrfs_encoded_read_private
{
9878 wait_queue_head_t wait
;
9880 blk_status_t status
;
9883 static void btrfs_encoded_read_endio(struct btrfs_bio
*bbio
)
9885 struct btrfs_encoded_read_private
*priv
= bbio
->private;
9887 if (bbio
->bio
.bi_status
) {
9889 * The memory barrier implied by the atomic_dec_return() here
9890 * pairs with the memory barrier implied by the
9891 * atomic_dec_return() or io_wait_event() in
9892 * btrfs_encoded_read_regular_fill_pages() to ensure that this
9893 * write is observed before the load of status in
9894 * btrfs_encoded_read_regular_fill_pages().
9896 WRITE_ONCE(priv
->status
, bbio
->bio
.bi_status
);
9898 if (!atomic_dec_return(&priv
->pending
))
9899 wake_up(&priv
->wait
);
9900 bio_put(&bbio
->bio
);
9903 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode
*inode
,
9904 u64 file_offset
, u64 disk_bytenr
,
9905 u64 disk_io_size
, struct page
**pages
)
9907 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
9908 struct btrfs_encoded_read_private priv
= {
9909 .pending
= ATOMIC_INIT(1),
9911 unsigned long i
= 0;
9912 struct btrfs_bio
*bbio
;
9914 init_waitqueue_head(&priv
.wait
);
9916 bbio
= btrfs_bio_alloc(BIO_MAX_VECS
, REQ_OP_READ
, fs_info
,
9917 btrfs_encoded_read_endio
, &priv
);
9918 bbio
->bio
.bi_iter
.bi_sector
= disk_bytenr
>> SECTOR_SHIFT
;
9919 bbio
->inode
= inode
;
9922 size_t bytes
= min_t(u64
, disk_io_size
, PAGE_SIZE
);
9924 if (bio_add_page(&bbio
->bio
, pages
[i
], bytes
, 0) < bytes
) {
9925 atomic_inc(&priv
.pending
);
9926 btrfs_submit_bio(bbio
, 0);
9928 bbio
= btrfs_bio_alloc(BIO_MAX_VECS
, REQ_OP_READ
, fs_info
,
9929 btrfs_encoded_read_endio
, &priv
);
9930 bbio
->bio
.bi_iter
.bi_sector
= disk_bytenr
>> SECTOR_SHIFT
;
9931 bbio
->inode
= inode
;
9936 disk_bytenr
+= bytes
;
9937 disk_io_size
-= bytes
;
9938 } while (disk_io_size
);
9940 atomic_inc(&priv
.pending
);
9941 btrfs_submit_bio(bbio
, 0);
9943 if (atomic_dec_return(&priv
.pending
))
9944 io_wait_event(priv
.wait
, !atomic_read(&priv
.pending
));
9945 /* See btrfs_encoded_read_endio() for ordering. */
9946 return blk_status_to_errno(READ_ONCE(priv
.status
));
9949 static ssize_t
btrfs_encoded_read_regular(struct kiocb
*iocb
,
9950 struct iov_iter
*iter
,
9951 u64 start
, u64 lockend
,
9952 struct extent_state
**cached_state
,
9953 u64 disk_bytenr
, u64 disk_io_size
,
9954 size_t count
, bool compressed
,
9957 struct btrfs_inode
*inode
= BTRFS_I(file_inode(iocb
->ki_filp
));
9958 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
9959 struct page
**pages
;
9960 unsigned long nr_pages
, i
;
9965 nr_pages
= DIV_ROUND_UP(disk_io_size
, PAGE_SIZE
);
9966 pages
= kcalloc(nr_pages
, sizeof(struct page
*), GFP_NOFS
);
9969 ret
= btrfs_alloc_page_array(nr_pages
, pages
);
9975 ret
= btrfs_encoded_read_regular_fill_pages(inode
, start
, disk_bytenr
,
9976 disk_io_size
, pages
);
9980 unlock_extent(io_tree
, start
, lockend
, cached_state
);
9981 btrfs_inode_unlock(inode
, BTRFS_ILOCK_SHARED
);
9988 i
= (iocb
->ki_pos
- start
) >> PAGE_SHIFT
;
9989 page_offset
= (iocb
->ki_pos
- start
) & (PAGE_SIZE
- 1);
9992 while (cur
< count
) {
9993 size_t bytes
= min_t(size_t, count
- cur
,
9994 PAGE_SIZE
- page_offset
);
9996 if (copy_page_to_iter(pages
[i
], page_offset
, bytes
,
10007 for (i
= 0; i
< nr_pages
; i
++) {
10009 __free_page(pages
[i
]);
10015 ssize_t
btrfs_encoded_read(struct kiocb
*iocb
, struct iov_iter
*iter
,
10016 struct btrfs_ioctl_encoded_io_args
*encoded
)
10018 struct btrfs_inode
*inode
= BTRFS_I(file_inode(iocb
->ki_filp
));
10019 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
10020 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
10022 size_t count
= iov_iter_count(iter
);
10023 u64 start
, lockend
, disk_bytenr
, disk_io_size
;
10024 struct extent_state
*cached_state
= NULL
;
10025 struct extent_map
*em
;
10026 bool unlocked
= false;
10028 file_accessed(iocb
->ki_filp
);
10030 btrfs_inode_lock(inode
, BTRFS_ILOCK_SHARED
);
10032 if (iocb
->ki_pos
>= inode
->vfs_inode
.i_size
) {
10033 btrfs_inode_unlock(inode
, BTRFS_ILOCK_SHARED
);
10036 start
= ALIGN_DOWN(iocb
->ki_pos
, fs_info
->sectorsize
);
10038 * We don't know how long the extent containing iocb->ki_pos is, but if
10039 * it's compressed we know that it won't be longer than this.
10041 lockend
= start
+ BTRFS_MAX_UNCOMPRESSED
- 1;
10044 struct btrfs_ordered_extent
*ordered
;
10046 ret
= btrfs_wait_ordered_range(&inode
->vfs_inode
, start
,
10047 lockend
- start
+ 1);
10049 goto out_unlock_inode
;
10050 lock_extent(io_tree
, start
, lockend
, &cached_state
);
10051 ordered
= btrfs_lookup_ordered_range(inode
, start
,
10052 lockend
- start
+ 1);
10055 btrfs_put_ordered_extent(ordered
);
10056 unlock_extent(io_tree
, start
, lockend
, &cached_state
);
10060 em
= btrfs_get_extent(inode
, NULL
, 0, start
, lockend
- start
+ 1);
10063 goto out_unlock_extent
;
10066 if (em
->block_start
== EXTENT_MAP_INLINE
) {
10067 u64 extent_start
= em
->start
;
10070 * For inline extents we get everything we need out of the
10073 free_extent_map(em
);
10075 ret
= btrfs_encoded_read_inline(iocb
, iter
, start
, lockend
,
10076 &cached_state
, extent_start
,
10077 count
, encoded
, &unlocked
);
10082 * We only want to return up to EOF even if the extent extends beyond
10085 encoded
->len
= min_t(u64
, extent_map_end(em
),
10086 inode
->vfs_inode
.i_size
) - iocb
->ki_pos
;
10087 if (em
->block_start
== EXTENT_MAP_HOLE
||
10088 test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)) {
10089 disk_bytenr
= EXTENT_MAP_HOLE
;
10090 count
= min_t(u64
, count
, encoded
->len
);
10091 encoded
->len
= count
;
10092 encoded
->unencoded_len
= count
;
10093 } else if (test_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
)) {
10094 disk_bytenr
= em
->block_start
;
10096 * Bail if the buffer isn't large enough to return the whole
10097 * compressed extent.
10099 if (em
->block_len
> count
) {
10103 disk_io_size
= em
->block_len
;
10104 count
= em
->block_len
;
10105 encoded
->unencoded_len
= em
->ram_bytes
;
10106 encoded
->unencoded_offset
= iocb
->ki_pos
- em
->orig_start
;
10107 ret
= btrfs_encoded_io_compression_from_extent(fs_info
,
10108 em
->compress_type
);
10111 encoded
->compression
= ret
;
10113 disk_bytenr
= em
->block_start
+ (start
- em
->start
);
10114 if (encoded
->len
> count
)
10115 encoded
->len
= count
;
10117 * Don't read beyond what we locked. This also limits the page
10118 * allocations that we'll do.
10120 disk_io_size
= min(lockend
+ 1, iocb
->ki_pos
+ encoded
->len
) - start
;
10121 count
= start
+ disk_io_size
- iocb
->ki_pos
;
10122 encoded
->len
= count
;
10123 encoded
->unencoded_len
= count
;
10124 disk_io_size
= ALIGN(disk_io_size
, fs_info
->sectorsize
);
10126 free_extent_map(em
);
10129 if (disk_bytenr
== EXTENT_MAP_HOLE
) {
10130 unlock_extent(io_tree
, start
, lockend
, &cached_state
);
10131 btrfs_inode_unlock(inode
, BTRFS_ILOCK_SHARED
);
10133 ret
= iov_iter_zero(count
, iter
);
10137 ret
= btrfs_encoded_read_regular(iocb
, iter
, start
, lockend
,
10138 &cached_state
, disk_bytenr
,
10139 disk_io_size
, count
,
10140 encoded
->compression
,
10146 iocb
->ki_pos
+= encoded
->len
;
10148 free_extent_map(em
);
10151 unlock_extent(io_tree
, start
, lockend
, &cached_state
);
10154 btrfs_inode_unlock(inode
, BTRFS_ILOCK_SHARED
);
10158 ssize_t
btrfs_do_encoded_write(struct kiocb
*iocb
, struct iov_iter
*from
,
10159 const struct btrfs_ioctl_encoded_io_args
*encoded
)
10161 struct btrfs_inode
*inode
= BTRFS_I(file_inode(iocb
->ki_filp
));
10162 struct btrfs_root
*root
= inode
->root
;
10163 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
10164 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
10165 struct extent_changeset
*data_reserved
= NULL
;
10166 struct extent_state
*cached_state
= NULL
;
10170 u64 num_bytes
, ram_bytes
, disk_num_bytes
;
10171 unsigned long nr_pages
, i
;
10172 struct page
**pages
;
10173 struct btrfs_key ins
;
10174 bool extent_reserved
= false;
10175 struct extent_map
*em
;
10178 switch (encoded
->compression
) {
10179 case BTRFS_ENCODED_IO_COMPRESSION_ZLIB
:
10180 compression
= BTRFS_COMPRESS_ZLIB
;
10182 case BTRFS_ENCODED_IO_COMPRESSION_ZSTD
:
10183 compression
= BTRFS_COMPRESS_ZSTD
;
10185 case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K
:
10186 case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K
:
10187 case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K
:
10188 case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K
:
10189 case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K
:
10190 /* The sector size must match for LZO. */
10191 if (encoded
->compression
-
10192 BTRFS_ENCODED_IO_COMPRESSION_LZO_4K
+ 12 !=
10193 fs_info
->sectorsize_bits
)
10195 compression
= BTRFS_COMPRESS_LZO
;
10200 if (encoded
->encryption
!= BTRFS_ENCODED_IO_ENCRYPTION_NONE
)
10203 orig_count
= iov_iter_count(from
);
10205 /* The extent size must be sane. */
10206 if (encoded
->unencoded_len
> BTRFS_MAX_UNCOMPRESSED
||
10207 orig_count
> BTRFS_MAX_COMPRESSED
|| orig_count
== 0)
10211 * The compressed data must be smaller than the decompressed data.
10213 * It's of course possible for data to compress to larger or the same
10214 * size, but the buffered I/O path falls back to no compression for such
10215 * data, and we don't want to break any assumptions by creating these
10218 * Note that this is less strict than the current check we have that the
10219 * compressed data must be at least one sector smaller than the
10220 * decompressed data. We only want to enforce the weaker requirement
10221 * from old kernels that it is at least one byte smaller.
10223 if (orig_count
>= encoded
->unencoded_len
)
10226 /* The extent must start on a sector boundary. */
10227 start
= iocb
->ki_pos
;
10228 if (!IS_ALIGNED(start
, fs_info
->sectorsize
))
10232 * The extent must end on a sector boundary. However, we allow a write
10233 * which ends at or extends i_size to have an unaligned length; we round
10234 * up the extent size and set i_size to the unaligned end.
10236 if (start
+ encoded
->len
< inode
->vfs_inode
.i_size
&&
10237 !IS_ALIGNED(start
+ encoded
->len
, fs_info
->sectorsize
))
10240 /* Finally, the offset in the unencoded data must be sector-aligned. */
10241 if (!IS_ALIGNED(encoded
->unencoded_offset
, fs_info
->sectorsize
))
10244 num_bytes
= ALIGN(encoded
->len
, fs_info
->sectorsize
);
10245 ram_bytes
= ALIGN(encoded
->unencoded_len
, fs_info
->sectorsize
);
10246 end
= start
+ num_bytes
- 1;
10249 * If the extent cannot be inline, the compressed data on disk must be
10250 * sector-aligned. For convenience, we extend it with zeroes if it
10253 disk_num_bytes
= ALIGN(orig_count
, fs_info
->sectorsize
);
10254 nr_pages
= DIV_ROUND_UP(disk_num_bytes
, PAGE_SIZE
);
10255 pages
= kvcalloc(nr_pages
, sizeof(struct page
*), GFP_KERNEL_ACCOUNT
);
10258 for (i
= 0; i
< nr_pages
; i
++) {
10259 size_t bytes
= min_t(size_t, PAGE_SIZE
, iov_iter_count(from
));
10262 pages
[i
] = alloc_page(GFP_KERNEL_ACCOUNT
);
10267 kaddr
= kmap_local_page(pages
[i
]);
10268 if (copy_from_iter(kaddr
, bytes
, from
) != bytes
) {
10269 kunmap_local(kaddr
);
10273 if (bytes
< PAGE_SIZE
)
10274 memset(kaddr
+ bytes
, 0, PAGE_SIZE
- bytes
);
10275 kunmap_local(kaddr
);
10279 struct btrfs_ordered_extent
*ordered
;
10281 ret
= btrfs_wait_ordered_range(&inode
->vfs_inode
, start
, num_bytes
);
10284 ret
= invalidate_inode_pages2_range(inode
->vfs_inode
.i_mapping
,
10285 start
>> PAGE_SHIFT
,
10286 end
>> PAGE_SHIFT
);
10289 lock_extent(io_tree
, start
, end
, &cached_state
);
10290 ordered
= btrfs_lookup_ordered_range(inode
, start
, num_bytes
);
10292 !filemap_range_has_page(inode
->vfs_inode
.i_mapping
, start
, end
))
10295 btrfs_put_ordered_extent(ordered
);
10296 unlock_extent(io_tree
, start
, end
, &cached_state
);
10301 * We don't use the higher-level delalloc space functions because our
10302 * num_bytes and disk_num_bytes are different.
10304 ret
= btrfs_alloc_data_chunk_ondemand(inode
, disk_num_bytes
);
10307 ret
= btrfs_qgroup_reserve_data(inode
, &data_reserved
, start
, num_bytes
);
10309 goto out_free_data_space
;
10310 ret
= btrfs_delalloc_reserve_metadata(inode
, num_bytes
, disk_num_bytes
,
10313 goto out_qgroup_free_data
;
10315 /* Try an inline extent first. */
10316 if (start
== 0 && encoded
->unencoded_len
== encoded
->len
&&
10317 encoded
->unencoded_offset
== 0) {
10318 ret
= cow_file_range_inline(inode
, encoded
->len
, orig_count
,
10319 compression
, pages
, true);
10323 goto out_delalloc_release
;
10327 ret
= btrfs_reserve_extent(root
, disk_num_bytes
, disk_num_bytes
,
10328 disk_num_bytes
, 0, 0, &ins
, 1, 1);
10330 goto out_delalloc_release
;
10331 extent_reserved
= true;
10333 em
= create_io_em(inode
, start
, num_bytes
,
10334 start
- encoded
->unencoded_offset
, ins
.objectid
,
10335 ins
.offset
, ins
.offset
, ram_bytes
, compression
,
10336 BTRFS_ORDERED_COMPRESSED
);
10339 goto out_free_reserved
;
10341 free_extent_map(em
);
10343 ret
= btrfs_add_ordered_extent(inode
, start
, num_bytes
, ram_bytes
,
10344 ins
.objectid
, ins
.offset
,
10345 encoded
->unencoded_offset
,
10346 (1 << BTRFS_ORDERED_ENCODED
) |
10347 (1 << BTRFS_ORDERED_COMPRESSED
),
10350 btrfs_drop_extent_map_range(inode
, start
, end
, false);
10351 goto out_free_reserved
;
10353 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
10355 if (start
+ encoded
->len
> inode
->vfs_inode
.i_size
)
10356 i_size_write(&inode
->vfs_inode
, start
+ encoded
->len
);
10358 unlock_extent(io_tree
, start
, end
, &cached_state
);
10360 btrfs_delalloc_release_extents(inode
, num_bytes
);
10362 btrfs_submit_compressed_write(inode
, start
, num_bytes
, ins
.objectid
,
10363 ins
.offset
, pages
, nr_pages
, 0, false);
10368 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
10369 btrfs_free_reserved_extent(fs_info
, ins
.objectid
, ins
.offset
, 1);
10370 out_delalloc_release
:
10371 btrfs_delalloc_release_extents(inode
, num_bytes
);
10372 btrfs_delalloc_release_metadata(inode
, disk_num_bytes
, ret
< 0);
10373 out_qgroup_free_data
:
10375 btrfs_qgroup_free_data(inode
, data_reserved
, start
, num_bytes
);
10376 out_free_data_space
:
10378 * If btrfs_reserve_extent() succeeded, then we already decremented
10381 if (!extent_reserved
)
10382 btrfs_free_reserved_data_space_noquota(fs_info
, disk_num_bytes
);
10384 unlock_extent(io_tree
, start
, end
, &cached_state
);
10386 for (i
= 0; i
< nr_pages
; i
++) {
10388 __free_page(pages
[i
]);
10393 iocb
->ki_pos
+= encoded
->len
;
10399 * Add an entry indicating a block group or device which is pinned by a
10400 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10401 * negative errno on failure.
10403 static int btrfs_add_swapfile_pin(struct inode
*inode
, void *ptr
,
10404 bool is_block_group
)
10406 struct btrfs_fs_info
*fs_info
= BTRFS_I(inode
)->root
->fs_info
;
10407 struct btrfs_swapfile_pin
*sp
, *entry
;
10408 struct rb_node
**p
;
10409 struct rb_node
*parent
= NULL
;
10411 sp
= kmalloc(sizeof(*sp
), GFP_NOFS
);
10416 sp
->is_block_group
= is_block_group
;
10417 sp
->bg_extent_count
= 1;
10419 spin_lock(&fs_info
->swapfile_pins_lock
);
10420 p
= &fs_info
->swapfile_pins
.rb_node
;
10423 entry
= rb_entry(parent
, struct btrfs_swapfile_pin
, node
);
10424 if (sp
->ptr
< entry
->ptr
||
10425 (sp
->ptr
== entry
->ptr
&& sp
->inode
< entry
->inode
)) {
10426 p
= &(*p
)->rb_left
;
10427 } else if (sp
->ptr
> entry
->ptr
||
10428 (sp
->ptr
== entry
->ptr
&& sp
->inode
> entry
->inode
)) {
10429 p
= &(*p
)->rb_right
;
10431 if (is_block_group
)
10432 entry
->bg_extent_count
++;
10433 spin_unlock(&fs_info
->swapfile_pins_lock
);
10438 rb_link_node(&sp
->node
, parent
, p
);
10439 rb_insert_color(&sp
->node
, &fs_info
->swapfile_pins
);
10440 spin_unlock(&fs_info
->swapfile_pins_lock
);
10444 /* Free all of the entries pinned by this swapfile. */
10445 static void btrfs_free_swapfile_pins(struct inode
*inode
)
10447 struct btrfs_fs_info
*fs_info
= BTRFS_I(inode
)->root
->fs_info
;
10448 struct btrfs_swapfile_pin
*sp
;
10449 struct rb_node
*node
, *next
;
10451 spin_lock(&fs_info
->swapfile_pins_lock
);
10452 node
= rb_first(&fs_info
->swapfile_pins
);
10454 next
= rb_next(node
);
10455 sp
= rb_entry(node
, struct btrfs_swapfile_pin
, node
);
10456 if (sp
->inode
== inode
) {
10457 rb_erase(&sp
->node
, &fs_info
->swapfile_pins
);
10458 if (sp
->is_block_group
) {
10459 btrfs_dec_block_group_swap_extents(sp
->ptr
,
10460 sp
->bg_extent_count
);
10461 btrfs_put_block_group(sp
->ptr
);
10467 spin_unlock(&fs_info
->swapfile_pins_lock
);
10470 struct btrfs_swap_info
{
10476 unsigned long nr_pages
;
10480 static int btrfs_add_swap_extent(struct swap_info_struct
*sis
,
10481 struct btrfs_swap_info
*bsi
)
10483 unsigned long nr_pages
;
10484 unsigned long max_pages
;
10485 u64 first_ppage
, first_ppage_reported
, next_ppage
;
10489 * Our swapfile may have had its size extended after the swap header was
10490 * written. In that case activating the swapfile should not go beyond
10491 * the max size set in the swap header.
10493 if (bsi
->nr_pages
>= sis
->max
)
10496 max_pages
= sis
->max
- bsi
->nr_pages
;
10497 first_ppage
= PAGE_ALIGN(bsi
->block_start
) >> PAGE_SHIFT
;
10498 next_ppage
= PAGE_ALIGN_DOWN(bsi
->block_start
+ bsi
->block_len
) >> PAGE_SHIFT
;
10500 if (first_ppage
>= next_ppage
)
10502 nr_pages
= next_ppage
- first_ppage
;
10503 nr_pages
= min(nr_pages
, max_pages
);
10505 first_ppage_reported
= first_ppage
;
10506 if (bsi
->start
== 0)
10507 first_ppage_reported
++;
10508 if (bsi
->lowest_ppage
> first_ppage_reported
)
10509 bsi
->lowest_ppage
= first_ppage_reported
;
10510 if (bsi
->highest_ppage
< (next_ppage
- 1))
10511 bsi
->highest_ppage
= next_ppage
- 1;
10513 ret
= add_swap_extent(sis
, bsi
->nr_pages
, nr_pages
, first_ppage
);
10516 bsi
->nr_extents
+= ret
;
10517 bsi
->nr_pages
+= nr_pages
;
10521 static void btrfs_swap_deactivate(struct file
*file
)
10523 struct inode
*inode
= file_inode(file
);
10525 btrfs_free_swapfile_pins(inode
);
10526 atomic_dec(&BTRFS_I(inode
)->root
->nr_swapfiles
);
10529 static int btrfs_swap_activate(struct swap_info_struct
*sis
, struct file
*file
,
10532 struct inode
*inode
= file_inode(file
);
10533 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
10534 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
10535 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
10536 struct extent_state
*cached_state
= NULL
;
10537 struct extent_map
*em
= NULL
;
10538 struct btrfs_device
*device
= NULL
;
10539 struct btrfs_swap_info bsi
= {
10540 .lowest_ppage
= (sector_t
)-1ULL,
10547 * If the swap file was just created, make sure delalloc is done. If the
10548 * file changes again after this, the user is doing something stupid and
10549 * we don't really care.
10551 ret
= btrfs_wait_ordered_range(inode
, 0, (u64
)-1);
10556 * The inode is locked, so these flags won't change after we check them.
10558 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_COMPRESS
) {
10559 btrfs_warn(fs_info
, "swapfile must not be compressed");
10562 if (!(BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
)) {
10563 btrfs_warn(fs_info
, "swapfile must not be copy-on-write");
10566 if (!(BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATASUM
)) {
10567 btrfs_warn(fs_info
, "swapfile must not be checksummed");
10572 * Balance or device remove/replace/resize can move stuff around from
10573 * under us. The exclop protection makes sure they aren't running/won't
10574 * run concurrently while we are mapping the swap extents, and
10575 * fs_info->swapfile_pins prevents them from running while the swap
10576 * file is active and moving the extents. Note that this also prevents
10577 * a concurrent device add which isn't actually necessary, but it's not
10578 * really worth the trouble to allow it.
10580 if (!btrfs_exclop_start(fs_info
, BTRFS_EXCLOP_SWAP_ACTIVATE
)) {
10581 btrfs_warn(fs_info
,
10582 "cannot activate swapfile while exclusive operation is running");
10587 * Prevent snapshot creation while we are activating the swap file.
10588 * We do not want to race with snapshot creation. If snapshot creation
10589 * already started before we bumped nr_swapfiles from 0 to 1 and
10590 * completes before the first write into the swap file after it is
10591 * activated, than that write would fallback to COW.
10593 if (!btrfs_drew_try_write_lock(&root
->snapshot_lock
)) {
10594 btrfs_exclop_finish(fs_info
);
10595 btrfs_warn(fs_info
,
10596 "cannot activate swapfile because snapshot creation is in progress");
10600 * Snapshots can create extents which require COW even if NODATACOW is
10601 * set. We use this counter to prevent snapshots. We must increment it
10602 * before walking the extents because we don't want a concurrent
10603 * snapshot to run after we've already checked the extents.
10605 * It is possible that subvolume is marked for deletion but still not
10606 * removed yet. To prevent this race, we check the root status before
10607 * activating the swapfile.
10609 spin_lock(&root
->root_item_lock
);
10610 if (btrfs_root_dead(root
)) {
10611 spin_unlock(&root
->root_item_lock
);
10613 btrfs_exclop_finish(fs_info
);
10614 btrfs_warn(fs_info
,
10615 "cannot activate swapfile because subvolume %llu is being deleted",
10616 root
->root_key
.objectid
);
10619 atomic_inc(&root
->nr_swapfiles
);
10620 spin_unlock(&root
->root_item_lock
);
10622 isize
= ALIGN_DOWN(inode
->i_size
, fs_info
->sectorsize
);
10624 lock_extent(io_tree
, 0, isize
- 1, &cached_state
);
10626 while (start
< isize
) {
10627 u64 logical_block_start
, physical_block_start
;
10628 struct btrfs_block_group
*bg
;
10629 u64 len
= isize
- start
;
10631 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, start
, len
);
10637 if (em
->block_start
== EXTENT_MAP_HOLE
) {
10638 btrfs_warn(fs_info
, "swapfile must not have holes");
10642 if (em
->block_start
== EXTENT_MAP_INLINE
) {
10644 * It's unlikely we'll ever actually find ourselves
10645 * here, as a file small enough to fit inline won't be
10646 * big enough to store more than the swap header, but in
10647 * case something changes in the future, let's catch it
10648 * here rather than later.
10650 btrfs_warn(fs_info
, "swapfile must not be inline");
10654 if (test_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
)) {
10655 btrfs_warn(fs_info
, "swapfile must not be compressed");
10660 logical_block_start
= em
->block_start
+ (start
- em
->start
);
10661 len
= min(len
, em
->len
- (start
- em
->start
));
10662 free_extent_map(em
);
10665 ret
= can_nocow_extent(inode
, start
, &len
, NULL
, NULL
, NULL
, false, true);
10671 btrfs_warn(fs_info
,
10672 "swapfile must not be copy-on-write");
10677 em
= btrfs_get_chunk_map(fs_info
, logical_block_start
, len
);
10683 if (em
->map_lookup
->type
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
10684 btrfs_warn(fs_info
,
10685 "swapfile must have single data profile");
10690 if (device
== NULL
) {
10691 device
= em
->map_lookup
->stripes
[0].dev
;
10692 ret
= btrfs_add_swapfile_pin(inode
, device
, false);
10697 } else if (device
!= em
->map_lookup
->stripes
[0].dev
) {
10698 btrfs_warn(fs_info
, "swapfile must be on one device");
10703 physical_block_start
= (em
->map_lookup
->stripes
[0].physical
+
10704 (logical_block_start
- em
->start
));
10705 len
= min(len
, em
->len
- (logical_block_start
- em
->start
));
10706 free_extent_map(em
);
10709 bg
= btrfs_lookup_block_group(fs_info
, logical_block_start
);
10711 btrfs_warn(fs_info
,
10712 "could not find block group containing swapfile");
10717 if (!btrfs_inc_block_group_swap_extents(bg
)) {
10718 btrfs_warn(fs_info
,
10719 "block group for swapfile at %llu is read-only%s",
10721 atomic_read(&fs_info
->scrubs_running
) ?
10722 " (scrub running)" : "");
10723 btrfs_put_block_group(bg
);
10728 ret
= btrfs_add_swapfile_pin(inode
, bg
, true);
10730 btrfs_put_block_group(bg
);
10737 if (bsi
.block_len
&&
10738 bsi
.block_start
+ bsi
.block_len
== physical_block_start
) {
10739 bsi
.block_len
+= len
;
10741 if (bsi
.block_len
) {
10742 ret
= btrfs_add_swap_extent(sis
, &bsi
);
10747 bsi
.block_start
= physical_block_start
;
10748 bsi
.block_len
= len
;
10755 ret
= btrfs_add_swap_extent(sis
, &bsi
);
10758 if (!IS_ERR_OR_NULL(em
))
10759 free_extent_map(em
);
10761 unlock_extent(io_tree
, 0, isize
- 1, &cached_state
);
10764 btrfs_swap_deactivate(file
);
10766 btrfs_drew_write_unlock(&root
->snapshot_lock
);
10768 btrfs_exclop_finish(fs_info
);
10774 sis
->bdev
= device
->bdev
;
10775 *span
= bsi
.highest_ppage
- bsi
.lowest_ppage
+ 1;
10776 sis
->max
= bsi
.nr_pages
;
10777 sis
->pages
= bsi
.nr_pages
- 1;
10778 sis
->highest_bit
= bsi
.nr_pages
- 1;
10779 return bsi
.nr_extents
;
10782 static void btrfs_swap_deactivate(struct file
*file
)
10786 static int btrfs_swap_activate(struct swap_info_struct
*sis
, struct file
*file
,
10789 return -EOPNOTSUPP
;
10794 * Update the number of bytes used in the VFS' inode. When we replace extents in
10795 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10796 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10797 * always get a correct value.
10799 void btrfs_update_inode_bytes(struct btrfs_inode
*inode
,
10800 const u64 add_bytes
,
10801 const u64 del_bytes
)
10803 if (add_bytes
== del_bytes
)
10806 spin_lock(&inode
->lock
);
10808 inode_sub_bytes(&inode
->vfs_inode
, del_bytes
);
10810 inode_add_bytes(&inode
->vfs_inode
, add_bytes
);
10811 spin_unlock(&inode
->lock
);
10815 * Verify that there are no ordered extents for a given file range.
10817 * @inode: The target inode.
10818 * @start: Start offset of the file range, should be sector size aligned.
10819 * @end: End offset (inclusive) of the file range, its value +1 should be
10820 * sector size aligned.
10822 * This should typically be used for cases where we locked an inode's VFS lock in
10823 * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
10824 * we have flushed all delalloc in the range, we have waited for all ordered
10825 * extents in the range to complete and finally we have locked the file range in
10826 * the inode's io_tree.
10828 void btrfs_assert_inode_range_clean(struct btrfs_inode
*inode
, u64 start
, u64 end
)
10830 struct btrfs_root
*root
= inode
->root
;
10831 struct btrfs_ordered_extent
*ordered
;
10833 if (!IS_ENABLED(CONFIG_BTRFS_ASSERT
))
10836 ordered
= btrfs_lookup_first_ordered_range(inode
, start
, end
+ 1 - start
);
10838 btrfs_err(root
->fs_info
,
10839 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
10840 start
, end
, btrfs_ino(inode
), root
->root_key
.objectid
,
10841 ordered
->file_offset
,
10842 ordered
->file_offset
+ ordered
->num_bytes
- 1);
10843 btrfs_put_ordered_extent(ordered
);
10846 ASSERT(ordered
== NULL
);
10849 static const struct inode_operations btrfs_dir_inode_operations
= {
10850 .getattr
= btrfs_getattr
,
10851 .lookup
= btrfs_lookup
,
10852 .create
= btrfs_create
,
10853 .unlink
= btrfs_unlink
,
10854 .link
= btrfs_link
,
10855 .mkdir
= btrfs_mkdir
,
10856 .rmdir
= btrfs_rmdir
,
10857 .rename
= btrfs_rename2
,
10858 .symlink
= btrfs_symlink
,
10859 .setattr
= btrfs_setattr
,
10860 .mknod
= btrfs_mknod
,
10861 .listxattr
= btrfs_listxattr
,
10862 .permission
= btrfs_permission
,
10863 .get_inode_acl
= btrfs_get_acl
,
10864 .set_acl
= btrfs_set_acl
,
10865 .update_time
= btrfs_update_time
,
10866 .tmpfile
= btrfs_tmpfile
,
10867 .fileattr_get
= btrfs_fileattr_get
,
10868 .fileattr_set
= btrfs_fileattr_set
,
10871 static const struct file_operations btrfs_dir_file_operations
= {
10872 .llseek
= generic_file_llseek
,
10873 .read
= generic_read_dir
,
10874 .iterate_shared
= btrfs_real_readdir
,
10875 .open
= btrfs_opendir
,
10876 .unlocked_ioctl
= btrfs_ioctl
,
10877 #ifdef CONFIG_COMPAT
10878 .compat_ioctl
= btrfs_compat_ioctl
,
10880 .release
= btrfs_release_file
,
10881 .fsync
= btrfs_sync_file
,
10885 * btrfs doesn't support the bmap operation because swapfiles
10886 * use bmap to make a mapping of extents in the file. They assume
10887 * these extents won't change over the life of the file and they
10888 * use the bmap result to do IO directly to the drive.
10890 * the btrfs bmap call would return logical addresses that aren't
10891 * suitable for IO and they also will change frequently as COW
10892 * operations happen. So, swapfile + btrfs == corruption.
10894 * For now we're avoiding this by dropping bmap.
10896 static const struct address_space_operations btrfs_aops
= {
10897 .read_folio
= btrfs_read_folio
,
10898 .writepages
= btrfs_writepages
,
10899 .readahead
= btrfs_readahead
,
10900 .direct_IO
= noop_direct_IO
,
10901 .invalidate_folio
= btrfs_invalidate_folio
,
10902 .release_folio
= btrfs_release_folio
,
10903 .migrate_folio
= btrfs_migrate_folio
,
10904 .dirty_folio
= filemap_dirty_folio
,
10905 .error_remove_page
= generic_error_remove_page
,
10906 .swap_activate
= btrfs_swap_activate
,
10907 .swap_deactivate
= btrfs_swap_deactivate
,
10910 static const struct inode_operations btrfs_file_inode_operations
= {
10911 .getattr
= btrfs_getattr
,
10912 .setattr
= btrfs_setattr
,
10913 .listxattr
= btrfs_listxattr
,
10914 .permission
= btrfs_permission
,
10915 .fiemap
= btrfs_fiemap
,
10916 .get_inode_acl
= btrfs_get_acl
,
10917 .set_acl
= btrfs_set_acl
,
10918 .update_time
= btrfs_update_time
,
10919 .fileattr_get
= btrfs_fileattr_get
,
10920 .fileattr_set
= btrfs_fileattr_set
,
10922 static const struct inode_operations btrfs_special_inode_operations
= {
10923 .getattr
= btrfs_getattr
,
10924 .setattr
= btrfs_setattr
,
10925 .permission
= btrfs_permission
,
10926 .listxattr
= btrfs_listxattr
,
10927 .get_inode_acl
= btrfs_get_acl
,
10928 .set_acl
= btrfs_set_acl
,
10929 .update_time
= btrfs_update_time
,
10931 static const struct inode_operations btrfs_symlink_inode_operations
= {
10932 .get_link
= page_get_link
,
10933 .getattr
= btrfs_getattr
,
10934 .setattr
= btrfs_setattr
,
10935 .permission
= btrfs_permission
,
10936 .listxattr
= btrfs_listxattr
,
10937 .update_time
= btrfs_update_time
,
10940 const struct dentry_operations btrfs_dentry_operations
= {
10941 .d_delete
= btrfs_dentry_delete
,