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 #include "raid-stripe-tree.h"
76 struct btrfs_iget_args {
78 struct btrfs_root *root;
81 struct btrfs_dio_data {
83 struct extent_changeset *data_reserved;
84 struct btrfs_ordered_extent *ordered;
85 bool data_space_reserved;
89 struct btrfs_dio_private {
94 /* This must be last */
95 struct btrfs_bio bbio;
98 static struct bio_set btrfs_dio_bioset;
100 struct btrfs_rename_ctx {
101 /* Output field. Stores the index number of the old directory entry. */
106 * Used by data_reloc_print_warning_inode() to pass needed info for filename
107 * resolution and output of error message.
109 struct data_reloc_warn {
110 struct btrfs_path path;
111 struct btrfs_fs_info *fs_info;
112 u64 extent_item_size;
118 * For the file_extent_tree, we want to hold the inode lock when we lookup and
119 * update the disk_i_size, but lockdep will complain because our io_tree we hold
120 * the tree lock and get the inode lock when setting delalloc. These two things
121 * are unrelated, so make a class for the file_extent_tree so we don't get the
122 * two locking patterns mixed up.
124 static struct lock_class_key file_extent_tree_class;
126 static const struct inode_operations btrfs_dir_inode_operations;
127 static const struct inode_operations btrfs_symlink_inode_operations;
128 static const struct inode_operations btrfs_special_inode_operations;
129 static const struct inode_operations btrfs_file_inode_operations;
130 static const struct address_space_operations btrfs_aops;
131 static const struct file_operations btrfs_dir_file_operations;
133 static struct kmem_cache *btrfs_inode_cachep;
135 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
136 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback);
138 static noinline int run_delalloc_cow(struct btrfs_inode *inode,
139 struct page *locked_page, u64 start,
140 u64 end, struct writeback_control *wbc,
142 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
143 u64 len, u64 orig_start, u64 block_start,
144 u64 block_len, u64 orig_block_len,
145 u64 ram_bytes, int compress_type,
148 static int data_reloc_print_warning_inode(u64 inum, u64 offset, u64 num_bytes,
149 u64 root, void *warn_ctx)
151 struct data_reloc_warn *warn = warn_ctx;
152 struct btrfs_fs_info *fs_info = warn->fs_info;
153 struct extent_buffer *eb;
154 struct btrfs_inode_item *inode_item;
155 struct inode_fs_paths *ipath = NULL;
156 struct btrfs_root *local_root;
157 struct btrfs_key key;
158 unsigned int nofs_flag;
162 local_root = btrfs_get_fs_root(fs_info, root, true);
163 if (IS_ERR(local_root)) {
164 ret = PTR_ERR(local_root);
168 /* This makes the path point to (inum INODE_ITEM ioff). */
170 key.type = BTRFS_INODE_ITEM_KEY;
173 ret = btrfs_search_slot(NULL, local_root, &key, &warn->path, 0, 0);
175 btrfs_put_root(local_root);
176 btrfs_release_path(&warn->path);
180 eb = warn->path.nodes[0];
181 inode_item = btrfs_item_ptr(eb, warn->path.slots[0], struct btrfs_inode_item);
182 nlink = btrfs_inode_nlink(eb, inode_item);
183 btrfs_release_path(&warn->path);
185 nofs_flag = memalloc_nofs_save();
186 ipath = init_ipath(4096, local_root, &warn->path);
187 memalloc_nofs_restore(nofs_flag);
189 btrfs_put_root(local_root);
190 ret = PTR_ERR(ipath);
193 * -ENOMEM, not a critical error, just output an generic error
197 "checksum error at logical %llu mirror %u root %llu, inode %llu offset %llu",
198 warn->logical, warn->mirror_num, root, inum, offset);
201 ret = paths_from_inode(inum, ipath);
206 * We deliberately ignore the bit ipath might have been too small to
207 * hold all of the paths here
209 for (int i = 0; i < ipath->fspath->elem_cnt; i++) {
211 "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu length %u links %u (path: %s)",
212 warn->logical, warn->mirror_num, root, inum, offset,
213 fs_info->sectorsize, nlink,
214 (char *)(unsigned long)ipath->fspath->val[i]);
217 btrfs_put_root(local_root);
223 "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu, path resolving failed with ret=%d",
224 warn->logical, warn->mirror_num, root, inum, offset, ret);
231 * Do extra user-friendly error output (e.g. lookup all the affected files).
233 * Return true if we succeeded doing the backref lookup.
234 * Return false if such lookup failed, and has to fallback to the old error message.
236 static void print_data_reloc_error(const struct btrfs_inode *inode, u64 file_off,
237 const u8 *csum, const u8 *csum_expected,
240 struct btrfs_fs_info *fs_info = inode->root->fs_info;
241 struct btrfs_path path = { 0 };
242 struct btrfs_key found_key = { 0 };
243 struct extent_buffer *eb;
244 struct btrfs_extent_item *ei;
245 const u32 csum_size = fs_info->csum_size;
251 mutex_lock(&fs_info->reloc_mutex);
252 logical = btrfs_get_reloc_bg_bytenr(fs_info);
253 mutex_unlock(&fs_info->reloc_mutex);
255 if (logical == U64_MAX) {
256 btrfs_warn_rl(fs_info, "has data reloc tree but no running relocation");
257 btrfs_warn_rl(fs_info,
258 "csum failed root %lld ino %llu off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
259 inode->root->root_key.objectid, btrfs_ino(inode), file_off,
260 CSUM_FMT_VALUE(csum_size, csum),
261 CSUM_FMT_VALUE(csum_size, csum_expected),
267 btrfs_warn_rl(fs_info,
268 "csum failed root %lld ino %llu off %llu logical %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
269 inode->root->root_key.objectid,
270 btrfs_ino(inode), file_off, logical,
271 CSUM_FMT_VALUE(csum_size, csum),
272 CSUM_FMT_VALUE(csum_size, csum_expected),
275 ret = extent_from_logical(fs_info, logical, &path, &found_key, &flags);
277 btrfs_err_rl(fs_info, "failed to lookup extent item for logical %llu: %d",
282 ei = btrfs_item_ptr(eb, path.slots[0], struct btrfs_extent_item);
283 item_size = btrfs_item_size(eb, path.slots[0]);
284 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
285 unsigned long ptr = 0;
290 ret = tree_backref_for_extent(&ptr, eb, &found_key, ei,
291 item_size, &ref_root,
294 btrfs_warn_rl(fs_info,
295 "failed to resolve tree backref for logical %llu: %d",
302 btrfs_warn_rl(fs_info,
303 "csum error at logical %llu mirror %u: metadata %s (level %d) in tree %llu",
305 (ref_level ? "node" : "leaf"),
306 ref_level, ref_root);
308 btrfs_release_path(&path);
310 struct btrfs_backref_walk_ctx ctx = { 0 };
311 struct data_reloc_warn reloc_warn = { 0 };
313 btrfs_release_path(&path);
315 ctx.bytenr = found_key.objectid;
316 ctx.extent_item_pos = logical - found_key.objectid;
317 ctx.fs_info = fs_info;
319 reloc_warn.logical = logical;
320 reloc_warn.extent_item_size = found_key.offset;
321 reloc_warn.mirror_num = mirror_num;
322 reloc_warn.fs_info = fs_info;
324 iterate_extent_inodes(&ctx, true,
325 data_reloc_print_warning_inode, &reloc_warn);
329 static void __cold btrfs_print_data_csum_error(struct btrfs_inode *inode,
330 u64 logical_start, u8 *csum, u8 *csum_expected, int mirror_num)
332 struct btrfs_root *root = inode->root;
333 const u32 csum_size = root->fs_info->csum_size;
335 /* For data reloc tree, it's better to do a backref lookup instead. */
336 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
337 return print_data_reloc_error(inode, logical_start, csum,
338 csum_expected, mirror_num);
340 /* Output without objectid, which is more meaningful */
341 if (root->root_key.objectid >= BTRFS_LAST_FREE_OBJECTID) {
342 btrfs_warn_rl(root->fs_info,
343 "csum failed root %lld ino %lld off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
344 root->root_key.objectid, btrfs_ino(inode),
346 CSUM_FMT_VALUE(csum_size, csum),
347 CSUM_FMT_VALUE(csum_size, csum_expected),
350 btrfs_warn_rl(root->fs_info,
351 "csum failed root %llu ino %llu off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
352 root->root_key.objectid, btrfs_ino(inode),
354 CSUM_FMT_VALUE(csum_size, csum),
355 CSUM_FMT_VALUE(csum_size, csum_expected),
361 * Lock inode i_rwsem based on arguments passed.
363 * ilock_flags can have the following bit set:
365 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
366 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
368 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
370 int btrfs_inode_lock(struct btrfs_inode *inode, unsigned int ilock_flags)
372 if (ilock_flags & BTRFS_ILOCK_SHARED) {
373 if (ilock_flags & BTRFS_ILOCK_TRY) {
374 if (!inode_trylock_shared(&inode->vfs_inode))
379 inode_lock_shared(&inode->vfs_inode);
381 if (ilock_flags & BTRFS_ILOCK_TRY) {
382 if (!inode_trylock(&inode->vfs_inode))
387 inode_lock(&inode->vfs_inode);
389 if (ilock_flags & BTRFS_ILOCK_MMAP)
390 down_write(&inode->i_mmap_lock);
395 * Unock inode i_rwsem.
397 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
398 * to decide whether the lock acquired is shared or exclusive.
400 void btrfs_inode_unlock(struct btrfs_inode *inode, unsigned int ilock_flags)
402 if (ilock_flags & BTRFS_ILOCK_MMAP)
403 up_write(&inode->i_mmap_lock);
404 if (ilock_flags & BTRFS_ILOCK_SHARED)
405 inode_unlock_shared(&inode->vfs_inode);
407 inode_unlock(&inode->vfs_inode);
411 * Cleanup all submitted ordered extents in specified range to handle errors
412 * from the btrfs_run_delalloc_range() callback.
414 * NOTE: caller must ensure that when an error happens, it can not call
415 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
416 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
417 * to be released, which we want to happen only when finishing the ordered
418 * extent (btrfs_finish_ordered_io()).
420 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
421 struct page *locked_page,
422 u64 offset, u64 bytes)
424 unsigned long index = offset >> PAGE_SHIFT;
425 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
426 u64 page_start = 0, page_end = 0;
430 page_start = page_offset(locked_page);
431 page_end = page_start + PAGE_SIZE - 1;
434 while (index <= end_index) {
436 * For locked page, we will call btrfs_mark_ordered_io_finished
437 * through btrfs_mark_ordered_io_finished() on it
438 * in run_delalloc_range() for the error handling, which will
439 * clear page Ordered and run the ordered extent accounting.
441 * Here we can't just clear the Ordered bit, or
442 * btrfs_mark_ordered_io_finished() would skip the accounting
443 * for the page range, and the ordered extent will never finish.
445 if (locked_page && index == (page_start >> PAGE_SHIFT)) {
449 page = find_get_page(inode->vfs_inode.i_mapping, index);
455 * Here we just clear all Ordered bits for every page in the
456 * range, then btrfs_mark_ordered_io_finished() will handle
457 * the ordered extent accounting for the range.
459 btrfs_folio_clamp_clear_ordered(inode->root->fs_info,
460 page_folio(page), offset, bytes);
465 /* The locked page covers the full range, nothing needs to be done */
466 if (bytes + offset <= page_start + PAGE_SIZE)
469 * In case this page belongs to the delalloc range being
470 * instantiated then skip it, since the first page of a range is
471 * going to be properly cleaned up by the caller of
474 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
475 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
476 offset = page_offset(locked_page) + PAGE_SIZE;
480 return btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes, false);
483 static int btrfs_dirty_inode(struct btrfs_inode *inode);
485 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
486 struct btrfs_new_inode_args *args)
490 if (args->default_acl) {
491 err = __btrfs_set_acl(trans, args->inode, args->default_acl,
497 err = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
501 if (!args->default_acl && !args->acl)
502 cache_no_acl(args->inode);
503 return btrfs_xattr_security_init(trans, args->inode, args->dir,
504 &args->dentry->d_name);
508 * this does all the hard work for inserting an inline extent into
509 * the btree. The caller should have done a btrfs_drop_extents so that
510 * no overlapping inline items exist in the btree
512 static int insert_inline_extent(struct btrfs_trans_handle *trans,
513 struct btrfs_path *path,
514 struct btrfs_inode *inode, bool extent_inserted,
515 size_t size, size_t compressed_size,
517 struct page **compressed_pages,
520 struct btrfs_root *root = inode->root;
521 struct extent_buffer *leaf;
522 struct page *page = NULL;
525 struct btrfs_file_extent_item *ei;
527 size_t cur_size = size;
530 ASSERT((compressed_size > 0 && compressed_pages) ||
531 (compressed_size == 0 && !compressed_pages));
533 if (compressed_size && compressed_pages)
534 cur_size = compressed_size;
536 if (!extent_inserted) {
537 struct btrfs_key key;
540 key.objectid = btrfs_ino(inode);
542 key.type = BTRFS_EXTENT_DATA_KEY;
544 datasize = btrfs_file_extent_calc_inline_size(cur_size);
545 ret = btrfs_insert_empty_item(trans, root, path, &key,
550 leaf = path->nodes[0];
551 ei = btrfs_item_ptr(leaf, path->slots[0],
552 struct btrfs_file_extent_item);
553 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
554 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
555 btrfs_set_file_extent_encryption(leaf, ei, 0);
556 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
557 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
558 ptr = btrfs_file_extent_inline_start(ei);
560 if (compress_type != BTRFS_COMPRESS_NONE) {
563 while (compressed_size > 0) {
564 cpage = compressed_pages[i];
565 cur_size = min_t(unsigned long, compressed_size,
568 kaddr = kmap_local_page(cpage);
569 write_extent_buffer(leaf, kaddr, ptr, cur_size);
574 compressed_size -= cur_size;
576 btrfs_set_file_extent_compression(leaf, ei,
579 page = find_get_page(inode->vfs_inode.i_mapping, 0);
580 btrfs_set_file_extent_compression(leaf, ei, 0);
581 kaddr = kmap_local_page(page);
582 write_extent_buffer(leaf, kaddr, ptr, size);
586 btrfs_mark_buffer_dirty(trans, leaf);
587 btrfs_release_path(path);
590 * We align size to sectorsize for inline extents just for simplicity
593 ret = btrfs_inode_set_file_extent_range(inode, 0,
594 ALIGN(size, root->fs_info->sectorsize));
599 * We're an inline extent, so nobody can extend the file past i_size
600 * without locking a page we already have locked.
602 * We must do any i_size and inode updates before we unlock the pages.
603 * Otherwise we could end up racing with unlink.
605 i_size = i_size_read(&inode->vfs_inode);
606 if (update_i_size && size > i_size) {
607 i_size_write(&inode->vfs_inode, size);
610 inode->disk_i_size = i_size;
618 * conditionally insert an inline extent into the file. This
619 * does the checks required to make sure the data is small enough
620 * to fit as an inline extent.
622 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 size,
623 size_t compressed_size,
625 struct page **compressed_pages,
628 struct btrfs_drop_extents_args drop_args = { 0 };
629 struct btrfs_root *root = inode->root;
630 struct btrfs_fs_info *fs_info = root->fs_info;
631 struct btrfs_trans_handle *trans;
632 u64 data_len = (compressed_size ?: size);
634 struct btrfs_path *path;
637 * We can create an inline extent if it ends at or beyond the current
638 * i_size, is no larger than a sector (decompressed), and the (possibly
639 * compressed) data fits in a leaf and the configured maximum inline
642 if (size < i_size_read(&inode->vfs_inode) ||
643 size > fs_info->sectorsize ||
644 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
645 data_len > fs_info->max_inline)
648 path = btrfs_alloc_path();
652 trans = btrfs_join_transaction(root);
654 btrfs_free_path(path);
655 return PTR_ERR(trans);
657 trans->block_rsv = &inode->block_rsv;
659 drop_args.path = path;
661 drop_args.end = fs_info->sectorsize;
662 drop_args.drop_cache = true;
663 drop_args.replace_extent = true;
664 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
665 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
667 btrfs_abort_transaction(trans, ret);
671 ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
672 size, compressed_size, compress_type,
673 compressed_pages, update_i_size);
674 if (ret && ret != -ENOSPC) {
675 btrfs_abort_transaction(trans, ret);
677 } else if (ret == -ENOSPC) {
682 btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
683 ret = btrfs_update_inode(trans, inode);
684 if (ret && ret != -ENOSPC) {
685 btrfs_abort_transaction(trans, ret);
687 } else if (ret == -ENOSPC) {
692 btrfs_set_inode_full_sync(inode);
695 * Don't forget to free the reserved space, as for inlined extent
696 * it won't count as data extent, free them directly here.
697 * And at reserve time, it's always aligned to page size, so
698 * just free one page here.
700 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE, NULL);
701 btrfs_free_path(path);
702 btrfs_end_transaction(trans);
706 struct async_extent {
711 unsigned long nr_pages;
713 struct list_head list;
717 struct btrfs_inode *inode;
718 struct page *locked_page;
721 blk_opf_t write_flags;
722 struct list_head extents;
723 struct cgroup_subsys_state *blkcg_css;
724 struct btrfs_work work;
725 struct async_cow *async_cow;
730 struct async_chunk chunks[];
733 static noinline int add_async_extent(struct async_chunk *cow,
734 u64 start, u64 ram_size,
737 unsigned long nr_pages,
740 struct async_extent *async_extent;
742 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
743 BUG_ON(!async_extent); /* -ENOMEM */
744 async_extent->start = start;
745 async_extent->ram_size = ram_size;
746 async_extent->compressed_size = compressed_size;
747 async_extent->pages = pages;
748 async_extent->nr_pages = nr_pages;
749 async_extent->compress_type = compress_type;
750 list_add_tail(&async_extent->list, &cow->extents);
755 * Check if the inode needs to be submitted to compression, based on mount
756 * options, defragmentation, properties or heuristics.
758 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
761 struct btrfs_fs_info *fs_info = inode->root->fs_info;
763 if (!btrfs_inode_can_compress(inode)) {
764 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
765 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
770 * Special check for subpage.
772 * We lock the full page then run each delalloc range in the page, thus
773 * for the following case, we will hit some subpage specific corner case:
776 * | |///////| |///////|
779 * In above case, both range A and range B will try to unlock the full
780 * page [0, 64K), causing the one finished later will have page
781 * unlocked already, triggering various page lock requirement BUG_ON()s.
783 * So here we add an artificial limit that subpage compression can only
784 * if the range is fully page aligned.
786 * In theory we only need to ensure the first page is fully covered, but
787 * the tailing partial page will be locked until the full compression
788 * finishes, delaying the write of other range.
790 * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
791 * first to prevent any submitted async extent to unlock the full page.
792 * By this, we can ensure for subpage case that only the last async_cow
793 * will unlock the full page.
795 if (fs_info->sectorsize < PAGE_SIZE) {
796 if (!PAGE_ALIGNED(start) ||
797 !PAGE_ALIGNED(end + 1))
802 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
805 if (inode->defrag_compress)
807 /* bad compression ratios */
808 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
810 if (btrfs_test_opt(fs_info, COMPRESS) ||
811 inode->flags & BTRFS_INODE_COMPRESS ||
812 inode->prop_compress)
813 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
817 static inline void inode_should_defrag(struct btrfs_inode *inode,
818 u64 start, u64 end, u64 num_bytes, u32 small_write)
820 /* If this is a small write inside eof, kick off a defrag */
821 if (num_bytes < small_write &&
822 (start > 0 || end + 1 < inode->disk_i_size))
823 btrfs_add_inode_defrag(NULL, inode, small_write);
827 * Work queue call back to started compression on a file and pages.
829 * This is done inside an ordered work queue, and the compression is spread
830 * across many cpus. The actual IO submission is step two, and the ordered work
831 * queue takes care of making sure that happens in the same order things were
832 * put onto the queue by writepages and friends.
834 * If this code finds it can't get good compression, it puts an entry onto the
835 * work queue to write the uncompressed bytes. This makes sure that both
836 * compressed inodes and uncompressed inodes are written in the same order that
837 * the flusher thread sent them down.
839 static void compress_file_range(struct btrfs_work *work)
841 struct async_chunk *async_chunk =
842 container_of(work, struct async_chunk, work);
843 struct btrfs_inode *inode = async_chunk->inode;
844 struct btrfs_fs_info *fs_info = inode->root->fs_info;
845 struct address_space *mapping = inode->vfs_inode.i_mapping;
846 u64 blocksize = fs_info->sectorsize;
847 u64 start = async_chunk->start;
848 u64 end = async_chunk->end;
853 unsigned long nr_pages;
854 unsigned long total_compressed = 0;
855 unsigned long total_in = 0;
858 int compress_type = fs_info->compress_type;
860 inode_should_defrag(inode, start, end, end - start + 1, SZ_16K);
863 * We need to call clear_page_dirty_for_io on each page in the range.
864 * Otherwise applications with the file mmap'd can wander in and change
865 * the page contents while we are compressing them.
867 extent_range_clear_dirty_for_io(&inode->vfs_inode, start, end);
870 * We need to save i_size before now because it could change in between
871 * us evaluating the size and assigning it. This is because we lock and
872 * unlock the page in truncate and fallocate, and then modify the i_size
875 * The barriers are to emulate READ_ONCE, remove that once i_size_read
879 i_size = i_size_read(&inode->vfs_inode);
881 actual_end = min_t(u64, i_size, end + 1);
884 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
885 nr_pages = min_t(unsigned long, nr_pages, BTRFS_MAX_COMPRESSED_PAGES);
888 * we don't want to send crud past the end of i_size through
889 * compression, that's just a waste of CPU time. So, if the
890 * end of the file is before the start of our current
891 * requested range of bytes, we bail out to the uncompressed
892 * cleanup code that can deal with all of this.
894 * It isn't really the fastest way to fix things, but this is a
895 * very uncommon corner.
897 if (actual_end <= start)
898 goto cleanup_and_bail_uncompressed;
900 total_compressed = actual_end - start;
903 * Skip compression for a small file range(<=blocksize) that
904 * isn't an inline extent, since it doesn't save disk space at all.
906 if (total_compressed <= blocksize &&
907 (start > 0 || end + 1 < inode->disk_i_size))
908 goto cleanup_and_bail_uncompressed;
911 * For subpage case, we require full page alignment for the sector
913 * Thus we must also check against @actual_end, not just @end.
915 if (blocksize < PAGE_SIZE) {
916 if (!PAGE_ALIGNED(start) ||
917 !PAGE_ALIGNED(round_up(actual_end, blocksize)))
918 goto cleanup_and_bail_uncompressed;
921 total_compressed = min_t(unsigned long, total_compressed,
922 BTRFS_MAX_UNCOMPRESSED);
927 * We do compression for mount -o compress and when the inode has not
928 * been flagged as NOCOMPRESS. This flag can change at any time if we
929 * discover bad compression ratios.
931 if (!inode_need_compress(inode, start, end))
932 goto cleanup_and_bail_uncompressed;
934 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
937 * Memory allocation failure is not a fatal error, we can fall
938 * back to uncompressed code.
940 goto cleanup_and_bail_uncompressed;
943 if (inode->defrag_compress)
944 compress_type = inode->defrag_compress;
945 else if (inode->prop_compress)
946 compress_type = inode->prop_compress;
948 /* Compression level is applied here. */
949 ret = btrfs_compress_pages(compress_type | (fs_info->compress_level << 4),
950 mapping, start, pages, &nr_pages, &total_in,
953 goto mark_incompressible;
956 * Zero the tail end of the last page, as we might be sending it down
959 poff = offset_in_page(total_compressed);
961 memzero_page(pages[nr_pages - 1], poff, PAGE_SIZE - poff);
964 * Try to create an inline extent.
966 * If we didn't compress the entire range, try to create an uncompressed
967 * inline extent, else a compressed one.
969 * Check cow_file_range() for why we don't even try to create inline
970 * extent for the subpage case.
972 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
973 if (total_in < actual_end) {
974 ret = cow_file_range_inline(inode, actual_end, 0,
975 BTRFS_COMPRESS_NONE, NULL,
978 ret = cow_file_range_inline(inode, actual_end,
980 compress_type, pages,
984 unsigned long clear_flags = EXTENT_DELALLOC |
985 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
986 EXTENT_DO_ACCOUNTING;
989 mapping_set_error(mapping, -EIO);
992 * inline extent creation worked or returned error,
993 * we don't need to create any more async work items.
994 * Unlock and free up our temp pages.
996 * We use DO_ACCOUNTING here because we need the
997 * delalloc_release_metadata to be done _after_ we drop
998 * our outstanding extent for clearing delalloc for this
1001 extent_clear_unlock_delalloc(inode, start, end,
1005 PAGE_START_WRITEBACK |
1006 PAGE_END_WRITEBACK);
1012 * We aren't doing an inline extent. Round the compressed size up to a
1013 * block size boundary so the allocator does sane things.
1015 total_compressed = ALIGN(total_compressed, blocksize);
1018 * One last check to make sure the compression is really a win, compare
1019 * the page count read with the blocks on disk, compression must free at
1022 total_in = round_up(total_in, fs_info->sectorsize);
1023 if (total_compressed + blocksize > total_in)
1024 goto mark_incompressible;
1027 * The async work queues will take care of doing actual allocation on
1028 * disk for these compressed pages, and will submit the bios.
1030 add_async_extent(async_chunk, start, total_in, total_compressed, pages,
1031 nr_pages, compress_type);
1032 if (start + total_in < end) {
1039 mark_incompressible:
1040 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) && !inode->prop_compress)
1041 inode->flags |= BTRFS_INODE_NOCOMPRESS;
1042 cleanup_and_bail_uncompressed:
1043 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
1044 BTRFS_COMPRESS_NONE);
1047 for (i = 0; i < nr_pages; i++) {
1048 WARN_ON(pages[i]->mapping);
1049 btrfs_free_compr_page(pages[i]);
1055 static void free_async_extent_pages(struct async_extent *async_extent)
1059 if (!async_extent->pages)
1062 for (i = 0; i < async_extent->nr_pages; i++) {
1063 WARN_ON(async_extent->pages[i]->mapping);
1064 btrfs_free_compr_page(async_extent->pages[i]);
1066 kfree(async_extent->pages);
1067 async_extent->nr_pages = 0;
1068 async_extent->pages = NULL;
1071 static void submit_uncompressed_range(struct btrfs_inode *inode,
1072 struct async_extent *async_extent,
1073 struct page *locked_page)
1075 u64 start = async_extent->start;
1076 u64 end = async_extent->start + async_extent->ram_size - 1;
1078 struct writeback_control wbc = {
1079 .sync_mode = WB_SYNC_ALL,
1080 .range_start = start,
1082 .no_cgroup_owner = 1,
1085 wbc_attach_fdatawrite_inode(&wbc, &inode->vfs_inode);
1086 ret = run_delalloc_cow(inode, locked_page, start, end, &wbc, false);
1087 wbc_detach_inode(&wbc);
1089 btrfs_cleanup_ordered_extents(inode, locked_page, start, end - start + 1);
1091 const u64 page_start = page_offset(locked_page);
1093 set_page_writeback(locked_page);
1094 end_page_writeback(locked_page);
1095 btrfs_mark_ordered_io_finished(inode, locked_page,
1096 page_start, PAGE_SIZE,
1098 mapping_set_error(locked_page->mapping, ret);
1099 unlock_page(locked_page);
1104 static void submit_one_async_extent(struct async_chunk *async_chunk,
1105 struct async_extent *async_extent,
1108 struct btrfs_inode *inode = async_chunk->inode;
1109 struct extent_io_tree *io_tree = &inode->io_tree;
1110 struct btrfs_root *root = inode->root;
1111 struct btrfs_fs_info *fs_info = root->fs_info;
1112 struct btrfs_ordered_extent *ordered;
1113 struct btrfs_key ins;
1114 struct page *locked_page = NULL;
1115 struct extent_map *em;
1117 u64 start = async_extent->start;
1118 u64 end = async_extent->start + async_extent->ram_size - 1;
1120 if (async_chunk->blkcg_css)
1121 kthread_associate_blkcg(async_chunk->blkcg_css);
1124 * If async_chunk->locked_page is in the async_extent range, we need to
1127 if (async_chunk->locked_page) {
1128 u64 locked_page_start = page_offset(async_chunk->locked_page);
1129 u64 locked_page_end = locked_page_start + PAGE_SIZE - 1;
1131 if (!(start >= locked_page_end || end <= locked_page_start))
1132 locked_page = async_chunk->locked_page;
1134 lock_extent(io_tree, start, end, NULL);
1136 if (async_extent->compress_type == BTRFS_COMPRESS_NONE) {
1137 submit_uncompressed_range(inode, async_extent, locked_page);
1141 ret = btrfs_reserve_extent(root, async_extent->ram_size,
1142 async_extent->compressed_size,
1143 async_extent->compressed_size,
1144 0, *alloc_hint, &ins, 1, 1);
1147 * We can't reserve contiguous space for the compressed size.
1148 * Unlikely, but it's possible that we could have enough
1149 * non-contiguous space for the uncompressed size instead. So
1150 * fall back to uncompressed.
1152 submit_uncompressed_range(inode, async_extent, locked_page);
1156 /* Here we're doing allocation and writeback of the compressed pages */
1157 em = create_io_em(inode, start,
1158 async_extent->ram_size, /* len */
1159 start, /* orig_start */
1160 ins.objectid, /* block_start */
1161 ins.offset, /* block_len */
1162 ins.offset, /* orig_block_len */
1163 async_extent->ram_size, /* ram_bytes */
1164 async_extent->compress_type,
1165 BTRFS_ORDERED_COMPRESSED);
1168 goto out_free_reserve;
1170 free_extent_map(em);
1172 ordered = btrfs_alloc_ordered_extent(inode, start, /* file_offset */
1173 async_extent->ram_size, /* num_bytes */
1174 async_extent->ram_size, /* ram_bytes */
1175 ins.objectid, /* disk_bytenr */
1176 ins.offset, /* disk_num_bytes */
1178 1 << BTRFS_ORDERED_COMPRESSED,
1179 async_extent->compress_type);
1180 if (IS_ERR(ordered)) {
1181 btrfs_drop_extent_map_range(inode, start, end, false);
1182 ret = PTR_ERR(ordered);
1183 goto out_free_reserve;
1185 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1187 /* Clear dirty, set writeback and unlock the pages. */
1188 extent_clear_unlock_delalloc(inode, start, end,
1189 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
1190 PAGE_UNLOCK | PAGE_START_WRITEBACK);
1191 btrfs_submit_compressed_write(ordered,
1192 async_extent->pages, /* compressed_pages */
1193 async_extent->nr_pages,
1194 async_chunk->write_flags, true);
1195 *alloc_hint = ins.objectid + ins.offset;
1197 if (async_chunk->blkcg_css)
1198 kthread_associate_blkcg(NULL);
1199 kfree(async_extent);
1203 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1204 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1205 mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
1206 extent_clear_unlock_delalloc(inode, start, end,
1207 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
1208 EXTENT_DELALLOC_NEW |
1209 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
1210 PAGE_UNLOCK | PAGE_START_WRITEBACK |
1211 PAGE_END_WRITEBACK);
1212 free_async_extent_pages(async_extent);
1213 if (async_chunk->blkcg_css)
1214 kthread_associate_blkcg(NULL);
1215 btrfs_debug(fs_info,
1216 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1217 root->root_key.objectid, btrfs_ino(inode), start,
1218 async_extent->ram_size, ret);
1219 kfree(async_extent);
1222 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1225 struct extent_map_tree *em_tree = &inode->extent_tree;
1226 struct extent_map *em;
1229 read_lock(&em_tree->lock);
1230 em = search_extent_mapping(em_tree, start, num_bytes);
1233 * if block start isn't an actual block number then find the
1234 * first block in this inode and use that as a hint. If that
1235 * block is also bogus then just don't worry about it.
1237 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1238 free_extent_map(em);
1239 em = search_extent_mapping(em_tree, 0, 0);
1240 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1241 alloc_hint = em->block_start;
1243 free_extent_map(em);
1245 alloc_hint = em->block_start;
1246 free_extent_map(em);
1249 read_unlock(&em_tree->lock);
1255 * when extent_io.c finds a delayed allocation range in the file,
1256 * the call backs end up in this code. The basic idea is to
1257 * allocate extents on disk for the range, and create ordered data structs
1258 * in ram to track those extents.
1260 * locked_page is the page that writepage had locked already. We use
1261 * it to make sure we don't do extra locks or unlocks.
1263 * When this function fails, it unlocks all pages except @locked_page.
1265 * When this function successfully creates an inline extent, it returns 1 and
1266 * unlocks all pages including locked_page and starts I/O on them.
1267 * (In reality inline extents are limited to a single page, so locked_page is
1268 * the only page handled anyway).
1270 * When this function succeed and creates a normal extent, the page locking
1271 * status depends on the passed in flags:
1273 * - If @keep_locked is set, all pages are kept locked.
1274 * - Else all pages except for @locked_page are unlocked.
1276 * When a failure happens in the second or later iteration of the
1277 * while-loop, the ordered extents created in previous iterations are kept
1278 * intact. So, the caller must clean them up by calling
1279 * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
1282 static noinline int cow_file_range(struct btrfs_inode *inode,
1283 struct page *locked_page, u64 start, u64 end,
1285 bool keep_locked, bool no_inline)
1287 struct btrfs_root *root = inode->root;
1288 struct btrfs_fs_info *fs_info = root->fs_info;
1290 u64 orig_start = start;
1292 unsigned long ram_size;
1293 u64 cur_alloc_size = 0;
1295 u64 blocksize = fs_info->sectorsize;
1296 struct btrfs_key ins;
1297 struct extent_map *em;
1298 unsigned clear_bits;
1299 unsigned long page_ops;
1300 bool extent_reserved = false;
1303 if (btrfs_is_free_space_inode(inode)) {
1308 num_bytes = ALIGN(end - start + 1, blocksize);
1309 num_bytes = max(blocksize, num_bytes);
1310 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1312 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1315 * Due to the page size limit, for subpage we can only trigger the
1316 * writeback for the dirty sectors of page, that means data writeback
1317 * is doing more writeback than what we want.
1319 * This is especially unexpected for some call sites like fallocate,
1320 * where we only increase i_size after everything is done.
1321 * This means we can trigger inline extent even if we didn't want to.
1322 * So here we skip inline extent creation completely.
1324 if (start == 0 && fs_info->sectorsize == PAGE_SIZE && !no_inline) {
1325 u64 actual_end = min_t(u64, i_size_read(&inode->vfs_inode),
1328 /* lets try to make an inline extent */
1329 ret = cow_file_range_inline(inode, actual_end, 0,
1330 BTRFS_COMPRESS_NONE, NULL, false);
1333 * We use DO_ACCOUNTING here because we need the
1334 * delalloc_release_metadata to be run _after_ we drop
1335 * our outstanding extent for clearing delalloc for this
1338 extent_clear_unlock_delalloc(inode, start, end,
1340 EXTENT_LOCKED | EXTENT_DELALLOC |
1341 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1342 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1343 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1345 * locked_page is locked by the caller of
1346 * writepage_delalloc(), not locked by
1347 * __process_pages_contig().
1349 * We can't let __process_pages_contig() to unlock it,
1350 * as it doesn't have any subpage::writers recorded.
1352 * Here we manually unlock the page, since the caller
1353 * can't determine if it's an inline extent or a
1354 * compressed extent.
1356 unlock_page(locked_page);
1359 } else if (ret < 0) {
1364 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1367 * Relocation relies on the relocated extents to have exactly the same
1368 * size as the original extents. Normally writeback for relocation data
1369 * extents follows a NOCOW path because relocation preallocates the
1370 * extents. However, due to an operation such as scrub turning a block
1371 * group to RO mode, it may fallback to COW mode, so we must make sure
1372 * an extent allocated during COW has exactly the requested size and can
1373 * not be split into smaller extents, otherwise relocation breaks and
1374 * fails during the stage where it updates the bytenr of file extent
1377 if (btrfs_is_data_reloc_root(root))
1378 min_alloc_size = num_bytes;
1380 min_alloc_size = fs_info->sectorsize;
1382 while (num_bytes > 0) {
1383 struct btrfs_ordered_extent *ordered;
1385 cur_alloc_size = num_bytes;
1386 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1387 min_alloc_size, 0, alloc_hint,
1389 if (ret == -EAGAIN) {
1391 * btrfs_reserve_extent only returns -EAGAIN for zoned
1392 * file systems, which is an indication that there are
1393 * no active zones to allocate from at the moment.
1395 * If this is the first loop iteration, wait for at
1396 * least one zone to finish before retrying the
1397 * allocation. Otherwise ask the caller to write out
1398 * the already allocated blocks before coming back to
1399 * us, or return -ENOSPC if it can't handle retries.
1401 ASSERT(btrfs_is_zoned(fs_info));
1402 if (start == orig_start) {
1403 wait_on_bit_io(&inode->root->fs_info->flags,
1404 BTRFS_FS_NEED_ZONE_FINISH,
1405 TASK_UNINTERRUPTIBLE);
1409 *done_offset = start - 1;
1416 cur_alloc_size = ins.offset;
1417 extent_reserved = true;
1419 ram_size = ins.offset;
1420 em = create_io_em(inode, start, ins.offset, /* len */
1421 start, /* orig_start */
1422 ins.objectid, /* block_start */
1423 ins.offset, /* block_len */
1424 ins.offset, /* orig_block_len */
1425 ram_size, /* ram_bytes */
1426 BTRFS_COMPRESS_NONE, /* compress_type */
1427 BTRFS_ORDERED_REGULAR /* type */);
1432 free_extent_map(em);
1434 ordered = btrfs_alloc_ordered_extent(inode, start, ram_size,
1435 ram_size, ins.objectid, cur_alloc_size,
1436 0, 1 << BTRFS_ORDERED_REGULAR,
1437 BTRFS_COMPRESS_NONE);
1438 if (IS_ERR(ordered)) {
1439 ret = PTR_ERR(ordered);
1440 goto out_drop_extent_cache;
1443 if (btrfs_is_data_reloc_root(root)) {
1444 ret = btrfs_reloc_clone_csums(ordered);
1447 * Only drop cache here, and process as normal.
1449 * We must not allow extent_clear_unlock_delalloc()
1450 * at out_unlock label to free meta of this ordered
1451 * extent, as its meta should be freed by
1452 * btrfs_finish_ordered_io().
1454 * So we must continue until @start is increased to
1455 * skip current ordered extent.
1458 btrfs_drop_extent_map_range(inode, start,
1459 start + ram_size - 1,
1462 btrfs_put_ordered_extent(ordered);
1464 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1467 * We're not doing compressed IO, don't unlock the first page
1468 * (which the caller expects to stay locked), don't clear any
1469 * dirty bits and don't set any writeback bits
1471 * Do set the Ordered (Private2) bit so we know this page was
1472 * properly setup for writepage.
1474 page_ops = (keep_locked ? 0 : PAGE_UNLOCK);
1475 page_ops |= PAGE_SET_ORDERED;
1477 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1479 EXTENT_LOCKED | EXTENT_DELALLOC,
1481 if (num_bytes < cur_alloc_size)
1484 num_bytes -= cur_alloc_size;
1485 alloc_hint = ins.objectid + ins.offset;
1486 start += cur_alloc_size;
1487 extent_reserved = false;
1490 * btrfs_reloc_clone_csums() error, since start is increased
1491 * extent_clear_unlock_delalloc() at out_unlock label won't
1492 * free metadata of current ordered extent, we're OK to exit.
1502 out_drop_extent_cache:
1503 btrfs_drop_extent_map_range(inode, start, start + ram_size - 1, false);
1505 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1506 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1509 * Now, we have three regions to clean up:
1511 * |-------(1)----|---(2)---|-------------(3)----------|
1512 * `- orig_start `- start `- start + cur_alloc_size `- end
1514 * We process each region below.
1517 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1518 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1519 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1522 * For the range (1). We have already instantiated the ordered extents
1523 * for this region. They are cleaned up by
1524 * btrfs_cleanup_ordered_extents() in e.g,
1525 * btrfs_run_delalloc_range(). EXTENT_LOCKED | EXTENT_DELALLOC are
1526 * already cleared in the above loop. And, EXTENT_DELALLOC_NEW |
1527 * EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV are handled by the cleanup
1530 * However, in case of @keep_locked, we still need to unlock the pages
1531 * (except @locked_page) to ensure all the pages are unlocked.
1533 if (keep_locked && orig_start < start) {
1535 mapping_set_error(inode->vfs_inode.i_mapping, ret);
1536 extent_clear_unlock_delalloc(inode, orig_start, start - 1,
1537 locked_page, 0, page_ops);
1541 * For the range (2). If we reserved an extent for our delalloc range
1542 * (or a subrange) and failed to create the respective ordered extent,
1543 * then it means that when we reserved the extent we decremented the
1544 * extent's size from the data space_info's bytes_may_use counter and
1545 * incremented the space_info's bytes_reserved counter by the same
1546 * amount. We must make sure extent_clear_unlock_delalloc() does not try
1547 * to decrement again the data space_info's bytes_may_use counter,
1548 * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
1550 if (extent_reserved) {
1551 extent_clear_unlock_delalloc(inode, start,
1552 start + cur_alloc_size - 1,
1556 start += cur_alloc_size;
1560 * For the range (3). We never touched the region. In addition to the
1561 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1562 * space_info's bytes_may_use counter, reserved in
1563 * btrfs_check_data_free_space().
1566 clear_bits |= EXTENT_CLEAR_DATA_RESV;
1567 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1568 clear_bits, page_ops);
1574 * Phase two of compressed writeback. This is the ordered portion of the code,
1575 * which only gets called in the order the work was queued. We walk all the
1576 * async extents created by compress_file_range and send them down to the disk.
1578 * If called with @do_free == true then it'll try to finish the work and free
1579 * the work struct eventually.
1581 static noinline void submit_compressed_extents(struct btrfs_work *work, bool do_free)
1583 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1585 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1586 struct async_extent *async_extent;
1587 unsigned long nr_pages;
1591 struct async_chunk *async_chunk;
1592 struct async_cow *async_cow;
1594 async_chunk = container_of(work, struct async_chunk, work);
1595 btrfs_add_delayed_iput(async_chunk->inode);
1596 if (async_chunk->blkcg_css)
1597 css_put(async_chunk->blkcg_css);
1599 async_cow = async_chunk->async_cow;
1600 if (atomic_dec_and_test(&async_cow->num_chunks))
1605 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1608 while (!list_empty(&async_chunk->extents)) {
1609 async_extent = list_entry(async_chunk->extents.next,
1610 struct async_extent, list);
1611 list_del(&async_extent->list);
1612 submit_one_async_extent(async_chunk, async_extent, &alloc_hint);
1615 /* atomic_sub_return implies a barrier */
1616 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1618 cond_wake_up_nomb(&fs_info->async_submit_wait);
1621 static bool run_delalloc_compressed(struct btrfs_inode *inode,
1622 struct page *locked_page, u64 start,
1623 u64 end, struct writeback_control *wbc)
1625 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1626 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1627 struct async_cow *ctx;
1628 struct async_chunk *async_chunk;
1629 unsigned long nr_pages;
1630 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1633 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1635 nofs_flag = memalloc_nofs_save();
1636 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1637 memalloc_nofs_restore(nofs_flag);
1641 unlock_extent(&inode->io_tree, start, end, NULL);
1642 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1644 async_chunk = ctx->chunks;
1645 atomic_set(&ctx->num_chunks, num_chunks);
1647 for (i = 0; i < num_chunks; i++) {
1648 u64 cur_end = min(end, start + SZ_512K - 1);
1651 * igrab is called higher up in the call chain, take only the
1652 * lightweight reference for the callback lifetime
1654 ihold(&inode->vfs_inode);
1655 async_chunk[i].async_cow = ctx;
1656 async_chunk[i].inode = inode;
1657 async_chunk[i].start = start;
1658 async_chunk[i].end = cur_end;
1659 async_chunk[i].write_flags = write_flags;
1660 INIT_LIST_HEAD(&async_chunk[i].extents);
1663 * The locked_page comes all the way from writepage and its
1664 * the original page we were actually given. As we spread
1665 * this large delalloc region across multiple async_chunk
1666 * structs, only the first struct needs a pointer to locked_page
1668 * This way we don't need racey decisions about who is supposed
1673 * Depending on the compressibility, the pages might or
1674 * might not go through async. We want all of them to
1675 * be accounted against wbc once. Let's do it here
1676 * before the paths diverge. wbc accounting is used
1677 * only for foreign writeback detection and doesn't
1678 * need full accuracy. Just account the whole thing
1679 * against the first page.
1681 wbc_account_cgroup_owner(wbc, locked_page,
1683 async_chunk[i].locked_page = locked_page;
1686 async_chunk[i].locked_page = NULL;
1689 if (blkcg_css != blkcg_root_css) {
1691 async_chunk[i].blkcg_css = blkcg_css;
1692 async_chunk[i].write_flags |= REQ_BTRFS_CGROUP_PUNT;
1694 async_chunk[i].blkcg_css = NULL;
1697 btrfs_init_work(&async_chunk[i].work, compress_file_range,
1698 submit_compressed_extents);
1700 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1701 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1703 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1705 start = cur_end + 1;
1711 * Run the delalloc range from start to end, and write back any dirty pages
1712 * covered by the range.
1714 static noinline int run_delalloc_cow(struct btrfs_inode *inode,
1715 struct page *locked_page, u64 start,
1716 u64 end, struct writeback_control *wbc,
1719 u64 done_offset = end;
1722 while (start <= end) {
1723 ret = cow_file_range(inode, locked_page, start, end, &done_offset,
1727 extent_write_locked_range(&inode->vfs_inode, locked_page, start,
1728 done_offset, wbc, pages_dirty);
1729 start = done_offset + 1;
1735 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1736 u64 bytenr, u64 num_bytes, bool nowait)
1738 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bytenr);
1739 struct btrfs_ordered_sum *sums;
1743 ret = btrfs_lookup_csums_list(csum_root, bytenr, bytenr + num_bytes - 1,
1745 if (ret == 0 && list_empty(&list))
1748 while (!list_empty(&list)) {
1749 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1750 list_del(&sums->list);
1758 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1759 const u64 start, const u64 end)
1761 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1762 const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1763 const u64 range_bytes = end + 1 - start;
1764 struct extent_io_tree *io_tree = &inode->io_tree;
1765 u64 range_start = start;
1770 * If EXTENT_NORESERVE is set it means that when the buffered write was
1771 * made we had not enough available data space and therefore we did not
1772 * reserve data space for it, since we though we could do NOCOW for the
1773 * respective file range (either there is prealloc extent or the inode
1774 * has the NOCOW bit set).
1776 * However when we need to fallback to COW mode (because for example the
1777 * block group for the corresponding extent was turned to RO mode by a
1778 * scrub or relocation) we need to do the following:
1780 * 1) We increment the bytes_may_use counter of the data space info.
1781 * If COW succeeds, it allocates a new data extent and after doing
1782 * that it decrements the space info's bytes_may_use counter and
1783 * increments its bytes_reserved counter by the same amount (we do
1784 * this at btrfs_add_reserved_bytes()). So we need to increment the
1785 * bytes_may_use counter to compensate (when space is reserved at
1786 * buffered write time, the bytes_may_use counter is incremented);
1788 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1789 * that if the COW path fails for any reason, it decrements (through
1790 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1791 * data space info, which we incremented in the step above.
1793 * If we need to fallback to cow and the inode corresponds to a free
1794 * space cache inode or an inode of the data relocation tree, we must
1795 * also increment bytes_may_use of the data space_info for the same
1796 * reason. Space caches and relocated data extents always get a prealloc
1797 * extent for them, however scrub or balance may have set the block
1798 * group that contains that extent to RO mode and therefore force COW
1799 * when starting writeback.
1801 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1802 EXTENT_NORESERVE, 0, NULL);
1803 if (count > 0 || is_space_ino || is_reloc_ino) {
1805 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1806 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1808 if (is_space_ino || is_reloc_ino)
1809 bytes = range_bytes;
1811 spin_lock(&sinfo->lock);
1812 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1813 spin_unlock(&sinfo->lock);
1816 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1821 * Don't try to create inline extents, as a mix of inline extent that
1822 * is written out and unlocked directly and a normal NOCOW extent
1825 ret = cow_file_range(inode, locked_page, start, end, NULL, false, true);
1830 struct can_nocow_file_extent_args {
1833 /* Start file offset of the range we want to NOCOW. */
1835 /* End file offset (inclusive) of the range we want to NOCOW. */
1837 bool writeback_path;
1840 * Free the path passed to can_nocow_file_extent() once it's not needed
1845 /* Output fields. Only set when can_nocow_file_extent() returns 1. */
1850 /* Number of bytes that can be written to in NOCOW mode. */
1855 * Check if we can NOCOW the file extent that the path points to.
1856 * This function may return with the path released, so the caller should check
1857 * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
1859 * Returns: < 0 on error
1860 * 0 if we can not NOCOW
1863 static int can_nocow_file_extent(struct btrfs_path *path,
1864 struct btrfs_key *key,
1865 struct btrfs_inode *inode,
1866 struct can_nocow_file_extent_args *args)
1868 const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
1869 struct extent_buffer *leaf = path->nodes[0];
1870 struct btrfs_root *root = inode->root;
1871 struct btrfs_file_extent_item *fi;
1876 bool nowait = path->nowait;
1878 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
1879 extent_type = btrfs_file_extent_type(leaf, fi);
1881 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1884 /* Can't access these fields unless we know it's not an inline extent. */
1885 args->disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1886 args->disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1887 args->extent_offset = btrfs_file_extent_offset(leaf, fi);
1889 if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1890 extent_type == BTRFS_FILE_EXTENT_REG)
1894 * If the extent was created before the generation where the last snapshot
1895 * for its subvolume was created, then this implies the extent is shared,
1896 * hence we must COW.
1898 if (!args->strict &&
1899 btrfs_file_extent_generation(leaf, fi) <=
1900 btrfs_root_last_snapshot(&root->root_item))
1903 /* An explicit hole, must COW. */
1904 if (args->disk_bytenr == 0)
1907 /* Compressed/encrypted/encoded extents must be COWed. */
1908 if (btrfs_file_extent_compression(leaf, fi) ||
1909 btrfs_file_extent_encryption(leaf, fi) ||
1910 btrfs_file_extent_other_encoding(leaf, fi))
1913 extent_end = btrfs_file_extent_end(path);
1916 * The following checks can be expensive, as they need to take other
1917 * locks and do btree or rbtree searches, so release the path to avoid
1918 * blocking other tasks for too long.
1920 btrfs_release_path(path);
1922 ret = btrfs_cross_ref_exist(root, btrfs_ino(inode),
1923 key->offset - args->extent_offset,
1924 args->disk_bytenr, args->strict, path);
1925 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1929 if (args->free_path) {
1931 * We don't need the path anymore, plus through the
1932 * csum_exist_in_range() call below we will end up allocating
1933 * another path. So free the path to avoid unnecessary extra
1936 btrfs_free_path(path);
1940 /* If there are pending snapshots for this root, we must COW. */
1941 if (args->writeback_path && !is_freespace_inode &&
1942 atomic_read(&root->snapshot_force_cow))
1945 args->disk_bytenr += args->extent_offset;
1946 args->disk_bytenr += args->start - key->offset;
1947 args->num_bytes = min(args->end + 1, extent_end) - args->start;
1950 * Force COW if csums exist in the range. This ensures that csums for a
1951 * given extent are either valid or do not exist.
1953 ret = csum_exist_in_range(root->fs_info, args->disk_bytenr, args->num_bytes,
1955 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1961 if (args->free_path && path)
1962 btrfs_free_path(path);
1964 return ret < 0 ? ret : can_nocow;
1968 * when nowcow writeback call back. This checks for snapshots or COW copies
1969 * of the extents that exist in the file, and COWs the file as required.
1971 * If no cow copies or snapshots exist, we write directly to the existing
1974 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1975 struct page *locked_page,
1976 const u64 start, const u64 end)
1978 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1979 struct btrfs_root *root = inode->root;
1980 struct btrfs_path *path;
1981 u64 cow_start = (u64)-1;
1982 u64 cur_offset = start;
1984 bool check_prev = true;
1985 u64 ino = btrfs_ino(inode);
1986 struct can_nocow_file_extent_args nocow_args = { 0 };
1989 * Normally on a zoned device we're only doing COW writes, but in case
1990 * of relocation on a zoned filesystem serializes I/O so that we're only
1991 * writing sequentially and can end up here as well.
1993 ASSERT(!btrfs_is_zoned(fs_info) || btrfs_is_data_reloc_root(root));
1995 path = btrfs_alloc_path();
2001 nocow_args.end = end;
2002 nocow_args.writeback_path = true;
2005 struct btrfs_block_group *nocow_bg = NULL;
2006 struct btrfs_ordered_extent *ordered;
2007 struct btrfs_key found_key;
2008 struct btrfs_file_extent_item *fi;
2009 struct extent_buffer *leaf;
2016 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
2022 * If there is no extent for our range when doing the initial
2023 * search, then go back to the previous slot as it will be the
2024 * one containing the search offset
2026 if (ret > 0 && path->slots[0] > 0 && check_prev) {
2027 leaf = path->nodes[0];
2028 btrfs_item_key_to_cpu(leaf, &found_key,
2029 path->slots[0] - 1);
2030 if (found_key.objectid == ino &&
2031 found_key.type == BTRFS_EXTENT_DATA_KEY)
2036 /* Go to next leaf if we have exhausted the current one */
2037 leaf = path->nodes[0];
2038 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2039 ret = btrfs_next_leaf(root, path);
2044 leaf = path->nodes[0];
2047 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2049 /* Didn't find anything for our INO */
2050 if (found_key.objectid > ino)
2053 * Keep searching until we find an EXTENT_ITEM or there are no
2054 * more extents for this inode
2056 if (WARN_ON_ONCE(found_key.objectid < ino) ||
2057 found_key.type < BTRFS_EXTENT_DATA_KEY) {
2062 /* Found key is not EXTENT_DATA_KEY or starts after req range */
2063 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
2064 found_key.offset > end)
2068 * If the found extent starts after requested offset, then
2069 * adjust extent_end to be right before this extent begins
2071 if (found_key.offset > cur_offset) {
2072 extent_end = found_key.offset;
2078 * Found extent which begins before our range and potentially
2081 fi = btrfs_item_ptr(leaf, path->slots[0],
2082 struct btrfs_file_extent_item);
2083 extent_type = btrfs_file_extent_type(leaf, fi);
2084 /* If this is triggered then we have a memory corruption. */
2085 ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
2086 if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
2090 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
2091 extent_end = btrfs_file_extent_end(path);
2094 * If the extent we got ends before our current offset, skip to
2097 if (extent_end <= cur_offset) {
2102 nocow_args.start = cur_offset;
2103 ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
2110 nocow_bg = btrfs_inc_nocow_writers(fs_info, nocow_args.disk_bytenr);
2114 * If we can't perform NOCOW writeback for the range,
2115 * then record the beginning of the range that needs to
2116 * be COWed. It will be written out before the next
2117 * NOCOW range if we find one, or when exiting this
2120 if (cow_start == (u64)-1)
2121 cow_start = cur_offset;
2122 cur_offset = extent_end;
2123 if (cur_offset > end)
2125 if (!path->nodes[0])
2132 * COW range from cow_start to found_key.offset - 1. As the key
2133 * will contain the beginning of the first extent that can be
2134 * NOCOW, following one which needs to be COW'ed
2136 if (cow_start != (u64)-1) {
2137 ret = fallback_to_cow(inode, locked_page,
2138 cow_start, found_key.offset - 1);
2139 cow_start = (u64)-1;
2141 btrfs_dec_nocow_writers(nocow_bg);
2146 nocow_end = cur_offset + nocow_args.num_bytes - 1;
2147 is_prealloc = extent_type == BTRFS_FILE_EXTENT_PREALLOC;
2149 u64 orig_start = found_key.offset - nocow_args.extent_offset;
2150 struct extent_map *em;
2152 em = create_io_em(inode, cur_offset, nocow_args.num_bytes,
2154 nocow_args.disk_bytenr, /* block_start */
2155 nocow_args.num_bytes, /* block_len */
2156 nocow_args.disk_num_bytes, /* orig_block_len */
2157 ram_bytes, BTRFS_COMPRESS_NONE,
2158 BTRFS_ORDERED_PREALLOC);
2160 btrfs_dec_nocow_writers(nocow_bg);
2164 free_extent_map(em);
2167 ordered = btrfs_alloc_ordered_extent(inode, cur_offset,
2168 nocow_args.num_bytes, nocow_args.num_bytes,
2169 nocow_args.disk_bytenr, nocow_args.num_bytes, 0,
2171 ? (1 << BTRFS_ORDERED_PREALLOC)
2172 : (1 << BTRFS_ORDERED_NOCOW),
2173 BTRFS_COMPRESS_NONE);
2174 btrfs_dec_nocow_writers(nocow_bg);
2175 if (IS_ERR(ordered)) {
2177 btrfs_drop_extent_map_range(inode, cur_offset,
2180 ret = PTR_ERR(ordered);
2184 if (btrfs_is_data_reloc_root(root))
2186 * Error handled later, as we must prevent
2187 * extent_clear_unlock_delalloc() in error handler
2188 * from freeing metadata of created ordered extent.
2190 ret = btrfs_reloc_clone_csums(ordered);
2191 btrfs_put_ordered_extent(ordered);
2193 extent_clear_unlock_delalloc(inode, cur_offset, nocow_end,
2194 locked_page, EXTENT_LOCKED |
2196 EXTENT_CLEAR_DATA_RESV,
2197 PAGE_UNLOCK | PAGE_SET_ORDERED);
2199 cur_offset = extent_end;
2202 * btrfs_reloc_clone_csums() error, now we're OK to call error
2203 * handler, as metadata for created ordered extent will only
2204 * be freed by btrfs_finish_ordered_io().
2208 if (cur_offset > end)
2211 btrfs_release_path(path);
2213 if (cur_offset <= end && cow_start == (u64)-1)
2214 cow_start = cur_offset;
2216 if (cow_start != (u64)-1) {
2218 ret = fallback_to_cow(inode, locked_page, cow_start, end);
2219 cow_start = (u64)-1;
2224 btrfs_free_path(path);
2229 * If an error happened while a COW region is outstanding, cur_offset
2230 * needs to be reset to cow_start to ensure the COW region is unlocked
2233 if (cow_start != (u64)-1)
2234 cur_offset = cow_start;
2235 if (cur_offset < end)
2236 extent_clear_unlock_delalloc(inode, cur_offset, end,
2237 locked_page, EXTENT_LOCKED |
2238 EXTENT_DELALLOC | EXTENT_DEFRAG |
2239 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
2240 PAGE_START_WRITEBACK |
2241 PAGE_END_WRITEBACK);
2242 btrfs_free_path(path);
2246 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
2248 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
2249 if (inode->defrag_bytes &&
2250 test_range_bit_exists(&inode->io_tree, start, end, EXTENT_DEFRAG))
2258 * Function to process delayed allocation (create CoW) for ranges which are
2259 * being touched for the first time.
2261 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
2262 u64 start, u64 end, struct writeback_control *wbc)
2264 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2268 * The range must cover part of the @locked_page, or a return of 1
2269 * can confuse the caller.
2271 ASSERT(!(end <= page_offset(locked_page) ||
2272 start >= page_offset(locked_page) + PAGE_SIZE));
2274 if (should_nocow(inode, start, end)) {
2275 ret = run_delalloc_nocow(inode, locked_page, start, end);
2279 if (btrfs_inode_can_compress(inode) &&
2280 inode_need_compress(inode, start, end) &&
2281 run_delalloc_compressed(inode, locked_page, start, end, wbc))
2285 ret = run_delalloc_cow(inode, locked_page, start, end, wbc,
2288 ret = cow_file_range(inode, locked_page, start, end, NULL,
2293 btrfs_cleanup_ordered_extents(inode, locked_page, start,
2298 void btrfs_split_delalloc_extent(struct btrfs_inode *inode,
2299 struct extent_state *orig, u64 split)
2301 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2304 /* not delalloc, ignore it */
2305 if (!(orig->state & EXTENT_DELALLOC))
2308 size = orig->end - orig->start + 1;
2309 if (size > fs_info->max_extent_size) {
2314 * See the explanation in btrfs_merge_delalloc_extent, the same
2315 * applies here, just in reverse.
2317 new_size = orig->end - split + 1;
2318 num_extents = count_max_extents(fs_info, new_size);
2319 new_size = split - orig->start;
2320 num_extents += count_max_extents(fs_info, new_size);
2321 if (count_max_extents(fs_info, size) >= num_extents)
2325 spin_lock(&inode->lock);
2326 btrfs_mod_outstanding_extents(inode, 1);
2327 spin_unlock(&inode->lock);
2331 * Handle merged delayed allocation extents so we can keep track of new extents
2332 * that are just merged onto old extents, such as when we are doing sequential
2333 * writes, so we can properly account for the metadata space we'll need.
2335 void btrfs_merge_delalloc_extent(struct btrfs_inode *inode, struct extent_state *new,
2336 struct extent_state *other)
2338 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2339 u64 new_size, old_size;
2342 /* not delalloc, ignore it */
2343 if (!(other->state & EXTENT_DELALLOC))
2346 if (new->start > other->start)
2347 new_size = new->end - other->start + 1;
2349 new_size = other->end - new->start + 1;
2351 /* we're not bigger than the max, unreserve the space and go */
2352 if (new_size <= fs_info->max_extent_size) {
2353 spin_lock(&inode->lock);
2354 btrfs_mod_outstanding_extents(inode, -1);
2355 spin_unlock(&inode->lock);
2360 * We have to add up either side to figure out how many extents were
2361 * accounted for before we merged into one big extent. If the number of
2362 * extents we accounted for is <= the amount we need for the new range
2363 * then we can return, otherwise drop. Think of it like this
2367 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2368 * need 2 outstanding extents, on one side we have 1 and the other side
2369 * we have 1 so they are == and we can return. But in this case
2371 * [MAX_SIZE+4k][MAX_SIZE+4k]
2373 * Each range on their own accounts for 2 extents, but merged together
2374 * they are only 3 extents worth of accounting, so we need to drop in
2377 old_size = other->end - other->start + 1;
2378 num_extents = count_max_extents(fs_info, old_size);
2379 old_size = new->end - new->start + 1;
2380 num_extents += count_max_extents(fs_info, old_size);
2381 if (count_max_extents(fs_info, new_size) >= num_extents)
2384 spin_lock(&inode->lock);
2385 btrfs_mod_outstanding_extents(inode, -1);
2386 spin_unlock(&inode->lock);
2389 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2390 struct btrfs_inode *inode)
2392 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2394 spin_lock(&root->delalloc_lock);
2395 if (list_empty(&inode->delalloc_inodes)) {
2396 list_add_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
2397 set_bit(BTRFS_INODE_IN_DELALLOC_LIST, &inode->runtime_flags);
2398 root->nr_delalloc_inodes++;
2399 if (root->nr_delalloc_inodes == 1) {
2400 spin_lock(&fs_info->delalloc_root_lock);
2401 BUG_ON(!list_empty(&root->delalloc_root));
2402 list_add_tail(&root->delalloc_root,
2403 &fs_info->delalloc_roots);
2404 spin_unlock(&fs_info->delalloc_root_lock);
2407 spin_unlock(&root->delalloc_lock);
2410 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2411 struct btrfs_inode *inode)
2413 struct btrfs_fs_info *fs_info = root->fs_info;
2415 if (!list_empty(&inode->delalloc_inodes)) {
2416 list_del_init(&inode->delalloc_inodes);
2417 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2418 &inode->runtime_flags);
2419 root->nr_delalloc_inodes--;
2420 if (!root->nr_delalloc_inodes) {
2421 ASSERT(list_empty(&root->delalloc_inodes));
2422 spin_lock(&fs_info->delalloc_root_lock);
2423 BUG_ON(list_empty(&root->delalloc_root));
2424 list_del_init(&root->delalloc_root);
2425 spin_unlock(&fs_info->delalloc_root_lock);
2430 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2431 struct btrfs_inode *inode)
2433 spin_lock(&root->delalloc_lock);
2434 __btrfs_del_delalloc_inode(root, inode);
2435 spin_unlock(&root->delalloc_lock);
2439 * Properly track delayed allocation bytes in the inode and to maintain the
2440 * list of inodes that have pending delalloc work to be done.
2442 void btrfs_set_delalloc_extent(struct btrfs_inode *inode, struct extent_state *state,
2445 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2447 if ((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC))
2450 * set_bit and clear bit hooks normally require _irqsave/restore
2451 * but in this case, we are only testing for the DELALLOC
2452 * bit, which is only set or cleared with irqs on
2454 if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2455 struct btrfs_root *root = inode->root;
2456 u64 len = state->end + 1 - state->start;
2457 u32 num_extents = count_max_extents(fs_info, len);
2458 bool do_list = !btrfs_is_free_space_inode(inode);
2460 spin_lock(&inode->lock);
2461 btrfs_mod_outstanding_extents(inode, num_extents);
2462 spin_unlock(&inode->lock);
2464 /* For sanity tests */
2465 if (btrfs_is_testing(fs_info))
2468 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2469 fs_info->delalloc_batch);
2470 spin_lock(&inode->lock);
2471 inode->delalloc_bytes += len;
2472 if (bits & EXTENT_DEFRAG)
2473 inode->defrag_bytes += len;
2474 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2475 &inode->runtime_flags))
2476 btrfs_add_delalloc_inodes(root, inode);
2477 spin_unlock(&inode->lock);
2480 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2481 (bits & EXTENT_DELALLOC_NEW)) {
2482 spin_lock(&inode->lock);
2483 inode->new_delalloc_bytes += state->end + 1 - state->start;
2484 spin_unlock(&inode->lock);
2489 * Once a range is no longer delalloc this function ensures that proper
2490 * accounting happens.
2492 void btrfs_clear_delalloc_extent(struct btrfs_inode *inode,
2493 struct extent_state *state, u32 bits)
2495 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2496 u64 len = state->end + 1 - state->start;
2497 u32 num_extents = count_max_extents(fs_info, len);
2499 if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
2500 spin_lock(&inode->lock);
2501 inode->defrag_bytes -= len;
2502 spin_unlock(&inode->lock);
2506 * set_bit and clear bit hooks normally require _irqsave/restore
2507 * but in this case, we are only testing for the DELALLOC
2508 * bit, which is only set or cleared with irqs on
2510 if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2511 struct btrfs_root *root = inode->root;
2512 bool do_list = !btrfs_is_free_space_inode(inode);
2514 spin_lock(&inode->lock);
2515 btrfs_mod_outstanding_extents(inode, -num_extents);
2516 spin_unlock(&inode->lock);
2519 * We don't reserve metadata space for space cache inodes so we
2520 * don't need to call delalloc_release_metadata if there is an
2523 if (bits & EXTENT_CLEAR_META_RESV &&
2524 root != fs_info->tree_root)
2525 btrfs_delalloc_release_metadata(inode, len, false);
2527 /* For sanity tests. */
2528 if (btrfs_is_testing(fs_info))
2531 if (!btrfs_is_data_reloc_root(root) &&
2532 do_list && !(state->state & EXTENT_NORESERVE) &&
2533 (bits & EXTENT_CLEAR_DATA_RESV))
2534 btrfs_free_reserved_data_space_noquota(fs_info, len);
2536 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2537 fs_info->delalloc_batch);
2538 spin_lock(&inode->lock);
2539 inode->delalloc_bytes -= len;
2540 if (do_list && inode->delalloc_bytes == 0 &&
2541 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2542 &inode->runtime_flags))
2543 btrfs_del_delalloc_inode(root, inode);
2544 spin_unlock(&inode->lock);
2547 if ((state->state & EXTENT_DELALLOC_NEW) &&
2548 (bits & EXTENT_DELALLOC_NEW)) {
2549 spin_lock(&inode->lock);
2550 ASSERT(inode->new_delalloc_bytes >= len);
2551 inode->new_delalloc_bytes -= len;
2552 if (bits & EXTENT_ADD_INODE_BYTES)
2553 inode_add_bytes(&inode->vfs_inode, len);
2554 spin_unlock(&inode->lock);
2558 static int btrfs_extract_ordered_extent(struct btrfs_bio *bbio,
2559 struct btrfs_ordered_extent *ordered)
2561 u64 start = (u64)bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT;
2562 u64 len = bbio->bio.bi_iter.bi_size;
2563 struct btrfs_ordered_extent *new;
2566 /* Must always be called for the beginning of an ordered extent. */
2567 if (WARN_ON_ONCE(start != ordered->disk_bytenr))
2570 /* No need to split if the ordered extent covers the entire bio. */
2571 if (ordered->disk_num_bytes == len) {
2572 refcount_inc(&ordered->refs);
2573 bbio->ordered = ordered;
2578 * Don't split the extent_map for NOCOW extents, as we're writing into
2579 * a pre-existing one.
2581 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
2582 ret = split_extent_map(bbio->inode, bbio->file_offset,
2583 ordered->num_bytes, len,
2584 ordered->disk_bytenr);
2589 new = btrfs_split_ordered_extent(ordered, len);
2591 return PTR_ERR(new);
2592 bbio->ordered = new;
2597 * given a list of ordered sums record them in the inode. This happens
2598 * at IO completion time based on sums calculated at bio submission time.
2600 static int add_pending_csums(struct btrfs_trans_handle *trans,
2601 struct list_head *list)
2603 struct btrfs_ordered_sum *sum;
2604 struct btrfs_root *csum_root = NULL;
2607 list_for_each_entry(sum, list, list) {
2608 trans->adding_csums = true;
2610 csum_root = btrfs_csum_root(trans->fs_info,
2612 ret = btrfs_csum_file_blocks(trans, csum_root, sum);
2613 trans->adding_csums = false;
2620 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2623 struct extent_state **cached_state)
2625 u64 search_start = start;
2626 const u64 end = start + len - 1;
2628 while (search_start < end) {
2629 const u64 search_len = end - search_start + 1;
2630 struct extent_map *em;
2634 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2638 if (em->block_start != EXTENT_MAP_HOLE)
2642 if (em->start < search_start)
2643 em_len -= search_start - em->start;
2644 if (em_len > search_len)
2645 em_len = search_len;
2647 ret = set_extent_bit(&inode->io_tree, search_start,
2648 search_start + em_len - 1,
2649 EXTENT_DELALLOC_NEW, cached_state);
2651 search_start = extent_map_end(em);
2652 free_extent_map(em);
2659 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2660 unsigned int extra_bits,
2661 struct extent_state **cached_state)
2663 WARN_ON(PAGE_ALIGNED(end));
2665 if (start >= i_size_read(&inode->vfs_inode) &&
2666 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2668 * There can't be any extents following eof in this case so just
2669 * set the delalloc new bit for the range directly.
2671 extra_bits |= EXTENT_DELALLOC_NEW;
2675 ret = btrfs_find_new_delalloc_bytes(inode, start,
2682 return set_extent_bit(&inode->io_tree, start, end,
2683 EXTENT_DELALLOC | extra_bits, cached_state);
2686 /* see btrfs_writepage_start_hook for details on why this is required */
2687 struct btrfs_writepage_fixup {
2689 struct btrfs_inode *inode;
2690 struct btrfs_work work;
2693 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2695 struct btrfs_writepage_fixup *fixup =
2696 container_of(work, struct btrfs_writepage_fixup, work);
2697 struct btrfs_ordered_extent *ordered;
2698 struct extent_state *cached_state = NULL;
2699 struct extent_changeset *data_reserved = NULL;
2700 struct page *page = fixup->page;
2701 struct btrfs_inode *inode = fixup->inode;
2702 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2703 u64 page_start = page_offset(page);
2704 u64 page_end = page_offset(page) + PAGE_SIZE - 1;
2706 bool free_delalloc_space = true;
2709 * This is similar to page_mkwrite, we need to reserve the space before
2710 * we take the page lock.
2712 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2718 * Before we queued this fixup, we took a reference on the page.
2719 * page->mapping may go NULL, but it shouldn't be moved to a different
2722 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2724 * Unfortunately this is a little tricky, either
2726 * 1) We got here and our page had already been dealt with and
2727 * we reserved our space, thus ret == 0, so we need to just
2728 * drop our space reservation and bail. This can happen the
2729 * first time we come into the fixup worker, or could happen
2730 * while waiting for the ordered extent.
2731 * 2) Our page was already dealt with, but we happened to get an
2732 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2733 * this case we obviously don't have anything to release, but
2734 * because the page was already dealt with we don't want to
2735 * mark the page with an error, so make sure we're resetting
2736 * ret to 0. This is why we have this check _before_ the ret
2737 * check, because we do not want to have a surprise ENOSPC
2738 * when the page was already properly dealt with.
2741 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2742 btrfs_delalloc_release_space(inode, data_reserved,
2743 page_start, PAGE_SIZE,
2751 * We can't mess with the page state unless it is locked, so now that
2752 * it is locked bail if we failed to make our space reservation.
2757 lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2759 /* already ordered? We're done */
2760 if (PageOrdered(page))
2763 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2765 unlock_extent(&inode->io_tree, page_start, page_end,
2768 btrfs_start_ordered_extent(ordered);
2769 btrfs_put_ordered_extent(ordered);
2773 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2779 * Everything went as planned, we're now the owner of a dirty page with
2780 * delayed allocation bits set and space reserved for our COW
2783 * The page was dirty when we started, nothing should have cleaned it.
2785 BUG_ON(!PageDirty(page));
2786 free_delalloc_space = false;
2788 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2789 if (free_delalloc_space)
2790 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2792 unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2796 * We hit ENOSPC or other errors. Update the mapping and page
2797 * to reflect the errors and clean the page.
2799 mapping_set_error(page->mapping, ret);
2800 btrfs_mark_ordered_io_finished(inode, page, page_start,
2802 clear_page_dirty_for_io(page);
2804 btrfs_folio_clear_checked(fs_info, page_folio(page), page_start, PAGE_SIZE);
2808 extent_changeset_free(data_reserved);
2810 * As a precaution, do a delayed iput in case it would be the last iput
2811 * that could need flushing space. Recursing back to fixup worker would
2814 btrfs_add_delayed_iput(inode);
2818 * There are a few paths in the higher layers of the kernel that directly
2819 * set the page dirty bit without asking the filesystem if it is a
2820 * good idea. This causes problems because we want to make sure COW
2821 * properly happens and the data=ordered rules are followed.
2823 * In our case any range that doesn't have the ORDERED bit set
2824 * hasn't been properly setup for IO. We kick off an async process
2825 * to fix it up. The async helper will wait for ordered extents, set
2826 * the delalloc bit and make it safe to write the page.
2828 int btrfs_writepage_cow_fixup(struct page *page)
2830 struct inode *inode = page->mapping->host;
2831 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
2832 struct btrfs_writepage_fixup *fixup;
2834 /* This page has ordered extent covering it already */
2835 if (PageOrdered(page))
2839 * PageChecked is set below when we create a fixup worker for this page,
2840 * don't try to create another one if we're already PageChecked()
2842 * The extent_io writepage code will redirty the page if we send back
2845 if (PageChecked(page))
2848 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2853 * We are already holding a reference to this inode from
2854 * write_cache_pages. We need to hold it because the space reservation
2855 * takes place outside of the page lock, and we can't trust
2856 * page->mapping outside of the page lock.
2859 btrfs_folio_set_checked(fs_info, page_folio(page), page_offset(page), PAGE_SIZE);
2861 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL);
2863 fixup->inode = BTRFS_I(inode);
2864 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2869 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2870 struct btrfs_inode *inode, u64 file_pos,
2871 struct btrfs_file_extent_item *stack_fi,
2872 const bool update_inode_bytes,
2873 u64 qgroup_reserved)
2875 struct btrfs_root *root = inode->root;
2876 const u64 sectorsize = root->fs_info->sectorsize;
2877 struct btrfs_path *path;
2878 struct extent_buffer *leaf;
2879 struct btrfs_key ins;
2880 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2881 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2882 u64 offset = btrfs_stack_file_extent_offset(stack_fi);
2883 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2884 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2885 struct btrfs_drop_extents_args drop_args = { 0 };
2888 path = btrfs_alloc_path();
2893 * we may be replacing one extent in the tree with another.
2894 * The new extent is pinned in the extent map, and we don't want
2895 * to drop it from the cache until it is completely in the btree.
2897 * So, tell btrfs_drop_extents to leave this extent in the cache.
2898 * the caller is expected to unpin it and allow it to be merged
2901 drop_args.path = path;
2902 drop_args.start = file_pos;
2903 drop_args.end = file_pos + num_bytes;
2904 drop_args.replace_extent = true;
2905 drop_args.extent_item_size = sizeof(*stack_fi);
2906 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2910 if (!drop_args.extent_inserted) {
2911 ins.objectid = btrfs_ino(inode);
2912 ins.offset = file_pos;
2913 ins.type = BTRFS_EXTENT_DATA_KEY;
2915 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2920 leaf = path->nodes[0];
2921 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2922 write_extent_buffer(leaf, stack_fi,
2923 btrfs_item_ptr_offset(leaf, path->slots[0]),
2924 sizeof(struct btrfs_file_extent_item));
2926 btrfs_mark_buffer_dirty(trans, leaf);
2927 btrfs_release_path(path);
2930 * If we dropped an inline extent here, we know the range where it is
2931 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2932 * number of bytes only for that range containing the inline extent.
2933 * The remaining of the range will be processed when clearning the
2934 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2936 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2937 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2939 inline_size = drop_args.bytes_found - inline_size;
2940 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2941 drop_args.bytes_found -= inline_size;
2942 num_bytes -= sectorsize;
2945 if (update_inode_bytes)
2946 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2948 ins.objectid = disk_bytenr;
2949 ins.offset = disk_num_bytes;
2950 ins.type = BTRFS_EXTENT_ITEM_KEY;
2952 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2956 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2958 qgroup_reserved, &ins);
2960 btrfs_free_path(path);
2965 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2968 struct btrfs_block_group *cache;
2970 cache = btrfs_lookup_block_group(fs_info, start);
2973 spin_lock(&cache->lock);
2974 cache->delalloc_bytes -= len;
2975 spin_unlock(&cache->lock);
2977 btrfs_put_block_group(cache);
2980 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2981 struct btrfs_ordered_extent *oe)
2983 struct btrfs_file_extent_item stack_fi;
2984 bool update_inode_bytes;
2985 u64 num_bytes = oe->num_bytes;
2986 u64 ram_bytes = oe->ram_bytes;
2988 memset(&stack_fi, 0, sizeof(stack_fi));
2989 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2990 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2991 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2992 oe->disk_num_bytes);
2993 btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
2994 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags)) {
2995 num_bytes = oe->truncated_len;
2996 ram_bytes = num_bytes;
2998 btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
2999 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
3000 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3001 /* Encryption and other encoding is reserved and all 0 */
3004 * For delalloc, when completing an ordered extent we update the inode's
3005 * bytes when clearing the range in the inode's io tree, so pass false
3006 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3007 * except if the ordered extent was truncated.
3009 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3010 test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
3011 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3013 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
3014 oe->file_offset, &stack_fi,
3015 update_inode_bytes, oe->qgroup_rsv);
3019 * As ordered data IO finishes, this gets called so we can finish
3020 * an ordered extent if the range of bytes in the file it covers are
3023 int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
3025 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
3026 struct btrfs_root *root = inode->root;
3027 struct btrfs_fs_info *fs_info = root->fs_info;
3028 struct btrfs_trans_handle *trans = NULL;
3029 struct extent_io_tree *io_tree = &inode->io_tree;
3030 struct extent_state *cached_state = NULL;
3032 int compress_type = 0;
3034 u64 logical_len = ordered_extent->num_bytes;
3035 bool freespace_inode;
3036 bool truncated = false;
3037 bool clear_reserved_extent = true;
3038 unsigned int clear_bits = EXTENT_DEFRAG;
3040 start = ordered_extent->file_offset;
3041 end = start + ordered_extent->num_bytes - 1;
3043 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3044 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3045 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3046 !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3047 clear_bits |= EXTENT_DELALLOC_NEW;
3049 freespace_inode = btrfs_is_free_space_inode(inode);
3050 if (!freespace_inode)
3051 btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
3053 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3058 if (btrfs_is_zoned(fs_info))
3059 btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3060 ordered_extent->disk_num_bytes);
3062 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3064 logical_len = ordered_extent->truncated_len;
3065 /* Truncated the entire extent, don't bother adding */
3070 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3071 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3073 btrfs_inode_safe_disk_i_size_write(inode, 0);
3074 if (freespace_inode)
3075 trans = btrfs_join_transaction_spacecache(root);
3077 trans = btrfs_join_transaction(root);
3078 if (IS_ERR(trans)) {
3079 ret = PTR_ERR(trans);
3083 trans->block_rsv = &inode->block_rsv;
3084 ret = btrfs_update_inode_fallback(trans, inode);
3085 if (ret) /* -ENOMEM or corruption */
3086 btrfs_abort_transaction(trans, ret);
3090 clear_bits |= EXTENT_LOCKED;
3091 lock_extent(io_tree, start, end, &cached_state);
3093 if (freespace_inode)
3094 trans = btrfs_join_transaction_spacecache(root);
3096 trans = btrfs_join_transaction(root);
3097 if (IS_ERR(trans)) {
3098 ret = PTR_ERR(trans);
3103 trans->block_rsv = &inode->block_rsv;
3105 ret = btrfs_insert_raid_extent(trans, ordered_extent);
3109 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3110 compress_type = ordered_extent->compress_type;
3111 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3112 BUG_ON(compress_type);
3113 ret = btrfs_mark_extent_written(trans, inode,
3114 ordered_extent->file_offset,
3115 ordered_extent->file_offset +
3117 btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3118 ordered_extent->disk_num_bytes);
3120 BUG_ON(root == fs_info->tree_root);
3121 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3123 clear_reserved_extent = false;
3124 btrfs_release_delalloc_bytes(fs_info,
3125 ordered_extent->disk_bytenr,
3126 ordered_extent->disk_num_bytes);
3130 btrfs_abort_transaction(trans, ret);
3134 ret = unpin_extent_cache(inode, ordered_extent->file_offset,
3135 ordered_extent->num_bytes, trans->transid);
3137 btrfs_abort_transaction(trans, ret);
3141 ret = add_pending_csums(trans, &ordered_extent->list);
3143 btrfs_abort_transaction(trans, ret);
3148 * If this is a new delalloc range, clear its new delalloc flag to
3149 * update the inode's number of bytes. This needs to be done first
3150 * before updating the inode item.
3152 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3153 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3154 clear_extent_bit(&inode->io_tree, start, end,
3155 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3158 btrfs_inode_safe_disk_i_size_write(inode, 0);
3159 ret = btrfs_update_inode_fallback(trans, inode);
3160 if (ret) { /* -ENOMEM or corruption */
3161 btrfs_abort_transaction(trans, ret);
3166 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3170 btrfs_end_transaction(trans);
3172 if (ret || truncated) {
3173 u64 unwritten_start = start;
3176 * If we failed to finish this ordered extent for any reason we
3177 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3178 * extent, and mark the inode with the error if it wasn't
3179 * already set. Any error during writeback would have already
3180 * set the mapping error, so we need to set it if we're the ones
3181 * marking this ordered extent as failed.
3183 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3184 &ordered_extent->flags))
3185 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3188 unwritten_start += logical_len;
3189 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3192 * Drop extent maps for the part of the extent we didn't write.
3194 * We have an exception here for the free_space_inode, this is
3195 * because when we do btrfs_get_extent() on the free space inode
3196 * we will search the commit root. If this is a new block group
3197 * we won't find anything, and we will trip over the assert in
3198 * writepage where we do ASSERT(em->block_start !=
3201 * Theoretically we could also skip this for any NOCOW extent as
3202 * we don't mess with the extent map tree in the NOCOW case, but
3203 * for now simply skip this if we are the free space inode.
3205 if (!btrfs_is_free_space_inode(inode))
3206 btrfs_drop_extent_map_range(inode, unwritten_start,
3210 * If the ordered extent had an IOERR or something else went
3211 * wrong we need to return the space for this ordered extent
3212 * back to the allocator. We only free the extent in the
3213 * truncated case if we didn't write out the extent at all.
3215 * If we made it past insert_reserved_file_extent before we
3216 * errored out then we don't need to do this as the accounting
3217 * has already been done.
3219 if ((ret || !logical_len) &&
3220 clear_reserved_extent &&
3221 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3222 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3224 * Discard the range before returning it back to the
3227 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3228 btrfs_discard_extent(fs_info,
3229 ordered_extent->disk_bytenr,
3230 ordered_extent->disk_num_bytes,
3232 btrfs_free_reserved_extent(fs_info,
3233 ordered_extent->disk_bytenr,
3234 ordered_extent->disk_num_bytes, 1);
3236 * Actually free the qgroup rsv which was released when
3237 * the ordered extent was created.
3239 btrfs_qgroup_free_refroot(fs_info, inode->root->root_key.objectid,
3240 ordered_extent->qgroup_rsv,
3241 BTRFS_QGROUP_RSV_DATA);
3246 * This needs to be done to make sure anybody waiting knows we are done
3247 * updating everything for this ordered extent.
3249 btrfs_remove_ordered_extent(inode, ordered_extent);
3252 btrfs_put_ordered_extent(ordered_extent);
3253 /* once for the tree */
3254 btrfs_put_ordered_extent(ordered_extent);
3259 int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered)
3261 if (btrfs_is_zoned(inode_to_fs_info(ordered->inode)) &&
3262 !test_bit(BTRFS_ORDERED_IOERR, &ordered->flags) &&
3263 list_empty(&ordered->bioc_list))
3264 btrfs_finish_ordered_zoned(ordered);
3265 return btrfs_finish_one_ordered(ordered);
3269 * Verify the checksum for a single sector without any extra action that depend
3270 * on the type of I/O.
3272 int btrfs_check_sector_csum(struct btrfs_fs_info *fs_info, struct page *page,
3273 u32 pgoff, u8 *csum, const u8 * const csum_expected)
3275 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3278 ASSERT(pgoff + fs_info->sectorsize <= PAGE_SIZE);
3280 shash->tfm = fs_info->csum_shash;
3282 kaddr = kmap_local_page(page) + pgoff;
3283 crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
3284 kunmap_local(kaddr);
3286 if (memcmp(csum, csum_expected, fs_info->csum_size))
3292 * Verify the checksum of a single data sector.
3294 * @bbio: btrfs_io_bio which contains the csum
3295 * @dev: device the sector is on
3296 * @bio_offset: offset to the beginning of the bio (in bytes)
3297 * @bv: bio_vec to check
3299 * Check if the checksum on a data block is valid. When a checksum mismatch is
3300 * detected, report the error and fill the corrupted range with zero.
3302 * Return %true if the sector is ok or had no checksum to start with, else %false.
3304 bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev,
3305 u32 bio_offset, struct bio_vec *bv)
3307 struct btrfs_inode *inode = bbio->inode;
3308 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3309 u64 file_offset = bbio->file_offset + bio_offset;
3310 u64 end = file_offset + bv->bv_len - 1;
3312 u8 csum[BTRFS_CSUM_SIZE];
3314 ASSERT(bv->bv_len == fs_info->sectorsize);
3319 if (btrfs_is_data_reloc_root(inode->root) &&
3320 test_range_bit(&inode->io_tree, file_offset, end, EXTENT_NODATASUM,
3322 /* Skip the range without csum for data reloc inode */
3323 clear_extent_bits(&inode->io_tree, file_offset, end,
3328 csum_expected = bbio->csum + (bio_offset >> fs_info->sectorsize_bits) *
3330 if (btrfs_check_sector_csum(fs_info, bv->bv_page, bv->bv_offset, csum,
3336 btrfs_print_data_csum_error(inode, file_offset, csum, csum_expected,
3339 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
3345 * Perform a delayed iput on @inode.
3347 * @inode: The inode we want to perform iput on
3349 * This function uses the generic vfs_inode::i_count to track whether we should
3350 * just decrement it (in case it's > 1) or if this is the last iput then link
3351 * the inode to the delayed iput machinery. Delayed iputs are processed at
3352 * transaction commit time/superblock commit/cleaner kthread.
3354 void btrfs_add_delayed_iput(struct btrfs_inode *inode)
3356 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3357 unsigned long flags;
3359 if (atomic_add_unless(&inode->vfs_inode.i_count, -1, 1))
3362 atomic_inc(&fs_info->nr_delayed_iputs);
3364 * Need to be irq safe here because we can be called from either an irq
3365 * context (see bio.c and btrfs_put_ordered_extent()) or a non-irq
3368 spin_lock_irqsave(&fs_info->delayed_iput_lock, flags);
3369 ASSERT(list_empty(&inode->delayed_iput));
3370 list_add_tail(&inode->delayed_iput, &fs_info->delayed_iputs);
3371 spin_unlock_irqrestore(&fs_info->delayed_iput_lock, flags);
3372 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3373 wake_up_process(fs_info->cleaner_kthread);
3376 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3377 struct btrfs_inode *inode)
3379 list_del_init(&inode->delayed_iput);
3380 spin_unlock_irq(&fs_info->delayed_iput_lock);
3381 iput(&inode->vfs_inode);
3382 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3383 wake_up(&fs_info->delayed_iputs_wait);
3384 spin_lock_irq(&fs_info->delayed_iput_lock);
3387 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3388 struct btrfs_inode *inode)
3390 if (!list_empty(&inode->delayed_iput)) {
3391 spin_lock_irq(&fs_info->delayed_iput_lock);
3392 if (!list_empty(&inode->delayed_iput))
3393 run_delayed_iput_locked(fs_info, inode);
3394 spin_unlock_irq(&fs_info->delayed_iput_lock);
3398 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3401 * btrfs_put_ordered_extent() can run in irq context (see bio.c), which
3402 * calls btrfs_add_delayed_iput() and that needs to lock
3403 * fs_info->delayed_iput_lock. So we need to disable irqs here to
3404 * prevent a deadlock.
3406 spin_lock_irq(&fs_info->delayed_iput_lock);
3407 while (!list_empty(&fs_info->delayed_iputs)) {
3408 struct btrfs_inode *inode;
3410 inode = list_first_entry(&fs_info->delayed_iputs,
3411 struct btrfs_inode, delayed_iput);
3412 run_delayed_iput_locked(fs_info, inode);
3413 if (need_resched()) {
3414 spin_unlock_irq(&fs_info->delayed_iput_lock);
3416 spin_lock_irq(&fs_info->delayed_iput_lock);
3419 spin_unlock_irq(&fs_info->delayed_iput_lock);
3423 * Wait for flushing all delayed iputs
3425 * @fs_info: the filesystem
3427 * This will wait on any delayed iputs that are currently running with KILLABLE
3428 * set. Once they are all done running we will return, unless we are killed in
3429 * which case we return EINTR. This helps in user operations like fallocate etc
3430 * that might get blocked on the iputs.
3432 * Return EINTR if we were killed, 0 if nothing's pending
3434 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3436 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3437 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3444 * This creates an orphan entry for the given inode in case something goes wrong
3445 * in the middle of an unlink.
3447 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3448 struct btrfs_inode *inode)
3452 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3453 if (ret && ret != -EEXIST) {
3454 btrfs_abort_transaction(trans, ret);
3462 * We have done the delete so we can go ahead and remove the orphan item for
3463 * this particular inode.
3465 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3466 struct btrfs_inode *inode)
3468 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3472 * this cleans up any orphans that may be left on the list from the last use
3475 int btrfs_orphan_cleanup(struct btrfs_root *root)
3477 struct btrfs_fs_info *fs_info = root->fs_info;
3478 struct btrfs_path *path;
3479 struct extent_buffer *leaf;
3480 struct btrfs_key key, found_key;
3481 struct btrfs_trans_handle *trans;
3482 struct inode *inode;
3483 u64 last_objectid = 0;
3484 int ret = 0, nr_unlink = 0;
3486 if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3489 path = btrfs_alloc_path();
3494 path->reada = READA_BACK;
3496 key.objectid = BTRFS_ORPHAN_OBJECTID;
3497 key.type = BTRFS_ORPHAN_ITEM_KEY;
3498 key.offset = (u64)-1;
3501 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3506 * if ret == 0 means we found what we were searching for, which
3507 * is weird, but possible, so only screw with path if we didn't
3508 * find the key and see if we have stuff that matches
3512 if (path->slots[0] == 0)
3517 /* pull out the item */
3518 leaf = path->nodes[0];
3519 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3521 /* make sure the item matches what we want */
3522 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3524 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3527 /* release the path since we're done with it */
3528 btrfs_release_path(path);
3531 * this is where we are basically btrfs_lookup, without the
3532 * crossing root thing. we store the inode number in the
3533 * offset of the orphan item.
3536 if (found_key.offset == last_objectid) {
3538 * We found the same inode as before. This means we were
3539 * not able to remove its items via eviction triggered
3540 * by an iput(). A transaction abort may have happened,
3541 * due to -ENOSPC for example, so try to grab the error
3542 * that lead to a transaction abort, if any.
3545 "Error removing orphan entry, stopping orphan cleanup");
3546 ret = BTRFS_FS_ERROR(fs_info) ?: -EINVAL;
3550 last_objectid = found_key.offset;
3552 found_key.objectid = found_key.offset;
3553 found_key.type = BTRFS_INODE_ITEM_KEY;
3554 found_key.offset = 0;
3555 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3556 if (IS_ERR(inode)) {
3557 ret = PTR_ERR(inode);
3563 if (!inode && root == fs_info->tree_root) {
3564 struct btrfs_root *dead_root;
3565 int is_dead_root = 0;
3568 * This is an orphan in the tree root. Currently these
3569 * could come from 2 sources:
3570 * a) a root (snapshot/subvolume) deletion in progress
3571 * b) a free space cache inode
3572 * We need to distinguish those two, as the orphan item
3573 * for a root must not get deleted before the deletion
3574 * of the snapshot/subvolume's tree completes.
3576 * btrfs_find_orphan_roots() ran before us, which has
3577 * found all deleted roots and loaded them into
3578 * fs_info->fs_roots_radix. So here we can find if an
3579 * orphan item corresponds to a deleted root by looking
3580 * up the root from that radix tree.
3583 spin_lock(&fs_info->fs_roots_radix_lock);
3584 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3585 (unsigned long)found_key.objectid);
3586 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3588 spin_unlock(&fs_info->fs_roots_radix_lock);
3591 /* prevent this orphan from being found again */
3592 key.offset = found_key.objectid - 1;
3599 * If we have an inode with links, there are a couple of
3602 * 1. We were halfway through creating fsverity metadata for the
3603 * file. In that case, the orphan item represents incomplete
3604 * fsverity metadata which must be cleaned up with
3605 * btrfs_drop_verity_items and deleting the orphan item.
3607 * 2. Old kernels (before v3.12) used to create an
3608 * orphan item for truncate indicating that there were possibly
3609 * extent items past i_size that needed to be deleted. In v3.12,
3610 * truncate was changed to update i_size in sync with the extent
3611 * items, but the (useless) orphan item was still created. Since
3612 * v4.18, we don't create the orphan item for truncate at all.
3614 * So, this item could mean that we need to do a truncate, but
3615 * only if this filesystem was last used on a pre-v3.12 kernel
3616 * and was not cleanly unmounted. The odds of that are quite
3617 * slim, and it's a pain to do the truncate now, so just delete
3620 * It's also possible that this orphan item was supposed to be
3621 * deleted but wasn't. The inode number may have been reused,
3622 * but either way, we can delete the orphan item.
3624 if (!inode || inode->i_nlink) {
3626 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3632 trans = btrfs_start_transaction(root, 1);
3633 if (IS_ERR(trans)) {
3634 ret = PTR_ERR(trans);
3637 btrfs_debug(fs_info, "auto deleting %Lu",
3638 found_key.objectid);
3639 ret = btrfs_del_orphan_item(trans, root,
3640 found_key.objectid);
3641 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 = inode_to_fs_info(inode);
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_set_atime(inode, btrfs_timespec_sec(leaf, &inode_item->atime),
3794 btrfs_timespec_nsec(leaf, &inode_item->atime));
3796 inode_set_mtime(inode, btrfs_timespec_sec(leaf, &inode_item->mtime),
3797 btrfs_timespec_nsec(leaf, &inode_item->mtime));
3799 inode_set_ctime(inode, btrfs_timespec_sec(leaf, &inode_item->ctime),
3800 btrfs_timespec_nsec(leaf, &inode_item->ctime));
3802 BTRFS_I(inode)->i_otime_sec = btrfs_timespec_sec(leaf, &inode_item->otime);
3803 BTRFS_I(inode)->i_otime_nsec = btrfs_timespec_nsec(leaf, &inode_item->otime);
3805 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3806 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3807 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3809 inode_set_iversion_queried(inode,
3810 btrfs_inode_sequence(leaf, inode_item));
3811 inode->i_generation = BTRFS_I(inode)->generation;
3813 rdev = btrfs_inode_rdev(leaf, inode_item);
3815 BTRFS_I(inode)->index_cnt = (u64)-1;
3816 btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
3817 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
3821 * If we were modified in the current generation and evicted from memory
3822 * and then re-read we need to do a full sync since we don't have any
3823 * idea about which extents were modified before we were evicted from
3826 * This is required for both inode re-read from disk and delayed inode
3827 * in the delayed_nodes xarray.
3829 if (BTRFS_I(inode)->last_trans == btrfs_get_fs_generation(fs_info))
3830 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3831 &BTRFS_I(inode)->runtime_flags);
3834 * We don't persist the id of the transaction where an unlink operation
3835 * against the inode was last made. So here we assume the inode might
3836 * have been evicted, and therefore the exact value of last_unlink_trans
3837 * lost, and set it to last_trans to avoid metadata inconsistencies
3838 * between the inode and its parent if the inode is fsync'ed and the log
3839 * replayed. For example, in the scenario:
3842 * ln mydir/foo mydir/bar
3845 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3846 * xfs_io -c fsync mydir/foo
3848 * mount fs, triggers fsync log replay
3850 * We must make sure that when we fsync our inode foo we also log its
3851 * parent inode, otherwise after log replay the parent still has the
3852 * dentry with the "bar" name but our inode foo has a link count of 1
3853 * and doesn't have an inode ref with the name "bar" anymore.
3855 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3856 * but it guarantees correctness at the expense of occasional full
3857 * transaction commits on fsync if our inode is a directory, or if our
3858 * inode is not a directory, logging its parent unnecessarily.
3860 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3863 * Same logic as for last_unlink_trans. We don't persist the generation
3864 * of the last transaction where this inode was used for a reflink
3865 * operation, so after eviction and reloading the inode we must be
3866 * pessimistic and assume the last transaction that modified the inode.
3868 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3871 if (inode->i_nlink != 1 ||
3872 path->slots[0] >= btrfs_header_nritems(leaf))
3875 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3876 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3879 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3880 if (location.type == BTRFS_INODE_REF_KEY) {
3881 struct btrfs_inode_ref *ref;
3883 ref = (struct btrfs_inode_ref *)ptr;
3884 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3885 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3886 struct btrfs_inode_extref *extref;
3888 extref = (struct btrfs_inode_extref *)ptr;
3889 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3894 * try to precache a NULL acl entry for files that don't have
3895 * any xattrs or acls
3897 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3898 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3899 if (first_xattr_slot != -1) {
3900 path->slots[0] = first_xattr_slot;
3901 ret = btrfs_load_inode_props(inode, path);
3904 "error loading props for ino %llu (root %llu): %d",
3905 btrfs_ino(BTRFS_I(inode)),
3906 root->root_key.objectid, ret);
3908 if (path != in_path)
3909 btrfs_free_path(path);
3912 cache_no_acl(inode);
3914 switch (inode->i_mode & S_IFMT) {
3916 inode->i_mapping->a_ops = &btrfs_aops;
3917 inode->i_fop = &btrfs_file_operations;
3918 inode->i_op = &btrfs_file_inode_operations;
3921 inode->i_fop = &btrfs_dir_file_operations;
3922 inode->i_op = &btrfs_dir_inode_operations;
3925 inode->i_op = &btrfs_symlink_inode_operations;
3926 inode_nohighmem(inode);
3927 inode->i_mapping->a_ops = &btrfs_aops;
3930 inode->i_op = &btrfs_special_inode_operations;
3931 init_special_inode(inode, inode->i_mode, rdev);
3935 btrfs_sync_inode_flags_to_i_flags(inode);
3940 * given a leaf and an inode, copy the inode fields into the leaf
3942 static void fill_inode_item(struct btrfs_trans_handle *trans,
3943 struct extent_buffer *leaf,
3944 struct btrfs_inode_item *item,
3945 struct inode *inode)
3947 struct btrfs_map_token token;
3950 btrfs_init_map_token(&token, leaf);
3952 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3953 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3954 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3955 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3956 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3958 btrfs_set_token_timespec_sec(&token, &item->atime,
3959 inode_get_atime_sec(inode));
3960 btrfs_set_token_timespec_nsec(&token, &item->atime,
3961 inode_get_atime_nsec(inode));
3963 btrfs_set_token_timespec_sec(&token, &item->mtime,
3964 inode_get_mtime_sec(inode));
3965 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3966 inode_get_mtime_nsec(inode));
3968 btrfs_set_token_timespec_sec(&token, &item->ctime,
3969 inode_get_ctime_sec(inode));
3970 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3971 inode_get_ctime_nsec(inode));
3973 btrfs_set_token_timespec_sec(&token, &item->otime, BTRFS_I(inode)->i_otime_sec);
3974 btrfs_set_token_timespec_nsec(&token, &item->otime, BTRFS_I(inode)->i_otime_nsec);
3976 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3977 btrfs_set_token_inode_generation(&token, item,
3978 BTRFS_I(inode)->generation);
3979 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3980 btrfs_set_token_inode_transid(&token, item, trans->transid);
3981 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3982 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
3983 BTRFS_I(inode)->ro_flags);
3984 btrfs_set_token_inode_flags(&token, item, flags);
3985 btrfs_set_token_inode_block_group(&token, item, 0);
3989 * copy everything in the in-memory inode into the btree.
3991 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3992 struct btrfs_inode *inode)
3994 struct btrfs_inode_item *inode_item;
3995 struct btrfs_path *path;
3996 struct extent_buffer *leaf;
3999 path = btrfs_alloc_path();
4003 ret = btrfs_lookup_inode(trans, inode->root, path, &inode->location, 1);
4010 leaf = path->nodes[0];
4011 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4012 struct btrfs_inode_item);
4014 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4015 btrfs_mark_buffer_dirty(trans, leaf);
4016 btrfs_set_inode_last_trans(trans, inode);
4019 btrfs_free_path(path);
4024 * copy everything in the in-memory inode into the btree.
4026 int btrfs_update_inode(struct btrfs_trans_handle *trans,
4027 struct btrfs_inode *inode)
4029 struct btrfs_root *root = inode->root;
4030 struct btrfs_fs_info *fs_info = root->fs_info;
4034 * If the inode is a free space inode, we can deadlock during commit
4035 * if we put it into the delayed code.
4037 * The data relocation inode should also be directly updated
4040 if (!btrfs_is_free_space_inode(inode)
4041 && !btrfs_is_data_reloc_root(root)
4042 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4043 btrfs_update_root_times(trans, root);
4045 ret = btrfs_delayed_update_inode(trans, inode);
4047 btrfs_set_inode_last_trans(trans, inode);
4051 return btrfs_update_inode_item(trans, inode);
4054 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4055 struct btrfs_inode *inode)
4059 ret = btrfs_update_inode(trans, inode);
4061 return btrfs_update_inode_item(trans, inode);
4066 * unlink helper that gets used here in inode.c and in the tree logging
4067 * recovery code. It remove a link in a directory with a given name, and
4068 * also drops the back refs in the inode to the directory
4070 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4071 struct btrfs_inode *dir,
4072 struct btrfs_inode *inode,
4073 const struct fscrypt_str *name,
4074 struct btrfs_rename_ctx *rename_ctx)
4076 struct btrfs_root *root = dir->root;
4077 struct btrfs_fs_info *fs_info = root->fs_info;
4078 struct btrfs_path *path;
4080 struct btrfs_dir_item *di;
4082 u64 ino = btrfs_ino(inode);
4083 u64 dir_ino = btrfs_ino(dir);
4085 path = btrfs_alloc_path();
4091 di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4092 if (IS_ERR_OR_NULL(di)) {
4093 ret = di ? PTR_ERR(di) : -ENOENT;
4096 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4099 btrfs_release_path(path);
4102 * If we don't have dir index, we have to get it by looking up
4103 * the inode ref, since we get the inode ref, remove it directly,
4104 * it is unnecessary to do delayed deletion.
4106 * But if we have dir index, needn't search inode ref to get it.
4107 * Since the inode ref is close to the inode item, it is better
4108 * that we delay to delete it, and just do this deletion when
4109 * we update the inode item.
4111 if (inode->dir_index) {
4112 ret = btrfs_delayed_delete_inode_ref(inode);
4114 index = inode->dir_index;
4119 ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4122 "failed to delete reference to %.*s, inode %llu parent %llu",
4123 name->len, name->name, ino, dir_ino);
4124 btrfs_abort_transaction(trans, ret);
4129 rename_ctx->index = index;
4131 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4133 btrfs_abort_transaction(trans, ret);
4138 * If we are in a rename context, we don't need to update anything in the
4139 * log. That will be done later during the rename by btrfs_log_new_name().
4140 * Besides that, doing it here would only cause extra unnecessary btree
4141 * operations on the log tree, increasing latency for applications.
4144 btrfs_del_inode_ref_in_log(trans, root, name, inode, dir_ino);
4145 btrfs_del_dir_entries_in_log(trans, root, name, dir, index);
4149 * If we have a pending delayed iput we could end up with the final iput
4150 * being run in btrfs-cleaner context. If we have enough of these built
4151 * up we can end up burning a lot of time in btrfs-cleaner without any
4152 * way to throttle the unlinks. Since we're currently holding a ref on
4153 * the inode we can run the delayed iput here without any issues as the
4154 * final iput won't be done until after we drop the ref we're currently
4157 btrfs_run_delayed_iput(fs_info, inode);
4159 btrfs_free_path(path);
4163 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4164 inode_inc_iversion(&inode->vfs_inode);
4165 inode_inc_iversion(&dir->vfs_inode);
4166 inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
4167 ret = btrfs_update_inode(trans, dir);
4172 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4173 struct btrfs_inode *dir, struct btrfs_inode *inode,
4174 const struct fscrypt_str *name)
4178 ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4180 drop_nlink(&inode->vfs_inode);
4181 ret = btrfs_update_inode(trans, inode);
4187 * helper to start transaction for unlink and rmdir.
4189 * unlink and rmdir are special in btrfs, they do not always free space, so
4190 * if we cannot make our reservations the normal way try and see if there is
4191 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4192 * allow the unlink to occur.
4194 static struct btrfs_trans_handle *__unlink_start_trans(struct btrfs_inode *dir)
4196 struct btrfs_root *root = dir->root;
4198 return btrfs_start_transaction_fallback_global_rsv(root,
4199 BTRFS_UNLINK_METADATA_UNITS);
4202 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4204 struct btrfs_trans_handle *trans;
4205 struct inode *inode = d_inode(dentry);
4207 struct fscrypt_name fname;
4209 ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4213 /* This needs to handle no-key deletions later on */
4215 trans = __unlink_start_trans(BTRFS_I(dir));
4216 if (IS_ERR(trans)) {
4217 ret = PTR_ERR(trans);
4221 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4224 ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4229 if (inode->i_nlink == 0) {
4230 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4236 btrfs_end_transaction(trans);
4237 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4239 fscrypt_free_filename(&fname);
4243 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4244 struct btrfs_inode *dir, struct dentry *dentry)
4246 struct btrfs_root *root = dir->root;
4247 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4248 struct btrfs_path *path;
4249 struct extent_buffer *leaf;
4250 struct btrfs_dir_item *di;
4251 struct btrfs_key key;
4255 u64 dir_ino = btrfs_ino(dir);
4256 struct fscrypt_name fname;
4258 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
4262 /* This needs to handle no-key deletions later on */
4264 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4265 objectid = inode->root->root_key.objectid;
4266 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4267 objectid = inode->location.objectid;
4270 fscrypt_free_filename(&fname);
4274 path = btrfs_alloc_path();
4280 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4281 &fname.disk_name, -1);
4282 if (IS_ERR_OR_NULL(di)) {
4283 ret = di ? PTR_ERR(di) : -ENOENT;
4287 leaf = path->nodes[0];
4288 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4289 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4290 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4292 btrfs_abort_transaction(trans, ret);
4295 btrfs_release_path(path);
4298 * This is a placeholder inode for a subvolume we didn't have a
4299 * reference to at the time of the snapshot creation. In the meantime
4300 * we could have renamed the real subvol link into our snapshot, so
4301 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4302 * Instead simply lookup the dir_index_item for this entry so we can
4303 * remove it. Otherwise we know we have a ref to the root and we can
4304 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4306 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4307 di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4308 if (IS_ERR_OR_NULL(di)) {
4313 btrfs_abort_transaction(trans, ret);
4317 leaf = path->nodes[0];
4318 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4320 btrfs_release_path(path);
4322 ret = btrfs_del_root_ref(trans, objectid,
4323 root->root_key.objectid, dir_ino,
4324 &index, &fname.disk_name);
4326 btrfs_abort_transaction(trans, ret);
4331 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4333 btrfs_abort_transaction(trans, ret);
4337 btrfs_i_size_write(dir, dir->vfs_inode.i_size - fname.disk_name.len * 2);
4338 inode_inc_iversion(&dir->vfs_inode);
4339 inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
4340 ret = btrfs_update_inode_fallback(trans, dir);
4342 btrfs_abort_transaction(trans, ret);
4344 btrfs_free_path(path);
4345 fscrypt_free_filename(&fname);
4350 * Helper to check if the subvolume references other subvolumes or if it's
4353 static noinline int may_destroy_subvol(struct btrfs_root *root)
4355 struct btrfs_fs_info *fs_info = root->fs_info;
4356 struct btrfs_path *path;
4357 struct btrfs_dir_item *di;
4358 struct btrfs_key key;
4359 struct fscrypt_str name = FSTR_INIT("default", 7);
4363 path = btrfs_alloc_path();
4367 /* Make sure this root isn't set as the default subvol */
4368 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4369 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4371 if (di && !IS_ERR(di)) {
4372 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4373 if (key.objectid == root->root_key.objectid) {
4376 "deleting default subvolume %llu is not allowed",
4380 btrfs_release_path(path);
4383 key.objectid = root->root_key.objectid;
4384 key.type = BTRFS_ROOT_REF_KEY;
4385 key.offset = (u64)-1;
4387 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4393 if (path->slots[0] > 0) {
4395 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4396 if (key.objectid == root->root_key.objectid &&
4397 key.type == BTRFS_ROOT_REF_KEY)
4401 btrfs_free_path(path);
4405 /* Delete all dentries for inodes belonging to the root */
4406 static void btrfs_prune_dentries(struct btrfs_root *root)
4408 struct btrfs_fs_info *fs_info = root->fs_info;
4409 struct rb_node *node;
4410 struct rb_node *prev;
4411 struct btrfs_inode *entry;
4412 struct inode *inode;
4415 if (!BTRFS_FS_ERROR(fs_info))
4416 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4418 spin_lock(&root->inode_lock);
4420 node = root->inode_tree.rb_node;
4424 entry = rb_entry(node, struct btrfs_inode, rb_node);
4426 if (objectid < btrfs_ino(entry))
4427 node = node->rb_left;
4428 else if (objectid > btrfs_ino(entry))
4429 node = node->rb_right;
4435 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4436 if (objectid <= btrfs_ino(entry)) {
4440 prev = rb_next(prev);
4444 entry = rb_entry(node, struct btrfs_inode, rb_node);
4445 objectid = btrfs_ino(entry) + 1;
4446 inode = igrab(&entry->vfs_inode);
4448 spin_unlock(&root->inode_lock);
4449 if (atomic_read(&inode->i_count) > 1)
4450 d_prune_aliases(inode);
4452 * btrfs_drop_inode will have it removed from the inode
4453 * cache when its usage count hits zero.
4457 spin_lock(&root->inode_lock);
4461 if (cond_resched_lock(&root->inode_lock))
4464 node = rb_next(node);
4466 spin_unlock(&root->inode_lock);
4469 int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry)
4471 struct btrfs_root *root = dir->root;
4472 struct btrfs_fs_info *fs_info = root->fs_info;
4473 struct inode *inode = d_inode(dentry);
4474 struct btrfs_root *dest = BTRFS_I(inode)->root;
4475 struct btrfs_trans_handle *trans;
4476 struct btrfs_block_rsv block_rsv;
4478 u64 qgroup_reserved = 0;
4481 down_write(&fs_info->subvol_sem);
4484 * Don't allow to delete a subvolume with send in progress. This is
4485 * inside the inode lock so the error handling that has to drop the bit
4486 * again is not run concurrently.
4488 spin_lock(&dest->root_item_lock);
4489 if (dest->send_in_progress) {
4490 spin_unlock(&dest->root_item_lock);
4492 "attempt to delete subvolume %llu during send",
4493 dest->root_key.objectid);
4497 if (atomic_read(&dest->nr_swapfiles)) {
4498 spin_unlock(&dest->root_item_lock);
4500 "attempt to delete subvolume %llu with active swapfile",
4501 root->root_key.objectid);
4505 root_flags = btrfs_root_flags(&dest->root_item);
4506 btrfs_set_root_flags(&dest->root_item,
4507 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4508 spin_unlock(&dest->root_item_lock);
4510 ret = may_destroy_subvol(dest);
4514 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4516 * One for dir inode,
4517 * two for dir entries,
4518 * two for root ref/backref.
4520 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4523 qgroup_reserved = block_rsv.qgroup_rsv_reserved;
4525 trans = btrfs_start_transaction(root, 0);
4526 if (IS_ERR(trans)) {
4527 ret = PTR_ERR(trans);
4530 ret = btrfs_record_root_in_trans(trans, root);
4532 btrfs_abort_transaction(trans, ret);
4535 btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
4536 qgroup_reserved = 0;
4537 trans->block_rsv = &block_rsv;
4538 trans->bytes_reserved = block_rsv.size;
4540 btrfs_record_snapshot_destroy(trans, dir);
4542 ret = btrfs_unlink_subvol(trans, dir, dentry);
4544 btrfs_abort_transaction(trans, ret);
4548 ret = btrfs_record_root_in_trans(trans, dest);
4550 btrfs_abort_transaction(trans, ret);
4554 memset(&dest->root_item.drop_progress, 0,
4555 sizeof(dest->root_item.drop_progress));
4556 btrfs_set_root_drop_level(&dest->root_item, 0);
4557 btrfs_set_root_refs(&dest->root_item, 0);
4559 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4560 ret = btrfs_insert_orphan_item(trans,
4562 dest->root_key.objectid);
4564 btrfs_abort_transaction(trans, ret);
4569 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4570 BTRFS_UUID_KEY_SUBVOL,
4571 dest->root_key.objectid);
4572 if (ret && ret != -ENOENT) {
4573 btrfs_abort_transaction(trans, ret);
4576 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4577 ret = btrfs_uuid_tree_remove(trans,
4578 dest->root_item.received_uuid,
4579 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4580 dest->root_key.objectid);
4581 if (ret && ret != -ENOENT) {
4582 btrfs_abort_transaction(trans, ret);
4587 free_anon_bdev(dest->anon_dev);
4590 trans->block_rsv = NULL;
4591 trans->bytes_reserved = 0;
4592 ret = btrfs_end_transaction(trans);
4593 inode->i_flags |= S_DEAD;
4595 btrfs_block_rsv_release(fs_info, &block_rsv, (u64)-1, NULL);
4596 if (qgroup_reserved)
4597 btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
4600 spin_lock(&dest->root_item_lock);
4601 root_flags = btrfs_root_flags(&dest->root_item);
4602 btrfs_set_root_flags(&dest->root_item,
4603 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4604 spin_unlock(&dest->root_item_lock);
4607 up_write(&fs_info->subvol_sem);
4609 d_invalidate(dentry);
4610 btrfs_prune_dentries(dest);
4611 ASSERT(dest->send_in_progress == 0);
4617 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4619 struct inode *inode = d_inode(dentry);
4620 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
4622 struct btrfs_trans_handle *trans;
4623 u64 last_unlink_trans;
4624 struct fscrypt_name fname;
4626 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4628 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
4629 if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4631 "extent tree v2 doesn't support snapshot deletion yet");
4634 return btrfs_delete_subvolume(BTRFS_I(dir), dentry);
4637 err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4641 /* This needs to handle no-key deletions later on */
4643 trans = __unlink_start_trans(BTRFS_I(dir));
4644 if (IS_ERR(trans)) {
4645 err = PTR_ERR(trans);
4649 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4650 err = btrfs_unlink_subvol(trans, BTRFS_I(dir), dentry);
4654 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4658 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4660 /* now the directory is empty */
4661 err = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4664 btrfs_i_size_write(BTRFS_I(inode), 0);
4666 * Propagate the last_unlink_trans value of the deleted dir to
4667 * its parent directory. This is to prevent an unrecoverable
4668 * log tree in the case we do something like this:
4670 * 2) create snapshot under dir foo
4671 * 3) delete the snapshot
4674 * 6) fsync foo or some file inside foo
4676 if (last_unlink_trans >= trans->transid)
4677 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4680 btrfs_end_transaction(trans);
4682 btrfs_btree_balance_dirty(fs_info);
4683 fscrypt_free_filename(&fname);
4689 * Read, zero a chunk and write a block.
4691 * @inode - inode that we're zeroing
4692 * @from - the offset to start zeroing
4693 * @len - the length to zero, 0 to zero the entire range respective to the
4695 * @front - zero up to the offset instead of from the offset on
4697 * This will find the block for the "from" offset and cow the block and zero the
4698 * part we want to zero. This is used with truncate and hole punching.
4700 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4703 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4704 struct address_space *mapping = inode->vfs_inode.i_mapping;
4705 struct extent_io_tree *io_tree = &inode->io_tree;
4706 struct btrfs_ordered_extent *ordered;
4707 struct extent_state *cached_state = NULL;
4708 struct extent_changeset *data_reserved = NULL;
4709 bool only_release_metadata = false;
4710 u32 blocksize = fs_info->sectorsize;
4711 pgoff_t index = from >> PAGE_SHIFT;
4712 unsigned offset = from & (blocksize - 1);
4714 gfp_t mask = btrfs_alloc_write_mask(mapping);
4715 size_t write_bytes = blocksize;
4720 if (IS_ALIGNED(offset, blocksize) &&
4721 (!len || IS_ALIGNED(len, blocksize)))
4724 block_start = round_down(from, blocksize);
4725 block_end = block_start + blocksize - 1;
4727 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4730 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
4731 /* For nocow case, no need to reserve data space */
4732 only_release_metadata = true;
4737 ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
4739 if (!only_release_metadata)
4740 btrfs_free_reserved_data_space(inode, data_reserved,
4741 block_start, blocksize);
4745 page = find_or_create_page(mapping, index, mask);
4747 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4749 btrfs_delalloc_release_extents(inode, blocksize);
4754 if (!PageUptodate(page)) {
4755 ret = btrfs_read_folio(NULL, page_folio(page));
4757 if (page->mapping != mapping) {
4762 if (!PageUptodate(page)) {
4769 * We unlock the page after the io is completed and then re-lock it
4770 * above. release_folio() could have come in between that and cleared
4771 * folio private, but left the page in the mapping. Set the page mapped
4772 * here to make sure it's properly set for the subpage stuff.
4774 ret = set_page_extent_mapped(page);
4778 wait_on_page_writeback(page);
4780 lock_extent(io_tree, block_start, block_end, &cached_state);
4782 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4784 unlock_extent(io_tree, block_start, block_end, &cached_state);
4787 btrfs_start_ordered_extent(ordered);
4788 btrfs_put_ordered_extent(ordered);
4792 clear_extent_bit(&inode->io_tree, block_start, block_end,
4793 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4796 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4799 unlock_extent(io_tree, block_start, block_end, &cached_state);
4803 if (offset != blocksize) {
4805 len = blocksize - offset;
4807 memzero_page(page, (block_start - page_offset(page)),
4810 memzero_page(page, (block_start - page_offset(page)) + offset,
4813 btrfs_folio_clear_checked(fs_info, page_folio(page), block_start,
4814 block_end + 1 - block_start);
4815 btrfs_folio_set_dirty(fs_info, page_folio(page), block_start,
4816 block_end + 1 - block_start);
4817 unlock_extent(io_tree, block_start, block_end, &cached_state);
4819 if (only_release_metadata)
4820 set_extent_bit(&inode->io_tree, block_start, block_end,
4821 EXTENT_NORESERVE, NULL);
4825 if (only_release_metadata)
4826 btrfs_delalloc_release_metadata(inode, blocksize, true);
4828 btrfs_delalloc_release_space(inode, data_reserved,
4829 block_start, blocksize, true);
4831 btrfs_delalloc_release_extents(inode, blocksize);
4835 if (only_release_metadata)
4836 btrfs_check_nocow_unlock(inode);
4837 extent_changeset_free(data_reserved);
4841 static int maybe_insert_hole(struct btrfs_inode *inode, u64 offset, u64 len)
4843 struct btrfs_root *root = inode->root;
4844 struct btrfs_fs_info *fs_info = root->fs_info;
4845 struct btrfs_trans_handle *trans;
4846 struct btrfs_drop_extents_args drop_args = { 0 };
4850 * If NO_HOLES is enabled, we don't need to do anything.
4851 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
4852 * or btrfs_update_inode() will be called, which guarantee that the next
4853 * fsync will know this inode was changed and needs to be logged.
4855 if (btrfs_fs_incompat(fs_info, NO_HOLES))
4859 * 1 - for the one we're dropping
4860 * 1 - for the one we're adding
4861 * 1 - for updating the inode.
4863 trans = btrfs_start_transaction(root, 3);
4865 return PTR_ERR(trans);
4867 drop_args.start = offset;
4868 drop_args.end = offset + len;
4869 drop_args.drop_cache = true;
4871 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4873 btrfs_abort_transaction(trans, ret);
4874 btrfs_end_transaction(trans);
4878 ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
4880 btrfs_abort_transaction(trans, ret);
4882 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
4883 btrfs_update_inode(trans, inode);
4885 btrfs_end_transaction(trans);
4890 * This function puts in dummy file extents for the area we're creating a hole
4891 * for. So if we are truncating this file to a larger size we need to insert
4892 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4893 * the range between oldsize and size
4895 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
4897 struct btrfs_root *root = inode->root;
4898 struct btrfs_fs_info *fs_info = root->fs_info;
4899 struct extent_io_tree *io_tree = &inode->io_tree;
4900 struct extent_map *em = NULL;
4901 struct extent_state *cached_state = NULL;
4902 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4903 u64 block_end = ALIGN(size, fs_info->sectorsize);
4910 * If our size started in the middle of a block we need to zero out the
4911 * rest of the block before we expand the i_size, otherwise we could
4912 * expose stale data.
4914 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4918 if (size <= hole_start)
4921 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
4923 cur_offset = hole_start;
4925 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4926 block_end - cur_offset);
4932 last_byte = min(extent_map_end(em), block_end);
4933 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4934 hole_size = last_byte - cur_offset;
4936 if (!(em->flags & EXTENT_FLAG_PREALLOC)) {
4937 struct extent_map *hole_em;
4939 err = maybe_insert_hole(inode, cur_offset, hole_size);
4943 err = btrfs_inode_set_file_extent_range(inode,
4944 cur_offset, hole_size);
4948 hole_em = alloc_extent_map();
4950 btrfs_drop_extent_map_range(inode, cur_offset,
4951 cur_offset + hole_size - 1,
4953 btrfs_set_inode_full_sync(inode);
4956 hole_em->start = cur_offset;
4957 hole_em->len = hole_size;
4958 hole_em->orig_start = cur_offset;
4960 hole_em->block_start = EXTENT_MAP_HOLE;
4961 hole_em->block_len = 0;
4962 hole_em->orig_block_len = 0;
4963 hole_em->ram_bytes = hole_size;
4964 hole_em->generation = btrfs_get_fs_generation(fs_info);
4966 err = btrfs_replace_extent_map_range(inode, hole_em, true);
4967 free_extent_map(hole_em);
4969 err = btrfs_inode_set_file_extent_range(inode,
4970 cur_offset, hole_size);
4975 free_extent_map(em);
4977 cur_offset = last_byte;
4978 if (cur_offset >= block_end)
4981 free_extent_map(em);
4982 unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
4986 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4988 struct btrfs_root *root = BTRFS_I(inode)->root;
4989 struct btrfs_trans_handle *trans;
4990 loff_t oldsize = i_size_read(inode);
4991 loff_t newsize = attr->ia_size;
4992 int mask = attr->ia_valid;
4996 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4997 * special case where we need to update the times despite not having
4998 * these flags set. For all other operations the VFS set these flags
4999 * explicitly if it wants a timestamp update.
5001 if (newsize != oldsize) {
5002 inode_inc_iversion(inode);
5003 if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5004 inode_set_mtime_to_ts(inode,
5005 inode_set_ctime_current(inode));
5009 if (newsize > oldsize) {
5011 * Don't do an expanding truncate while snapshotting is ongoing.
5012 * This is to ensure the snapshot captures a fully consistent
5013 * state of this file - if the snapshot captures this expanding
5014 * truncation, it must capture all writes that happened before
5017 btrfs_drew_write_lock(&root->snapshot_lock);
5018 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5020 btrfs_drew_write_unlock(&root->snapshot_lock);
5024 trans = btrfs_start_transaction(root, 1);
5025 if (IS_ERR(trans)) {
5026 btrfs_drew_write_unlock(&root->snapshot_lock);
5027 return PTR_ERR(trans);
5030 i_size_write(inode, newsize);
5031 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5032 pagecache_isize_extended(inode, oldsize, newsize);
5033 ret = btrfs_update_inode(trans, BTRFS_I(inode));
5034 btrfs_drew_write_unlock(&root->snapshot_lock);
5035 btrfs_end_transaction(trans);
5037 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
5039 if (btrfs_is_zoned(fs_info)) {
5040 ret = btrfs_wait_ordered_range(inode,
5041 ALIGN(newsize, fs_info->sectorsize),
5048 * We're truncating a file that used to have good data down to
5049 * zero. Make sure any new writes to the file get on disk
5053 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5054 &BTRFS_I(inode)->runtime_flags);
5056 truncate_setsize(inode, newsize);
5058 inode_dio_wait(inode);
5060 ret = btrfs_truncate(BTRFS_I(inode), newsize == oldsize);
5061 if (ret && inode->i_nlink) {
5065 * Truncate failed, so fix up the in-memory size. We
5066 * adjusted disk_i_size down as we removed extents, so
5067 * wait for disk_i_size to be stable and then update the
5068 * in-memory size to match.
5070 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5073 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5080 static int btrfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5083 struct inode *inode = d_inode(dentry);
5084 struct btrfs_root *root = BTRFS_I(inode)->root;
5087 if (btrfs_root_readonly(root))
5090 err = setattr_prepare(idmap, dentry, attr);
5094 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5095 err = btrfs_setsize(inode, attr);
5100 if (attr->ia_valid) {
5101 setattr_copy(idmap, inode, attr);
5102 inode_inc_iversion(inode);
5103 err = btrfs_dirty_inode(BTRFS_I(inode));
5105 if (!err && attr->ia_valid & ATTR_MODE)
5106 err = posix_acl_chmod(idmap, dentry, inode->i_mode);
5113 * While truncating the inode pages during eviction, we get the VFS
5114 * calling btrfs_invalidate_folio() against each folio of the inode. This
5115 * is slow because the calls to btrfs_invalidate_folio() result in a
5116 * huge amount of calls to lock_extent() and clear_extent_bit(),
5117 * which keep merging and splitting extent_state structures over and over,
5118 * wasting lots of time.
5120 * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5121 * skip all those expensive operations on a per folio basis and do only
5122 * the ordered io finishing, while we release here the extent_map and
5123 * extent_state structures, without the excessive merging and splitting.
5125 static void evict_inode_truncate_pages(struct inode *inode)
5127 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5128 struct rb_node *node;
5130 ASSERT(inode->i_state & I_FREEING);
5131 truncate_inode_pages_final(&inode->i_data);
5133 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5136 * Keep looping until we have no more ranges in the io tree.
5137 * We can have ongoing bios started by readahead that have
5138 * their endio callback (extent_io.c:end_bio_extent_readpage)
5139 * still in progress (unlocked the pages in the bio but did not yet
5140 * unlocked the ranges in the io tree). Therefore this means some
5141 * ranges can still be locked and eviction started because before
5142 * submitting those bios, which are executed by a separate task (work
5143 * queue kthread), inode references (inode->i_count) were not taken
5144 * (which would be dropped in the end io callback of each bio).
5145 * Therefore here we effectively end up waiting for those bios and
5146 * anyone else holding locked ranges without having bumped the inode's
5147 * reference count - if we don't do it, when they access the inode's
5148 * io_tree to unlock a range it may be too late, leading to an
5149 * use-after-free issue.
5151 spin_lock(&io_tree->lock);
5152 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5153 struct extent_state *state;
5154 struct extent_state *cached_state = NULL;
5157 unsigned state_flags;
5159 node = rb_first(&io_tree->state);
5160 state = rb_entry(node, struct extent_state, rb_node);
5161 start = state->start;
5163 state_flags = state->state;
5164 spin_unlock(&io_tree->lock);
5166 lock_extent(io_tree, start, end, &cached_state);
5169 * If still has DELALLOC flag, the extent didn't reach disk,
5170 * and its reserved space won't be freed by delayed_ref.
5171 * So we need to free its reserved space here.
5172 * (Refer to comment in btrfs_invalidate_folio, case 2)
5174 * Note, end is the bytenr of last byte, so we need + 1 here.
5176 if (state_flags & EXTENT_DELALLOC)
5177 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5178 end - start + 1, NULL);
5180 clear_extent_bit(io_tree, start, end,
5181 EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5185 spin_lock(&io_tree->lock);
5187 spin_unlock(&io_tree->lock);
5190 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5191 struct btrfs_block_rsv *rsv)
5193 struct btrfs_fs_info *fs_info = root->fs_info;
5194 struct btrfs_trans_handle *trans;
5195 u64 delayed_refs_extra = btrfs_calc_delayed_ref_bytes(fs_info, 1);
5199 * Eviction should be taking place at some place safe because of our
5200 * delayed iputs. However the normal flushing code will run delayed
5201 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5203 * We reserve the delayed_refs_extra here again because we can't use
5204 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5205 * above. We reserve our extra bit here because we generate a ton of
5206 * delayed refs activity by truncating.
5208 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5209 * if we fail to make this reservation we can re-try without the
5210 * delayed_refs_extra so we can make some forward progress.
5212 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5213 BTRFS_RESERVE_FLUSH_EVICT);
5215 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5216 BTRFS_RESERVE_FLUSH_EVICT);
5219 "could not allocate space for delete; will truncate on mount");
5220 return ERR_PTR(-ENOSPC);
5222 delayed_refs_extra = 0;
5225 trans = btrfs_join_transaction(root);
5229 if (delayed_refs_extra) {
5230 trans->block_rsv = &fs_info->trans_block_rsv;
5231 trans->bytes_reserved = delayed_refs_extra;
5232 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5233 delayed_refs_extra, true);
5238 void btrfs_evict_inode(struct inode *inode)
5240 struct btrfs_fs_info *fs_info;
5241 struct btrfs_trans_handle *trans;
5242 struct btrfs_root *root = BTRFS_I(inode)->root;
5243 struct btrfs_block_rsv *rsv = NULL;
5246 trace_btrfs_inode_evict(inode);
5249 fsverity_cleanup_inode(inode);
5254 fs_info = inode_to_fs_info(inode);
5255 evict_inode_truncate_pages(inode);
5257 if (inode->i_nlink &&
5258 ((btrfs_root_refs(&root->root_item) != 0 &&
5259 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5260 btrfs_is_free_space_inode(BTRFS_I(inode))))
5263 if (is_bad_inode(inode))
5266 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5269 if (inode->i_nlink > 0) {
5270 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5271 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5276 * This makes sure the inode item in tree is uptodate and the space for
5277 * the inode update is released.
5279 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5284 * This drops any pending insert or delete operations we have for this
5285 * inode. We could have a delayed dir index deletion queued up, but
5286 * we're removing the inode completely so that'll be taken care of in
5289 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5291 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5294 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5295 rsv->failfast = true;
5297 btrfs_i_size_write(BTRFS_I(inode), 0);
5300 struct btrfs_truncate_control control = {
5301 .inode = BTRFS_I(inode),
5302 .ino = btrfs_ino(BTRFS_I(inode)),
5307 trans = evict_refill_and_join(root, rsv);
5311 trans->block_rsv = rsv;
5313 ret = btrfs_truncate_inode_items(trans, root, &control);
5314 trans->block_rsv = &fs_info->trans_block_rsv;
5315 btrfs_end_transaction(trans);
5317 * We have not added new delayed items for our inode after we
5318 * have flushed its delayed items, so no need to throttle on
5319 * delayed items. However we have modified extent buffers.
5321 btrfs_btree_balance_dirty_nodelay(fs_info);
5322 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5329 * Errors here aren't a big deal, it just means we leave orphan items in
5330 * the tree. They will be cleaned up on the next mount. If the inode
5331 * number gets reused, cleanup deletes the orphan item without doing
5332 * anything, and unlink reuses the existing orphan item.
5334 * If it turns out that we are dropping too many of these, we might want
5335 * to add a mechanism for retrying these after a commit.
5337 trans = evict_refill_and_join(root, rsv);
5338 if (!IS_ERR(trans)) {
5339 trans->block_rsv = rsv;
5340 btrfs_orphan_del(trans, BTRFS_I(inode));
5341 trans->block_rsv = &fs_info->trans_block_rsv;
5342 btrfs_end_transaction(trans);
5346 btrfs_free_block_rsv(fs_info, rsv);
5348 * If we didn't successfully delete, the orphan item will still be in
5349 * the tree and we'll retry on the next mount. Again, we might also want
5350 * to retry these periodically in the future.
5352 btrfs_remove_delayed_node(BTRFS_I(inode));
5353 fsverity_cleanup_inode(inode);
5358 * Return the key found in the dir entry in the location pointer, fill @type
5359 * with BTRFS_FT_*, and return 0.
5361 * If no dir entries were found, returns -ENOENT.
5362 * If found a corrupted location in dir entry, returns -EUCLEAN.
5364 static int btrfs_inode_by_name(struct btrfs_inode *dir, struct dentry *dentry,
5365 struct btrfs_key *location, u8 *type)
5367 struct btrfs_dir_item *di;
5368 struct btrfs_path *path;
5369 struct btrfs_root *root = dir->root;
5371 struct fscrypt_name fname;
5373 path = btrfs_alloc_path();
5377 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
5381 * fscrypt_setup_filename() should never return a positive value, but
5382 * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
5386 /* This needs to handle no-key deletions later on */
5388 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
5389 &fname.disk_name, 0);
5390 if (IS_ERR_OR_NULL(di)) {
5391 ret = di ? PTR_ERR(di) : -ENOENT;
5395 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5396 if (location->type != BTRFS_INODE_ITEM_KEY &&
5397 location->type != BTRFS_ROOT_ITEM_KEY) {
5399 btrfs_warn(root->fs_info,
5400 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5401 __func__, fname.disk_name.name, btrfs_ino(dir),
5402 location->objectid, location->type, location->offset);
5405 *type = btrfs_dir_ftype(path->nodes[0], di);
5407 fscrypt_free_filename(&fname);
5408 btrfs_free_path(path);
5413 * when we hit a tree root in a directory, the btrfs part of the inode
5414 * needs to be changed to reflect the root directory of the tree root. This
5415 * is kind of like crossing a mount point.
5417 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5418 struct btrfs_inode *dir,
5419 struct dentry *dentry,
5420 struct btrfs_key *location,
5421 struct btrfs_root **sub_root)
5423 struct btrfs_path *path;
5424 struct btrfs_root *new_root;
5425 struct btrfs_root_ref *ref;
5426 struct extent_buffer *leaf;
5427 struct btrfs_key key;
5430 struct fscrypt_name fname;
5432 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
5436 path = btrfs_alloc_path();
5443 key.objectid = dir->root->root_key.objectid;
5444 key.type = BTRFS_ROOT_REF_KEY;
5445 key.offset = location->objectid;
5447 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5454 leaf = path->nodes[0];
5455 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5456 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5457 btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5460 ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5461 (unsigned long)(ref + 1), fname.disk_name.len);
5465 btrfs_release_path(path);
5467 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5468 if (IS_ERR(new_root)) {
5469 err = PTR_ERR(new_root);
5473 *sub_root = new_root;
5474 location->objectid = btrfs_root_dirid(&new_root->root_item);
5475 location->type = BTRFS_INODE_ITEM_KEY;
5476 location->offset = 0;
5479 btrfs_free_path(path);
5480 fscrypt_free_filename(&fname);
5484 static void inode_tree_add(struct btrfs_inode *inode)
5486 struct btrfs_root *root = inode->root;
5487 struct btrfs_inode *entry;
5489 struct rb_node *parent;
5490 struct rb_node *new = &inode->rb_node;
5491 u64 ino = btrfs_ino(inode);
5493 if (inode_unhashed(&inode->vfs_inode))
5496 spin_lock(&root->inode_lock);
5497 p = &root->inode_tree.rb_node;
5500 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5502 if (ino < btrfs_ino(entry))
5503 p = &parent->rb_left;
5504 else if (ino > btrfs_ino(entry))
5505 p = &parent->rb_right;
5507 WARN_ON(!(entry->vfs_inode.i_state &
5508 (I_WILL_FREE | I_FREEING)));
5509 rb_replace_node(parent, new, &root->inode_tree);
5510 RB_CLEAR_NODE(parent);
5511 spin_unlock(&root->inode_lock);
5515 rb_link_node(new, parent, p);
5516 rb_insert_color(new, &root->inode_tree);
5517 spin_unlock(&root->inode_lock);
5520 static void inode_tree_del(struct btrfs_inode *inode)
5522 struct btrfs_root *root = inode->root;
5525 spin_lock(&root->inode_lock);
5526 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5527 rb_erase(&inode->rb_node, &root->inode_tree);
5528 RB_CLEAR_NODE(&inode->rb_node);
5529 empty = RB_EMPTY_ROOT(&root->inode_tree);
5531 spin_unlock(&root->inode_lock);
5533 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5534 spin_lock(&root->inode_lock);
5535 empty = RB_EMPTY_ROOT(&root->inode_tree);
5536 spin_unlock(&root->inode_lock);
5538 btrfs_add_dead_root(root);
5543 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5545 struct btrfs_iget_args *args = p;
5547 inode->i_ino = args->ino;
5548 BTRFS_I(inode)->location.objectid = args->ino;
5549 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5550 BTRFS_I(inode)->location.offset = 0;
5551 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5552 BUG_ON(args->root && !BTRFS_I(inode)->root);
5554 if (args->root && args->root == args->root->fs_info->tree_root &&
5555 args->ino != BTRFS_BTREE_INODE_OBJECTID)
5556 set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5557 &BTRFS_I(inode)->runtime_flags);
5561 static int btrfs_find_actor(struct inode *inode, void *opaque)
5563 struct btrfs_iget_args *args = opaque;
5565 return args->ino == BTRFS_I(inode)->location.objectid &&
5566 args->root == BTRFS_I(inode)->root;
5569 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5570 struct btrfs_root *root)
5572 struct inode *inode;
5573 struct btrfs_iget_args args;
5574 unsigned long hashval = btrfs_inode_hash(ino, root);
5579 inode = iget5_locked(s, hashval, btrfs_find_actor,
5580 btrfs_init_locked_inode,
5586 * Get an inode object given its inode number and corresponding root.
5587 * Path can be preallocated to prevent recursing back to iget through
5588 * allocator. NULL is also valid but may require an additional allocation
5591 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5592 struct btrfs_root *root, struct btrfs_path *path)
5594 struct inode *inode;
5596 inode = btrfs_iget_locked(s, ino, root);
5598 return ERR_PTR(-ENOMEM);
5600 if (inode->i_state & I_NEW) {
5603 ret = btrfs_read_locked_inode(inode, path);
5605 inode_tree_add(BTRFS_I(inode));
5606 unlock_new_inode(inode);
5610 * ret > 0 can come from btrfs_search_slot called by
5611 * btrfs_read_locked_inode, this means the inode item
5616 inode = ERR_PTR(ret);
5623 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5625 return btrfs_iget_path(s, ino, root, NULL);
5628 static struct inode *new_simple_dir(struct inode *dir,
5629 struct btrfs_key *key,
5630 struct btrfs_root *root)
5632 struct timespec64 ts;
5633 struct inode *inode = new_inode(dir->i_sb);
5636 return ERR_PTR(-ENOMEM);
5638 BTRFS_I(inode)->root = btrfs_grab_root(root);
5639 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5640 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5642 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5644 * We only need lookup, the rest is read-only and there's no inode
5645 * associated with the dentry
5647 inode->i_op = &simple_dir_inode_operations;
5648 inode->i_opflags &= ~IOP_XATTR;
5649 inode->i_fop = &simple_dir_operations;
5650 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5652 ts = inode_set_ctime_current(inode);
5653 inode_set_mtime_to_ts(inode, ts);
5654 inode_set_atime_to_ts(inode, inode_get_atime(dir));
5655 BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
5656 BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
5658 inode->i_uid = dir->i_uid;
5659 inode->i_gid = dir->i_gid;
5664 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5665 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5666 static_assert(BTRFS_FT_DIR == FT_DIR);
5667 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5668 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5669 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5670 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5671 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5673 static inline u8 btrfs_inode_type(struct inode *inode)
5675 return fs_umode_to_ftype(inode->i_mode);
5678 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5680 struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
5681 struct inode *inode;
5682 struct btrfs_root *root = BTRFS_I(dir)->root;
5683 struct btrfs_root *sub_root = root;
5684 struct btrfs_key location;
5688 if (dentry->d_name.len > BTRFS_NAME_LEN)
5689 return ERR_PTR(-ENAMETOOLONG);
5691 ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
5693 return ERR_PTR(ret);
5695 if (location.type == BTRFS_INODE_ITEM_KEY) {
5696 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5700 /* Do extra check against inode mode with di_type */
5701 if (btrfs_inode_type(inode) != di_type) {
5703 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5704 inode->i_mode, btrfs_inode_type(inode),
5707 return ERR_PTR(-EUCLEAN);
5712 ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
5713 &location, &sub_root);
5716 inode = ERR_PTR(ret);
5718 inode = new_simple_dir(dir, &location, root);
5720 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5721 btrfs_put_root(sub_root);
5726 down_read(&fs_info->cleanup_work_sem);
5727 if (!sb_rdonly(inode->i_sb))
5728 ret = btrfs_orphan_cleanup(sub_root);
5729 up_read(&fs_info->cleanup_work_sem);
5732 inode = ERR_PTR(ret);
5739 static int btrfs_dentry_delete(const struct dentry *dentry)
5741 struct btrfs_root *root;
5742 struct inode *inode = d_inode(dentry);
5744 if (!inode && !IS_ROOT(dentry))
5745 inode = d_inode(dentry->d_parent);
5748 root = BTRFS_I(inode)->root;
5749 if (btrfs_root_refs(&root->root_item) == 0)
5752 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5758 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5761 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5763 if (inode == ERR_PTR(-ENOENT))
5765 return d_splice_alias(inode, dentry);
5769 * Find the highest existing sequence number in a directory and then set the
5770 * in-memory index_cnt variable to the first free sequence number.
5772 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5774 struct btrfs_root *root = inode->root;
5775 struct btrfs_key key, found_key;
5776 struct btrfs_path *path;
5777 struct extent_buffer *leaf;
5780 key.objectid = btrfs_ino(inode);
5781 key.type = BTRFS_DIR_INDEX_KEY;
5782 key.offset = (u64)-1;
5784 path = btrfs_alloc_path();
5788 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5791 /* FIXME: we should be able to handle this */
5796 if (path->slots[0] == 0) {
5797 inode->index_cnt = BTRFS_DIR_START_INDEX;
5803 leaf = path->nodes[0];
5804 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5806 if (found_key.objectid != btrfs_ino(inode) ||
5807 found_key.type != BTRFS_DIR_INDEX_KEY) {
5808 inode->index_cnt = BTRFS_DIR_START_INDEX;
5812 inode->index_cnt = found_key.offset + 1;
5814 btrfs_free_path(path);
5818 static int btrfs_get_dir_last_index(struct btrfs_inode *dir, u64 *index)
5822 btrfs_inode_lock(dir, 0);
5823 if (dir->index_cnt == (u64)-1) {
5824 ret = btrfs_inode_delayed_dir_index_count(dir);
5826 ret = btrfs_set_inode_index_count(dir);
5832 /* index_cnt is the index number of next new entry, so decrement it. */
5833 *index = dir->index_cnt - 1;
5835 btrfs_inode_unlock(dir, 0);
5841 * All this infrastructure exists because dir_emit can fault, and we are holding
5842 * the tree lock when doing readdir. For now just allocate a buffer and copy
5843 * our information into that, and then dir_emit from the buffer. This is
5844 * similar to what NFS does, only we don't keep the buffer around in pagecache
5845 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5846 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5849 static int btrfs_opendir(struct inode *inode, struct file *file)
5851 struct btrfs_file_private *private;
5855 ret = btrfs_get_dir_last_index(BTRFS_I(inode), &last_index);
5859 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5862 private->last_index = last_index;
5863 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5864 if (!private->filldir_buf) {
5868 file->private_data = private;
5872 static loff_t btrfs_dir_llseek(struct file *file, loff_t offset, int whence)
5874 struct btrfs_file_private *private = file->private_data;
5877 ret = btrfs_get_dir_last_index(BTRFS_I(file_inode(file)),
5878 &private->last_index);
5882 return generic_file_llseek(file, offset, whence);
5892 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5895 struct dir_entry *entry = addr;
5896 char *name = (char *)(entry + 1);
5898 ctx->pos = get_unaligned(&entry->offset);
5899 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5900 get_unaligned(&entry->ino),
5901 get_unaligned(&entry->type)))
5903 addr += sizeof(struct dir_entry) +
5904 get_unaligned(&entry->name_len);
5910 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5912 struct inode *inode = file_inode(file);
5913 struct btrfs_root *root = BTRFS_I(inode)->root;
5914 struct btrfs_file_private *private = file->private_data;
5915 struct btrfs_dir_item *di;
5916 struct btrfs_key key;
5917 struct btrfs_key found_key;
5918 struct btrfs_path *path;
5920 LIST_HEAD(ins_list);
5921 LIST_HEAD(del_list);
5928 struct btrfs_key location;
5930 if (!dir_emit_dots(file, ctx))
5933 path = btrfs_alloc_path();
5937 addr = private->filldir_buf;
5938 path->reada = READA_FORWARD;
5940 put = btrfs_readdir_get_delayed_items(inode, private->last_index,
5941 &ins_list, &del_list);
5944 key.type = BTRFS_DIR_INDEX_KEY;
5945 key.offset = ctx->pos;
5946 key.objectid = btrfs_ino(BTRFS_I(inode));
5948 btrfs_for_each_slot(root, &key, &found_key, path, ret) {
5949 struct dir_entry *entry;
5950 struct extent_buffer *leaf = path->nodes[0];
5953 if (found_key.objectid != key.objectid)
5955 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5957 if (found_key.offset < ctx->pos)
5959 if (found_key.offset > private->last_index)
5961 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5963 di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
5964 name_len = btrfs_dir_name_len(leaf, di);
5965 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5967 btrfs_release_path(path);
5968 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5971 addr = private->filldir_buf;
5977 ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
5979 name_ptr = (char *)(entry + 1);
5980 read_extent_buffer(leaf, name_ptr,
5981 (unsigned long)(di + 1), name_len);
5982 put_unaligned(name_len, &entry->name_len);
5983 put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
5984 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5985 put_unaligned(location.objectid, &entry->ino);
5986 put_unaligned(found_key.offset, &entry->offset);
5988 addr += sizeof(struct dir_entry) + name_len;
5989 total_len += sizeof(struct dir_entry) + name_len;
5991 /* Catch error encountered during iteration */
5995 btrfs_release_path(path);
5997 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6001 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6006 * Stop new entries from being returned after we return the last
6009 * New directory entries are assigned a strictly increasing
6010 * offset. This means that new entries created during readdir
6011 * are *guaranteed* to be seen in the future by that readdir.
6012 * This has broken buggy programs which operate on names as
6013 * they're returned by readdir. Until we re-use freed offsets
6014 * we have this hack to stop new entries from being returned
6015 * under the assumption that they'll never reach this huge
6018 * This is being careful not to overflow 32bit loff_t unless the
6019 * last entry requires it because doing so has broken 32bit apps
6022 if (ctx->pos >= INT_MAX)
6023 ctx->pos = LLONG_MAX;
6030 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6031 btrfs_free_path(path);
6036 * This is somewhat expensive, updating the tree every time the
6037 * inode changes. But, it is most likely to find the inode in cache.
6038 * FIXME, needs more benchmarking...there are no reasons other than performance
6039 * to keep or drop this code.
6041 static int btrfs_dirty_inode(struct btrfs_inode *inode)
6043 struct btrfs_root *root = inode->root;
6044 struct btrfs_fs_info *fs_info = root->fs_info;
6045 struct btrfs_trans_handle *trans;
6048 if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
6051 trans = btrfs_join_transaction(root);
6053 return PTR_ERR(trans);
6055 ret = btrfs_update_inode(trans, inode);
6056 if (ret == -ENOSPC || ret == -EDQUOT) {
6057 /* whoops, lets try again with the full transaction */
6058 btrfs_end_transaction(trans);
6059 trans = btrfs_start_transaction(root, 1);
6061 return PTR_ERR(trans);
6063 ret = btrfs_update_inode(trans, inode);
6065 btrfs_end_transaction(trans);
6066 if (inode->delayed_node)
6067 btrfs_balance_delayed_items(fs_info);
6073 * This is a copy of file_update_time. We need this so we can return error on
6074 * ENOSPC for updating the inode in the case of file write and mmap writes.
6076 static int btrfs_update_time(struct inode *inode, int flags)
6078 struct btrfs_root *root = BTRFS_I(inode)->root;
6081 if (btrfs_root_readonly(root))
6084 dirty = inode_update_timestamps(inode, flags);
6085 return dirty ? btrfs_dirty_inode(BTRFS_I(inode)) : 0;
6089 * helper to find a free sequence number in a given directory. This current
6090 * code is very simple, later versions will do smarter things in the btree
6092 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6096 if (dir->index_cnt == (u64)-1) {
6097 ret = btrfs_inode_delayed_dir_index_count(dir);
6099 ret = btrfs_set_inode_index_count(dir);
6105 *index = dir->index_cnt;
6111 static int btrfs_insert_inode_locked(struct inode *inode)
6113 struct btrfs_iget_args args;
6115 args.ino = BTRFS_I(inode)->location.objectid;
6116 args.root = BTRFS_I(inode)->root;
6118 return insert_inode_locked4(inode,
6119 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6120 btrfs_find_actor, &args);
6123 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6124 unsigned int *trans_num_items)
6126 struct inode *dir = args->dir;
6127 struct inode *inode = args->inode;
6130 if (!args->orphan) {
6131 ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6137 ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6139 fscrypt_free_filename(&args->fname);
6143 /* 1 to add inode item */
6144 *trans_num_items = 1;
6145 /* 1 to add compression property */
6146 if (BTRFS_I(dir)->prop_compress)
6147 (*trans_num_items)++;
6148 /* 1 to add default ACL xattr */
6149 if (args->default_acl)
6150 (*trans_num_items)++;
6151 /* 1 to add access ACL xattr */
6153 (*trans_num_items)++;
6154 #ifdef CONFIG_SECURITY
6155 /* 1 to add LSM xattr */
6156 if (dir->i_security)
6157 (*trans_num_items)++;
6160 /* 1 to add orphan item */
6161 (*trans_num_items)++;
6165 * 1 to add dir index
6166 * 1 to update parent inode item
6168 * No need for 1 unit for the inode ref item because it is
6169 * inserted in a batch together with the inode item at
6170 * btrfs_create_new_inode().
6172 *trans_num_items += 3;
6177 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6179 posix_acl_release(args->acl);
6180 posix_acl_release(args->default_acl);
6181 fscrypt_free_filename(&args->fname);
6185 * Inherit flags from the parent inode.
6187 * Currently only the compression flags and the cow flags are inherited.
6189 static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
6195 if (flags & BTRFS_INODE_NOCOMPRESS) {
6196 inode->flags &= ~BTRFS_INODE_COMPRESS;
6197 inode->flags |= BTRFS_INODE_NOCOMPRESS;
6198 } else if (flags & BTRFS_INODE_COMPRESS) {
6199 inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
6200 inode->flags |= BTRFS_INODE_COMPRESS;
6203 if (flags & BTRFS_INODE_NODATACOW) {
6204 inode->flags |= BTRFS_INODE_NODATACOW;
6205 if (S_ISREG(inode->vfs_inode.i_mode))
6206 inode->flags |= BTRFS_INODE_NODATASUM;
6209 btrfs_sync_inode_flags_to_i_flags(&inode->vfs_inode);
6212 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6213 struct btrfs_new_inode_args *args)
6215 struct timespec64 ts;
6216 struct inode *dir = args->dir;
6217 struct inode *inode = args->inode;
6218 const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6219 struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6220 struct btrfs_root *root;
6221 struct btrfs_inode_item *inode_item;
6222 struct btrfs_key *location;
6223 struct btrfs_path *path;
6225 struct btrfs_inode_ref *ref;
6226 struct btrfs_key key[2];
6228 struct btrfs_item_batch batch;
6232 path = btrfs_alloc_path();
6237 BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6238 root = BTRFS_I(inode)->root;
6240 ret = btrfs_get_free_objectid(root, &objectid);
6243 inode->i_ino = objectid;
6247 * O_TMPFILE, set link count to 0, so that after this point, we
6248 * fill in an inode item with the correct link count.
6250 set_nlink(inode, 0);
6252 trace_btrfs_inode_request(dir);
6254 ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6258 /* index_cnt is ignored for everything but a dir. */
6259 BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6260 BTRFS_I(inode)->generation = trans->transid;
6261 inode->i_generation = BTRFS_I(inode)->generation;
6264 * We don't have any capability xattrs set here yet, shortcut any
6265 * queries for the xattrs here. If we add them later via the inode
6266 * security init path or any other path this flag will be cleared.
6268 set_bit(BTRFS_INODE_NO_CAP_XATTR, &BTRFS_I(inode)->runtime_flags);
6271 * Subvolumes don't inherit flags from their parent directory.
6272 * Originally this was probably by accident, but we probably can't
6273 * change it now without compatibility issues.
6276 btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
6278 if (S_ISREG(inode->i_mode)) {
6279 if (btrfs_test_opt(fs_info, NODATASUM))
6280 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6281 if (btrfs_test_opt(fs_info, NODATACOW))
6282 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6283 BTRFS_INODE_NODATASUM;
6286 location = &BTRFS_I(inode)->location;
6287 location->objectid = objectid;
6288 location->offset = 0;
6289 location->type = BTRFS_INODE_ITEM_KEY;
6291 ret = btrfs_insert_inode_locked(inode);
6294 BTRFS_I(dir)->index_cnt--;
6299 * We could have gotten an inode number from somebody who was fsynced
6300 * and then removed in this same transaction, so let's just set full
6301 * sync since it will be a full sync anyway and this will blow away the
6302 * old info in the log.
6304 btrfs_set_inode_full_sync(BTRFS_I(inode));
6306 key[0].objectid = objectid;
6307 key[0].type = BTRFS_INODE_ITEM_KEY;
6310 sizes[0] = sizeof(struct btrfs_inode_item);
6312 if (!args->orphan) {
6314 * Start new inodes with an inode_ref. This is slightly more
6315 * efficient for small numbers of hard links since they will
6316 * be packed into one item. Extended refs will kick in if we
6317 * add more hard links than can fit in the ref item.
6319 key[1].objectid = objectid;
6320 key[1].type = BTRFS_INODE_REF_KEY;
6322 key[1].offset = objectid;
6323 sizes[1] = 2 + sizeof(*ref);
6325 key[1].offset = btrfs_ino(BTRFS_I(dir));
6326 sizes[1] = name->len + sizeof(*ref);
6330 batch.keys = &key[0];
6331 batch.data_sizes = &sizes[0];
6332 batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6333 batch.nr = args->orphan ? 1 : 2;
6334 ret = btrfs_insert_empty_items(trans, root, path, &batch);
6336 btrfs_abort_transaction(trans, ret);
6340 ts = simple_inode_init_ts(inode);
6341 BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
6342 BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
6345 * We're going to fill the inode item now, so at this point the inode
6346 * must be fully initialized.
6349 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6350 struct btrfs_inode_item);
6351 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6352 sizeof(*inode_item));
6353 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6355 if (!args->orphan) {
6356 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6357 struct btrfs_inode_ref);
6358 ptr = (unsigned long)(ref + 1);
6360 btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6361 btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6362 write_extent_buffer(path->nodes[0], "..", ptr, 2);
6364 btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6366 btrfs_set_inode_ref_index(path->nodes[0], ref,
6367 BTRFS_I(inode)->dir_index);
6368 write_extent_buffer(path->nodes[0], name->name, ptr,
6373 btrfs_mark_buffer_dirty(trans, path->nodes[0]);
6375 * We don't need the path anymore, plus inheriting properties, adding
6376 * ACLs, security xattrs, orphan item or adding the link, will result in
6377 * allocating yet another path. So just free our path.
6379 btrfs_free_path(path);
6383 struct inode *parent;
6386 * Subvolumes inherit properties from their parent subvolume,
6387 * not the directory they were created in.
6389 parent = btrfs_iget(fs_info->sb, BTRFS_FIRST_FREE_OBJECTID,
6390 BTRFS_I(dir)->root);
6391 if (IS_ERR(parent)) {
6392 ret = PTR_ERR(parent);
6394 ret = btrfs_inode_inherit_props(trans, inode, parent);
6398 ret = btrfs_inode_inherit_props(trans, inode, dir);
6402 "error inheriting props for ino %llu (root %llu): %d",
6403 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid,
6408 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6411 if (!args->subvol) {
6412 ret = btrfs_init_inode_security(trans, args);
6414 btrfs_abort_transaction(trans, ret);
6419 inode_tree_add(BTRFS_I(inode));
6421 trace_btrfs_inode_new(inode);
6422 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6424 btrfs_update_root_times(trans, root);
6427 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6429 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6430 0, BTRFS_I(inode)->dir_index);
6433 btrfs_abort_transaction(trans, ret);
6441 * discard_new_inode() calls iput(), but the caller owns the reference
6445 discard_new_inode(inode);
6447 btrfs_free_path(path);
6452 * utility function to add 'inode' into 'parent_inode' with
6453 * a give name and a given sequence number.
6454 * if 'add_backref' is true, also insert a backref from the
6455 * inode to the parent directory.
6457 int btrfs_add_link(struct btrfs_trans_handle *trans,
6458 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6459 const struct fscrypt_str *name, int add_backref, u64 index)
6462 struct btrfs_key key;
6463 struct btrfs_root *root = parent_inode->root;
6464 u64 ino = btrfs_ino(inode);
6465 u64 parent_ino = btrfs_ino(parent_inode);
6467 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6468 memcpy(&key, &inode->root->root_key, sizeof(key));
6471 key.type = BTRFS_INODE_ITEM_KEY;
6475 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6476 ret = btrfs_add_root_ref(trans, key.objectid,
6477 root->root_key.objectid, parent_ino,
6479 } else if (add_backref) {
6480 ret = btrfs_insert_inode_ref(trans, root, name,
6481 ino, parent_ino, index);
6484 /* Nothing to clean up yet */
6488 ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6489 btrfs_inode_type(&inode->vfs_inode), index);
6490 if (ret == -EEXIST || ret == -EOVERFLOW)
6493 btrfs_abort_transaction(trans, ret);
6497 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6499 inode_inc_iversion(&parent_inode->vfs_inode);
6501 * If we are replaying a log tree, we do not want to update the mtime
6502 * and ctime of the parent directory with the current time, since the
6503 * log replay procedure is responsible for setting them to their correct
6504 * values (the ones it had when the fsync was done).
6506 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags))
6507 inode_set_mtime_to_ts(&parent_inode->vfs_inode,
6508 inode_set_ctime_current(&parent_inode->vfs_inode));
6510 ret = btrfs_update_inode(trans, parent_inode);
6512 btrfs_abort_transaction(trans, ret);
6516 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6519 err = btrfs_del_root_ref(trans, key.objectid,
6520 root->root_key.objectid, parent_ino,
6521 &local_index, name);
6523 btrfs_abort_transaction(trans, err);
6524 } else if (add_backref) {
6528 err = btrfs_del_inode_ref(trans, root, name, ino, parent_ino,
6531 btrfs_abort_transaction(trans, err);
6534 /* Return the original error code */
6538 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6539 struct inode *inode)
6541 struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6542 struct btrfs_root *root = BTRFS_I(dir)->root;
6543 struct btrfs_new_inode_args new_inode_args = {
6548 unsigned int trans_num_items;
6549 struct btrfs_trans_handle *trans;
6552 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6556 trans = btrfs_start_transaction(root, trans_num_items);
6557 if (IS_ERR(trans)) {
6558 err = PTR_ERR(trans);
6559 goto out_new_inode_args;
6562 err = btrfs_create_new_inode(trans, &new_inode_args);
6564 d_instantiate_new(dentry, inode);
6566 btrfs_end_transaction(trans);
6567 btrfs_btree_balance_dirty(fs_info);
6569 btrfs_new_inode_args_destroy(&new_inode_args);
6576 static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
6577 struct dentry *dentry, umode_t mode, dev_t rdev)
6579 struct inode *inode;
6581 inode = new_inode(dir->i_sb);
6584 inode_init_owner(idmap, inode, dir, mode);
6585 inode->i_op = &btrfs_special_inode_operations;
6586 init_special_inode(inode, inode->i_mode, rdev);
6587 return btrfs_create_common(dir, dentry, inode);
6590 static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
6591 struct dentry *dentry, umode_t mode, bool excl)
6593 struct inode *inode;
6595 inode = new_inode(dir->i_sb);
6598 inode_init_owner(idmap, inode, dir, mode);
6599 inode->i_fop = &btrfs_file_operations;
6600 inode->i_op = &btrfs_file_inode_operations;
6601 inode->i_mapping->a_ops = &btrfs_aops;
6602 return btrfs_create_common(dir, dentry, inode);
6605 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6606 struct dentry *dentry)
6608 struct btrfs_trans_handle *trans = NULL;
6609 struct btrfs_root *root = BTRFS_I(dir)->root;
6610 struct inode *inode = d_inode(old_dentry);
6611 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
6612 struct fscrypt_name fname;
6617 /* do not allow sys_link's with other subvols of the same device */
6618 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6621 if (inode->i_nlink >= BTRFS_LINK_MAX)
6624 err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
6628 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6633 * 2 items for inode and inode ref
6634 * 2 items for dir items
6635 * 1 item for parent inode
6636 * 1 item for orphan item deletion if O_TMPFILE
6638 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6639 if (IS_ERR(trans)) {
6640 err = PTR_ERR(trans);
6645 /* There are several dir indexes for this inode, clear the cache. */
6646 BTRFS_I(inode)->dir_index = 0ULL;
6648 inode_inc_iversion(inode);
6649 inode_set_ctime_current(inode);
6651 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6653 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6654 &fname.disk_name, 1, index);
6659 struct dentry *parent = dentry->d_parent;
6661 err = btrfs_update_inode(trans, BTRFS_I(inode));
6664 if (inode->i_nlink == 1) {
6666 * If new hard link count is 1, it's a file created
6667 * with open(2) O_TMPFILE flag.
6669 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6673 d_instantiate(dentry, inode);
6674 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6678 fscrypt_free_filename(&fname);
6680 btrfs_end_transaction(trans);
6682 inode_dec_link_count(inode);
6685 btrfs_btree_balance_dirty(fs_info);
6689 static int btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
6690 struct dentry *dentry, umode_t mode)
6692 struct inode *inode;
6694 inode = new_inode(dir->i_sb);
6697 inode_init_owner(idmap, inode, dir, S_IFDIR | mode);
6698 inode->i_op = &btrfs_dir_inode_operations;
6699 inode->i_fop = &btrfs_dir_file_operations;
6700 return btrfs_create_common(dir, dentry, inode);
6703 static noinline int uncompress_inline(struct btrfs_path *path,
6705 struct btrfs_file_extent_item *item)
6708 struct extent_buffer *leaf = path->nodes[0];
6711 unsigned long inline_size;
6715 compress_type = btrfs_file_extent_compression(leaf, item);
6716 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6717 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6718 tmp = kmalloc(inline_size, GFP_NOFS);
6721 ptr = btrfs_file_extent_inline_start(item);
6723 read_extent_buffer(leaf, tmp, ptr, inline_size);
6725 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6726 ret = btrfs_decompress(compress_type, tmp, page, 0, inline_size, max_size);
6729 * decompression code contains a memset to fill in any space between the end
6730 * of the uncompressed data and the end of max_size in case the decompressed
6731 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6732 * the end of an inline extent and the beginning of the next block, so we
6733 * cover that region here.
6736 if (max_size < PAGE_SIZE)
6737 memzero_page(page, max_size, PAGE_SIZE - max_size);
6742 static int read_inline_extent(struct btrfs_inode *inode, struct btrfs_path *path,
6745 struct btrfs_file_extent_item *fi;
6749 if (!page || PageUptodate(page))
6752 ASSERT(page_offset(page) == 0);
6754 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6755 struct btrfs_file_extent_item);
6756 if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
6757 return uncompress_inline(path, page, fi);
6759 copy_size = min_t(u64, PAGE_SIZE,
6760 btrfs_file_extent_ram_bytes(path->nodes[0], fi));
6761 kaddr = kmap_local_page(page);
6762 read_extent_buffer(path->nodes[0], kaddr,
6763 btrfs_file_extent_inline_start(fi), copy_size);
6764 kunmap_local(kaddr);
6765 if (copy_size < PAGE_SIZE)
6766 memzero_page(page, copy_size, PAGE_SIZE - copy_size);
6771 * Lookup the first extent overlapping a range in a file.
6773 * @inode: file to search in
6774 * @page: page to read extent data into if the extent is inline
6775 * @pg_offset: offset into @page to copy to
6776 * @start: file offset
6777 * @len: length of range starting at @start
6779 * Return the first &struct extent_map which overlaps the given range, reading
6780 * it from the B-tree and caching it if necessary. Note that there may be more
6781 * extents which overlap the given range after the returned extent_map.
6783 * If @page is not NULL and the extent is inline, this also reads the extent
6784 * data directly into the page and marks the extent up to date in the io_tree.
6786 * Return: ERR_PTR on error, non-NULL extent_map on success.
6788 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6789 struct page *page, size_t pg_offset,
6792 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6794 u64 extent_start = 0;
6796 u64 objectid = btrfs_ino(inode);
6797 int extent_type = -1;
6798 struct btrfs_path *path = NULL;
6799 struct btrfs_root *root = inode->root;
6800 struct btrfs_file_extent_item *item;
6801 struct extent_buffer *leaf;
6802 struct btrfs_key found_key;
6803 struct extent_map *em = NULL;
6804 struct extent_map_tree *em_tree = &inode->extent_tree;
6806 read_lock(&em_tree->lock);
6807 em = lookup_extent_mapping(em_tree, start, len);
6808 read_unlock(&em_tree->lock);
6811 if (em->start > start || em->start + em->len <= start)
6812 free_extent_map(em);
6813 else if (em->block_start == EXTENT_MAP_INLINE && page)
6814 free_extent_map(em);
6818 em = alloc_extent_map();
6823 em->start = EXTENT_MAP_HOLE;
6824 em->orig_start = EXTENT_MAP_HOLE;
6826 em->block_len = (u64)-1;
6828 path = btrfs_alloc_path();
6834 /* Chances are we'll be called again, so go ahead and do readahead */
6835 path->reada = READA_FORWARD;
6838 * The same explanation in load_free_space_cache applies here as well,
6839 * we only read when we're loading the free space cache, and at that
6840 * point the commit_root has everything we need.
6842 if (btrfs_is_free_space_inode(inode)) {
6843 path->search_commit_root = 1;
6844 path->skip_locking = 1;
6847 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6850 } else if (ret > 0) {
6851 if (path->slots[0] == 0)
6857 leaf = path->nodes[0];
6858 item = btrfs_item_ptr(leaf, path->slots[0],
6859 struct btrfs_file_extent_item);
6860 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6861 if (found_key.objectid != objectid ||
6862 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6864 * If we backup past the first extent we want to move forward
6865 * and see if there is an extent in front of us, otherwise we'll
6866 * say there is a hole for our whole search range which can
6873 extent_type = btrfs_file_extent_type(leaf, item);
6874 extent_start = found_key.offset;
6875 extent_end = btrfs_file_extent_end(path);
6876 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6877 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6878 /* Only regular file could have regular/prealloc extent */
6879 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6882 "regular/prealloc extent found for non-regular inode %llu",
6886 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6888 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6889 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6894 if (start >= extent_end) {
6896 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6897 ret = btrfs_next_leaf(root, path);
6903 leaf = path->nodes[0];
6905 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6906 if (found_key.objectid != objectid ||
6907 found_key.type != BTRFS_EXTENT_DATA_KEY)
6909 if (start + len <= found_key.offset)
6911 if (start > found_key.offset)
6914 /* New extent overlaps with existing one */
6916 em->orig_start = start;
6917 em->len = found_key.offset - start;
6918 em->block_start = EXTENT_MAP_HOLE;
6922 btrfs_extent_item_to_extent_map(inode, path, item, em);
6924 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6925 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6927 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6929 * Inline extent can only exist at file offset 0. This is
6930 * ensured by tree-checker and inline extent creation path.
6931 * Thus all members representing file offsets should be zero.
6933 ASSERT(pg_offset == 0);
6934 ASSERT(extent_start == 0);
6935 ASSERT(em->start == 0);
6938 * btrfs_extent_item_to_extent_map() should have properly
6939 * initialized em members already.
6941 * Other members are not utilized for inline extents.
6943 ASSERT(em->block_start == EXTENT_MAP_INLINE);
6944 ASSERT(em->len == fs_info->sectorsize);
6946 ret = read_inline_extent(inode, path, page);
6953 em->orig_start = start;
6955 em->block_start = EXTENT_MAP_HOLE;
6958 btrfs_release_path(path);
6959 if (em->start > start || extent_map_end(em) <= start) {
6961 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6962 em->start, em->len, start, len);
6967 write_lock(&em_tree->lock);
6968 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6969 write_unlock(&em_tree->lock);
6971 btrfs_free_path(path);
6973 trace_btrfs_get_extent(root, inode, em);
6976 free_extent_map(em);
6977 return ERR_PTR(ret);
6982 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
6983 struct btrfs_dio_data *dio_data,
6986 const u64 orig_start,
6987 const u64 block_start,
6988 const u64 block_len,
6989 const u64 orig_block_len,
6990 const u64 ram_bytes,
6993 struct extent_map *em = NULL;
6994 struct btrfs_ordered_extent *ordered;
6996 if (type != BTRFS_ORDERED_NOCOW) {
6997 em = create_io_em(inode, start, len, orig_start, block_start,
6998 block_len, orig_block_len, ram_bytes,
6999 BTRFS_COMPRESS_NONE, /* compress_type */
7004 ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
7005 block_start, block_len, 0,
7007 (1 << BTRFS_ORDERED_DIRECT),
7008 BTRFS_COMPRESS_NONE);
7009 if (IS_ERR(ordered)) {
7011 free_extent_map(em);
7012 btrfs_drop_extent_map_range(inode, start,
7013 start + len - 1, false);
7015 em = ERR_CAST(ordered);
7017 ASSERT(!dio_data->ordered);
7018 dio_data->ordered = ordered;
7025 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7026 struct btrfs_dio_data *dio_data,
7029 struct btrfs_root *root = inode->root;
7030 struct btrfs_fs_info *fs_info = root->fs_info;
7031 struct extent_map *em;
7032 struct btrfs_key ins;
7036 alloc_hint = get_extent_allocation_hint(inode, start, len);
7038 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7039 0, alloc_hint, &ins, 1, 1);
7040 if (ret == -EAGAIN) {
7041 ASSERT(btrfs_is_zoned(fs_info));
7042 wait_on_bit_io(&inode->root->fs_info->flags, BTRFS_FS_NEED_ZONE_FINISH,
7043 TASK_UNINTERRUPTIBLE);
7047 return ERR_PTR(ret);
7049 em = btrfs_create_dio_extent(inode, dio_data, start, ins.offset, start,
7050 ins.objectid, ins.offset, ins.offset,
7051 ins.offset, BTRFS_ORDERED_REGULAR);
7052 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7054 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7060 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7062 struct btrfs_block_group *block_group;
7063 bool readonly = false;
7065 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7066 if (!block_group || block_group->ro)
7069 btrfs_put_block_group(block_group);
7074 * Check if we can do nocow write into the range [@offset, @offset + @len)
7076 * @offset: File offset
7077 * @len: The length to write, will be updated to the nocow writeable
7079 * @orig_start: (optional) Return the original file offset of the file extent
7080 * @orig_len: (optional) Return the original on-disk length of the file extent
7081 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7082 * @strict: if true, omit optimizations that might force us into unnecessary
7083 * cow. e.g., don't trust generation number.
7086 * >0 and update @len if we can do nocow write
7087 * 0 if we can't do nocow write
7088 * <0 if error happened
7090 * NOTE: This only checks the file extents, caller is responsible to wait for
7091 * any ordered extents.
7093 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7094 u64 *orig_start, u64 *orig_block_len,
7095 u64 *ram_bytes, bool nowait, bool strict)
7097 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
7098 struct can_nocow_file_extent_args nocow_args = { 0 };
7099 struct btrfs_path *path;
7101 struct extent_buffer *leaf;
7102 struct btrfs_root *root = BTRFS_I(inode)->root;
7103 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7104 struct btrfs_file_extent_item *fi;
7105 struct btrfs_key key;
7108 path = btrfs_alloc_path();
7111 path->nowait = nowait;
7113 ret = btrfs_lookup_file_extent(NULL, root, path,
7114 btrfs_ino(BTRFS_I(inode)), offset, 0);
7119 if (path->slots[0] == 0) {
7120 /* can't find the item, must cow */
7127 leaf = path->nodes[0];
7128 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7129 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7130 key.type != BTRFS_EXTENT_DATA_KEY) {
7131 /* not our file or wrong item type, must cow */
7135 if (key.offset > offset) {
7136 /* Wrong offset, must cow */
7140 if (btrfs_file_extent_end(path) <= offset)
7143 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7144 found_type = btrfs_file_extent_type(leaf, fi);
7146 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7148 nocow_args.start = offset;
7149 nocow_args.end = offset + *len - 1;
7150 nocow_args.strict = strict;
7151 nocow_args.free_path = true;
7153 ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
7154 /* can_nocow_file_extent() has freed the path. */
7158 /* Treat errors as not being able to NOCOW. */
7164 if (btrfs_extent_readonly(fs_info, nocow_args.disk_bytenr))
7167 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7168 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7171 range_end = round_up(offset + nocow_args.num_bytes,
7172 root->fs_info->sectorsize) - 1;
7173 ret = test_range_bit_exists(io_tree, offset, range_end, EXTENT_DELALLOC);
7181 *orig_start = key.offset - nocow_args.extent_offset;
7183 *orig_block_len = nocow_args.disk_num_bytes;
7185 *len = nocow_args.num_bytes;
7188 btrfs_free_path(path);
7192 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7193 struct extent_state **cached_state,
7194 unsigned int iomap_flags)
7196 const bool writing = (iomap_flags & IOMAP_WRITE);
7197 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7198 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7199 struct btrfs_ordered_extent *ordered;
7204 if (!try_lock_extent(io_tree, lockstart, lockend,
7208 lock_extent(io_tree, lockstart, lockend, cached_state);
7211 * We're concerned with the entire range that we're going to be
7212 * doing DIO to, so we need to make sure there's no ordered
7213 * extents in this range.
7215 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7216 lockend - lockstart + 1);
7219 * We need to make sure there are no buffered pages in this
7220 * range either, we could have raced between the invalidate in
7221 * generic_file_direct_write and locking the extent. The
7222 * invalidate needs to happen so that reads after a write do not
7226 (!writing || !filemap_range_has_page(inode->i_mapping,
7227 lockstart, lockend)))
7230 unlock_extent(io_tree, lockstart, lockend, cached_state);
7234 btrfs_put_ordered_extent(ordered);
7239 * If we are doing a DIO read and the ordered extent we
7240 * found is for a buffered write, we can not wait for it
7241 * to complete and retry, because if we do so we can
7242 * deadlock with concurrent buffered writes on page
7243 * locks. This happens only if our DIO read covers more
7244 * than one extent map, if at this point has already
7245 * created an ordered extent for a previous extent map
7246 * and locked its range in the inode's io tree, and a
7247 * concurrent write against that previous extent map's
7248 * range and this range started (we unlock the ranges
7249 * in the io tree only when the bios complete and
7250 * buffered writes always lock pages before attempting
7251 * to lock range in the io tree).
7254 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7255 btrfs_start_ordered_extent(ordered);
7257 ret = nowait ? -EAGAIN : -ENOTBLK;
7258 btrfs_put_ordered_extent(ordered);
7261 * We could trigger writeback for this range (and wait
7262 * for it to complete) and then invalidate the pages for
7263 * this range (through invalidate_inode_pages2_range()),
7264 * but that can lead us to a deadlock with a concurrent
7265 * call to readahead (a buffered read or a defrag call
7266 * triggered a readahead) on a page lock due to an
7267 * ordered dio extent we created before but did not have
7268 * yet a corresponding bio submitted (whence it can not
7269 * complete), which makes readahead wait for that
7270 * ordered extent to complete while holding a lock on
7273 ret = nowait ? -EAGAIN : -ENOTBLK;
7285 /* The callers of this must take lock_extent() */
7286 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7287 u64 len, u64 orig_start, u64 block_start,
7288 u64 block_len, u64 orig_block_len,
7289 u64 ram_bytes, int compress_type,
7292 struct extent_map *em;
7295 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7296 type == BTRFS_ORDERED_COMPRESSED ||
7297 type == BTRFS_ORDERED_NOCOW ||
7298 type == BTRFS_ORDERED_REGULAR);
7300 em = alloc_extent_map();
7302 return ERR_PTR(-ENOMEM);
7305 em->orig_start = orig_start;
7307 em->block_len = block_len;
7308 em->block_start = block_start;
7309 em->orig_block_len = orig_block_len;
7310 em->ram_bytes = ram_bytes;
7311 em->generation = -1;
7312 em->flags |= EXTENT_FLAG_PINNED;
7313 if (type == BTRFS_ORDERED_PREALLOC)
7314 em->flags |= EXTENT_FLAG_FILLING;
7315 else if (type == BTRFS_ORDERED_COMPRESSED)
7316 extent_map_set_compression(em, compress_type);
7318 ret = btrfs_replace_extent_map_range(inode, em, true);
7320 free_extent_map(em);
7321 return ERR_PTR(ret);
7324 /* em got 2 refs now, callers needs to do free_extent_map once. */
7329 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7330 struct inode *inode,
7331 struct btrfs_dio_data *dio_data,
7332 u64 start, u64 *lenp,
7333 unsigned int iomap_flags)
7335 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7336 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
7337 struct extent_map *em = *map;
7339 u64 block_start, orig_start, orig_block_len, ram_bytes;
7340 struct btrfs_block_group *bg;
7341 bool can_nocow = false;
7342 bool space_reserved = false;
7348 * We don't allocate a new extent in the following cases
7350 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7352 * 2) The extent is marked as PREALLOC. We're good to go here and can
7353 * just use the extent.
7356 if ((em->flags & EXTENT_FLAG_PREALLOC) ||
7357 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7358 em->block_start != EXTENT_MAP_HOLE)) {
7359 if (em->flags & EXTENT_FLAG_PREALLOC)
7360 type = BTRFS_ORDERED_PREALLOC;
7362 type = BTRFS_ORDERED_NOCOW;
7363 len = min(len, em->len - (start - em->start));
7364 block_start = em->block_start + (start - em->start);
7366 if (can_nocow_extent(inode, start, &len, &orig_start,
7367 &orig_block_len, &ram_bytes, false, false) == 1) {
7368 bg = btrfs_inc_nocow_writers(fs_info, block_start);
7376 struct extent_map *em2;
7378 /* We can NOCOW, so only need to reserve metadata space. */
7379 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7382 /* Our caller expects us to free the input extent map. */
7383 free_extent_map(em);
7385 btrfs_dec_nocow_writers(bg);
7386 if (nowait && (ret == -ENOSPC || ret == -EDQUOT))
7390 space_reserved = true;
7392 em2 = btrfs_create_dio_extent(BTRFS_I(inode), dio_data, start, len,
7393 orig_start, block_start,
7394 len, orig_block_len,
7396 btrfs_dec_nocow_writers(bg);
7397 if (type == BTRFS_ORDERED_PREALLOC) {
7398 free_extent_map(em);
7408 dio_data->nocow_done = true;
7410 /* Our caller expects us to free the input extent map. */
7411 free_extent_map(em);
7420 * If we could not allocate data space before locking the file
7421 * range and we can't do a NOCOW write, then we have to fail.
7423 if (!dio_data->data_space_reserved) {
7429 * We have to COW and we have already reserved data space before,
7430 * so now we reserve only metadata.
7432 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7436 space_reserved = true;
7438 em = btrfs_new_extent_direct(BTRFS_I(inode), dio_data, start, len);
7444 len = min(len, em->len - (start - em->start));
7446 btrfs_delalloc_release_metadata(BTRFS_I(inode),
7447 prev_len - len, true);
7451 * We have created our ordered extent, so we can now release our reservation
7452 * for an outstanding extent.
7454 btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
7457 * Need to update the i_size under the extent lock so buffered
7458 * readers will get the updated i_size when we unlock.
7460 if (start + len > i_size_read(inode))
7461 i_size_write(inode, start + len);
7463 if (ret && space_reserved) {
7464 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7465 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7471 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7472 loff_t length, unsigned int flags, struct iomap *iomap,
7473 struct iomap *srcmap)
7475 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7476 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
7477 struct extent_map *em;
7478 struct extent_state *cached_state = NULL;
7479 struct btrfs_dio_data *dio_data = iter->private;
7480 u64 lockstart, lockend;
7481 const bool write = !!(flags & IOMAP_WRITE);
7484 const u64 data_alloc_len = length;
7485 bool unlock_extents = false;
7488 * We could potentially fault if we have a buffer > PAGE_SIZE, and if
7489 * we're NOWAIT we may submit a bio for a partial range and return
7490 * EIOCBQUEUED, which would result in an errant short read.
7492 * The best way to handle this would be to allow for partial completions
7493 * of iocb's, so we could submit the partial bio, return and fault in
7494 * the rest of the pages, and then submit the io for the rest of the
7495 * range. However we don't have that currently, so simply return
7496 * -EAGAIN at this point so that the normal path is used.
7498 if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE)
7502 * Cap the size of reads to that usually seen in buffered I/O as we need
7503 * to allocate a contiguous array for the checksums.
7506 len = min_t(u64, len, fs_info->sectorsize * BTRFS_MAX_BIO_SECTORS);
7509 lockend = start + len - 1;
7512 * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
7513 * enough if we've written compressed pages to this area, so we need to
7514 * flush the dirty pages again to make absolutely sure that any
7515 * outstanding dirty pages are on disk - the first flush only starts
7516 * compression on the data, while keeping the pages locked, so by the
7517 * time the second flush returns we know bios for the compressed pages
7518 * were submitted and finished, and the pages no longer under writeback.
7520 * If we have a NOWAIT request and we have any pages in the range that
7521 * are locked, likely due to compression still in progress, we don't want
7522 * to block on page locks. We also don't want to block on pages marked as
7523 * dirty or under writeback (same as for the non-compression case).
7524 * iomap_dio_rw() did the same check, but after that and before we got
7525 * here, mmap'ed writes may have happened or buffered reads started
7526 * (readpage() and readahead(), which lock pages), as we haven't locked
7527 * the file range yet.
7529 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7530 &BTRFS_I(inode)->runtime_flags)) {
7531 if (flags & IOMAP_NOWAIT) {
7532 if (filemap_range_needs_writeback(inode->i_mapping,
7533 lockstart, lockend))
7536 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7537 start + length - 1);
7543 memset(dio_data, 0, sizeof(*dio_data));
7546 * We always try to allocate data space and must do it before locking
7547 * the file range, to avoid deadlocks with concurrent writes to the same
7548 * range if the range has several extents and the writes don't expand the
7549 * current i_size (the inode lock is taken in shared mode). If we fail to
7550 * allocate data space here we continue and later, after locking the
7551 * file range, we fail with ENOSPC only if we figure out we can not do a
7554 if (write && !(flags & IOMAP_NOWAIT)) {
7555 ret = btrfs_check_data_free_space(BTRFS_I(inode),
7556 &dio_data->data_reserved,
7557 start, data_alloc_len, false);
7559 dio_data->data_space_reserved = true;
7560 else if (ret && !(BTRFS_I(inode)->flags &
7561 (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
7566 * If this errors out it's because we couldn't invalidate pagecache for
7567 * this range and we need to fallback to buffered IO, or we are doing a
7568 * NOWAIT read/write and we need to block.
7570 ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags);
7574 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7581 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7582 * io. INLINE is special, and we could probably kludge it in here, but
7583 * it's still buffered so for safety lets just fall back to the generic
7586 * For COMPRESSED we _have_ to read the entire extent in so we can
7587 * decompress it, so there will be buffering required no matter what we
7588 * do, so go ahead and fallback to buffered.
7590 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7591 * to buffered IO. Don't blame me, this is the price we pay for using
7594 if (extent_map_is_compressed(em) ||
7595 em->block_start == EXTENT_MAP_INLINE) {
7596 free_extent_map(em);
7598 * If we are in a NOWAIT context, return -EAGAIN in order to
7599 * fallback to buffered IO. This is not only because we can
7600 * block with buffered IO (no support for NOWAIT semantics at
7601 * the moment) but also to avoid returning short reads to user
7602 * space - this happens if we were able to read some data from
7603 * previous non-compressed extents and then when we fallback to
7604 * buffered IO, at btrfs_file_read_iter() by calling
7605 * filemap_read(), we fail to fault in pages for the read buffer,
7606 * in which case filemap_read() returns a short read (the number
7607 * of bytes previously read is > 0, so it does not return -EFAULT).
7609 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
7613 len = min(len, em->len - (start - em->start));
7616 * If we have a NOWAIT request and the range contains multiple extents
7617 * (or a mix of extents and holes), then we return -EAGAIN to make the
7618 * caller fallback to a context where it can do a blocking (without
7619 * NOWAIT) request. This way we avoid doing partial IO and returning
7620 * success to the caller, which is not optimal for writes and for reads
7621 * it can result in unexpected behaviour for an application.
7623 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7624 * iomap_dio_rw(), we can end up returning less data then what the caller
7625 * asked for, resulting in an unexpected, and incorrect, short read.
7626 * That is, the caller asked to read N bytes and we return less than that,
7627 * which is wrong unless we are crossing EOF. This happens if we get a
7628 * page fault error when trying to fault in pages for the buffer that is
7629 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7630 * have previously submitted bios for other extents in the range, in
7631 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7632 * those bios have completed by the time we get the page fault error,
7633 * which we return back to our caller - we should only return EIOCBQUEUED
7634 * after we have submitted bios for all the extents in the range.
7636 if ((flags & IOMAP_NOWAIT) && len < length) {
7637 free_extent_map(em);
7643 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7644 start, &len, flags);
7647 unlock_extents = true;
7648 /* Recalc len in case the new em is smaller than requested */
7649 len = min(len, em->len - (start - em->start));
7650 if (dio_data->data_space_reserved) {
7652 u64 release_len = 0;
7654 if (dio_data->nocow_done) {
7655 release_offset = start;
7656 release_len = data_alloc_len;
7657 } else if (len < data_alloc_len) {
7658 release_offset = start + len;
7659 release_len = data_alloc_len - len;
7662 if (release_len > 0)
7663 btrfs_free_reserved_data_space(BTRFS_I(inode),
7664 dio_data->data_reserved,
7670 * We need to unlock only the end area that we aren't using.
7671 * The rest is going to be unlocked by the endio routine.
7673 lockstart = start + len;
7674 if (lockstart < lockend)
7675 unlock_extents = true;
7679 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7682 free_extent_state(cached_state);
7685 * Translate extent map information to iomap.
7686 * We trim the extents (and move the addr) even though iomap code does
7687 * that, since we have locked only the parts we are performing I/O in.
7689 if ((em->block_start == EXTENT_MAP_HOLE) ||
7690 ((em->flags & EXTENT_FLAG_PREALLOC) && !write)) {
7691 iomap->addr = IOMAP_NULL_ADDR;
7692 iomap->type = IOMAP_HOLE;
7694 iomap->addr = em->block_start + (start - em->start);
7695 iomap->type = IOMAP_MAPPED;
7697 iomap->offset = start;
7698 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7699 iomap->length = len;
7700 free_extent_map(em);
7705 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7708 if (dio_data->data_space_reserved) {
7709 btrfs_free_reserved_data_space(BTRFS_I(inode),
7710 dio_data->data_reserved,
7711 start, data_alloc_len);
7712 extent_changeset_free(dio_data->data_reserved);
7718 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7719 ssize_t written, unsigned int flags, struct iomap *iomap)
7721 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7722 struct btrfs_dio_data *dio_data = iter->private;
7723 size_t submitted = dio_data->submitted;
7724 const bool write = !!(flags & IOMAP_WRITE);
7727 if (!write && (iomap->type == IOMAP_HOLE)) {
7728 /* If reading from a hole, unlock and return */
7729 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1,
7734 if (submitted < length) {
7736 length -= submitted;
7738 btrfs_finish_ordered_extent(dio_data->ordered, NULL,
7739 pos, length, false);
7741 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7742 pos + length - 1, NULL);
7746 btrfs_put_ordered_extent(dio_data->ordered);
7747 dio_data->ordered = NULL;
7751 extent_changeset_free(dio_data->data_reserved);
7755 static void btrfs_dio_end_io(struct btrfs_bio *bbio)
7757 struct btrfs_dio_private *dip =
7758 container_of(bbio, struct btrfs_dio_private, bbio);
7759 struct btrfs_inode *inode = bbio->inode;
7760 struct bio *bio = &bbio->bio;
7762 if (bio->bi_status) {
7763 btrfs_warn(inode->root->fs_info,
7764 "direct IO failed ino %llu op 0x%0x offset %#llx len %u err no %d",
7765 btrfs_ino(inode), bio->bi_opf,
7766 dip->file_offset, dip->bytes, bio->bi_status);
7769 if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
7770 btrfs_finish_ordered_extent(bbio->ordered, NULL,
7771 dip->file_offset, dip->bytes,
7774 unlock_extent(&inode->io_tree, dip->file_offset,
7775 dip->file_offset + dip->bytes - 1, NULL);
7778 bbio->bio.bi_private = bbio->private;
7779 iomap_dio_bio_end_io(bio);
7782 static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio,
7785 struct btrfs_bio *bbio = btrfs_bio(bio);
7786 struct btrfs_dio_private *dip =
7787 container_of(bbio, struct btrfs_dio_private, bbio);
7788 struct btrfs_dio_data *dio_data = iter->private;
7790 btrfs_bio_init(bbio, BTRFS_I(iter->inode)->root->fs_info,
7791 btrfs_dio_end_io, bio->bi_private);
7792 bbio->inode = BTRFS_I(iter->inode);
7793 bbio->file_offset = file_offset;
7795 dip->file_offset = file_offset;
7796 dip->bytes = bio->bi_iter.bi_size;
7798 dio_data->submitted += bio->bi_iter.bi_size;
7801 * Check if we are doing a partial write. If we are, we need to split
7802 * the ordered extent to match the submitted bio. Hang on to the
7803 * remaining unfinishable ordered_extent in dio_data so that it can be
7804 * cancelled in iomap_end to avoid a deadlock wherein faulting the
7805 * remaining pages is blocked on the outstanding ordered extent.
7807 if (iter->flags & IOMAP_WRITE) {
7810 ret = btrfs_extract_ordered_extent(bbio, dio_data->ordered);
7812 btrfs_finish_ordered_extent(dio_data->ordered, NULL,
7813 file_offset, dip->bytes,
7815 bio->bi_status = errno_to_blk_status(ret);
7816 iomap_dio_bio_end_io(bio);
7821 btrfs_submit_bio(bbio, 0);
7824 static const struct iomap_ops btrfs_dio_iomap_ops = {
7825 .iomap_begin = btrfs_dio_iomap_begin,
7826 .iomap_end = btrfs_dio_iomap_end,
7829 static const struct iomap_dio_ops btrfs_dio_ops = {
7830 .submit_io = btrfs_dio_submit_io,
7831 .bio_set = &btrfs_dio_bioset,
7834 ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, size_t done_before)
7836 struct btrfs_dio_data data = { 0 };
7838 return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
7839 IOMAP_DIO_PARTIAL, &data, done_before);
7842 struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
7845 struct btrfs_dio_data data = { 0 };
7847 return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
7848 IOMAP_DIO_PARTIAL, &data, done_before);
7851 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7854 struct btrfs_inode *btrfs_inode = BTRFS_I(inode);
7857 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
7862 * fiemap_prep() called filemap_write_and_wait() for the whole possible
7863 * file range (0 to LLONG_MAX), but that is not enough if we have
7864 * compression enabled. The first filemap_fdatawrite_range() only kicks
7865 * in the compression of data (in an async thread) and will return
7866 * before the compression is done and writeback is started. A second
7867 * filemap_fdatawrite_range() is needed to wait for the compression to
7868 * complete and writeback to start. We also need to wait for ordered
7869 * extents to complete, because our fiemap implementation uses mainly
7870 * file extent items to list the extents, searching for extent maps
7871 * only for file ranges with holes or prealloc extents to figure out
7872 * if we have delalloc in those ranges.
7874 if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
7875 ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
7880 btrfs_inode_lock(btrfs_inode, BTRFS_ILOCK_SHARED);
7883 * We did an initial flush to avoid holding the inode's lock while
7884 * triggering writeback and waiting for the completion of IO and ordered
7885 * extents. Now after we locked the inode we do it again, because it's
7886 * possible a new write may have happened in between those two steps.
7888 if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
7889 ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
7891 btrfs_inode_unlock(btrfs_inode, BTRFS_ILOCK_SHARED);
7896 ret = extent_fiemap(btrfs_inode, fieinfo, start, len);
7897 btrfs_inode_unlock(btrfs_inode, BTRFS_ILOCK_SHARED);
7902 static int btrfs_writepages(struct address_space *mapping,
7903 struct writeback_control *wbc)
7905 return extent_writepages(mapping, wbc);
7908 static void btrfs_readahead(struct readahead_control *rac)
7910 extent_readahead(rac);
7914 * For release_folio() and invalidate_folio() we have a race window where
7915 * folio_end_writeback() is called but the subpage spinlock is not yet released.
7916 * If we continue to release/invalidate the page, we could cause use-after-free
7917 * for subpage spinlock. So this function is to spin and wait for subpage
7920 static void wait_subpage_spinlock(struct page *page)
7922 struct btrfs_fs_info *fs_info = page_to_fs_info(page);
7923 struct folio *folio = page_folio(page);
7924 struct btrfs_subpage *subpage;
7926 if (!btrfs_is_subpage(fs_info, page->mapping))
7929 ASSERT(folio_test_private(folio) && folio_get_private(folio));
7930 subpage = folio_get_private(folio);
7933 * This may look insane as we just acquire the spinlock and release it,
7934 * without doing anything. But we just want to make sure no one is
7935 * still holding the subpage spinlock.
7936 * And since the page is not dirty nor writeback, and we have page
7937 * locked, the only possible way to hold a spinlock is from the endio
7938 * function to clear page writeback.
7940 * Here we just acquire the spinlock so that all existing callers
7941 * should exit and we're safe to release/invalidate the page.
7943 spin_lock_irq(&subpage->lock);
7944 spin_unlock_irq(&subpage->lock);
7947 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7949 int ret = try_release_extent_mapping(&folio->page, gfp_flags);
7952 wait_subpage_spinlock(&folio->page);
7953 clear_page_extent_mapped(&folio->page);
7958 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7960 if (folio_test_writeback(folio) || folio_test_dirty(folio))
7962 return __btrfs_release_folio(folio, gfp_flags);
7965 #ifdef CONFIG_MIGRATION
7966 static int btrfs_migrate_folio(struct address_space *mapping,
7967 struct folio *dst, struct folio *src,
7968 enum migrate_mode mode)
7970 int ret = filemap_migrate_folio(mapping, dst, src, mode);
7972 if (ret != MIGRATEPAGE_SUCCESS)
7975 if (folio_test_ordered(src)) {
7976 folio_clear_ordered(src);
7977 folio_set_ordered(dst);
7980 return MIGRATEPAGE_SUCCESS;
7983 #define btrfs_migrate_folio NULL
7986 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
7989 struct btrfs_inode *inode = folio_to_inode(folio);
7990 struct btrfs_fs_info *fs_info = inode->root->fs_info;
7991 struct extent_io_tree *tree = &inode->io_tree;
7992 struct extent_state *cached_state = NULL;
7993 u64 page_start = folio_pos(folio);
7994 u64 page_end = page_start + folio_size(folio) - 1;
7996 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
7999 * We have folio locked so no new ordered extent can be created on this
8000 * page, nor bio can be submitted for this folio.
8002 * But already submitted bio can still be finished on this folio.
8003 * Furthermore, endio function won't skip folio which has Ordered
8004 * (Private2) already cleared, so it's possible for endio and
8005 * invalidate_folio to do the same ordered extent accounting twice
8008 * So here we wait for any submitted bios to finish, so that we won't
8009 * do double ordered extent accounting on the same folio.
8011 folio_wait_writeback(folio);
8012 wait_subpage_spinlock(&folio->page);
8015 * For subpage case, we have call sites like
8016 * btrfs_punch_hole_lock_range() which passes range not aligned to
8018 * If the range doesn't cover the full folio, we don't need to and
8019 * shouldn't clear page extent mapped, as folio->private can still
8020 * record subpage dirty bits for other part of the range.
8022 * For cases that invalidate the full folio even the range doesn't
8023 * cover the full folio, like invalidating the last folio, we're
8024 * still safe to wait for ordered extent to finish.
8026 if (!(offset == 0 && length == folio_size(folio))) {
8027 btrfs_release_folio(folio, GFP_NOFS);
8031 if (!inode_evicting)
8032 lock_extent(tree, page_start, page_end, &cached_state);
8035 while (cur < page_end) {
8036 struct btrfs_ordered_extent *ordered;
8039 u32 extra_flags = 0;
8041 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8042 page_end + 1 - cur);
8044 range_end = page_end;
8046 * No ordered extent covering this range, we are safe
8047 * to delete all extent states in the range.
8049 extra_flags = EXTENT_CLEAR_ALL_BITS;
8052 if (ordered->file_offset > cur) {
8054 * There is a range between [cur, oe->file_offset) not
8055 * covered by any ordered extent.
8056 * We are safe to delete all extent states, and handle
8057 * the ordered extent in the next iteration.
8059 range_end = ordered->file_offset - 1;
8060 extra_flags = EXTENT_CLEAR_ALL_BITS;
8064 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8066 ASSERT(range_end + 1 - cur < U32_MAX);
8067 range_len = range_end + 1 - cur;
8068 if (!btrfs_folio_test_ordered(fs_info, folio, cur, range_len)) {
8070 * If Ordered (Private2) is cleared, it means endio has
8071 * already been executed for the range.
8072 * We can't delete the extent states as
8073 * btrfs_finish_ordered_io() may still use some of them.
8077 btrfs_folio_clear_ordered(fs_info, folio, cur, range_len);
8080 * IO on this page will never be started, so we need to account
8081 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8082 * here, must leave that up for the ordered extent completion.
8084 * This will also unlock the range for incoming
8085 * btrfs_finish_ordered_io().
8087 if (!inode_evicting)
8088 clear_extent_bit(tree, cur, range_end,
8090 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8091 EXTENT_DEFRAG, &cached_state);
8093 spin_lock_irq(&inode->ordered_tree_lock);
8094 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8095 ordered->truncated_len = min(ordered->truncated_len,
8096 cur - ordered->file_offset);
8097 spin_unlock_irq(&inode->ordered_tree_lock);
8100 * If the ordered extent has finished, we're safe to delete all
8101 * the extent states of the range, otherwise
8102 * btrfs_finish_ordered_io() will get executed by endio for
8103 * other pages, so we can't delete extent states.
8105 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8106 cur, range_end + 1 - cur)) {
8107 btrfs_finish_ordered_io(ordered);
8109 * The ordered extent has finished, now we're again
8110 * safe to delete all extent states of the range.
8112 extra_flags = EXTENT_CLEAR_ALL_BITS;
8116 btrfs_put_ordered_extent(ordered);
8118 * Qgroup reserved space handler
8119 * Sector(s) here will be either:
8121 * 1) Already written to disk or bio already finished
8122 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8123 * Qgroup will be handled by its qgroup_record then.
8124 * btrfs_qgroup_free_data() call will do nothing here.
8126 * 2) Not written to disk yet
8127 * Then btrfs_qgroup_free_data() call will clear the
8128 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8129 * reserved data space.
8130 * Since the IO will never happen for this page.
8132 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur, NULL);
8133 if (!inode_evicting) {
8134 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8135 EXTENT_DELALLOC | EXTENT_UPTODATE |
8136 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
8137 extra_flags, &cached_state);
8139 cur = range_end + 1;
8142 * We have iterated through all ordered extents of the page, the page
8143 * should not have Ordered (Private2) anymore, or the above iteration
8144 * did something wrong.
8146 ASSERT(!folio_test_ordered(folio));
8147 btrfs_folio_clear_checked(fs_info, folio, folio_pos(folio), folio_size(folio));
8148 if (!inode_evicting)
8149 __btrfs_release_folio(folio, GFP_NOFS);
8150 clear_page_extent_mapped(&folio->page);
8154 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8155 * called from a page fault handler when a page is first dirtied. Hence we must
8156 * be careful to check for EOF conditions here. We set the page up correctly
8157 * for a written page which means we get ENOSPC checking when writing into
8158 * holes and correct delalloc and unwritten extent mapping on filesystems that
8159 * support these features.
8161 * We are not allowed to take the i_mutex here so we have to play games to
8162 * protect against truncate races as the page could now be beyond EOF. Because
8163 * truncate_setsize() writes the inode size before removing pages, once we have
8164 * the page lock we can determine safely if the page is beyond EOF. If it is not
8165 * beyond EOF, then the page is guaranteed safe against truncation until we
8168 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8170 struct page *page = vmf->page;
8171 struct folio *folio = page_folio(page);
8172 struct inode *inode = file_inode(vmf->vma->vm_file);
8173 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
8174 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8175 struct btrfs_ordered_extent *ordered;
8176 struct extent_state *cached_state = NULL;
8177 struct extent_changeset *data_reserved = NULL;
8178 unsigned long zero_start;
8188 ASSERT(folio_order(folio) == 0);
8190 reserved_space = PAGE_SIZE;
8192 sb_start_pagefault(inode->i_sb);
8193 page_start = page_offset(page);
8194 page_end = page_start + PAGE_SIZE - 1;
8198 * Reserving delalloc space after obtaining the page lock can lead to
8199 * deadlock. For example, if a dirty page is locked by this function
8200 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8201 * dirty page write out, then the btrfs_writepages() function could
8202 * end up waiting indefinitely to get a lock on the page currently
8203 * being processed by btrfs_page_mkwrite() function.
8205 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8206 page_start, reserved_space);
8208 ret2 = file_update_time(vmf->vma->vm_file);
8212 ret = vmf_error(ret2);
8218 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8220 down_read(&BTRFS_I(inode)->i_mmap_lock);
8222 size = i_size_read(inode);
8224 if ((page->mapping != inode->i_mapping) ||
8225 (page_start >= size)) {
8226 /* page got truncated out from underneath us */
8229 wait_on_page_writeback(page);
8231 lock_extent(io_tree, page_start, page_end, &cached_state);
8232 ret2 = set_page_extent_mapped(page);
8234 ret = vmf_error(ret2);
8235 unlock_extent(io_tree, page_start, page_end, &cached_state);
8240 * we can't set the delalloc bits if there are pending ordered
8241 * extents. Drop our locks and wait for them to finish
8243 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8246 unlock_extent(io_tree, page_start, page_end, &cached_state);
8248 up_read(&BTRFS_I(inode)->i_mmap_lock);
8249 btrfs_start_ordered_extent(ordered);
8250 btrfs_put_ordered_extent(ordered);
8254 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8255 reserved_space = round_up(size - page_start,
8256 fs_info->sectorsize);
8257 if (reserved_space < PAGE_SIZE) {
8258 end = page_start + reserved_space - 1;
8259 btrfs_delalloc_release_space(BTRFS_I(inode),
8260 data_reserved, page_start,
8261 PAGE_SIZE - reserved_space, true);
8266 * page_mkwrite gets called when the page is firstly dirtied after it's
8267 * faulted in, but write(2) could also dirty a page and set delalloc
8268 * bits, thus in this case for space account reason, we still need to
8269 * clear any delalloc bits within this page range since we have to
8270 * reserve data&meta space before lock_page() (see above comments).
8272 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8273 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8274 EXTENT_DEFRAG, &cached_state);
8276 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8279 unlock_extent(io_tree, page_start, page_end, &cached_state);
8280 ret = VM_FAULT_SIGBUS;
8284 /* page is wholly or partially inside EOF */
8285 if (page_start + PAGE_SIZE > size)
8286 zero_start = offset_in_page(size);
8288 zero_start = PAGE_SIZE;
8290 if (zero_start != PAGE_SIZE)
8291 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8293 btrfs_folio_clear_checked(fs_info, folio, page_start, PAGE_SIZE);
8294 btrfs_folio_set_dirty(fs_info, folio, page_start, end + 1 - page_start);
8295 btrfs_folio_set_uptodate(fs_info, folio, page_start, end + 1 - page_start);
8297 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8299 unlock_extent(io_tree, page_start, page_end, &cached_state);
8300 up_read(&BTRFS_I(inode)->i_mmap_lock);
8302 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8303 sb_end_pagefault(inode->i_sb);
8304 extent_changeset_free(data_reserved);
8305 return VM_FAULT_LOCKED;
8309 up_read(&BTRFS_I(inode)->i_mmap_lock);
8311 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8312 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8313 reserved_space, (ret != 0));
8315 sb_end_pagefault(inode->i_sb);
8316 extent_changeset_free(data_reserved);
8320 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
8322 struct btrfs_truncate_control control = {
8324 .ino = btrfs_ino(inode),
8325 .min_type = BTRFS_EXTENT_DATA_KEY,
8326 .clear_extent_range = true,
8328 struct btrfs_root *root = inode->root;
8329 struct btrfs_fs_info *fs_info = root->fs_info;
8330 struct btrfs_block_rsv *rsv;
8332 struct btrfs_trans_handle *trans;
8333 u64 mask = fs_info->sectorsize - 1;
8334 const u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8336 if (!skip_writeback) {
8337 ret = btrfs_wait_ordered_range(&inode->vfs_inode,
8338 inode->vfs_inode.i_size & (~mask),
8345 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8346 * things going on here:
8348 * 1) We need to reserve space to update our inode.
8350 * 2) We need to have something to cache all the space that is going to
8351 * be free'd up by the truncate operation, but also have some slack
8352 * space reserved in case it uses space during the truncate (thank you
8353 * very much snapshotting).
8355 * And we need these to be separate. The fact is we can use a lot of
8356 * space doing the truncate, and we have no earthly idea how much space
8357 * we will use, so we need the truncate reservation to be separate so it
8358 * doesn't end up using space reserved for updating the inode. We also
8359 * need to be able to stop the transaction and start a new one, which
8360 * means we need to be able to update the inode several times, and we
8361 * have no idea of knowing how many times that will be, so we can't just
8362 * reserve 1 item for the entirety of the operation, so that has to be
8363 * done separately as well.
8365 * So that leaves us with
8367 * 1) rsv - for the truncate reservation, which we will steal from the
8368 * transaction reservation.
8369 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8370 * updating the inode.
8372 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8375 rsv->size = min_size;
8376 rsv->failfast = true;
8379 * 1 for the truncate slack space
8380 * 1 for updating the inode.
8382 trans = btrfs_start_transaction(root, 2);
8383 if (IS_ERR(trans)) {
8384 ret = PTR_ERR(trans);
8388 /* Migrate the slack space for the truncate to our reserve */
8389 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8392 * We have reserved 2 metadata units when we started the transaction and
8393 * min_size matches 1 unit, so this should never fail, but if it does,
8394 * it's not critical we just fail truncation.
8397 btrfs_end_transaction(trans);
8401 trans->block_rsv = rsv;
8404 struct extent_state *cached_state = NULL;
8405 const u64 new_size = inode->vfs_inode.i_size;
8406 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8408 control.new_size = new_size;
8409 lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
8411 * We want to drop from the next block forward in case this new
8412 * size is not block aligned since we will be keeping the last
8413 * block of the extent just the way it is.
8415 btrfs_drop_extent_map_range(inode,
8416 ALIGN(new_size, fs_info->sectorsize),
8419 ret = btrfs_truncate_inode_items(trans, root, &control);
8421 inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
8422 btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
8424 unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
8426 trans->block_rsv = &fs_info->trans_block_rsv;
8427 if (ret != -ENOSPC && ret != -EAGAIN)
8430 ret = btrfs_update_inode(trans, inode);
8434 btrfs_end_transaction(trans);
8435 btrfs_btree_balance_dirty(fs_info);
8437 trans = btrfs_start_transaction(root, 2);
8438 if (IS_ERR(trans)) {
8439 ret = PTR_ERR(trans);
8444 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8445 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8446 rsv, min_size, false);
8448 * We have reserved 2 metadata units when we started the
8449 * transaction and min_size matches 1 unit, so this should never
8450 * fail, but if it does, it's not critical we just fail truncation.
8455 trans->block_rsv = rsv;
8459 * We can't call btrfs_truncate_block inside a trans handle as we could
8460 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8461 * know we've truncated everything except the last little bit, and can
8462 * do btrfs_truncate_block and then update the disk_i_size.
8464 if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8465 btrfs_end_transaction(trans);
8466 btrfs_btree_balance_dirty(fs_info);
8468 ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size, 0, 0);
8471 trans = btrfs_start_transaction(root, 1);
8472 if (IS_ERR(trans)) {
8473 ret = PTR_ERR(trans);
8476 btrfs_inode_safe_disk_i_size_write(inode, 0);
8482 trans->block_rsv = &fs_info->trans_block_rsv;
8483 ret2 = btrfs_update_inode(trans, inode);
8487 ret2 = btrfs_end_transaction(trans);
8490 btrfs_btree_balance_dirty(fs_info);
8493 btrfs_free_block_rsv(fs_info, rsv);
8495 * So if we truncate and then write and fsync we normally would just
8496 * write the extents that changed, which is a problem if we need to
8497 * first truncate that entire inode. So set this flag so we write out
8498 * all of the extents in the inode to the sync log so we're completely
8501 * If no extents were dropped or trimmed we don't need to force the next
8502 * fsync to truncate all the inode's items from the log and re-log them
8503 * all. This means the truncate operation did not change the file size,
8504 * or changed it to a smaller size but there was only an implicit hole
8505 * between the old i_size and the new i_size, and there were no prealloc
8506 * extents beyond i_size to drop.
8508 if (control.extents_found > 0)
8509 btrfs_set_inode_full_sync(inode);
8514 struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
8517 struct inode *inode;
8519 inode = new_inode(dir->i_sb);
8522 * Subvolumes don't inherit the sgid bit or the parent's gid if
8523 * the parent's sgid bit is set. This is probably a bug.
8525 inode_init_owner(idmap, inode, NULL,
8526 S_IFDIR | (~current_umask() & S_IRWXUGO));
8527 inode->i_op = &btrfs_dir_inode_operations;
8528 inode->i_fop = &btrfs_dir_file_operations;
8533 struct inode *btrfs_alloc_inode(struct super_block *sb)
8535 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8536 struct btrfs_inode *ei;
8537 struct inode *inode;
8538 struct extent_io_tree *file_extent_tree = NULL;
8540 /* Self tests may pass a NULL fs_info. */
8541 if (fs_info && !btrfs_fs_incompat(fs_info, NO_HOLES)) {
8542 file_extent_tree = kmalloc(sizeof(struct extent_io_tree), GFP_KERNEL);
8543 if (!file_extent_tree)
8547 ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8549 kfree(file_extent_tree);
8556 ei->last_sub_trans = 0;
8557 ei->logged_trans = 0;
8558 ei->delalloc_bytes = 0;
8559 ei->new_delalloc_bytes = 0;
8560 ei->defrag_bytes = 0;
8561 ei->disk_i_size = 0;
8565 ei->index_cnt = (u64)-1;
8567 ei->last_unlink_trans = 0;
8568 ei->last_reflink_trans = 0;
8569 ei->last_log_commit = 0;
8571 spin_lock_init(&ei->lock);
8572 ei->outstanding_extents = 0;
8573 if (sb->s_magic != BTRFS_TEST_MAGIC)
8574 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8575 BTRFS_BLOCK_RSV_DELALLOC);
8576 ei->runtime_flags = 0;
8577 ei->prop_compress = BTRFS_COMPRESS_NONE;
8578 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8580 ei->delayed_node = NULL;
8582 ei->i_otime_sec = 0;
8583 ei->i_otime_nsec = 0;
8585 inode = &ei->vfs_inode;
8586 extent_map_tree_init(&ei->extent_tree);
8588 /* This io tree sets the valid inode. */
8589 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
8590 ei->io_tree.inode = ei;
8592 ei->file_extent_tree = file_extent_tree;
8593 if (file_extent_tree) {
8594 extent_io_tree_init(fs_info, ei->file_extent_tree,
8595 IO_TREE_INODE_FILE_EXTENT);
8596 /* Lockdep class is set only for the file extent tree. */
8597 lockdep_set_class(&ei->file_extent_tree->lock, &file_extent_tree_class);
8599 mutex_init(&ei->log_mutex);
8600 spin_lock_init(&ei->ordered_tree_lock);
8601 ei->ordered_tree = RB_ROOT;
8602 ei->ordered_tree_last = NULL;
8603 INIT_LIST_HEAD(&ei->delalloc_inodes);
8604 INIT_LIST_HEAD(&ei->delayed_iput);
8605 RB_CLEAR_NODE(&ei->rb_node);
8606 init_rwsem(&ei->i_mmap_lock);
8611 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8612 void btrfs_test_destroy_inode(struct inode *inode)
8614 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8615 kfree(BTRFS_I(inode)->file_extent_tree);
8616 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8620 void btrfs_free_inode(struct inode *inode)
8622 kfree(BTRFS_I(inode)->file_extent_tree);
8623 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8626 void btrfs_destroy_inode(struct inode *vfs_inode)
8628 struct btrfs_ordered_extent *ordered;
8629 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8630 struct btrfs_root *root = inode->root;
8631 bool freespace_inode;
8633 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8634 WARN_ON(vfs_inode->i_data.nrpages);
8635 WARN_ON(inode->block_rsv.reserved);
8636 WARN_ON(inode->block_rsv.size);
8637 WARN_ON(inode->outstanding_extents);
8638 if (!S_ISDIR(vfs_inode->i_mode)) {
8639 WARN_ON(inode->delalloc_bytes);
8640 WARN_ON(inode->new_delalloc_bytes);
8642 WARN_ON(inode->csum_bytes);
8643 WARN_ON(inode->defrag_bytes);
8646 * This can happen where we create an inode, but somebody else also
8647 * created the same inode and we need to destroy the one we already
8654 * If this is a free space inode do not take the ordered extents lockdep
8657 freespace_inode = btrfs_is_free_space_inode(inode);
8660 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8664 btrfs_err(root->fs_info,
8665 "found ordered extent %llu %llu on inode cleanup",
8666 ordered->file_offset, ordered->num_bytes);
8668 if (!freespace_inode)
8669 btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
8671 btrfs_remove_ordered_extent(inode, ordered);
8672 btrfs_put_ordered_extent(ordered);
8673 btrfs_put_ordered_extent(ordered);
8676 btrfs_qgroup_check_reserved_leak(inode);
8677 inode_tree_del(inode);
8678 btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
8679 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8680 btrfs_put_root(inode->root);
8683 int btrfs_drop_inode(struct inode *inode)
8685 struct btrfs_root *root = BTRFS_I(inode)->root;
8690 /* the snap/subvol tree is on deleting */
8691 if (btrfs_root_refs(&root->root_item) == 0)
8694 return generic_drop_inode(inode);
8697 static void init_once(void *foo)
8699 struct btrfs_inode *ei = foo;
8701 inode_init_once(&ei->vfs_inode);
8704 void __cold btrfs_destroy_cachep(void)
8707 * Make sure all delayed rcu free inodes are flushed before we
8711 bioset_exit(&btrfs_dio_bioset);
8712 kmem_cache_destroy(btrfs_inode_cachep);
8715 int __init btrfs_init_cachep(void)
8717 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8718 sizeof(struct btrfs_inode), 0,
8719 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8721 if (!btrfs_inode_cachep)
8724 if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE,
8725 offsetof(struct btrfs_dio_private, bbio.bio),
8731 btrfs_destroy_cachep();
8735 static int btrfs_getattr(struct mnt_idmap *idmap,
8736 const struct path *path, struct kstat *stat,
8737 u32 request_mask, unsigned int flags)
8741 struct inode *inode = d_inode(path->dentry);
8742 u32 blocksize = btrfs_sb(inode->i_sb)->sectorsize;
8743 u32 bi_flags = BTRFS_I(inode)->flags;
8744 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8746 stat->result_mask |= STATX_BTIME;
8747 stat->btime.tv_sec = BTRFS_I(inode)->i_otime_sec;
8748 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime_nsec;
8749 if (bi_flags & BTRFS_INODE_APPEND)
8750 stat->attributes |= STATX_ATTR_APPEND;
8751 if (bi_flags & BTRFS_INODE_COMPRESS)
8752 stat->attributes |= STATX_ATTR_COMPRESSED;
8753 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8754 stat->attributes |= STATX_ATTR_IMMUTABLE;
8755 if (bi_flags & BTRFS_INODE_NODUMP)
8756 stat->attributes |= STATX_ATTR_NODUMP;
8757 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8758 stat->attributes |= STATX_ATTR_VERITY;
8760 stat->attributes_mask |= (STATX_ATTR_APPEND |
8761 STATX_ATTR_COMPRESSED |
8762 STATX_ATTR_IMMUTABLE |
8765 generic_fillattr(idmap, request_mask, inode, stat);
8766 stat->dev = BTRFS_I(inode)->root->anon_dev;
8768 spin_lock(&BTRFS_I(inode)->lock);
8769 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8770 inode_bytes = inode_get_bytes(inode);
8771 spin_unlock(&BTRFS_I(inode)->lock);
8772 stat->blocks = (ALIGN(inode_bytes, blocksize) +
8773 ALIGN(delalloc_bytes, blocksize)) >> SECTOR_SHIFT;
8777 static int btrfs_rename_exchange(struct inode *old_dir,
8778 struct dentry *old_dentry,
8779 struct inode *new_dir,
8780 struct dentry *new_dentry)
8782 struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8783 struct btrfs_trans_handle *trans;
8784 unsigned int trans_num_items;
8785 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8786 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8787 struct inode *new_inode = new_dentry->d_inode;
8788 struct inode *old_inode = old_dentry->d_inode;
8789 struct btrfs_rename_ctx old_rename_ctx;
8790 struct btrfs_rename_ctx new_rename_ctx;
8791 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8792 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8797 bool need_abort = false;
8798 struct fscrypt_name old_fname, new_fname;
8799 struct fscrypt_str *old_name, *new_name;
8802 * For non-subvolumes allow exchange only within one subvolume, in the
8803 * same inode namespace. Two subvolumes (represented as directory) can
8804 * be exchanged as they're a logical link and have a fixed inode number.
8807 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8808 new_ino != BTRFS_FIRST_FREE_OBJECTID))
8811 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8815 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8817 fscrypt_free_filename(&old_fname);
8821 old_name = &old_fname.disk_name;
8822 new_name = &new_fname.disk_name;
8824 /* close the race window with snapshot create/destroy ioctl */
8825 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8826 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8827 down_read(&fs_info->subvol_sem);
8831 * 1 to remove old dir item
8832 * 1 to remove old dir index
8833 * 1 to add new dir item
8834 * 1 to add new dir index
8835 * 1 to update parent inode
8837 * If the parents are the same, we only need to account for one
8839 trans_num_items = (old_dir == new_dir ? 9 : 10);
8840 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8842 * 1 to remove old root ref
8843 * 1 to remove old root backref
8844 * 1 to add new root ref
8845 * 1 to add new root backref
8847 trans_num_items += 4;
8850 * 1 to update inode item
8851 * 1 to remove old inode ref
8852 * 1 to add new inode ref
8854 trans_num_items += 3;
8856 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
8857 trans_num_items += 4;
8859 trans_num_items += 3;
8860 trans = btrfs_start_transaction(root, trans_num_items);
8861 if (IS_ERR(trans)) {
8862 ret = PTR_ERR(trans);
8867 ret = btrfs_record_root_in_trans(trans, dest);
8873 * We need to find a free sequence number both in the source and
8874 * in the destination directory for the exchange.
8876 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8879 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8883 BTRFS_I(old_inode)->dir_index = 0ULL;
8884 BTRFS_I(new_inode)->dir_index = 0ULL;
8886 /* Reference for the source. */
8887 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8888 /* force full log commit if subvolume involved. */
8889 btrfs_set_log_full_commit(trans);
8891 ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
8892 btrfs_ino(BTRFS_I(new_dir)),
8899 /* And now for the dest. */
8900 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8901 /* force full log commit if subvolume involved. */
8902 btrfs_set_log_full_commit(trans);
8904 ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
8905 btrfs_ino(BTRFS_I(old_dir)),
8909 btrfs_abort_transaction(trans, ret);
8914 /* Update inode version and ctime/mtime. */
8915 inode_inc_iversion(old_dir);
8916 inode_inc_iversion(new_dir);
8917 inode_inc_iversion(old_inode);
8918 inode_inc_iversion(new_inode);
8919 simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8921 if (old_dentry->d_parent != new_dentry->d_parent) {
8922 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8923 BTRFS_I(old_inode), true);
8924 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8925 BTRFS_I(new_inode), true);
8928 /* src is a subvolume */
8929 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8930 ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8931 } else { /* src is an inode */
8932 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8933 BTRFS_I(old_dentry->d_inode),
8934 old_name, &old_rename_ctx);
8936 ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8939 btrfs_abort_transaction(trans, ret);
8943 /* dest is a subvolume */
8944 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8945 ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8946 } else { /* dest is an inode */
8947 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8948 BTRFS_I(new_dentry->d_inode),
8949 new_name, &new_rename_ctx);
8951 ret = btrfs_update_inode(trans, BTRFS_I(new_inode));
8954 btrfs_abort_transaction(trans, ret);
8958 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8959 new_name, 0, old_idx);
8961 btrfs_abort_transaction(trans, ret);
8965 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8966 old_name, 0, new_idx);
8968 btrfs_abort_transaction(trans, ret);
8972 if (old_inode->i_nlink == 1)
8973 BTRFS_I(old_inode)->dir_index = old_idx;
8974 if (new_inode->i_nlink == 1)
8975 BTRFS_I(new_inode)->dir_index = new_idx;
8978 * Now pin the logs of the roots. We do it to ensure that no other task
8979 * can sync the logs while we are in progress with the rename, because
8980 * that could result in an inconsistency in case any of the inodes that
8981 * are part of this rename operation were logged before.
8983 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8984 btrfs_pin_log_trans(root);
8985 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
8986 btrfs_pin_log_trans(dest);
8988 /* Do the log updates for all inodes. */
8989 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8990 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8991 old_rename_ctx.index, new_dentry->d_parent);
8992 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
8993 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
8994 new_rename_ctx.index, old_dentry->d_parent);
8996 /* Now unpin the logs. */
8997 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
8998 btrfs_end_log_trans(root);
8999 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9000 btrfs_end_log_trans(dest);
9002 ret2 = btrfs_end_transaction(trans);
9003 ret = ret ? ret : ret2;
9005 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9006 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9007 up_read(&fs_info->subvol_sem);
9009 fscrypt_free_filename(&new_fname);
9010 fscrypt_free_filename(&old_fname);
9014 static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
9017 struct inode *inode;
9019 inode = new_inode(dir->i_sb);
9021 inode_init_owner(idmap, inode, dir,
9022 S_IFCHR | WHITEOUT_MODE);
9023 inode->i_op = &btrfs_special_inode_operations;
9024 init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
9029 static int btrfs_rename(struct mnt_idmap *idmap,
9030 struct inode *old_dir, struct dentry *old_dentry,
9031 struct inode *new_dir, struct dentry *new_dentry,
9034 struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
9035 struct btrfs_new_inode_args whiteout_args = {
9037 .dentry = old_dentry,
9039 struct btrfs_trans_handle *trans;
9040 unsigned int trans_num_items;
9041 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9042 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9043 struct inode *new_inode = d_inode(new_dentry);
9044 struct inode *old_inode = d_inode(old_dentry);
9045 struct btrfs_rename_ctx rename_ctx;
9049 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9050 struct fscrypt_name old_fname, new_fname;
9052 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9055 /* we only allow rename subvolume link between subvolumes */
9056 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9059 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9060 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9063 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9064 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9067 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
9071 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
9073 fscrypt_free_filename(&old_fname);
9077 /* check for collisions, even if the name isn't there */
9078 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
9080 if (ret == -EEXIST) {
9082 * eexist without a new_inode */
9083 if (WARN_ON(!new_inode)) {
9084 goto out_fscrypt_names;
9087 /* maybe -EOVERFLOW */
9088 goto out_fscrypt_names;
9094 * we're using rename to replace one file with another. Start IO on it
9095 * now so we don't add too much work to the end of the transaction
9097 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9098 filemap_flush(old_inode->i_mapping);
9100 if (flags & RENAME_WHITEOUT) {
9101 whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
9102 if (!whiteout_args.inode) {
9104 goto out_fscrypt_names;
9106 ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
9108 goto out_whiteout_inode;
9110 /* 1 to update the old parent inode. */
9111 trans_num_items = 1;
9114 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9115 /* Close the race window with snapshot create/destroy ioctl */
9116 down_read(&fs_info->subvol_sem);
9118 * 1 to remove old root ref
9119 * 1 to remove old root backref
9120 * 1 to add new root ref
9121 * 1 to add new root backref
9123 trans_num_items += 4;
9127 * 1 to remove old inode ref
9128 * 1 to add new inode ref
9130 trans_num_items += 3;
9133 * 1 to remove old dir item
9134 * 1 to remove old dir index
9135 * 1 to add new dir item
9136 * 1 to add new dir index
9138 trans_num_items += 4;
9139 /* 1 to update new parent inode if it's not the same as the old parent */
9140 if (new_dir != old_dir)
9145 * 1 to remove inode ref
9146 * 1 to remove dir item
9147 * 1 to remove dir index
9148 * 1 to possibly add orphan item
9150 trans_num_items += 5;
9152 trans = btrfs_start_transaction(root, trans_num_items);
9153 if (IS_ERR(trans)) {
9154 ret = PTR_ERR(trans);
9159 ret = btrfs_record_root_in_trans(trans, dest);
9164 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9168 BTRFS_I(old_inode)->dir_index = 0ULL;
9169 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9170 /* force full log commit if subvolume involved. */
9171 btrfs_set_log_full_commit(trans);
9173 ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
9174 old_ino, btrfs_ino(BTRFS_I(new_dir)),
9180 inode_inc_iversion(old_dir);
9181 inode_inc_iversion(new_dir);
9182 inode_inc_iversion(old_inode);
9183 simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
9185 if (old_dentry->d_parent != new_dentry->d_parent)
9186 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9187 BTRFS_I(old_inode), true);
9189 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9190 ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
9192 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9193 BTRFS_I(d_inode(old_dentry)),
9194 &old_fname.disk_name, &rename_ctx);
9196 ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
9199 btrfs_abort_transaction(trans, ret);
9204 inode_inc_iversion(new_inode);
9205 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9206 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9207 ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
9208 BUG_ON(new_inode->i_nlink == 0);
9210 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9211 BTRFS_I(d_inode(new_dentry)),
9212 &new_fname.disk_name);
9214 if (!ret && new_inode->i_nlink == 0)
9215 ret = btrfs_orphan_add(trans,
9216 BTRFS_I(d_inode(new_dentry)));
9218 btrfs_abort_transaction(trans, ret);
9223 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9224 &new_fname.disk_name, 0, index);
9226 btrfs_abort_transaction(trans, ret);
9230 if (old_inode->i_nlink == 1)
9231 BTRFS_I(old_inode)->dir_index = index;
9233 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9234 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9235 rename_ctx.index, new_dentry->d_parent);
9237 if (flags & RENAME_WHITEOUT) {
9238 ret = btrfs_create_new_inode(trans, &whiteout_args);
9240 btrfs_abort_transaction(trans, ret);
9243 unlock_new_inode(whiteout_args.inode);
9244 iput(whiteout_args.inode);
9245 whiteout_args.inode = NULL;
9249 ret2 = btrfs_end_transaction(trans);
9250 ret = ret ? ret : ret2;
9252 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9253 up_read(&fs_info->subvol_sem);
9254 if (flags & RENAME_WHITEOUT)
9255 btrfs_new_inode_args_destroy(&whiteout_args);
9257 if (flags & RENAME_WHITEOUT)
9258 iput(whiteout_args.inode);
9260 fscrypt_free_filename(&old_fname);
9261 fscrypt_free_filename(&new_fname);
9265 static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
9266 struct dentry *old_dentry, struct inode *new_dir,
9267 struct dentry *new_dentry, unsigned int flags)
9271 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9274 if (flags & RENAME_EXCHANGE)
9275 ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9278 ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
9281 btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
9286 struct btrfs_delalloc_work {
9287 struct inode *inode;
9288 struct completion completion;
9289 struct list_head list;
9290 struct btrfs_work work;
9293 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9295 struct btrfs_delalloc_work *delalloc_work;
9296 struct inode *inode;
9298 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9300 inode = delalloc_work->inode;
9301 filemap_flush(inode->i_mapping);
9302 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9303 &BTRFS_I(inode)->runtime_flags))
9304 filemap_flush(inode->i_mapping);
9307 complete(&delalloc_work->completion);
9310 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9312 struct btrfs_delalloc_work *work;
9314 work = kmalloc(sizeof(*work), GFP_NOFS);
9318 init_completion(&work->completion);
9319 INIT_LIST_HEAD(&work->list);
9320 work->inode = inode;
9321 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL);
9327 * some fairly slow code that needs optimization. This walks the list
9328 * of all the inodes with pending delalloc and forces them to disk.
9330 static int start_delalloc_inodes(struct btrfs_root *root,
9331 struct writeback_control *wbc, bool snapshot,
9332 bool in_reclaim_context)
9334 struct btrfs_inode *binode;
9335 struct inode *inode;
9336 struct btrfs_delalloc_work *work, *next;
9340 bool full_flush = wbc->nr_to_write == LONG_MAX;
9342 mutex_lock(&root->delalloc_mutex);
9343 spin_lock(&root->delalloc_lock);
9344 list_splice_init(&root->delalloc_inodes, &splice);
9345 while (!list_empty(&splice)) {
9346 binode = list_entry(splice.next, struct btrfs_inode,
9349 list_move_tail(&binode->delalloc_inodes,
9350 &root->delalloc_inodes);
9352 if (in_reclaim_context &&
9353 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9356 inode = igrab(&binode->vfs_inode);
9358 cond_resched_lock(&root->delalloc_lock);
9361 spin_unlock(&root->delalloc_lock);
9364 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9365 &binode->runtime_flags);
9367 work = btrfs_alloc_delalloc_work(inode);
9373 list_add_tail(&work->list, &works);
9374 btrfs_queue_work(root->fs_info->flush_workers,
9377 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9378 btrfs_add_delayed_iput(BTRFS_I(inode));
9379 if (ret || wbc->nr_to_write <= 0)
9383 spin_lock(&root->delalloc_lock);
9385 spin_unlock(&root->delalloc_lock);
9388 list_for_each_entry_safe(work, next, &works, list) {
9389 list_del_init(&work->list);
9390 wait_for_completion(&work->completion);
9394 if (!list_empty(&splice)) {
9395 spin_lock(&root->delalloc_lock);
9396 list_splice_tail(&splice, &root->delalloc_inodes);
9397 spin_unlock(&root->delalloc_lock);
9399 mutex_unlock(&root->delalloc_mutex);
9403 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9405 struct writeback_control wbc = {
9406 .nr_to_write = LONG_MAX,
9407 .sync_mode = WB_SYNC_NONE,
9409 .range_end = LLONG_MAX,
9411 struct btrfs_fs_info *fs_info = root->fs_info;
9413 if (BTRFS_FS_ERROR(fs_info))
9416 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9419 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9420 bool in_reclaim_context)
9422 struct writeback_control wbc = {
9424 .sync_mode = WB_SYNC_NONE,
9426 .range_end = LLONG_MAX,
9428 struct btrfs_root *root;
9432 if (BTRFS_FS_ERROR(fs_info))
9435 mutex_lock(&fs_info->delalloc_root_mutex);
9436 spin_lock(&fs_info->delalloc_root_lock);
9437 list_splice_init(&fs_info->delalloc_roots, &splice);
9438 while (!list_empty(&splice)) {
9440 * Reset nr_to_write here so we know that we're doing a full
9444 wbc.nr_to_write = LONG_MAX;
9446 root = list_first_entry(&splice, struct btrfs_root,
9448 root = btrfs_grab_root(root);
9450 list_move_tail(&root->delalloc_root,
9451 &fs_info->delalloc_roots);
9452 spin_unlock(&fs_info->delalloc_root_lock);
9454 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9455 btrfs_put_root(root);
9456 if (ret < 0 || wbc.nr_to_write <= 0)
9458 spin_lock(&fs_info->delalloc_root_lock);
9460 spin_unlock(&fs_info->delalloc_root_lock);
9464 if (!list_empty(&splice)) {
9465 spin_lock(&fs_info->delalloc_root_lock);
9466 list_splice_tail(&splice, &fs_info->delalloc_roots);
9467 spin_unlock(&fs_info->delalloc_root_lock);
9469 mutex_unlock(&fs_info->delalloc_root_mutex);
9473 static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
9474 struct dentry *dentry, const char *symname)
9476 struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
9477 struct btrfs_trans_handle *trans;
9478 struct btrfs_root *root = BTRFS_I(dir)->root;
9479 struct btrfs_path *path;
9480 struct btrfs_key key;
9481 struct inode *inode;
9482 struct btrfs_new_inode_args new_inode_args = {
9486 unsigned int trans_num_items;
9491 struct btrfs_file_extent_item *ei;
9492 struct extent_buffer *leaf;
9494 name_len = strlen(symname);
9495 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9496 return -ENAMETOOLONG;
9498 inode = new_inode(dir->i_sb);
9501 inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
9502 inode->i_op = &btrfs_symlink_inode_operations;
9503 inode_nohighmem(inode);
9504 inode->i_mapping->a_ops = &btrfs_aops;
9505 btrfs_i_size_write(BTRFS_I(inode), name_len);
9506 inode_set_bytes(inode, name_len);
9508 new_inode_args.inode = inode;
9509 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9512 /* 1 additional item for the inline extent */
9515 trans = btrfs_start_transaction(root, trans_num_items);
9516 if (IS_ERR(trans)) {
9517 err = PTR_ERR(trans);
9518 goto out_new_inode_args;
9521 err = btrfs_create_new_inode(trans, &new_inode_args);
9525 path = btrfs_alloc_path();
9528 btrfs_abort_transaction(trans, err);
9529 discard_new_inode(inode);
9533 key.objectid = btrfs_ino(BTRFS_I(inode));
9535 key.type = BTRFS_EXTENT_DATA_KEY;
9536 datasize = btrfs_file_extent_calc_inline_size(name_len);
9537 err = btrfs_insert_empty_item(trans, root, path, &key,
9540 btrfs_abort_transaction(trans, err);
9541 btrfs_free_path(path);
9542 discard_new_inode(inode);
9546 leaf = path->nodes[0];
9547 ei = btrfs_item_ptr(leaf, path->slots[0],
9548 struct btrfs_file_extent_item);
9549 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9550 btrfs_set_file_extent_type(leaf, ei,
9551 BTRFS_FILE_EXTENT_INLINE);
9552 btrfs_set_file_extent_encryption(leaf, ei, 0);
9553 btrfs_set_file_extent_compression(leaf, ei, 0);
9554 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9555 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9557 ptr = btrfs_file_extent_inline_start(ei);
9558 write_extent_buffer(leaf, symname, ptr, name_len);
9559 btrfs_mark_buffer_dirty(trans, leaf);
9560 btrfs_free_path(path);
9562 d_instantiate_new(dentry, inode);
9565 btrfs_end_transaction(trans);
9566 btrfs_btree_balance_dirty(fs_info);
9568 btrfs_new_inode_args_destroy(&new_inode_args);
9575 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9576 struct btrfs_trans_handle *trans_in,
9577 struct btrfs_inode *inode,
9578 struct btrfs_key *ins,
9581 struct btrfs_file_extent_item stack_fi;
9582 struct btrfs_replace_extent_info extent_info;
9583 struct btrfs_trans_handle *trans = trans_in;
9584 struct btrfs_path *path;
9585 u64 start = ins->objectid;
9586 u64 len = ins->offset;
9587 u64 qgroup_released = 0;
9590 memset(&stack_fi, 0, sizeof(stack_fi));
9592 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9593 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9594 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9595 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9596 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9597 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9598 /* Encryption and other encoding is reserved and all 0 */
9600 ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
9602 return ERR_PTR(ret);
9605 ret = insert_reserved_file_extent(trans, inode,
9606 file_offset, &stack_fi,
9607 true, qgroup_released);
9613 extent_info.disk_offset = start;
9614 extent_info.disk_len = len;
9615 extent_info.data_offset = 0;
9616 extent_info.data_len = len;
9617 extent_info.file_offset = file_offset;
9618 extent_info.extent_buf = (char *)&stack_fi;
9619 extent_info.is_new_extent = true;
9620 extent_info.update_times = true;
9621 extent_info.qgroup_reserved = qgroup_released;
9622 extent_info.insertions = 0;
9624 path = btrfs_alloc_path();
9630 ret = btrfs_replace_file_extents(inode, path, file_offset,
9631 file_offset + len - 1, &extent_info,
9633 btrfs_free_path(path);
9640 * We have released qgroup data range at the beginning of the function,
9641 * and normally qgroup_released bytes will be freed when committing
9643 * But if we error out early, we have to free what we have released
9644 * or we leak qgroup data reservation.
9646 btrfs_qgroup_free_refroot(inode->root->fs_info,
9647 inode->root->root_key.objectid, qgroup_released,
9648 BTRFS_QGROUP_RSV_DATA);
9649 return ERR_PTR(ret);
9652 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9653 u64 start, u64 num_bytes, u64 min_size,
9654 loff_t actual_len, u64 *alloc_hint,
9655 struct btrfs_trans_handle *trans)
9657 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
9658 struct extent_map *em;
9659 struct btrfs_root *root = BTRFS_I(inode)->root;
9660 struct btrfs_key ins;
9661 u64 cur_offset = start;
9662 u64 clear_offset = start;
9665 u64 last_alloc = (u64)-1;
9667 bool own_trans = true;
9668 u64 end = start + num_bytes - 1;
9672 while (num_bytes > 0) {
9673 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9674 cur_bytes = max(cur_bytes, min_size);
9676 * If we are severely fragmented we could end up with really
9677 * small allocations, so if the allocator is returning small
9678 * chunks lets make its job easier by only searching for those
9681 cur_bytes = min(cur_bytes, last_alloc);
9682 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9683 min_size, 0, *alloc_hint, &ins, 1, 0);
9688 * We've reserved this space, and thus converted it from
9689 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9690 * from here on out we will only need to clear our reservation
9691 * for the remaining unreserved area, so advance our
9692 * clear_offset by our extent size.
9694 clear_offset += ins.offset;
9696 last_alloc = ins.offset;
9697 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9700 * Now that we inserted the prealloc extent we can finally
9701 * decrement the number of reservations in the block group.
9702 * If we did it before, we could race with relocation and have
9703 * relocation miss the reserved extent, making it fail later.
9705 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9706 if (IS_ERR(trans)) {
9707 ret = PTR_ERR(trans);
9708 btrfs_free_reserved_extent(fs_info, ins.objectid,
9713 em = alloc_extent_map();
9715 btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9716 cur_offset + ins.offset - 1, false);
9717 btrfs_set_inode_full_sync(BTRFS_I(inode));
9721 em->start = cur_offset;
9722 em->orig_start = cur_offset;
9723 em->len = ins.offset;
9724 em->block_start = ins.objectid;
9725 em->block_len = ins.offset;
9726 em->orig_block_len = ins.offset;
9727 em->ram_bytes = ins.offset;
9728 em->flags |= EXTENT_FLAG_PREALLOC;
9729 em->generation = trans->transid;
9731 ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9732 free_extent_map(em);
9734 num_bytes -= ins.offset;
9735 cur_offset += ins.offset;
9736 *alloc_hint = ins.objectid + ins.offset;
9738 inode_inc_iversion(inode);
9739 inode_set_ctime_current(inode);
9740 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9741 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9742 (actual_len > inode->i_size) &&
9743 (cur_offset > inode->i_size)) {
9744 if (cur_offset > actual_len)
9745 i_size = actual_len;
9747 i_size = cur_offset;
9748 i_size_write(inode, i_size);
9749 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9752 ret = btrfs_update_inode(trans, BTRFS_I(inode));
9755 btrfs_abort_transaction(trans, ret);
9757 btrfs_end_transaction(trans);
9762 btrfs_end_transaction(trans);
9766 if (clear_offset < end)
9767 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9768 end - clear_offset + 1);
9772 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9773 u64 start, u64 num_bytes, u64 min_size,
9774 loff_t actual_len, u64 *alloc_hint)
9776 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9777 min_size, actual_len, alloc_hint,
9781 int btrfs_prealloc_file_range_trans(struct inode *inode,
9782 struct btrfs_trans_handle *trans, int mode,
9783 u64 start, u64 num_bytes, u64 min_size,
9784 loff_t actual_len, u64 *alloc_hint)
9786 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9787 min_size, actual_len, alloc_hint, trans);
9790 static int btrfs_permission(struct mnt_idmap *idmap,
9791 struct inode *inode, int mask)
9793 struct btrfs_root *root = BTRFS_I(inode)->root;
9794 umode_t mode = inode->i_mode;
9796 if (mask & MAY_WRITE &&
9797 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9798 if (btrfs_root_readonly(root))
9800 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9803 return generic_permission(idmap, inode, mask);
9806 static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
9807 struct file *file, umode_t mode)
9809 struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
9810 struct btrfs_trans_handle *trans;
9811 struct btrfs_root *root = BTRFS_I(dir)->root;
9812 struct inode *inode;
9813 struct btrfs_new_inode_args new_inode_args = {
9815 .dentry = file->f_path.dentry,
9818 unsigned int trans_num_items;
9821 inode = new_inode(dir->i_sb);
9824 inode_init_owner(idmap, inode, dir, mode);
9825 inode->i_fop = &btrfs_file_operations;
9826 inode->i_op = &btrfs_file_inode_operations;
9827 inode->i_mapping->a_ops = &btrfs_aops;
9829 new_inode_args.inode = inode;
9830 ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9834 trans = btrfs_start_transaction(root, trans_num_items);
9835 if (IS_ERR(trans)) {
9836 ret = PTR_ERR(trans);
9837 goto out_new_inode_args;
9840 ret = btrfs_create_new_inode(trans, &new_inode_args);
9843 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9844 * set it to 1 because d_tmpfile() will issue a warning if the count is
9847 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9849 set_nlink(inode, 1);
9852 d_tmpfile(file, inode);
9853 unlock_new_inode(inode);
9854 mark_inode_dirty(inode);
9857 btrfs_end_transaction(trans);
9858 btrfs_btree_balance_dirty(fs_info);
9860 btrfs_new_inode_args_destroy(&new_inode_args);
9864 return finish_open_simple(file, ret);
9867 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
9869 struct btrfs_fs_info *fs_info = inode->root->fs_info;
9870 unsigned long index = start >> PAGE_SHIFT;
9871 unsigned long end_index = end >> PAGE_SHIFT;
9875 ASSERT(end + 1 - start <= U32_MAX);
9876 len = end + 1 - start;
9877 while (index <= end_index) {
9878 page = find_get_page(inode->vfs_inode.i_mapping, index);
9879 ASSERT(page); /* Pages should be in the extent_io_tree */
9881 /* This is for data, which doesn't yet support larger folio. */
9882 ASSERT(folio_order(page_folio(page)) == 0);
9883 btrfs_folio_set_writeback(fs_info, page_folio(page), start, len);
9889 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
9892 switch (compress_type) {
9893 case BTRFS_COMPRESS_NONE:
9894 return BTRFS_ENCODED_IO_COMPRESSION_NONE;
9895 case BTRFS_COMPRESS_ZLIB:
9896 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
9897 case BTRFS_COMPRESS_LZO:
9899 * The LZO format depends on the sector size. 64K is the maximum
9900 * sector size that we support.
9902 if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
9904 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
9905 (fs_info->sectorsize_bits - 12);
9906 case BTRFS_COMPRESS_ZSTD:
9907 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
9913 static ssize_t btrfs_encoded_read_inline(
9915 struct iov_iter *iter, u64 start,
9917 struct extent_state **cached_state,
9918 u64 extent_start, size_t count,
9919 struct btrfs_ioctl_encoded_io_args *encoded,
9922 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9923 struct btrfs_root *root = inode->root;
9924 struct btrfs_fs_info *fs_info = root->fs_info;
9925 struct extent_io_tree *io_tree = &inode->io_tree;
9926 struct btrfs_path *path;
9927 struct extent_buffer *leaf;
9928 struct btrfs_file_extent_item *item;
9934 path = btrfs_alloc_path();
9939 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
9943 /* The extent item disappeared? */
9948 leaf = path->nodes[0];
9949 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
9951 ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
9952 ptr = btrfs_file_extent_inline_start(item);
9954 encoded->len = min_t(u64, extent_start + ram_bytes,
9955 inode->vfs_inode.i_size) - iocb->ki_pos;
9956 ret = btrfs_encoded_io_compression_from_extent(fs_info,
9957 btrfs_file_extent_compression(leaf, item));
9960 encoded->compression = ret;
9961 if (encoded->compression) {
9964 inline_size = btrfs_file_extent_inline_item_len(leaf,
9966 if (inline_size > count) {
9970 count = inline_size;
9971 encoded->unencoded_len = ram_bytes;
9972 encoded->unencoded_offset = iocb->ki_pos - extent_start;
9974 count = min_t(u64, count, encoded->len);
9975 encoded->len = count;
9976 encoded->unencoded_len = count;
9977 ptr += iocb->ki_pos - extent_start;
9980 tmp = kmalloc(count, GFP_NOFS);
9985 read_extent_buffer(leaf, tmp, ptr, count);
9986 btrfs_release_path(path);
9987 unlock_extent(io_tree, start, lockend, cached_state);
9988 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9991 ret = copy_to_iter(tmp, count, iter);
9996 btrfs_free_path(path);
10000 struct btrfs_encoded_read_private {
10001 wait_queue_head_t wait;
10003 blk_status_t status;
10006 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
10008 struct btrfs_encoded_read_private *priv = bbio->private;
10010 if (bbio->bio.bi_status) {
10012 * The memory barrier implied by the atomic_dec_return() here
10013 * pairs with the memory barrier implied by the
10014 * atomic_dec_return() or io_wait_event() in
10015 * btrfs_encoded_read_regular_fill_pages() to ensure that this
10016 * write is observed before the load of status in
10017 * btrfs_encoded_read_regular_fill_pages().
10019 WRITE_ONCE(priv->status, bbio->bio.bi_status);
10021 if (!atomic_dec_return(&priv->pending))
10022 wake_up(&priv->wait);
10023 bio_put(&bbio->bio);
10026 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
10027 u64 file_offset, u64 disk_bytenr,
10028 u64 disk_io_size, struct page **pages)
10030 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10031 struct btrfs_encoded_read_private priv = {
10032 .pending = ATOMIC_INIT(1),
10034 unsigned long i = 0;
10035 struct btrfs_bio *bbio;
10037 init_waitqueue_head(&priv.wait);
10039 bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, fs_info,
10040 btrfs_encoded_read_endio, &priv);
10041 bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
10042 bbio->inode = inode;
10045 size_t bytes = min_t(u64, disk_io_size, PAGE_SIZE);
10047 if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
10048 atomic_inc(&priv.pending);
10049 btrfs_submit_bio(bbio, 0);
10051 bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, fs_info,
10052 btrfs_encoded_read_endio, &priv);
10053 bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
10054 bbio->inode = inode;
10059 disk_bytenr += bytes;
10060 disk_io_size -= bytes;
10061 } while (disk_io_size);
10063 atomic_inc(&priv.pending);
10064 btrfs_submit_bio(bbio, 0);
10066 if (atomic_dec_return(&priv.pending))
10067 io_wait_event(priv.wait, !atomic_read(&priv.pending));
10068 /* See btrfs_encoded_read_endio() for ordering. */
10069 return blk_status_to_errno(READ_ONCE(priv.status));
10072 static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
10073 struct iov_iter *iter,
10074 u64 start, u64 lockend,
10075 struct extent_state **cached_state,
10076 u64 disk_bytenr, u64 disk_io_size,
10077 size_t count, bool compressed,
10080 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10081 struct extent_io_tree *io_tree = &inode->io_tree;
10082 struct page **pages;
10083 unsigned long nr_pages, i;
10085 size_t page_offset;
10088 nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
10089 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
10092 ret = btrfs_alloc_page_array(nr_pages, pages, 0);
10098 ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
10099 disk_io_size, pages);
10103 unlock_extent(io_tree, start, lockend, cached_state);
10104 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10111 i = (iocb->ki_pos - start) >> PAGE_SHIFT;
10112 page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
10115 while (cur < count) {
10116 size_t bytes = min_t(size_t, count - cur,
10117 PAGE_SIZE - page_offset);
10119 if (copy_page_to_iter(pages[i], page_offset, bytes,
10130 for (i = 0; i < nr_pages; i++) {
10132 __free_page(pages[i]);
10138 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
10139 struct btrfs_ioctl_encoded_io_args *encoded)
10141 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10142 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10143 struct extent_io_tree *io_tree = &inode->io_tree;
10145 size_t count = iov_iter_count(iter);
10146 u64 start, lockend, disk_bytenr, disk_io_size;
10147 struct extent_state *cached_state = NULL;
10148 struct extent_map *em;
10149 bool unlocked = false;
10151 file_accessed(iocb->ki_filp);
10153 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
10155 if (iocb->ki_pos >= inode->vfs_inode.i_size) {
10156 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10159 start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
10161 * We don't know how long the extent containing iocb->ki_pos is, but if
10162 * it's compressed we know that it won't be longer than this.
10164 lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
10167 struct btrfs_ordered_extent *ordered;
10169 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
10170 lockend - start + 1);
10172 goto out_unlock_inode;
10173 lock_extent(io_tree, start, lockend, &cached_state);
10174 ordered = btrfs_lookup_ordered_range(inode, start,
10175 lockend - start + 1);
10178 btrfs_put_ordered_extent(ordered);
10179 unlock_extent(io_tree, start, lockend, &cached_state);
10183 em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
10186 goto out_unlock_extent;
10189 if (em->block_start == EXTENT_MAP_INLINE) {
10190 u64 extent_start = em->start;
10193 * For inline extents we get everything we need out of the
10196 free_extent_map(em);
10198 ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
10199 &cached_state, extent_start,
10200 count, encoded, &unlocked);
10205 * We only want to return up to EOF even if the extent extends beyond
10208 encoded->len = min_t(u64, extent_map_end(em),
10209 inode->vfs_inode.i_size) - iocb->ki_pos;
10210 if (em->block_start == EXTENT_MAP_HOLE ||
10211 (em->flags & EXTENT_FLAG_PREALLOC)) {
10212 disk_bytenr = EXTENT_MAP_HOLE;
10213 count = min_t(u64, count, encoded->len);
10214 encoded->len = count;
10215 encoded->unencoded_len = count;
10216 } else if (extent_map_is_compressed(em)) {
10217 disk_bytenr = em->block_start;
10219 * Bail if the buffer isn't large enough to return the whole
10220 * compressed extent.
10222 if (em->block_len > count) {
10226 disk_io_size = em->block_len;
10227 count = em->block_len;
10228 encoded->unencoded_len = em->ram_bytes;
10229 encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
10230 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10231 extent_map_compression(em));
10234 encoded->compression = ret;
10236 disk_bytenr = em->block_start + (start - em->start);
10237 if (encoded->len > count)
10238 encoded->len = count;
10240 * Don't read beyond what we locked. This also limits the page
10241 * allocations that we'll do.
10243 disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
10244 count = start + disk_io_size - iocb->ki_pos;
10245 encoded->len = count;
10246 encoded->unencoded_len = count;
10247 disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
10249 free_extent_map(em);
10252 if (disk_bytenr == EXTENT_MAP_HOLE) {
10253 unlock_extent(io_tree, start, lockend, &cached_state);
10254 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10256 ret = iov_iter_zero(count, iter);
10260 ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
10261 &cached_state, disk_bytenr,
10262 disk_io_size, count,
10263 encoded->compression,
10269 iocb->ki_pos += encoded->len;
10271 free_extent_map(em);
10274 unlock_extent(io_tree, start, lockend, &cached_state);
10277 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10281 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
10282 const struct btrfs_ioctl_encoded_io_args *encoded)
10284 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10285 struct btrfs_root *root = inode->root;
10286 struct btrfs_fs_info *fs_info = root->fs_info;
10287 struct extent_io_tree *io_tree = &inode->io_tree;
10288 struct extent_changeset *data_reserved = NULL;
10289 struct extent_state *cached_state = NULL;
10290 struct btrfs_ordered_extent *ordered;
10294 u64 num_bytes, ram_bytes, disk_num_bytes;
10295 unsigned long nr_pages, i;
10296 struct page **pages;
10297 struct btrfs_key ins;
10298 bool extent_reserved = false;
10299 struct extent_map *em;
10302 switch (encoded->compression) {
10303 case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
10304 compression = BTRFS_COMPRESS_ZLIB;
10306 case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
10307 compression = BTRFS_COMPRESS_ZSTD;
10309 case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
10310 case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
10311 case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
10312 case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
10313 case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
10314 /* The sector size must match for LZO. */
10315 if (encoded->compression -
10316 BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
10317 fs_info->sectorsize_bits)
10319 compression = BTRFS_COMPRESS_LZO;
10324 if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
10328 * Compressed extents should always have checksums, so error out if we
10329 * have a NOCOW file or inode was created while mounted with NODATASUM.
10331 if (inode->flags & BTRFS_INODE_NODATASUM)
10334 orig_count = iov_iter_count(from);
10336 /* The extent size must be sane. */
10337 if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
10338 orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
10342 * The compressed data must be smaller than the decompressed data.
10344 * It's of course possible for data to compress to larger or the same
10345 * size, but the buffered I/O path falls back to no compression for such
10346 * data, and we don't want to break any assumptions by creating these
10349 * Note that this is less strict than the current check we have that the
10350 * compressed data must be at least one sector smaller than the
10351 * decompressed data. We only want to enforce the weaker requirement
10352 * from old kernels that it is at least one byte smaller.
10354 if (orig_count >= encoded->unencoded_len)
10357 /* The extent must start on a sector boundary. */
10358 start = iocb->ki_pos;
10359 if (!IS_ALIGNED(start, fs_info->sectorsize))
10363 * The extent must end on a sector boundary. However, we allow a write
10364 * which ends at or extends i_size to have an unaligned length; we round
10365 * up the extent size and set i_size to the unaligned end.
10367 if (start + encoded->len < inode->vfs_inode.i_size &&
10368 !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
10371 /* Finally, the offset in the unencoded data must be sector-aligned. */
10372 if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
10375 num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10376 ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10377 end = start + num_bytes - 1;
10380 * If the extent cannot be inline, the compressed data on disk must be
10381 * sector-aligned. For convenience, we extend it with zeroes if it
10384 disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10385 nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
10386 pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
10389 for (i = 0; i < nr_pages; i++) {
10390 size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
10393 pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
10398 kaddr = kmap_local_page(pages[i]);
10399 if (copy_from_iter(kaddr, bytes, from) != bytes) {
10400 kunmap_local(kaddr);
10404 if (bytes < PAGE_SIZE)
10405 memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
10406 kunmap_local(kaddr);
10410 struct btrfs_ordered_extent *ordered;
10412 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
10415 ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10416 start >> PAGE_SHIFT,
10417 end >> PAGE_SHIFT);
10420 lock_extent(io_tree, start, end, &cached_state);
10421 ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10423 !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10426 btrfs_put_ordered_extent(ordered);
10427 unlock_extent(io_tree, start, end, &cached_state);
10432 * We don't use the higher-level delalloc space functions because our
10433 * num_bytes and disk_num_bytes are different.
10435 ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10438 ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10440 goto out_free_data_space;
10441 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10444 goto out_qgroup_free_data;
10446 /* Try an inline extent first. */
10447 if (start == 0 && encoded->unencoded_len == encoded->len &&
10448 encoded->unencoded_offset == 0) {
10449 ret = cow_file_range_inline(inode, encoded->len, orig_count,
10450 compression, pages, true);
10454 goto out_delalloc_release;
10458 ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10459 disk_num_bytes, 0, 0, &ins, 1, 1);
10461 goto out_delalloc_release;
10462 extent_reserved = true;
10464 em = create_io_em(inode, start, num_bytes,
10465 start - encoded->unencoded_offset, ins.objectid,
10466 ins.offset, ins.offset, ram_bytes, compression,
10467 BTRFS_ORDERED_COMPRESSED);
10470 goto out_free_reserved;
10472 free_extent_map(em);
10474 ordered = btrfs_alloc_ordered_extent(inode, start, num_bytes, ram_bytes,
10475 ins.objectid, ins.offset,
10476 encoded->unencoded_offset,
10477 (1 << BTRFS_ORDERED_ENCODED) |
10478 (1 << BTRFS_ORDERED_COMPRESSED),
10480 if (IS_ERR(ordered)) {
10481 btrfs_drop_extent_map_range(inode, start, end, false);
10482 ret = PTR_ERR(ordered);
10483 goto out_free_reserved;
10485 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10487 if (start + encoded->len > inode->vfs_inode.i_size)
10488 i_size_write(&inode->vfs_inode, start + encoded->len);
10490 unlock_extent(io_tree, start, end, &cached_state);
10492 btrfs_delalloc_release_extents(inode, num_bytes);
10494 btrfs_submit_compressed_write(ordered, pages, nr_pages, 0, false);
10499 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10500 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
10501 out_delalloc_release:
10502 btrfs_delalloc_release_extents(inode, num_bytes);
10503 btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10504 out_qgroup_free_data:
10506 btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes, NULL);
10507 out_free_data_space:
10509 * If btrfs_reserve_extent() succeeded, then we already decremented
10512 if (!extent_reserved)
10513 btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
10515 unlock_extent(io_tree, start, end, &cached_state);
10517 for (i = 0; i < nr_pages; i++) {
10519 __free_page(pages[i]);
10524 iocb->ki_pos += encoded->len;
10530 * Add an entry indicating a block group or device which is pinned by a
10531 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10532 * negative errno on failure.
10534 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10535 bool is_block_group)
10537 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10538 struct btrfs_swapfile_pin *sp, *entry;
10539 struct rb_node **p;
10540 struct rb_node *parent = NULL;
10542 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10547 sp->is_block_group = is_block_group;
10548 sp->bg_extent_count = 1;
10550 spin_lock(&fs_info->swapfile_pins_lock);
10551 p = &fs_info->swapfile_pins.rb_node;
10554 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10555 if (sp->ptr < entry->ptr ||
10556 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10557 p = &(*p)->rb_left;
10558 } else if (sp->ptr > entry->ptr ||
10559 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10560 p = &(*p)->rb_right;
10562 if (is_block_group)
10563 entry->bg_extent_count++;
10564 spin_unlock(&fs_info->swapfile_pins_lock);
10569 rb_link_node(&sp->node, parent, p);
10570 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10571 spin_unlock(&fs_info->swapfile_pins_lock);
10575 /* Free all of the entries pinned by this swapfile. */
10576 static void btrfs_free_swapfile_pins(struct inode *inode)
10578 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10579 struct btrfs_swapfile_pin *sp;
10580 struct rb_node *node, *next;
10582 spin_lock(&fs_info->swapfile_pins_lock);
10583 node = rb_first(&fs_info->swapfile_pins);
10585 next = rb_next(node);
10586 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10587 if (sp->inode == inode) {
10588 rb_erase(&sp->node, &fs_info->swapfile_pins);
10589 if (sp->is_block_group) {
10590 btrfs_dec_block_group_swap_extents(sp->ptr,
10591 sp->bg_extent_count);
10592 btrfs_put_block_group(sp->ptr);
10598 spin_unlock(&fs_info->swapfile_pins_lock);
10601 struct btrfs_swap_info {
10607 unsigned long nr_pages;
10611 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10612 struct btrfs_swap_info *bsi)
10614 unsigned long nr_pages;
10615 unsigned long max_pages;
10616 u64 first_ppage, first_ppage_reported, next_ppage;
10620 * Our swapfile may have had its size extended after the swap header was
10621 * written. In that case activating the swapfile should not go beyond
10622 * the max size set in the swap header.
10624 if (bsi->nr_pages >= sis->max)
10627 max_pages = sis->max - bsi->nr_pages;
10628 first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
10629 next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
10631 if (first_ppage >= next_ppage)
10633 nr_pages = next_ppage - first_ppage;
10634 nr_pages = min(nr_pages, max_pages);
10636 first_ppage_reported = first_ppage;
10637 if (bsi->start == 0)
10638 first_ppage_reported++;
10639 if (bsi->lowest_ppage > first_ppage_reported)
10640 bsi->lowest_ppage = first_ppage_reported;
10641 if (bsi->highest_ppage < (next_ppage - 1))
10642 bsi->highest_ppage = next_ppage - 1;
10644 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10647 bsi->nr_extents += ret;
10648 bsi->nr_pages += nr_pages;
10652 static void btrfs_swap_deactivate(struct file *file)
10654 struct inode *inode = file_inode(file);
10656 btrfs_free_swapfile_pins(inode);
10657 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10660 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10663 struct inode *inode = file_inode(file);
10664 struct btrfs_root *root = BTRFS_I(inode)->root;
10665 struct btrfs_fs_info *fs_info = root->fs_info;
10666 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10667 struct extent_state *cached_state = NULL;
10668 struct extent_map *em = NULL;
10669 struct btrfs_chunk_map *map = NULL;
10670 struct btrfs_device *device = NULL;
10671 struct btrfs_swap_info bsi = {
10672 .lowest_ppage = (sector_t)-1ULL,
10679 * If the swap file was just created, make sure delalloc is done. If the
10680 * file changes again after this, the user is doing something stupid and
10681 * we don't really care.
10683 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10688 * The inode is locked, so these flags won't change after we check them.
10690 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10691 btrfs_warn(fs_info, "swapfile must not be compressed");
10694 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10695 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10698 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10699 btrfs_warn(fs_info, "swapfile must not be checksummed");
10704 * Balance or device remove/replace/resize can move stuff around from
10705 * under us. The exclop protection makes sure they aren't running/won't
10706 * run concurrently while we are mapping the swap extents, and
10707 * fs_info->swapfile_pins prevents them from running while the swap
10708 * file is active and moving the extents. Note that this also prevents
10709 * a concurrent device add which isn't actually necessary, but it's not
10710 * really worth the trouble to allow it.
10712 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10713 btrfs_warn(fs_info,
10714 "cannot activate swapfile while exclusive operation is running");
10719 * Prevent snapshot creation while we are activating the swap file.
10720 * We do not want to race with snapshot creation. If snapshot creation
10721 * already started before we bumped nr_swapfiles from 0 to 1 and
10722 * completes before the first write into the swap file after it is
10723 * activated, than that write would fallback to COW.
10725 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10726 btrfs_exclop_finish(fs_info);
10727 btrfs_warn(fs_info,
10728 "cannot activate swapfile because snapshot creation is in progress");
10732 * Snapshots can create extents which require COW even if NODATACOW is
10733 * set. We use this counter to prevent snapshots. We must increment it
10734 * before walking the extents because we don't want a concurrent
10735 * snapshot to run after we've already checked the extents.
10737 * It is possible that subvolume is marked for deletion but still not
10738 * removed yet. To prevent this race, we check the root status before
10739 * activating the swapfile.
10741 spin_lock(&root->root_item_lock);
10742 if (btrfs_root_dead(root)) {
10743 spin_unlock(&root->root_item_lock);
10745 btrfs_exclop_finish(fs_info);
10746 btrfs_warn(fs_info,
10747 "cannot activate swapfile because subvolume %llu is being deleted",
10748 root->root_key.objectid);
10751 atomic_inc(&root->nr_swapfiles);
10752 spin_unlock(&root->root_item_lock);
10754 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10756 lock_extent(io_tree, 0, isize - 1, &cached_state);
10758 while (start < isize) {
10759 u64 logical_block_start, physical_block_start;
10760 struct btrfs_block_group *bg;
10761 u64 len = isize - start;
10763 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10769 if (em->block_start == EXTENT_MAP_HOLE) {
10770 btrfs_warn(fs_info, "swapfile must not have holes");
10774 if (em->block_start == EXTENT_MAP_INLINE) {
10776 * It's unlikely we'll ever actually find ourselves
10777 * here, as a file small enough to fit inline won't be
10778 * big enough to store more than the swap header, but in
10779 * case something changes in the future, let's catch it
10780 * here rather than later.
10782 btrfs_warn(fs_info, "swapfile must not be inline");
10786 if (extent_map_is_compressed(em)) {
10787 btrfs_warn(fs_info, "swapfile must not be compressed");
10792 logical_block_start = em->block_start + (start - em->start);
10793 len = min(len, em->len - (start - em->start));
10794 free_extent_map(em);
10797 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, false, true);
10803 btrfs_warn(fs_info,
10804 "swapfile must not be copy-on-write");
10809 map = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10811 ret = PTR_ERR(map);
10815 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10816 btrfs_warn(fs_info,
10817 "swapfile must have single data profile");
10822 if (device == NULL) {
10823 device = map->stripes[0].dev;
10824 ret = btrfs_add_swapfile_pin(inode, device, false);
10829 } else if (device != map->stripes[0].dev) {
10830 btrfs_warn(fs_info, "swapfile must be on one device");
10835 physical_block_start = (map->stripes[0].physical +
10836 (logical_block_start - map->start));
10837 len = min(len, map->chunk_len - (logical_block_start - map->start));
10838 btrfs_free_chunk_map(map);
10841 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10843 btrfs_warn(fs_info,
10844 "could not find block group containing swapfile");
10849 if (!btrfs_inc_block_group_swap_extents(bg)) {
10850 btrfs_warn(fs_info,
10851 "block group for swapfile at %llu is read-only%s",
10853 atomic_read(&fs_info->scrubs_running) ?
10854 " (scrub running)" : "");
10855 btrfs_put_block_group(bg);
10860 ret = btrfs_add_swapfile_pin(inode, bg, true);
10862 btrfs_put_block_group(bg);
10869 if (bsi.block_len &&
10870 bsi.block_start + bsi.block_len == physical_block_start) {
10871 bsi.block_len += len;
10873 if (bsi.block_len) {
10874 ret = btrfs_add_swap_extent(sis, &bsi);
10879 bsi.block_start = physical_block_start;
10880 bsi.block_len = len;
10887 ret = btrfs_add_swap_extent(sis, &bsi);
10890 if (!IS_ERR_OR_NULL(em))
10891 free_extent_map(em);
10892 if (!IS_ERR_OR_NULL(map))
10893 btrfs_free_chunk_map(map);
10895 unlock_extent(io_tree, 0, isize - 1, &cached_state);
10898 btrfs_swap_deactivate(file);
10900 btrfs_drew_write_unlock(&root->snapshot_lock);
10902 btrfs_exclop_finish(fs_info);
10908 sis->bdev = device->bdev;
10909 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10910 sis->max = bsi.nr_pages;
10911 sis->pages = bsi.nr_pages - 1;
10912 sis->highest_bit = bsi.nr_pages - 1;
10913 return bsi.nr_extents;
10916 static void btrfs_swap_deactivate(struct file *file)
10920 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10923 return -EOPNOTSUPP;
10928 * Update the number of bytes used in the VFS' inode. When we replace extents in
10929 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10930 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10931 * always get a correct value.
10933 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10934 const u64 add_bytes,
10935 const u64 del_bytes)
10937 if (add_bytes == del_bytes)
10940 spin_lock(&inode->lock);
10942 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10944 inode_add_bytes(&inode->vfs_inode, add_bytes);
10945 spin_unlock(&inode->lock);
10949 * Verify that there are no ordered extents for a given file range.
10951 * @inode: The target inode.
10952 * @start: Start offset of the file range, should be sector size aligned.
10953 * @end: End offset (inclusive) of the file range, its value +1 should be
10954 * sector size aligned.
10956 * This should typically be used for cases where we locked an inode's VFS lock in
10957 * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
10958 * we have flushed all delalloc in the range, we have waited for all ordered
10959 * extents in the range to complete and finally we have locked the file range in
10960 * the inode's io_tree.
10962 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
10964 struct btrfs_root *root = inode->root;
10965 struct btrfs_ordered_extent *ordered;
10967 if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
10970 ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
10972 btrfs_err(root->fs_info,
10973 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
10974 start, end, btrfs_ino(inode), root->root_key.objectid,
10975 ordered->file_offset,
10976 ordered->file_offset + ordered->num_bytes - 1);
10977 btrfs_put_ordered_extent(ordered);
10980 ASSERT(ordered == NULL);
10983 static const struct inode_operations btrfs_dir_inode_operations = {
10984 .getattr = btrfs_getattr,
10985 .lookup = btrfs_lookup,
10986 .create = btrfs_create,
10987 .unlink = btrfs_unlink,
10988 .link = btrfs_link,
10989 .mkdir = btrfs_mkdir,
10990 .rmdir = btrfs_rmdir,
10991 .rename = btrfs_rename2,
10992 .symlink = btrfs_symlink,
10993 .setattr = btrfs_setattr,
10994 .mknod = btrfs_mknod,
10995 .listxattr = btrfs_listxattr,
10996 .permission = btrfs_permission,
10997 .get_inode_acl = btrfs_get_acl,
10998 .set_acl = btrfs_set_acl,
10999 .update_time = btrfs_update_time,
11000 .tmpfile = btrfs_tmpfile,
11001 .fileattr_get = btrfs_fileattr_get,
11002 .fileattr_set = btrfs_fileattr_set,
11005 static const struct file_operations btrfs_dir_file_operations = {
11006 .llseek = btrfs_dir_llseek,
11007 .read = generic_read_dir,
11008 .iterate_shared = btrfs_real_readdir,
11009 .open = btrfs_opendir,
11010 .unlocked_ioctl = btrfs_ioctl,
11011 #ifdef CONFIG_COMPAT
11012 .compat_ioctl = btrfs_compat_ioctl,
11014 .release = btrfs_release_file,
11015 .fsync = btrfs_sync_file,
11019 * btrfs doesn't support the bmap operation because swapfiles
11020 * use bmap to make a mapping of extents in the file. They assume
11021 * these extents won't change over the life of the file and they
11022 * use the bmap result to do IO directly to the drive.
11024 * the btrfs bmap call would return logical addresses that aren't
11025 * suitable for IO and they also will change frequently as COW
11026 * operations happen. So, swapfile + btrfs == corruption.
11028 * For now we're avoiding this by dropping bmap.
11030 static const struct address_space_operations btrfs_aops = {
11031 .read_folio = btrfs_read_folio,
11032 .writepages = btrfs_writepages,
11033 .readahead = btrfs_readahead,
11034 .invalidate_folio = btrfs_invalidate_folio,
11035 .release_folio = btrfs_release_folio,
11036 .migrate_folio = btrfs_migrate_folio,
11037 .dirty_folio = filemap_dirty_folio,
11038 .error_remove_folio = generic_error_remove_folio,
11039 .swap_activate = btrfs_swap_activate,
11040 .swap_deactivate = btrfs_swap_deactivate,
11043 static const struct inode_operations btrfs_file_inode_operations = {
11044 .getattr = btrfs_getattr,
11045 .setattr = btrfs_setattr,
11046 .listxattr = btrfs_listxattr,
11047 .permission = btrfs_permission,
11048 .fiemap = btrfs_fiemap,
11049 .get_inode_acl = btrfs_get_acl,
11050 .set_acl = btrfs_set_acl,
11051 .update_time = btrfs_update_time,
11052 .fileattr_get = btrfs_fileattr_get,
11053 .fileattr_set = btrfs_fileattr_set,
11055 static const struct inode_operations btrfs_special_inode_operations = {
11056 .getattr = btrfs_getattr,
11057 .setattr = btrfs_setattr,
11058 .permission = btrfs_permission,
11059 .listxattr = btrfs_listxattr,
11060 .get_inode_acl = btrfs_get_acl,
11061 .set_acl = btrfs_set_acl,
11062 .update_time = btrfs_update_time,
11064 static const struct inode_operations btrfs_symlink_inode_operations = {
11065 .get_link = page_get_link,
11066 .getattr = btrfs_getattr,
11067 .setattr = btrfs_setattr,
11068 .permission = btrfs_permission,
11069 .listxattr = btrfs_listxattr,
11070 .update_time = btrfs_update_time,
11073 const struct dentry_operations btrfs_dentry_operations = {
11074 .d_delete = btrfs_dentry_delete,