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"
75 struct btrfs_iget_args {
77 struct btrfs_root *root;
80 struct btrfs_dio_data {
82 struct extent_changeset *data_reserved;
83 struct btrfs_ordered_extent *ordered;
84 bool data_space_reserved;
88 struct btrfs_dio_private {
93 /* This must be last */
94 struct btrfs_bio bbio;
97 static struct bio_set btrfs_dio_bioset;
99 struct btrfs_rename_ctx {
100 /* Output field. Stores the index number of the old directory entry. */
105 * Used by data_reloc_print_warning_inode() to pass needed info for filename
106 * resolution and output of error message.
108 struct data_reloc_warn {
109 struct btrfs_path path;
110 struct btrfs_fs_info *fs_info;
111 u64 extent_item_size;
116 static const struct inode_operations btrfs_dir_inode_operations;
117 static const struct inode_operations btrfs_symlink_inode_operations;
118 static const struct inode_operations btrfs_special_inode_operations;
119 static const struct inode_operations btrfs_file_inode_operations;
120 static const struct address_space_operations btrfs_aops;
121 static const struct file_operations btrfs_dir_file_operations;
123 static struct kmem_cache *btrfs_inode_cachep;
125 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
126 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback);
128 static noinline int cow_file_range(struct btrfs_inode *inode,
129 struct page *locked_page,
130 u64 start, u64 end, int *page_started,
131 unsigned long *nr_written, u64 *done_offset,
132 bool keep_locked, bool no_inline);
133 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
134 u64 len, u64 orig_start, u64 block_start,
135 u64 block_len, u64 orig_block_len,
136 u64 ram_bytes, int compress_type,
139 static int data_reloc_print_warning_inode(u64 inum, u64 offset, u64 num_bytes,
140 u64 root, void *warn_ctx)
142 struct data_reloc_warn *warn = warn_ctx;
143 struct btrfs_fs_info *fs_info = warn->fs_info;
144 struct extent_buffer *eb;
145 struct btrfs_inode_item *inode_item;
146 struct inode_fs_paths *ipath = NULL;
147 struct btrfs_root *local_root;
148 struct btrfs_key key;
149 unsigned int nofs_flag;
153 local_root = btrfs_get_fs_root(fs_info, root, true);
154 if (IS_ERR(local_root)) {
155 ret = PTR_ERR(local_root);
159 /* This makes the path point to (inum INODE_ITEM ioff). */
161 key.type = BTRFS_INODE_ITEM_KEY;
164 ret = btrfs_search_slot(NULL, local_root, &key, &warn->path, 0, 0);
166 btrfs_put_root(local_root);
167 btrfs_release_path(&warn->path);
171 eb = warn->path.nodes[0];
172 inode_item = btrfs_item_ptr(eb, warn->path.slots[0], struct btrfs_inode_item);
173 nlink = btrfs_inode_nlink(eb, inode_item);
174 btrfs_release_path(&warn->path);
176 nofs_flag = memalloc_nofs_save();
177 ipath = init_ipath(4096, local_root, &warn->path);
178 memalloc_nofs_restore(nofs_flag);
180 btrfs_put_root(local_root);
181 ret = PTR_ERR(ipath);
184 * -ENOMEM, not a critical error, just output an generic error
188 "checksum error at logical %llu mirror %u root %llu, inode %llu offset %llu",
189 warn->logical, warn->mirror_num, root, inum, offset);
192 ret = paths_from_inode(inum, ipath);
197 * We deliberately ignore the bit ipath might have been too small to
198 * hold all of the paths here
200 for (int i = 0; i < ipath->fspath->elem_cnt; i++) {
202 "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu length %u links %u (path: %s)",
203 warn->logical, warn->mirror_num, root, inum, offset,
204 fs_info->sectorsize, nlink,
205 (char *)(unsigned long)ipath->fspath->val[i]);
208 btrfs_put_root(local_root);
214 "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu, path resolving failed with ret=%d",
215 warn->logical, warn->mirror_num, root, inum, offset, ret);
222 * Do extra user-friendly error output (e.g. lookup all the affected files).
224 * Return true if we succeeded doing the backref lookup.
225 * Return false if such lookup failed, and has to fallback to the old error message.
227 static void print_data_reloc_error(const struct btrfs_inode *inode, u64 file_off,
228 const u8 *csum, const u8 *csum_expected,
231 struct btrfs_fs_info *fs_info = inode->root->fs_info;
232 struct btrfs_path path = { 0 };
233 struct btrfs_key found_key = { 0 };
234 struct extent_buffer *eb;
235 struct btrfs_extent_item *ei;
236 const u32 csum_size = fs_info->csum_size;
242 mutex_lock(&fs_info->reloc_mutex);
243 logical = btrfs_get_reloc_bg_bytenr(fs_info);
244 mutex_unlock(&fs_info->reloc_mutex);
246 if (logical == U64_MAX) {
247 btrfs_warn_rl(fs_info, "has data reloc tree but no running relocation");
248 btrfs_warn_rl(fs_info,
249 "csum failed root %lld ino %llu off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
250 inode->root->root_key.objectid, btrfs_ino(inode), file_off,
251 CSUM_FMT_VALUE(csum_size, csum),
252 CSUM_FMT_VALUE(csum_size, csum_expected),
258 btrfs_warn_rl(fs_info,
259 "csum failed root %lld ino %llu off %llu logical %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
260 inode->root->root_key.objectid,
261 btrfs_ino(inode), file_off, logical,
262 CSUM_FMT_VALUE(csum_size, csum),
263 CSUM_FMT_VALUE(csum_size, csum_expected),
266 ret = extent_from_logical(fs_info, logical, &path, &found_key, &flags);
268 btrfs_err_rl(fs_info, "failed to lookup extent item for logical %llu: %d",
273 ei = btrfs_item_ptr(eb, path.slots[0], struct btrfs_extent_item);
274 item_size = btrfs_item_size(eb, path.slots[0]);
275 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
276 unsigned long ptr = 0;
281 ret = tree_backref_for_extent(&ptr, eb, &found_key, ei,
282 item_size, &ref_root,
285 btrfs_warn_rl(fs_info,
286 "failed to resolve tree backref for logical %llu: %d",
293 btrfs_warn_rl(fs_info,
294 "csum error at logical %llu mirror %u: metadata %s (level %d) in tree %llu",
296 (ref_level ? "node" : "leaf"),
297 ref_level, ref_root);
299 btrfs_release_path(&path);
301 struct btrfs_backref_walk_ctx ctx = { 0 };
302 struct data_reloc_warn reloc_warn = { 0 };
304 btrfs_release_path(&path);
306 ctx.bytenr = found_key.objectid;
307 ctx.extent_item_pos = logical - found_key.objectid;
308 ctx.fs_info = fs_info;
310 reloc_warn.logical = logical;
311 reloc_warn.extent_item_size = found_key.offset;
312 reloc_warn.mirror_num = mirror_num;
313 reloc_warn.fs_info = fs_info;
315 iterate_extent_inodes(&ctx, true,
316 data_reloc_print_warning_inode, &reloc_warn);
320 static void __cold btrfs_print_data_csum_error(struct btrfs_inode *inode,
321 u64 logical_start, u8 *csum, u8 *csum_expected, int mirror_num)
323 struct btrfs_root *root = inode->root;
324 const u32 csum_size = root->fs_info->csum_size;
326 /* For data reloc tree, it's better to do a backref lookup instead. */
327 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
328 return print_data_reloc_error(inode, logical_start, csum,
329 csum_expected, mirror_num);
331 /* Output without objectid, which is more meaningful */
332 if (root->root_key.objectid >= BTRFS_LAST_FREE_OBJECTID) {
333 btrfs_warn_rl(root->fs_info,
334 "csum failed root %lld ino %lld off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
335 root->root_key.objectid, btrfs_ino(inode),
337 CSUM_FMT_VALUE(csum_size, csum),
338 CSUM_FMT_VALUE(csum_size, csum_expected),
341 btrfs_warn_rl(root->fs_info,
342 "csum failed root %llu ino %llu off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
343 root->root_key.objectid, btrfs_ino(inode),
345 CSUM_FMT_VALUE(csum_size, csum),
346 CSUM_FMT_VALUE(csum_size, csum_expected),
352 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
354 * ilock_flags can have the following bit set:
356 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
357 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
359 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
361 int btrfs_inode_lock(struct btrfs_inode *inode, unsigned int ilock_flags)
363 if (ilock_flags & BTRFS_ILOCK_SHARED) {
364 if (ilock_flags & BTRFS_ILOCK_TRY) {
365 if (!inode_trylock_shared(&inode->vfs_inode))
370 inode_lock_shared(&inode->vfs_inode);
372 if (ilock_flags & BTRFS_ILOCK_TRY) {
373 if (!inode_trylock(&inode->vfs_inode))
378 inode_lock(&inode->vfs_inode);
380 if (ilock_flags & BTRFS_ILOCK_MMAP)
381 down_write(&inode->i_mmap_lock);
386 * btrfs_inode_unlock - unock inode i_rwsem
388 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
389 * to decide whether the lock acquired is shared or exclusive.
391 void btrfs_inode_unlock(struct btrfs_inode *inode, unsigned int ilock_flags)
393 if (ilock_flags & BTRFS_ILOCK_MMAP)
394 up_write(&inode->i_mmap_lock);
395 if (ilock_flags & BTRFS_ILOCK_SHARED)
396 inode_unlock_shared(&inode->vfs_inode);
398 inode_unlock(&inode->vfs_inode);
402 * Cleanup all submitted ordered extents in specified range to handle errors
403 * from the btrfs_run_delalloc_range() callback.
405 * NOTE: caller must ensure that when an error happens, it can not call
406 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
407 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
408 * to be released, which we want to happen only when finishing the ordered
409 * extent (btrfs_finish_ordered_io()).
411 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
412 struct page *locked_page,
413 u64 offset, u64 bytes)
415 unsigned long index = offset >> PAGE_SHIFT;
416 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
417 u64 page_start = 0, page_end = 0;
421 page_start = page_offset(locked_page);
422 page_end = page_start + PAGE_SIZE - 1;
425 while (index <= end_index) {
427 * For locked page, we will call end_extent_writepage() on it
428 * in run_delalloc_range() for the error handling. That
429 * end_extent_writepage() function will call
430 * btrfs_mark_ordered_io_finished() to clear page Ordered and
431 * run the ordered extent accounting.
433 * Here we can't just clear the Ordered bit, or
434 * btrfs_mark_ordered_io_finished() would skip the accounting
435 * for the page range, and the ordered extent will never finish.
437 if (locked_page && index == (page_start >> PAGE_SHIFT)) {
441 page = find_get_page(inode->vfs_inode.i_mapping, index);
447 * Here we just clear all Ordered bits for every page in the
448 * range, then btrfs_mark_ordered_io_finished() will handle
449 * the ordered extent accounting for the range.
451 btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
457 /* The locked page covers the full range, nothing needs to be done */
458 if (bytes + offset <= page_start + PAGE_SIZE)
461 * In case this page belongs to the delalloc range being
462 * instantiated then skip it, since the first page of a range is
463 * going to be properly cleaned up by the caller of
466 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
467 bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
468 offset = page_offset(locked_page) + PAGE_SIZE;
472 return btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes, false);
475 static int btrfs_dirty_inode(struct btrfs_inode *inode);
477 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
478 struct btrfs_new_inode_args *args)
482 if (args->default_acl) {
483 err = __btrfs_set_acl(trans, args->inode, args->default_acl,
489 err = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
493 if (!args->default_acl && !args->acl)
494 cache_no_acl(args->inode);
495 return btrfs_xattr_security_init(trans, args->inode, args->dir,
496 &args->dentry->d_name);
500 * this does all the hard work for inserting an inline extent into
501 * the btree. The caller should have done a btrfs_drop_extents so that
502 * no overlapping inline items exist in the btree
504 static int insert_inline_extent(struct btrfs_trans_handle *trans,
505 struct btrfs_path *path,
506 struct btrfs_inode *inode, bool extent_inserted,
507 size_t size, size_t compressed_size,
509 struct page **compressed_pages,
512 struct btrfs_root *root = inode->root;
513 struct extent_buffer *leaf;
514 struct page *page = NULL;
517 struct btrfs_file_extent_item *ei;
519 size_t cur_size = size;
522 ASSERT((compressed_size > 0 && compressed_pages) ||
523 (compressed_size == 0 && !compressed_pages));
525 if (compressed_size && compressed_pages)
526 cur_size = compressed_size;
528 if (!extent_inserted) {
529 struct btrfs_key key;
532 key.objectid = btrfs_ino(inode);
534 key.type = BTRFS_EXTENT_DATA_KEY;
536 datasize = btrfs_file_extent_calc_inline_size(cur_size);
537 ret = btrfs_insert_empty_item(trans, root, path, &key,
542 leaf = path->nodes[0];
543 ei = btrfs_item_ptr(leaf, path->slots[0],
544 struct btrfs_file_extent_item);
545 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
546 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
547 btrfs_set_file_extent_encryption(leaf, ei, 0);
548 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
549 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
550 ptr = btrfs_file_extent_inline_start(ei);
552 if (compress_type != BTRFS_COMPRESS_NONE) {
555 while (compressed_size > 0) {
556 cpage = compressed_pages[i];
557 cur_size = min_t(unsigned long, compressed_size,
560 kaddr = kmap_local_page(cpage);
561 write_extent_buffer(leaf, kaddr, ptr, cur_size);
566 compressed_size -= cur_size;
568 btrfs_set_file_extent_compression(leaf, ei,
571 page = find_get_page(inode->vfs_inode.i_mapping, 0);
572 btrfs_set_file_extent_compression(leaf, ei, 0);
573 kaddr = kmap_local_page(page);
574 write_extent_buffer(leaf, kaddr, ptr, size);
578 btrfs_mark_buffer_dirty(leaf);
579 btrfs_release_path(path);
582 * We align size to sectorsize for inline extents just for simplicity
585 ret = btrfs_inode_set_file_extent_range(inode, 0,
586 ALIGN(size, root->fs_info->sectorsize));
591 * We're an inline extent, so nobody can extend the file past i_size
592 * without locking a page we already have locked.
594 * We must do any i_size and inode updates before we unlock the pages.
595 * Otherwise we could end up racing with unlink.
597 i_size = i_size_read(&inode->vfs_inode);
598 if (update_i_size && size > i_size) {
599 i_size_write(&inode->vfs_inode, size);
602 inode->disk_i_size = i_size;
610 * conditionally insert an inline extent into the file. This
611 * does the checks required to make sure the data is small enough
612 * to fit as an inline extent.
614 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 size,
615 size_t compressed_size,
617 struct page **compressed_pages,
620 struct btrfs_drop_extents_args drop_args = { 0 };
621 struct btrfs_root *root = inode->root;
622 struct btrfs_fs_info *fs_info = root->fs_info;
623 struct btrfs_trans_handle *trans;
624 u64 data_len = (compressed_size ?: size);
626 struct btrfs_path *path;
629 * We can create an inline extent if it ends at or beyond the current
630 * i_size, is no larger than a sector (decompressed), and the (possibly
631 * compressed) data fits in a leaf and the configured maximum inline
634 if (size < i_size_read(&inode->vfs_inode) ||
635 size > fs_info->sectorsize ||
636 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
637 data_len > fs_info->max_inline)
640 path = btrfs_alloc_path();
644 trans = btrfs_join_transaction(root);
646 btrfs_free_path(path);
647 return PTR_ERR(trans);
649 trans->block_rsv = &inode->block_rsv;
651 drop_args.path = path;
653 drop_args.end = fs_info->sectorsize;
654 drop_args.drop_cache = true;
655 drop_args.replace_extent = true;
656 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
657 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
659 btrfs_abort_transaction(trans, ret);
663 ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
664 size, compressed_size, compress_type,
665 compressed_pages, update_i_size);
666 if (ret && ret != -ENOSPC) {
667 btrfs_abort_transaction(trans, ret);
669 } else if (ret == -ENOSPC) {
674 btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
675 ret = btrfs_update_inode(trans, root, inode);
676 if (ret && ret != -ENOSPC) {
677 btrfs_abort_transaction(trans, ret);
679 } else if (ret == -ENOSPC) {
684 btrfs_set_inode_full_sync(inode);
687 * Don't forget to free the reserved space, as for inlined extent
688 * it won't count as data extent, free them directly here.
689 * And at reserve time, it's always aligned to page size, so
690 * just free one page here.
692 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
693 btrfs_free_path(path);
694 btrfs_end_transaction(trans);
698 struct async_extent {
703 unsigned long nr_pages;
705 struct list_head list;
709 struct btrfs_inode *inode;
710 struct page *locked_page;
713 blk_opf_t write_flags;
714 struct list_head extents;
715 struct cgroup_subsys_state *blkcg_css;
716 struct btrfs_work work;
717 struct async_cow *async_cow;
722 struct async_chunk chunks[];
725 static noinline int add_async_extent(struct async_chunk *cow,
726 u64 start, u64 ram_size,
729 unsigned long nr_pages,
732 struct async_extent *async_extent;
734 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
735 BUG_ON(!async_extent); /* -ENOMEM */
736 async_extent->start = start;
737 async_extent->ram_size = ram_size;
738 async_extent->compressed_size = compressed_size;
739 async_extent->pages = pages;
740 async_extent->nr_pages = nr_pages;
741 async_extent->compress_type = compress_type;
742 list_add_tail(&async_extent->list, &cow->extents);
747 * Check if the inode needs to be submitted to compression, based on mount
748 * options, defragmentation, properties or heuristics.
750 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
753 struct btrfs_fs_info *fs_info = inode->root->fs_info;
755 if (!btrfs_inode_can_compress(inode)) {
756 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
757 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
762 * Special check for subpage.
764 * We lock the full page then run each delalloc range in the page, thus
765 * for the following case, we will hit some subpage specific corner case:
768 * | |///////| |///////|
771 * In above case, both range A and range B will try to unlock the full
772 * page [0, 64K), causing the one finished later will have page
773 * unlocked already, triggering various page lock requirement BUG_ON()s.
775 * So here we add an artificial limit that subpage compression can only
776 * if the range is fully page aligned.
778 * In theory we only need to ensure the first page is fully covered, but
779 * the tailing partial page will be locked until the full compression
780 * finishes, delaying the write of other range.
782 * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
783 * first to prevent any submitted async extent to unlock the full page.
784 * By this, we can ensure for subpage case that only the last async_cow
785 * will unlock the full page.
787 if (fs_info->sectorsize < PAGE_SIZE) {
788 if (!PAGE_ALIGNED(start) ||
789 !PAGE_ALIGNED(end + 1))
794 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
797 if (inode->defrag_compress)
799 /* bad compression ratios */
800 if (inode->flags & BTRFS_INODE_NOCOMPRESS)
802 if (btrfs_test_opt(fs_info, COMPRESS) ||
803 inode->flags & BTRFS_INODE_COMPRESS ||
804 inode->prop_compress)
805 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
809 static inline void inode_should_defrag(struct btrfs_inode *inode,
810 u64 start, u64 end, u64 num_bytes, u32 small_write)
812 /* If this is a small write inside eof, kick off a defrag */
813 if (num_bytes < small_write &&
814 (start > 0 || end + 1 < inode->disk_i_size))
815 btrfs_add_inode_defrag(NULL, inode, small_write);
819 * we create compressed extents in two phases. The first
820 * phase compresses a range of pages that have already been
821 * locked (both pages and state bits are locked).
823 * This is done inside an ordered work queue, and the compression
824 * is spread across many cpus. The actual IO submission is step
825 * two, and the ordered work queue takes care of making sure that
826 * happens in the same order things were put onto the queue by
827 * writepages and friends.
829 * If this code finds it can't get good compression, it puts an
830 * entry onto the work queue to write the uncompressed bytes. This
831 * makes sure that both compressed inodes and uncompressed inodes
832 * are written in the same order that the flusher thread sent them
835 static noinline int compress_file_range(struct async_chunk *async_chunk)
837 struct btrfs_inode *inode = async_chunk->inode;
838 struct btrfs_fs_info *fs_info = inode->root->fs_info;
839 struct address_space *mapping = inode->vfs_inode.i_mapping;
840 u64 blocksize = fs_info->sectorsize;
841 u64 start = async_chunk->start;
842 u64 end = async_chunk->end;
846 struct page **pages = NULL;
847 unsigned long nr_pages;
848 unsigned long total_compressed = 0;
849 unsigned long total_in = 0;
852 int compress_type = fs_info->compress_type;
853 int compressed_extents = 0;
856 inode_should_defrag(inode, start, end, end - start + 1, SZ_16K);
859 * We need to save i_size before now because it could change in between
860 * us evaluating the size and assigning it. This is because we lock and
861 * unlock the page in truncate and fallocate, and then modify the i_size
864 * The barriers are to emulate READ_ONCE, remove that once i_size_read
868 i_size = i_size_read(&inode->vfs_inode);
870 actual_end = min_t(u64, i_size, end + 1);
873 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
874 nr_pages = min_t(unsigned long, nr_pages, BTRFS_MAX_COMPRESSED_PAGES);
877 * we don't want to send crud past the end of i_size through
878 * compression, that's just a waste of CPU time. So, if the
879 * end of the file is before the start of our current
880 * requested range of bytes, we bail out to the uncompressed
881 * cleanup code that can deal with all of this.
883 * It isn't really the fastest way to fix things, but this is a
884 * very uncommon corner.
886 if (actual_end <= start)
887 goto cleanup_and_bail_uncompressed;
889 total_compressed = actual_end - start;
892 * Skip compression for a small file range(<=blocksize) that
893 * isn't an inline extent, since it doesn't save disk space at all.
895 if (total_compressed <= blocksize &&
896 (start > 0 || end + 1 < inode->disk_i_size))
897 goto cleanup_and_bail_uncompressed;
900 * For subpage case, we require full page alignment for the sector
902 * Thus we must also check against @actual_end, not just @end.
904 if (blocksize < PAGE_SIZE) {
905 if (!PAGE_ALIGNED(start) ||
906 !PAGE_ALIGNED(round_up(actual_end, blocksize)))
907 goto cleanup_and_bail_uncompressed;
910 total_compressed = min_t(unsigned long, total_compressed,
911 BTRFS_MAX_UNCOMPRESSED);
916 * we do compression for mount -o compress and when the
917 * inode has not been flagged as nocompress. This flag can
918 * change at any time if we discover bad compression ratios.
920 if (inode_need_compress(inode, start, end)) {
922 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
924 /* just bail out to the uncompressed code */
929 if (inode->defrag_compress)
930 compress_type = inode->defrag_compress;
931 else if (inode->prop_compress)
932 compress_type = inode->prop_compress;
935 * we need to call clear_page_dirty_for_io on each
936 * page in the range. Otherwise applications with the file
937 * mmap'd can wander in and change the page contents while
938 * we are compressing them.
940 * If the compression fails for any reason, we set the pages
941 * dirty again later on.
943 * Note that the remaining part is redirtied, the start pointer
944 * has moved, the end is the original one.
947 extent_range_clear_dirty_for_io(&inode->vfs_inode, start, end);
951 /* Compression level is applied here and only here */
952 ret = btrfs_compress_pages(
953 compress_type | (fs_info->compress_level << 4),
961 unsigned long offset = offset_in_page(total_compressed);
962 struct page *page = pages[nr_pages - 1];
964 /* zero the tail end of the last page, we might be
965 * sending it down to disk
968 memzero_page(page, offset, PAGE_SIZE - offset);
974 * Check cow_file_range() for why we don't even try to create inline
975 * extent for subpage case.
977 if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
978 /* lets try to make an inline extent */
979 if (ret || total_in < actual_end) {
980 /* we didn't compress the entire range, try
981 * to make an uncompressed inline extent.
983 ret = cow_file_range_inline(inode, actual_end,
984 0, BTRFS_COMPRESS_NONE,
987 /* try making a compressed inline extent */
988 ret = cow_file_range_inline(inode, actual_end,
990 compress_type, pages,
994 unsigned long clear_flags = EXTENT_DELALLOC |
995 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
996 EXTENT_DO_ACCOUNTING;
999 mapping_set_error(mapping, -EIO);
1002 * inline extent creation worked or returned error,
1003 * we don't need to create any more async work items.
1004 * Unlock and free up our temp pages.
1006 * We use DO_ACCOUNTING here because we need the
1007 * delalloc_release_metadata to be done _after_ we drop
1008 * our outstanding extent for clearing delalloc for this
1011 extent_clear_unlock_delalloc(inode, start, end,
1015 PAGE_START_WRITEBACK |
1016 PAGE_END_WRITEBACK);
1019 * Ensure we only free the compressed pages if we have
1020 * them allocated, as we can still reach here with
1021 * inode_need_compress() == false.
1024 for (i = 0; i < nr_pages; i++) {
1025 WARN_ON(pages[i]->mapping);
1034 if (will_compress) {
1036 * we aren't doing an inline extent round the compressed size
1037 * up to a block size boundary so the allocator does sane
1040 total_compressed = ALIGN(total_compressed, blocksize);
1043 * one last check to make sure the compression is really a
1044 * win, compare the page count read with the blocks on disk,
1045 * compression must free at least one sector size
1047 total_in = round_up(total_in, fs_info->sectorsize);
1048 if (total_compressed + blocksize <= total_in) {
1049 compressed_extents++;
1052 * The async work queues will take care of doing actual
1053 * allocation on disk for these compressed pages, and
1054 * will submit them to the elevator.
1056 add_async_extent(async_chunk, start, total_in,
1057 total_compressed, pages, nr_pages,
1060 if (start + total_in < end) {
1066 return compressed_extents;
1071 * the compression code ran but failed to make things smaller,
1072 * free any pages it allocated and our page pointer array
1074 for (i = 0; i < nr_pages; i++) {
1075 WARN_ON(pages[i]->mapping);
1080 total_compressed = 0;
1083 /* flag the file so we don't compress in the future */
1084 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
1085 !(inode->prop_compress)) {
1086 inode->flags |= BTRFS_INODE_NOCOMPRESS;
1089 cleanup_and_bail_uncompressed:
1091 * No compression, but we still need to write the pages in the file
1092 * we've been given so far. redirty the locked page if it corresponds
1093 * to our extent and set things up for the async work queue to run
1094 * cow_file_range to do the normal delalloc dance.
1096 if (async_chunk->locked_page &&
1097 (page_offset(async_chunk->locked_page) >= start &&
1098 page_offset(async_chunk->locked_page)) <= end) {
1099 __set_page_dirty_nobuffers(async_chunk->locked_page);
1100 /* unlocked later on in the async handlers */
1104 extent_range_redirty_for_io(&inode->vfs_inode, start, end);
1105 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
1106 BTRFS_COMPRESS_NONE);
1107 compressed_extents++;
1109 return compressed_extents;
1112 static void free_async_extent_pages(struct async_extent *async_extent)
1116 if (!async_extent->pages)
1119 for (i = 0; i < async_extent->nr_pages; i++) {
1120 WARN_ON(async_extent->pages[i]->mapping);
1121 put_page(async_extent->pages[i]);
1123 kfree(async_extent->pages);
1124 async_extent->nr_pages = 0;
1125 async_extent->pages = NULL;
1128 static int submit_uncompressed_range(struct btrfs_inode *inode,
1129 struct async_extent *async_extent,
1130 struct page *locked_page)
1132 u64 start = async_extent->start;
1133 u64 end = async_extent->start + async_extent->ram_size - 1;
1134 unsigned long nr_written = 0;
1135 int page_started = 0;
1137 struct writeback_control wbc = {
1138 .sync_mode = WB_SYNC_ALL,
1139 .range_start = start,
1141 .no_cgroup_owner = 1,
1145 * Call cow_file_range() to run the delalloc range directly, since we
1146 * won't go to NOCOW or async path again.
1148 * Also we call cow_file_range() with @unlock_page == 0, so that we
1149 * can directly submit them without interruption.
1151 ret = cow_file_range(inode, locked_page, start, end, &page_started,
1152 &nr_written, NULL, true, false);
1153 /* Inline extent inserted, page gets unlocked and everything is done */
1158 btrfs_cleanup_ordered_extents(inode, locked_page, start, end - start + 1);
1160 const u64 page_start = page_offset(locked_page);
1161 const u64 page_end = page_start + PAGE_SIZE - 1;
1163 set_page_writeback(locked_page);
1164 end_page_writeback(locked_page);
1165 end_extent_writepage(locked_page, ret, page_start, page_end);
1166 unlock_page(locked_page);
1171 /* All pages will be unlocked, including @locked_page */
1172 wbc_attach_fdatawrite_inode(&wbc, &inode->vfs_inode);
1173 ret = extent_write_locked_range(&inode->vfs_inode, start, end, &wbc);
1174 wbc_detach_inode(&wbc);
1178 static int submit_one_async_extent(struct btrfs_inode *inode,
1179 struct async_chunk *async_chunk,
1180 struct async_extent *async_extent,
1183 struct extent_io_tree *io_tree = &inode->io_tree;
1184 struct btrfs_root *root = inode->root;
1185 struct btrfs_fs_info *fs_info = root->fs_info;
1186 struct btrfs_ordered_extent *ordered;
1187 struct btrfs_key ins;
1188 struct page *locked_page = NULL;
1189 struct extent_map *em;
1191 u64 start = async_extent->start;
1192 u64 end = async_extent->start + async_extent->ram_size - 1;
1194 if (async_chunk->blkcg_css)
1195 kthread_associate_blkcg(async_chunk->blkcg_css);
1198 * If async_chunk->locked_page is in the async_extent range, we need to
1201 if (async_chunk->locked_page) {
1202 u64 locked_page_start = page_offset(async_chunk->locked_page);
1203 u64 locked_page_end = locked_page_start + PAGE_SIZE - 1;
1205 if (!(start >= locked_page_end || end <= locked_page_start))
1206 locked_page = async_chunk->locked_page;
1208 lock_extent(io_tree, start, end, NULL);
1210 /* We have fall back to uncompressed write */
1211 if (!async_extent->pages) {
1212 ret = submit_uncompressed_range(inode, async_extent, locked_page);
1216 ret = btrfs_reserve_extent(root, async_extent->ram_size,
1217 async_extent->compressed_size,
1218 async_extent->compressed_size,
1219 0, *alloc_hint, &ins, 1, 1);
1222 * Here we used to try again by going back to non-compressed
1223 * path for ENOSPC. But we can't reserve space even for
1224 * compressed size, how could it work for uncompressed size
1225 * which requires larger size? So here we directly go error
1231 /* Here we're doing allocation and writeback of the compressed pages */
1232 em = create_io_em(inode, start,
1233 async_extent->ram_size, /* len */
1234 start, /* orig_start */
1235 ins.objectid, /* block_start */
1236 ins.offset, /* block_len */
1237 ins.offset, /* orig_block_len */
1238 async_extent->ram_size, /* ram_bytes */
1239 async_extent->compress_type,
1240 BTRFS_ORDERED_COMPRESSED);
1243 goto out_free_reserve;
1245 free_extent_map(em);
1247 ordered = btrfs_alloc_ordered_extent(inode, start, /* file_offset */
1248 async_extent->ram_size, /* num_bytes */
1249 async_extent->ram_size, /* ram_bytes */
1250 ins.objectid, /* disk_bytenr */
1251 ins.offset, /* disk_num_bytes */
1253 1 << BTRFS_ORDERED_COMPRESSED,
1254 async_extent->compress_type);
1255 if (IS_ERR(ordered)) {
1256 btrfs_drop_extent_map_range(inode, start, end, false);
1257 ret = PTR_ERR(ordered);
1258 goto out_free_reserve;
1260 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1262 /* Clear dirty, set writeback and unlock the pages. */
1263 extent_clear_unlock_delalloc(inode, start, end,
1264 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
1265 PAGE_UNLOCK | PAGE_START_WRITEBACK);
1266 btrfs_submit_compressed_write(ordered,
1267 async_extent->pages, /* compressed_pages */
1268 async_extent->nr_pages,
1269 async_chunk->write_flags, true);
1270 *alloc_hint = ins.objectid + ins.offset;
1272 if (async_chunk->blkcg_css)
1273 kthread_associate_blkcg(NULL);
1274 kfree(async_extent);
1278 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1279 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1281 mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
1282 extent_clear_unlock_delalloc(inode, start, end,
1283 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
1284 EXTENT_DELALLOC_NEW |
1285 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
1286 PAGE_UNLOCK | PAGE_START_WRITEBACK |
1287 PAGE_END_WRITEBACK);
1288 free_async_extent_pages(async_extent);
1293 * Phase two of compressed writeback. This is the ordered portion of the code,
1294 * which only gets called in the order the work was queued. We walk all the
1295 * async extents created by compress_file_range and send them down to the disk.
1297 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
1299 struct btrfs_inode *inode = async_chunk->inode;
1300 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1301 struct async_extent *async_extent;
1305 while (!list_empty(&async_chunk->extents)) {
1309 async_extent = list_entry(async_chunk->extents.next,
1310 struct async_extent, list);
1311 list_del(&async_extent->list);
1312 extent_start = async_extent->start;
1313 ram_size = async_extent->ram_size;
1315 ret = submit_one_async_extent(inode, async_chunk, async_extent,
1317 btrfs_debug(fs_info,
1318 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1319 inode->root->root_key.objectid,
1320 btrfs_ino(inode), extent_start, ram_size, ret);
1324 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1327 struct extent_map_tree *em_tree = &inode->extent_tree;
1328 struct extent_map *em;
1331 read_lock(&em_tree->lock);
1332 em = search_extent_mapping(em_tree, start, num_bytes);
1335 * if block start isn't an actual block number then find the
1336 * first block in this inode and use that as a hint. If that
1337 * block is also bogus then just don't worry about it.
1339 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1340 free_extent_map(em);
1341 em = search_extent_mapping(em_tree, 0, 0);
1342 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1343 alloc_hint = em->block_start;
1345 free_extent_map(em);
1347 alloc_hint = em->block_start;
1348 free_extent_map(em);
1351 read_unlock(&em_tree->lock);
1357 * when extent_io.c finds a delayed allocation range in the file,
1358 * the call backs end up in this code. The basic idea is to
1359 * allocate extents on disk for the range, and create ordered data structs
1360 * in ram to track those extents.
1362 * locked_page is the page that writepage had locked already. We use
1363 * it to make sure we don't do extra locks or unlocks.
1365 * When this function fails, it unlocks all pages except @locked_page.
1367 * When this function successfully creates an inline extent, it sets page_started
1368 * to 1 and unlocks all pages including locked_page and starts I/O on them.
1369 * (In reality inline extents are limited to a single page, so locked_page is
1370 * the only page handled anyway).
1372 * When this function succeed and creates a normal extent, the page locking
1373 * status depends on the passed in flags:
1375 * - If @keep_locked is set, all pages are kept locked.
1376 * - Else all pages except for @locked_page are unlocked.
1378 * When a failure happens in the second or later iteration of the
1379 * while-loop, the ordered extents created in previous iterations are kept
1380 * intact. So, the caller must clean them up by calling
1381 * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
1384 static noinline int cow_file_range(struct btrfs_inode *inode,
1385 struct page *locked_page,
1386 u64 start, u64 end, int *page_started,
1387 unsigned long *nr_written, u64 *done_offset,
1388 bool keep_locked, bool no_inline)
1390 struct btrfs_root *root = inode->root;
1391 struct btrfs_fs_info *fs_info = root->fs_info;
1393 u64 orig_start = start;
1395 unsigned long ram_size;
1396 u64 cur_alloc_size = 0;
1398 u64 blocksize = fs_info->sectorsize;
1399 struct btrfs_key ins;
1400 struct extent_map *em;
1401 unsigned clear_bits;
1402 unsigned long page_ops;
1403 bool extent_reserved = false;
1406 if (btrfs_is_free_space_inode(inode)) {
1411 num_bytes = ALIGN(end - start + 1, blocksize);
1412 num_bytes = max(blocksize, num_bytes);
1413 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1415 inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1418 * Due to the page size limit, for subpage we can only trigger the
1419 * writeback for the dirty sectors of page, that means data writeback
1420 * is doing more writeback than what we want.
1422 * This is especially unexpected for some call sites like fallocate,
1423 * where we only increase i_size after everything is done.
1424 * This means we can trigger inline extent even if we didn't want to.
1425 * So here we skip inline extent creation completely.
1427 if (start == 0 && fs_info->sectorsize == PAGE_SIZE && !no_inline) {
1428 u64 actual_end = min_t(u64, i_size_read(&inode->vfs_inode),
1431 /* lets try to make an inline extent */
1432 ret = cow_file_range_inline(inode, actual_end, 0,
1433 BTRFS_COMPRESS_NONE, NULL, false);
1436 * We use DO_ACCOUNTING here because we need the
1437 * delalloc_release_metadata to be run _after_ we drop
1438 * our outstanding extent for clearing delalloc for this
1441 extent_clear_unlock_delalloc(inode, start, end,
1443 EXTENT_LOCKED | EXTENT_DELALLOC |
1444 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1445 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1446 PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1447 *nr_written = *nr_written +
1448 (end - start + PAGE_SIZE) / PAGE_SIZE;
1451 * locked_page is locked by the caller of
1452 * writepage_delalloc(), not locked by
1453 * __process_pages_contig().
1455 * We can't let __process_pages_contig() to unlock it,
1456 * as it doesn't have any subpage::writers recorded.
1458 * Here we manually unlock the page, since the caller
1459 * can't use page_started to determine if it's an
1460 * inline extent or a compressed extent.
1462 unlock_page(locked_page);
1464 } else if (ret < 0) {
1469 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1472 * Relocation relies on the relocated extents to have exactly the same
1473 * size as the original extents. Normally writeback for relocation data
1474 * extents follows a NOCOW path because relocation preallocates the
1475 * extents. However, due to an operation such as scrub turning a block
1476 * group to RO mode, it may fallback to COW mode, so we must make sure
1477 * an extent allocated during COW has exactly the requested size and can
1478 * not be split into smaller extents, otherwise relocation breaks and
1479 * fails during the stage where it updates the bytenr of file extent
1482 if (btrfs_is_data_reloc_root(root))
1483 min_alloc_size = num_bytes;
1485 min_alloc_size = fs_info->sectorsize;
1487 while (num_bytes > 0) {
1488 struct btrfs_ordered_extent *ordered;
1490 cur_alloc_size = num_bytes;
1491 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1492 min_alloc_size, 0, alloc_hint,
1496 cur_alloc_size = ins.offset;
1497 extent_reserved = true;
1499 ram_size = ins.offset;
1500 em = create_io_em(inode, start, ins.offset, /* len */
1501 start, /* orig_start */
1502 ins.objectid, /* block_start */
1503 ins.offset, /* block_len */
1504 ins.offset, /* orig_block_len */
1505 ram_size, /* ram_bytes */
1506 BTRFS_COMPRESS_NONE, /* compress_type */
1507 BTRFS_ORDERED_REGULAR /* type */);
1512 free_extent_map(em);
1514 ordered = btrfs_alloc_ordered_extent(inode, start, ram_size,
1515 ram_size, ins.objectid, cur_alloc_size,
1516 0, 1 << BTRFS_ORDERED_REGULAR,
1517 BTRFS_COMPRESS_NONE);
1518 if (IS_ERR(ordered)) {
1519 ret = PTR_ERR(ordered);
1520 goto out_drop_extent_cache;
1523 if (btrfs_is_data_reloc_root(root)) {
1524 ret = btrfs_reloc_clone_csums(ordered);
1527 * Only drop cache here, and process as normal.
1529 * We must not allow extent_clear_unlock_delalloc()
1530 * at out_unlock label to free meta of this ordered
1531 * extent, as its meta should be freed by
1532 * btrfs_finish_ordered_io().
1534 * So we must continue until @start is increased to
1535 * skip current ordered extent.
1538 btrfs_drop_extent_map_range(inode, start,
1539 start + ram_size - 1,
1542 btrfs_put_ordered_extent(ordered);
1544 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1547 * We're not doing compressed IO, don't unlock the first page
1548 * (which the caller expects to stay locked), don't clear any
1549 * dirty bits and don't set any writeback bits
1551 * Do set the Ordered (Private2) bit so we know this page was
1552 * properly setup for writepage.
1554 page_ops = (keep_locked ? 0 : PAGE_UNLOCK);
1555 page_ops |= PAGE_SET_ORDERED;
1557 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1559 EXTENT_LOCKED | EXTENT_DELALLOC,
1561 if (num_bytes < cur_alloc_size)
1564 num_bytes -= cur_alloc_size;
1565 alloc_hint = ins.objectid + ins.offset;
1566 start += cur_alloc_size;
1567 extent_reserved = false;
1570 * btrfs_reloc_clone_csums() error, since start is increased
1571 * extent_clear_unlock_delalloc() at out_unlock label won't
1572 * free metadata of current ordered extent, we're OK to exit.
1580 out_drop_extent_cache:
1581 btrfs_drop_extent_map_range(inode, start, start + ram_size - 1, false);
1583 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1584 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1587 * If done_offset is non-NULL and ret == -EAGAIN, we expect the
1588 * caller to write out the successfully allocated region and retry.
1590 if (done_offset && ret == -EAGAIN) {
1591 if (orig_start < start)
1592 *done_offset = start - 1;
1594 *done_offset = start;
1596 } else if (ret == -EAGAIN) {
1597 /* Convert to -ENOSPC since the caller cannot retry. */
1602 * Now, we have three regions to clean up:
1604 * |-------(1)----|---(2)---|-------------(3)----------|
1605 * `- orig_start `- start `- start + cur_alloc_size `- end
1607 * We process each region below.
1610 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1611 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1612 page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1615 * For the range (1). We have already instantiated the ordered extents
1616 * for this region. They are cleaned up by
1617 * btrfs_cleanup_ordered_extents() in e.g,
1618 * btrfs_run_delalloc_range(). EXTENT_LOCKED | EXTENT_DELALLOC are
1619 * already cleared in the above loop. And, EXTENT_DELALLOC_NEW |
1620 * EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV are handled by the cleanup
1623 * However, in case of @keep_locked, we still need to unlock the pages
1624 * (except @locked_page) to ensure all the pages are unlocked.
1626 if (keep_locked && orig_start < start) {
1628 mapping_set_error(inode->vfs_inode.i_mapping, ret);
1629 extent_clear_unlock_delalloc(inode, orig_start, start - 1,
1630 locked_page, 0, page_ops);
1634 * For the range (2). If we reserved an extent for our delalloc range
1635 * (or a subrange) and failed to create the respective ordered extent,
1636 * then it means that when we reserved the extent we decremented the
1637 * extent's size from the data space_info's bytes_may_use counter and
1638 * incremented the space_info's bytes_reserved counter by the same
1639 * amount. We must make sure extent_clear_unlock_delalloc() does not try
1640 * to decrement again the data space_info's bytes_may_use counter,
1641 * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
1643 if (extent_reserved) {
1644 extent_clear_unlock_delalloc(inode, start,
1645 start + cur_alloc_size - 1,
1649 start += cur_alloc_size;
1653 * For the range (3). We never touched the region. In addition to the
1654 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1655 * space_info's bytes_may_use counter, reserved in
1656 * btrfs_check_data_free_space().
1659 clear_bits |= EXTENT_CLEAR_DATA_RESV;
1660 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1661 clear_bits, page_ops);
1667 * work queue call back to started compression on a file and pages
1669 static noinline void async_cow_start(struct btrfs_work *work)
1671 struct async_chunk *async_chunk;
1672 int compressed_extents;
1674 async_chunk = container_of(work, struct async_chunk, work);
1676 compressed_extents = compress_file_range(async_chunk);
1677 if (compressed_extents == 0) {
1678 btrfs_add_delayed_iput(async_chunk->inode);
1679 async_chunk->inode = NULL;
1684 * work queue call back to submit previously compressed pages
1686 static noinline void async_cow_submit(struct btrfs_work *work)
1688 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1690 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1691 unsigned long nr_pages;
1693 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1697 * ->inode could be NULL if async_chunk_start has failed to compress,
1698 * in which case we don't have anything to submit, yet we need to
1699 * always adjust ->async_delalloc_pages as its paired with the init
1700 * happening in run_delalloc_compressed
1702 if (async_chunk->inode)
1703 submit_compressed_extents(async_chunk);
1705 /* atomic_sub_return implies a barrier */
1706 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1708 cond_wake_up_nomb(&fs_info->async_submit_wait);
1711 static noinline void async_cow_free(struct btrfs_work *work)
1713 struct async_chunk *async_chunk;
1714 struct async_cow *async_cow;
1716 async_chunk = container_of(work, struct async_chunk, work);
1717 if (async_chunk->inode)
1718 btrfs_add_delayed_iput(async_chunk->inode);
1719 if (async_chunk->blkcg_css)
1720 css_put(async_chunk->blkcg_css);
1722 async_cow = async_chunk->async_cow;
1723 if (atomic_dec_and_test(&async_cow->num_chunks))
1727 static bool run_delalloc_compressed(struct btrfs_inode *inode,
1728 struct writeback_control *wbc,
1729 struct page *locked_page,
1730 u64 start, u64 end, int *page_started,
1731 unsigned long *nr_written)
1733 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1734 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1735 struct async_cow *ctx;
1736 struct async_chunk *async_chunk;
1737 unsigned long nr_pages;
1738 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1741 const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1743 nofs_flag = memalloc_nofs_save();
1744 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1745 memalloc_nofs_restore(nofs_flag);
1749 unlock_extent(&inode->io_tree, start, end, NULL);
1750 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1752 async_chunk = ctx->chunks;
1753 atomic_set(&ctx->num_chunks, num_chunks);
1755 for (i = 0; i < num_chunks; i++) {
1756 u64 cur_end = min(end, start + SZ_512K - 1);
1759 * igrab is called higher up in the call chain, take only the
1760 * lightweight reference for the callback lifetime
1762 ihold(&inode->vfs_inode);
1763 async_chunk[i].async_cow = ctx;
1764 async_chunk[i].inode = inode;
1765 async_chunk[i].start = start;
1766 async_chunk[i].end = cur_end;
1767 async_chunk[i].write_flags = write_flags;
1768 INIT_LIST_HEAD(&async_chunk[i].extents);
1771 * The locked_page comes all the way from writepage and its
1772 * the original page we were actually given. As we spread
1773 * this large delalloc region across multiple async_chunk
1774 * structs, only the first struct needs a pointer to locked_page
1776 * This way we don't need racey decisions about who is supposed
1781 * Depending on the compressibility, the pages might or
1782 * might not go through async. We want all of them to
1783 * be accounted against wbc once. Let's do it here
1784 * before the paths diverge. wbc accounting is used
1785 * only for foreign writeback detection and doesn't
1786 * need full accuracy. Just account the whole thing
1787 * against the first page.
1789 wbc_account_cgroup_owner(wbc, locked_page,
1791 async_chunk[i].locked_page = locked_page;
1794 async_chunk[i].locked_page = NULL;
1797 if (blkcg_css != blkcg_root_css) {
1799 async_chunk[i].blkcg_css = blkcg_css;
1800 async_chunk[i].write_flags |= REQ_BTRFS_CGROUP_PUNT;
1802 async_chunk[i].blkcg_css = NULL;
1805 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1806 async_cow_submit, async_cow_free);
1808 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1809 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1811 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1813 *nr_written += nr_pages;
1814 start = cur_end + 1;
1820 static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1821 struct page *locked_page, u64 start,
1822 u64 end, int *page_started,
1823 unsigned long *nr_written,
1824 struct writeback_control *wbc)
1826 u64 done_offset = end;
1828 bool locked_page_done = false;
1830 while (start <= end) {
1831 ret = cow_file_range(inode, locked_page, start, end, page_started,
1832 nr_written, &done_offset, true, false);
1833 if (ret && ret != -EAGAIN)
1836 if (*page_started) {
1844 if (done_offset == start) {
1845 wait_on_bit_io(&inode->root->fs_info->flags,
1846 BTRFS_FS_NEED_ZONE_FINISH,
1847 TASK_UNINTERRUPTIBLE);
1851 if (!locked_page_done) {
1852 __set_page_dirty_nobuffers(locked_page);
1853 account_page_redirty(locked_page);
1855 locked_page_done = true;
1856 extent_write_locked_range(&inode->vfs_inode, start, done_offset,
1858 start = done_offset + 1;
1866 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1867 u64 bytenr, u64 num_bytes, bool nowait)
1869 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bytenr);
1870 struct btrfs_ordered_sum *sums;
1874 ret = btrfs_lookup_csums_list(csum_root, bytenr, bytenr + num_bytes - 1,
1876 if (ret == 0 && list_empty(&list))
1879 while (!list_empty(&list)) {
1880 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1881 list_del(&sums->list);
1889 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1890 const u64 start, const u64 end)
1892 const bool is_space_ino = btrfs_is_free_space_inode(inode);
1893 const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1894 const u64 range_bytes = end + 1 - start;
1895 struct extent_io_tree *io_tree = &inode->io_tree;
1896 int page_started = 0;
1897 unsigned long nr_written;
1898 u64 range_start = start;
1903 * If EXTENT_NORESERVE is set it means that when the buffered write was
1904 * made we had not enough available data space and therefore we did not
1905 * reserve data space for it, since we though we could do NOCOW for the
1906 * respective file range (either there is prealloc extent or the inode
1907 * has the NOCOW bit set).
1909 * However when we need to fallback to COW mode (because for example the
1910 * block group for the corresponding extent was turned to RO mode by a
1911 * scrub or relocation) we need to do the following:
1913 * 1) We increment the bytes_may_use counter of the data space info.
1914 * If COW succeeds, it allocates a new data extent and after doing
1915 * that it decrements the space info's bytes_may_use counter and
1916 * increments its bytes_reserved counter by the same amount (we do
1917 * this at btrfs_add_reserved_bytes()). So we need to increment the
1918 * bytes_may_use counter to compensate (when space is reserved at
1919 * buffered write time, the bytes_may_use counter is incremented);
1921 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1922 * that if the COW path fails for any reason, it decrements (through
1923 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1924 * data space info, which we incremented in the step above.
1926 * If we need to fallback to cow and the inode corresponds to a free
1927 * space cache inode or an inode of the data relocation tree, we must
1928 * also increment bytes_may_use of the data space_info for the same
1929 * reason. Space caches and relocated data extents always get a prealloc
1930 * extent for them, however scrub or balance may have set the block
1931 * group that contains that extent to RO mode and therefore force COW
1932 * when starting writeback.
1934 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1935 EXTENT_NORESERVE, 0, NULL);
1936 if (count > 0 || is_space_ino || is_reloc_ino) {
1938 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1939 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1941 if (is_space_ino || is_reloc_ino)
1942 bytes = range_bytes;
1944 spin_lock(&sinfo->lock);
1945 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1946 spin_unlock(&sinfo->lock);
1949 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1954 * Don't try to create inline extents, as a mix of inline extent that
1955 * is written out and unlocked directly and a normal NOCOW extent
1958 ret = cow_file_range(inode, locked_page, start, end, &page_started,
1959 &nr_written, NULL, false, true);
1960 ASSERT(!page_started);
1964 struct can_nocow_file_extent_args {
1967 /* Start file offset of the range we want to NOCOW. */
1969 /* End file offset (inclusive) of the range we want to NOCOW. */
1971 bool writeback_path;
1974 * Free the path passed to can_nocow_file_extent() once it's not needed
1979 /* Output fields. Only set when can_nocow_file_extent() returns 1. */
1984 /* Number of bytes that can be written to in NOCOW mode. */
1989 * Check if we can NOCOW the file extent that the path points to.
1990 * This function may return with the path released, so the caller should check
1991 * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
1993 * Returns: < 0 on error
1994 * 0 if we can not NOCOW
1997 static int can_nocow_file_extent(struct btrfs_path *path,
1998 struct btrfs_key *key,
1999 struct btrfs_inode *inode,
2000 struct can_nocow_file_extent_args *args)
2002 const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
2003 struct extent_buffer *leaf = path->nodes[0];
2004 struct btrfs_root *root = inode->root;
2005 struct btrfs_file_extent_item *fi;
2010 bool nowait = path->nowait;
2012 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
2013 extent_type = btrfs_file_extent_type(leaf, fi);
2015 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
2018 /* Can't access these fields unless we know it's not an inline extent. */
2019 args->disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2020 args->disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
2021 args->extent_offset = btrfs_file_extent_offset(leaf, fi);
2023 if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
2024 extent_type == BTRFS_FILE_EXTENT_REG)
2028 * If the extent was created before the generation where the last snapshot
2029 * for its subvolume was created, then this implies the extent is shared,
2030 * hence we must COW.
2032 if (!args->strict &&
2033 btrfs_file_extent_generation(leaf, fi) <=
2034 btrfs_root_last_snapshot(&root->root_item))
2037 /* An explicit hole, must COW. */
2038 if (args->disk_bytenr == 0)
2041 /* Compressed/encrypted/encoded extents must be COWed. */
2042 if (btrfs_file_extent_compression(leaf, fi) ||
2043 btrfs_file_extent_encryption(leaf, fi) ||
2044 btrfs_file_extent_other_encoding(leaf, fi))
2047 extent_end = btrfs_file_extent_end(path);
2050 * The following checks can be expensive, as they need to take other
2051 * locks and do btree or rbtree searches, so release the path to avoid
2052 * blocking other tasks for too long.
2054 btrfs_release_path(path);
2056 ret = btrfs_cross_ref_exist(root, btrfs_ino(inode),
2057 key->offset - args->extent_offset,
2058 args->disk_bytenr, args->strict, path);
2059 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
2063 if (args->free_path) {
2065 * We don't need the path anymore, plus through the
2066 * csum_exist_in_range() call below we will end up allocating
2067 * another path. So free the path to avoid unnecessary extra
2070 btrfs_free_path(path);
2074 /* If there are pending snapshots for this root, we must COW. */
2075 if (args->writeback_path && !is_freespace_inode &&
2076 atomic_read(&root->snapshot_force_cow))
2079 args->disk_bytenr += args->extent_offset;
2080 args->disk_bytenr += args->start - key->offset;
2081 args->num_bytes = min(args->end + 1, extent_end) - args->start;
2084 * Force COW if csums exist in the range. This ensures that csums for a
2085 * given extent are either valid or do not exist.
2087 ret = csum_exist_in_range(root->fs_info, args->disk_bytenr, args->num_bytes,
2089 WARN_ON_ONCE(ret > 0 && is_freespace_inode);
2095 if (args->free_path && path)
2096 btrfs_free_path(path);
2098 return ret < 0 ? ret : can_nocow;
2102 * when nowcow writeback call back. This checks for snapshots or COW copies
2103 * of the extents that exist in the file, and COWs the file as required.
2105 * If no cow copies or snapshots exist, we write directly to the existing
2108 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
2109 struct page *locked_page,
2110 const u64 start, const u64 end)
2112 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2113 struct btrfs_root *root = inode->root;
2114 struct btrfs_path *path;
2115 u64 cow_start = (u64)-1;
2116 u64 cur_offset = start;
2118 bool check_prev = true;
2119 u64 ino = btrfs_ino(inode);
2120 struct btrfs_block_group *bg;
2122 struct can_nocow_file_extent_args nocow_args = { 0 };
2124 path = btrfs_alloc_path();
2126 extent_clear_unlock_delalloc(inode, start, end, locked_page,
2127 EXTENT_LOCKED | EXTENT_DELALLOC |
2128 EXTENT_DO_ACCOUNTING |
2129 EXTENT_DEFRAG, PAGE_UNLOCK |
2130 PAGE_START_WRITEBACK |
2131 PAGE_END_WRITEBACK);
2135 nocow_args.end = end;
2136 nocow_args.writeback_path = true;
2139 struct btrfs_ordered_extent *ordered;
2140 struct btrfs_key found_key;
2141 struct btrfs_file_extent_item *fi;
2142 struct extent_buffer *leaf;
2151 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
2157 * If there is no extent for our range when doing the initial
2158 * search, then go back to the previous slot as it will be the
2159 * one containing the search offset
2161 if (ret > 0 && path->slots[0] > 0 && check_prev) {
2162 leaf = path->nodes[0];
2163 btrfs_item_key_to_cpu(leaf, &found_key,
2164 path->slots[0] - 1);
2165 if (found_key.objectid == ino &&
2166 found_key.type == BTRFS_EXTENT_DATA_KEY)
2171 /* Go to next leaf if we have exhausted the current one */
2172 leaf = path->nodes[0];
2173 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2174 ret = btrfs_next_leaf(root, path);
2176 if (cow_start != (u64)-1)
2177 cur_offset = cow_start;
2182 leaf = path->nodes[0];
2185 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2187 /* Didn't find anything for our INO */
2188 if (found_key.objectid > ino)
2191 * Keep searching until we find an EXTENT_ITEM or there are no
2192 * more extents for this inode
2194 if (WARN_ON_ONCE(found_key.objectid < ino) ||
2195 found_key.type < BTRFS_EXTENT_DATA_KEY) {
2200 /* Found key is not EXTENT_DATA_KEY or starts after req range */
2201 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
2202 found_key.offset > end)
2206 * If the found extent starts after requested offset, then
2207 * adjust extent_end to be right before this extent begins
2209 if (found_key.offset > cur_offset) {
2210 extent_end = found_key.offset;
2216 * Found extent which begins before our range and potentially
2219 fi = btrfs_item_ptr(leaf, path->slots[0],
2220 struct btrfs_file_extent_item);
2221 extent_type = btrfs_file_extent_type(leaf, fi);
2222 /* If this is triggered then we have a memory corruption. */
2223 ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
2224 if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
2228 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
2229 extent_end = btrfs_file_extent_end(path);
2232 * If the extent we got ends before our current offset, skip to
2235 if (extent_end <= cur_offset) {
2240 nocow_args.start = cur_offset;
2241 ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
2243 if (cow_start != (u64)-1)
2244 cur_offset = cow_start;
2246 } else if (ret == 0) {
2251 bg = btrfs_inc_nocow_writers(fs_info, nocow_args.disk_bytenr);
2256 * If nocow is false then record the beginning of the range
2257 * that needs to be COWed
2260 if (cow_start == (u64)-1)
2261 cow_start = cur_offset;
2262 cur_offset = extent_end;
2263 if (cur_offset > end)
2265 if (!path->nodes[0])
2272 * COW range from cow_start to found_key.offset - 1. As the key
2273 * will contain the beginning of the first extent that can be
2274 * NOCOW, following one which needs to be COW'ed
2276 if (cow_start != (u64)-1) {
2277 ret = fallback_to_cow(inode, locked_page,
2278 cow_start, found_key.offset - 1);
2281 cow_start = (u64)-1;
2284 nocow_end = cur_offset + nocow_args.num_bytes - 1;
2285 is_prealloc = extent_type == BTRFS_FILE_EXTENT_PREALLOC;
2287 u64 orig_start = found_key.offset - nocow_args.extent_offset;
2288 struct extent_map *em;
2290 em = create_io_em(inode, cur_offset, nocow_args.num_bytes,
2292 nocow_args.disk_bytenr, /* block_start */
2293 nocow_args.num_bytes, /* block_len */
2294 nocow_args.disk_num_bytes, /* orig_block_len */
2295 ram_bytes, BTRFS_COMPRESS_NONE,
2296 BTRFS_ORDERED_PREALLOC);
2301 free_extent_map(em);
2304 ordered = btrfs_alloc_ordered_extent(inode, cur_offset,
2305 nocow_args.num_bytes, nocow_args.num_bytes,
2306 nocow_args.disk_bytenr, nocow_args.num_bytes, 0,
2308 ? (1 << BTRFS_ORDERED_PREALLOC)
2309 : (1 << BTRFS_ORDERED_NOCOW),
2310 BTRFS_COMPRESS_NONE);
2311 if (IS_ERR(ordered)) {
2313 btrfs_drop_extent_map_range(inode, cur_offset,
2316 ret = PTR_ERR(ordered);
2321 btrfs_dec_nocow_writers(bg);
2325 if (btrfs_is_data_reloc_root(root))
2327 * Error handled later, as we must prevent
2328 * extent_clear_unlock_delalloc() in error handler
2329 * from freeing metadata of created ordered extent.
2331 ret = btrfs_reloc_clone_csums(ordered);
2332 btrfs_put_ordered_extent(ordered);
2334 extent_clear_unlock_delalloc(inode, cur_offset, nocow_end,
2335 locked_page, EXTENT_LOCKED |
2337 EXTENT_CLEAR_DATA_RESV,
2338 PAGE_UNLOCK | PAGE_SET_ORDERED);
2340 cur_offset = extent_end;
2343 * btrfs_reloc_clone_csums() error, now we're OK to call error
2344 * handler, as metadata for created ordered extent will only
2345 * be freed by btrfs_finish_ordered_io().
2349 if (cur_offset > end)
2352 btrfs_release_path(path);
2354 if (cur_offset <= end && cow_start == (u64)-1)
2355 cow_start = cur_offset;
2357 if (cow_start != (u64)-1) {
2359 ret = fallback_to_cow(inode, locked_page, cow_start, end);
2366 btrfs_dec_nocow_writers(bg);
2368 if (ret && cur_offset < end)
2369 extent_clear_unlock_delalloc(inode, cur_offset, end,
2370 locked_page, EXTENT_LOCKED |
2371 EXTENT_DELALLOC | EXTENT_DEFRAG |
2372 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
2373 PAGE_START_WRITEBACK |
2374 PAGE_END_WRITEBACK);
2375 btrfs_free_path(path);
2379 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
2381 if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
2382 if (inode->defrag_bytes &&
2383 test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
2392 * Function to process delayed allocation (create CoW) for ranges which are
2393 * being touched for the first time.
2395 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
2396 u64 start, u64 end, int *page_started, unsigned long *nr_written,
2397 struct writeback_control *wbc)
2400 const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2403 * The range must cover part of the @locked_page, or the returned
2404 * @page_started can confuse the caller.
2406 ASSERT(!(end <= page_offset(locked_page) ||
2407 start >= page_offset(locked_page) + PAGE_SIZE));
2409 if (should_nocow(inode, start, end)) {
2411 * Normally on a zoned device we're only doing COW writes, but
2412 * in case of relocation on a zoned filesystem we have taken
2413 * precaution, that we're only writing sequentially. It's safe
2414 * to use run_delalloc_nocow() here, like for regular
2415 * preallocated inodes.
2417 ASSERT(!zoned || btrfs_is_data_reloc_root(inode->root));
2418 ret = run_delalloc_nocow(inode, locked_page, start, end);
2422 if (btrfs_inode_can_compress(inode) &&
2423 inode_need_compress(inode, start, end) &&
2424 run_delalloc_compressed(inode, wbc, locked_page, start,
2425 end, page_started, nr_written))
2429 ret = run_delalloc_zoned(inode, locked_page, start, end,
2430 page_started, nr_written, wbc);
2432 ret = cow_file_range(inode, locked_page, start, end,
2433 page_started, nr_written, NULL, false, false);
2438 btrfs_cleanup_ordered_extents(inode, locked_page, start,
2443 void btrfs_split_delalloc_extent(struct btrfs_inode *inode,
2444 struct extent_state *orig, u64 split)
2446 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2449 /* not delalloc, ignore it */
2450 if (!(orig->state & EXTENT_DELALLOC))
2453 size = orig->end - orig->start + 1;
2454 if (size > fs_info->max_extent_size) {
2459 * See the explanation in btrfs_merge_delalloc_extent, the same
2460 * applies here, just in reverse.
2462 new_size = orig->end - split + 1;
2463 num_extents = count_max_extents(fs_info, new_size);
2464 new_size = split - orig->start;
2465 num_extents += count_max_extents(fs_info, new_size);
2466 if (count_max_extents(fs_info, size) >= num_extents)
2470 spin_lock(&inode->lock);
2471 btrfs_mod_outstanding_extents(inode, 1);
2472 spin_unlock(&inode->lock);
2476 * Handle merged delayed allocation extents so we can keep track of new extents
2477 * that are just merged onto old extents, such as when we are doing sequential
2478 * writes, so we can properly account for the metadata space we'll need.
2480 void btrfs_merge_delalloc_extent(struct btrfs_inode *inode, struct extent_state *new,
2481 struct extent_state *other)
2483 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2484 u64 new_size, old_size;
2487 /* not delalloc, ignore it */
2488 if (!(other->state & EXTENT_DELALLOC))
2491 if (new->start > other->start)
2492 new_size = new->end - other->start + 1;
2494 new_size = other->end - new->start + 1;
2496 /* we're not bigger than the max, unreserve the space and go */
2497 if (new_size <= fs_info->max_extent_size) {
2498 spin_lock(&inode->lock);
2499 btrfs_mod_outstanding_extents(inode, -1);
2500 spin_unlock(&inode->lock);
2505 * We have to add up either side to figure out how many extents were
2506 * accounted for before we merged into one big extent. If the number of
2507 * extents we accounted for is <= the amount we need for the new range
2508 * then we can return, otherwise drop. Think of it like this
2512 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2513 * need 2 outstanding extents, on one side we have 1 and the other side
2514 * we have 1 so they are == and we can return. But in this case
2516 * [MAX_SIZE+4k][MAX_SIZE+4k]
2518 * Each range on their own accounts for 2 extents, but merged together
2519 * they are only 3 extents worth of accounting, so we need to drop in
2522 old_size = other->end - other->start + 1;
2523 num_extents = count_max_extents(fs_info, old_size);
2524 old_size = new->end - new->start + 1;
2525 num_extents += count_max_extents(fs_info, old_size);
2526 if (count_max_extents(fs_info, new_size) >= num_extents)
2529 spin_lock(&inode->lock);
2530 btrfs_mod_outstanding_extents(inode, -1);
2531 spin_unlock(&inode->lock);
2534 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2535 struct btrfs_inode *inode)
2537 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2539 spin_lock(&root->delalloc_lock);
2540 if (list_empty(&inode->delalloc_inodes)) {
2541 list_add_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
2542 set_bit(BTRFS_INODE_IN_DELALLOC_LIST, &inode->runtime_flags);
2543 root->nr_delalloc_inodes++;
2544 if (root->nr_delalloc_inodes == 1) {
2545 spin_lock(&fs_info->delalloc_root_lock);
2546 BUG_ON(!list_empty(&root->delalloc_root));
2547 list_add_tail(&root->delalloc_root,
2548 &fs_info->delalloc_roots);
2549 spin_unlock(&fs_info->delalloc_root_lock);
2552 spin_unlock(&root->delalloc_lock);
2555 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2556 struct btrfs_inode *inode)
2558 struct btrfs_fs_info *fs_info = root->fs_info;
2560 if (!list_empty(&inode->delalloc_inodes)) {
2561 list_del_init(&inode->delalloc_inodes);
2562 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2563 &inode->runtime_flags);
2564 root->nr_delalloc_inodes--;
2565 if (!root->nr_delalloc_inodes) {
2566 ASSERT(list_empty(&root->delalloc_inodes));
2567 spin_lock(&fs_info->delalloc_root_lock);
2568 BUG_ON(list_empty(&root->delalloc_root));
2569 list_del_init(&root->delalloc_root);
2570 spin_unlock(&fs_info->delalloc_root_lock);
2575 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2576 struct btrfs_inode *inode)
2578 spin_lock(&root->delalloc_lock);
2579 __btrfs_del_delalloc_inode(root, inode);
2580 spin_unlock(&root->delalloc_lock);
2584 * Properly track delayed allocation bytes in the inode and to maintain the
2585 * list of inodes that have pending delalloc work to be done.
2587 void btrfs_set_delalloc_extent(struct btrfs_inode *inode, struct extent_state *state,
2590 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2592 if ((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC))
2595 * set_bit and clear bit hooks normally require _irqsave/restore
2596 * but in this case, we are only testing for the DELALLOC
2597 * bit, which is only set or cleared with irqs on
2599 if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2600 struct btrfs_root *root = inode->root;
2601 u64 len = state->end + 1 - state->start;
2602 u32 num_extents = count_max_extents(fs_info, len);
2603 bool do_list = !btrfs_is_free_space_inode(inode);
2605 spin_lock(&inode->lock);
2606 btrfs_mod_outstanding_extents(inode, num_extents);
2607 spin_unlock(&inode->lock);
2609 /* For sanity tests */
2610 if (btrfs_is_testing(fs_info))
2613 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2614 fs_info->delalloc_batch);
2615 spin_lock(&inode->lock);
2616 inode->delalloc_bytes += len;
2617 if (bits & EXTENT_DEFRAG)
2618 inode->defrag_bytes += len;
2619 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2620 &inode->runtime_flags))
2621 btrfs_add_delalloc_inodes(root, inode);
2622 spin_unlock(&inode->lock);
2625 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2626 (bits & EXTENT_DELALLOC_NEW)) {
2627 spin_lock(&inode->lock);
2628 inode->new_delalloc_bytes += state->end + 1 - state->start;
2629 spin_unlock(&inode->lock);
2634 * Once a range is no longer delalloc this function ensures that proper
2635 * accounting happens.
2637 void btrfs_clear_delalloc_extent(struct btrfs_inode *inode,
2638 struct extent_state *state, u32 bits)
2640 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2641 u64 len = state->end + 1 - state->start;
2642 u32 num_extents = count_max_extents(fs_info, len);
2644 if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
2645 spin_lock(&inode->lock);
2646 inode->defrag_bytes -= len;
2647 spin_unlock(&inode->lock);
2651 * set_bit and clear bit hooks normally require _irqsave/restore
2652 * but in this case, we are only testing for the DELALLOC
2653 * bit, which is only set or cleared with irqs on
2655 if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2656 struct btrfs_root *root = inode->root;
2657 bool do_list = !btrfs_is_free_space_inode(inode);
2659 spin_lock(&inode->lock);
2660 btrfs_mod_outstanding_extents(inode, -num_extents);
2661 spin_unlock(&inode->lock);
2664 * We don't reserve metadata space for space cache inodes so we
2665 * don't need to call delalloc_release_metadata if there is an
2668 if (bits & EXTENT_CLEAR_META_RESV &&
2669 root != fs_info->tree_root)
2670 btrfs_delalloc_release_metadata(inode, len, false);
2672 /* For sanity tests. */
2673 if (btrfs_is_testing(fs_info))
2676 if (!btrfs_is_data_reloc_root(root) &&
2677 do_list && !(state->state & EXTENT_NORESERVE) &&
2678 (bits & EXTENT_CLEAR_DATA_RESV))
2679 btrfs_free_reserved_data_space_noquota(fs_info, len);
2681 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2682 fs_info->delalloc_batch);
2683 spin_lock(&inode->lock);
2684 inode->delalloc_bytes -= len;
2685 if (do_list && inode->delalloc_bytes == 0 &&
2686 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2687 &inode->runtime_flags))
2688 btrfs_del_delalloc_inode(root, inode);
2689 spin_unlock(&inode->lock);
2692 if ((state->state & EXTENT_DELALLOC_NEW) &&
2693 (bits & EXTENT_DELALLOC_NEW)) {
2694 spin_lock(&inode->lock);
2695 ASSERT(inode->new_delalloc_bytes >= len);
2696 inode->new_delalloc_bytes -= len;
2697 if (bits & EXTENT_ADD_INODE_BYTES)
2698 inode_add_bytes(&inode->vfs_inode, len);
2699 spin_unlock(&inode->lock);
2703 static int btrfs_extract_ordered_extent(struct btrfs_bio *bbio,
2704 struct btrfs_ordered_extent *ordered)
2706 u64 start = (u64)bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT;
2707 u64 len = bbio->bio.bi_iter.bi_size;
2708 struct btrfs_ordered_extent *new;
2711 /* Must always be called for the beginning of an ordered extent. */
2712 if (WARN_ON_ONCE(start != ordered->disk_bytenr))
2715 /* No need to split if the ordered extent covers the entire bio. */
2716 if (ordered->disk_num_bytes == len) {
2717 refcount_inc(&ordered->refs);
2718 bbio->ordered = ordered;
2723 * Don't split the extent_map for NOCOW extents, as we're writing into
2724 * a pre-existing one.
2726 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
2727 ret = split_extent_map(bbio->inode, bbio->file_offset,
2728 ordered->num_bytes, len,
2729 ordered->disk_bytenr);
2734 new = btrfs_split_ordered_extent(ordered, len);
2736 return PTR_ERR(new);
2737 bbio->ordered = new;
2742 * given a list of ordered sums record them in the inode. This happens
2743 * at IO completion time based on sums calculated at bio submission time.
2745 static int add_pending_csums(struct btrfs_trans_handle *trans,
2746 struct list_head *list)
2748 struct btrfs_ordered_sum *sum;
2749 struct btrfs_root *csum_root = NULL;
2752 list_for_each_entry(sum, list, list) {
2753 trans->adding_csums = true;
2755 csum_root = btrfs_csum_root(trans->fs_info,
2757 ret = btrfs_csum_file_blocks(trans, csum_root, sum);
2758 trans->adding_csums = false;
2765 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2768 struct extent_state **cached_state)
2770 u64 search_start = start;
2771 const u64 end = start + len - 1;
2773 while (search_start < end) {
2774 const u64 search_len = end - search_start + 1;
2775 struct extent_map *em;
2779 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2783 if (em->block_start != EXTENT_MAP_HOLE)
2787 if (em->start < search_start)
2788 em_len -= search_start - em->start;
2789 if (em_len > search_len)
2790 em_len = search_len;
2792 ret = set_extent_bit(&inode->io_tree, search_start,
2793 search_start + em_len - 1,
2794 EXTENT_DELALLOC_NEW, cached_state);
2796 search_start = extent_map_end(em);
2797 free_extent_map(em);
2804 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2805 unsigned int extra_bits,
2806 struct extent_state **cached_state)
2808 WARN_ON(PAGE_ALIGNED(end));
2810 if (start >= i_size_read(&inode->vfs_inode) &&
2811 !(inode->flags & BTRFS_INODE_PREALLOC)) {
2813 * There can't be any extents following eof in this case so just
2814 * set the delalloc new bit for the range directly.
2816 extra_bits |= EXTENT_DELALLOC_NEW;
2820 ret = btrfs_find_new_delalloc_bytes(inode, start,
2827 return set_extent_bit(&inode->io_tree, start, end,
2828 EXTENT_DELALLOC | extra_bits, cached_state);
2831 /* see btrfs_writepage_start_hook for details on why this is required */
2832 struct btrfs_writepage_fixup {
2834 struct btrfs_inode *inode;
2835 struct btrfs_work work;
2838 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2840 struct btrfs_writepage_fixup *fixup;
2841 struct btrfs_ordered_extent *ordered;
2842 struct extent_state *cached_state = NULL;
2843 struct extent_changeset *data_reserved = NULL;
2845 struct btrfs_inode *inode;
2849 bool free_delalloc_space = true;
2851 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2853 inode = fixup->inode;
2854 page_start = page_offset(page);
2855 page_end = page_offset(page) + PAGE_SIZE - 1;
2858 * This is similar to page_mkwrite, we need to reserve the space before
2859 * we take the page lock.
2861 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2867 * Before we queued this fixup, we took a reference on the page.
2868 * page->mapping may go NULL, but it shouldn't be moved to a different
2871 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2873 * Unfortunately this is a little tricky, either
2875 * 1) We got here and our page had already been dealt with and
2876 * we reserved our space, thus ret == 0, so we need to just
2877 * drop our space reservation and bail. This can happen the
2878 * first time we come into the fixup worker, or could happen
2879 * while waiting for the ordered extent.
2880 * 2) Our page was already dealt with, but we happened to get an
2881 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2882 * this case we obviously don't have anything to release, but
2883 * because the page was already dealt with we don't want to
2884 * mark the page with an error, so make sure we're resetting
2885 * ret to 0. This is why we have this check _before_ the ret
2886 * check, because we do not want to have a surprise ENOSPC
2887 * when the page was already properly dealt with.
2890 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2891 btrfs_delalloc_release_space(inode, data_reserved,
2892 page_start, PAGE_SIZE,
2900 * We can't mess with the page state unless it is locked, so now that
2901 * it is locked bail if we failed to make our space reservation.
2906 lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2908 /* already ordered? We're done */
2909 if (PageOrdered(page))
2912 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2914 unlock_extent(&inode->io_tree, page_start, page_end,
2917 btrfs_start_ordered_extent(ordered);
2918 btrfs_put_ordered_extent(ordered);
2922 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2928 * Everything went as planned, we're now the owner of a dirty page with
2929 * delayed allocation bits set and space reserved for our COW
2932 * The page was dirty when we started, nothing should have cleaned it.
2934 BUG_ON(!PageDirty(page));
2935 free_delalloc_space = false;
2937 btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2938 if (free_delalloc_space)
2939 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2941 unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2945 * We hit ENOSPC or other errors. Update the mapping and page
2946 * to reflect the errors and clean the page.
2948 mapping_set_error(page->mapping, ret);
2949 end_extent_writepage(page, ret, page_start, page_end);
2950 clear_page_dirty_for_io(page);
2952 btrfs_page_clear_checked(inode->root->fs_info, page, page_start, PAGE_SIZE);
2956 extent_changeset_free(data_reserved);
2958 * As a precaution, do a delayed iput in case it would be the last iput
2959 * that could need flushing space. Recursing back to fixup worker would
2962 btrfs_add_delayed_iput(inode);
2966 * There are a few paths in the higher layers of the kernel that directly
2967 * set the page dirty bit without asking the filesystem if it is a
2968 * good idea. This causes problems because we want to make sure COW
2969 * properly happens and the data=ordered rules are followed.
2971 * In our case any range that doesn't have the ORDERED bit set
2972 * hasn't been properly setup for IO. We kick off an async process
2973 * to fix it up. The async helper will wait for ordered extents, set
2974 * the delalloc bit and make it safe to write the page.
2976 int btrfs_writepage_cow_fixup(struct page *page)
2978 struct inode *inode = page->mapping->host;
2979 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2980 struct btrfs_writepage_fixup *fixup;
2982 /* This page has ordered extent covering it already */
2983 if (PageOrdered(page))
2987 * PageChecked is set below when we create a fixup worker for this page,
2988 * don't try to create another one if we're already PageChecked()
2990 * The extent_io writepage code will redirty the page if we send back
2993 if (PageChecked(page))
2996 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
3001 * We are already holding a reference to this inode from
3002 * write_cache_pages. We need to hold it because the space reservation
3003 * takes place outside of the page lock, and we can't trust
3004 * page->mapping outside of the page lock.
3007 btrfs_page_set_checked(fs_info, page, page_offset(page), PAGE_SIZE);
3009 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
3011 fixup->inode = BTRFS_I(inode);
3012 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
3017 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
3018 struct btrfs_inode *inode, u64 file_pos,
3019 struct btrfs_file_extent_item *stack_fi,
3020 const bool update_inode_bytes,
3021 u64 qgroup_reserved)
3023 struct btrfs_root *root = inode->root;
3024 const u64 sectorsize = root->fs_info->sectorsize;
3025 struct btrfs_path *path;
3026 struct extent_buffer *leaf;
3027 struct btrfs_key ins;
3028 u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
3029 u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
3030 u64 offset = btrfs_stack_file_extent_offset(stack_fi);
3031 u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
3032 u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
3033 struct btrfs_drop_extents_args drop_args = { 0 };
3036 path = btrfs_alloc_path();
3041 * we may be replacing one extent in the tree with another.
3042 * The new extent is pinned in the extent map, and we don't want
3043 * to drop it from the cache until it is completely in the btree.
3045 * So, tell btrfs_drop_extents to leave this extent in the cache.
3046 * the caller is expected to unpin it and allow it to be merged
3049 drop_args.path = path;
3050 drop_args.start = file_pos;
3051 drop_args.end = file_pos + num_bytes;
3052 drop_args.replace_extent = true;
3053 drop_args.extent_item_size = sizeof(*stack_fi);
3054 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
3058 if (!drop_args.extent_inserted) {
3059 ins.objectid = btrfs_ino(inode);
3060 ins.offset = file_pos;
3061 ins.type = BTRFS_EXTENT_DATA_KEY;
3063 ret = btrfs_insert_empty_item(trans, root, path, &ins,
3068 leaf = path->nodes[0];
3069 btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
3070 write_extent_buffer(leaf, stack_fi,
3071 btrfs_item_ptr_offset(leaf, path->slots[0]),
3072 sizeof(struct btrfs_file_extent_item));
3074 btrfs_mark_buffer_dirty(leaf);
3075 btrfs_release_path(path);
3078 * If we dropped an inline extent here, we know the range where it is
3079 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
3080 * number of bytes only for that range containing the inline extent.
3081 * The remaining of the range will be processed when clearning the
3082 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
3084 if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
3085 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
3087 inline_size = drop_args.bytes_found - inline_size;
3088 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
3089 drop_args.bytes_found -= inline_size;
3090 num_bytes -= sectorsize;
3093 if (update_inode_bytes)
3094 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
3096 ins.objectid = disk_bytenr;
3097 ins.offset = disk_num_bytes;
3098 ins.type = BTRFS_EXTENT_ITEM_KEY;
3100 ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
3104 ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
3106 qgroup_reserved, &ins);
3108 btrfs_free_path(path);
3113 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
3116 struct btrfs_block_group *cache;
3118 cache = btrfs_lookup_block_group(fs_info, start);
3121 spin_lock(&cache->lock);
3122 cache->delalloc_bytes -= len;
3123 spin_unlock(&cache->lock);
3125 btrfs_put_block_group(cache);
3128 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
3129 struct btrfs_ordered_extent *oe)
3131 struct btrfs_file_extent_item stack_fi;
3132 bool update_inode_bytes;
3133 u64 num_bytes = oe->num_bytes;
3134 u64 ram_bytes = oe->ram_bytes;
3136 memset(&stack_fi, 0, sizeof(stack_fi));
3137 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
3138 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
3139 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
3140 oe->disk_num_bytes);
3141 btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
3142 if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags)) {
3143 num_bytes = oe->truncated_len;
3144 ram_bytes = num_bytes;
3146 btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
3147 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
3148 btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3149 /* Encryption and other encoding is reserved and all 0 */
3152 * For delalloc, when completing an ordered extent we update the inode's
3153 * bytes when clearing the range in the inode's io tree, so pass false
3154 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3155 * except if the ordered extent was truncated.
3157 update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3158 test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
3159 test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3161 return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
3162 oe->file_offset, &stack_fi,
3163 update_inode_bytes, oe->qgroup_rsv);
3167 * As ordered data IO finishes, this gets called so we can finish
3168 * an ordered extent if the range of bytes in the file it covers are
3171 int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
3173 struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
3174 struct btrfs_root *root = inode->root;
3175 struct btrfs_fs_info *fs_info = root->fs_info;
3176 struct btrfs_trans_handle *trans = NULL;
3177 struct extent_io_tree *io_tree = &inode->io_tree;
3178 struct extent_state *cached_state = NULL;
3180 int compress_type = 0;
3182 u64 logical_len = ordered_extent->num_bytes;
3183 bool freespace_inode;
3184 bool truncated = false;
3185 bool clear_reserved_extent = true;
3186 unsigned int clear_bits = EXTENT_DEFRAG;
3188 start = ordered_extent->file_offset;
3189 end = start + ordered_extent->num_bytes - 1;
3191 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3192 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3193 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3194 !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3195 clear_bits |= EXTENT_DELALLOC_NEW;
3197 freespace_inode = btrfs_is_free_space_inode(inode);
3198 if (!freespace_inode)
3199 btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
3201 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3206 if (btrfs_is_zoned(fs_info))
3207 btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3208 ordered_extent->disk_num_bytes);
3210 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3212 logical_len = ordered_extent->truncated_len;
3213 /* Truncated the entire extent, don't bother adding */
3218 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3219 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3221 btrfs_inode_safe_disk_i_size_write(inode, 0);
3222 if (freespace_inode)
3223 trans = btrfs_join_transaction_spacecache(root);
3225 trans = btrfs_join_transaction(root);
3226 if (IS_ERR(trans)) {
3227 ret = PTR_ERR(trans);
3231 trans->block_rsv = &inode->block_rsv;
3232 ret = btrfs_update_inode_fallback(trans, root, inode);
3233 if (ret) /* -ENOMEM or corruption */
3234 btrfs_abort_transaction(trans, ret);
3238 clear_bits |= EXTENT_LOCKED;
3239 lock_extent(io_tree, start, end, &cached_state);
3241 if (freespace_inode)
3242 trans = btrfs_join_transaction_spacecache(root);
3244 trans = btrfs_join_transaction(root);
3245 if (IS_ERR(trans)) {
3246 ret = PTR_ERR(trans);
3251 trans->block_rsv = &inode->block_rsv;
3253 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3254 compress_type = ordered_extent->compress_type;
3255 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3256 BUG_ON(compress_type);
3257 ret = btrfs_mark_extent_written(trans, inode,
3258 ordered_extent->file_offset,
3259 ordered_extent->file_offset +
3261 btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3262 ordered_extent->disk_num_bytes);
3264 BUG_ON(root == fs_info->tree_root);
3265 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3267 clear_reserved_extent = false;
3268 btrfs_release_delalloc_bytes(fs_info,
3269 ordered_extent->disk_bytenr,
3270 ordered_extent->disk_num_bytes);
3273 unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3274 ordered_extent->num_bytes, trans->transid);
3276 btrfs_abort_transaction(trans, ret);
3280 ret = add_pending_csums(trans, &ordered_extent->list);
3282 btrfs_abort_transaction(trans, ret);
3287 * If this is a new delalloc range, clear its new delalloc flag to
3288 * update the inode's number of bytes. This needs to be done first
3289 * before updating the inode item.
3291 if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3292 !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3293 clear_extent_bit(&inode->io_tree, start, end,
3294 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3297 btrfs_inode_safe_disk_i_size_write(inode, 0);
3298 ret = btrfs_update_inode_fallback(trans, root, inode);
3299 if (ret) { /* -ENOMEM or corruption */
3300 btrfs_abort_transaction(trans, ret);
3305 clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3309 btrfs_end_transaction(trans);
3311 if (ret || truncated) {
3312 u64 unwritten_start = start;
3315 * If we failed to finish this ordered extent for any reason we
3316 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3317 * extent, and mark the inode with the error if it wasn't
3318 * already set. Any error during writeback would have already
3319 * set the mapping error, so we need to set it if we're the ones
3320 * marking this ordered extent as failed.
3322 if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3323 &ordered_extent->flags))
3324 mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3327 unwritten_start += logical_len;
3328 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3330 /* Drop extent maps for the part of the extent we didn't write. */
3331 btrfs_drop_extent_map_range(inode, unwritten_start, end, false);
3334 * If the ordered extent had an IOERR or something else went
3335 * wrong we need to return the space for this ordered extent
3336 * back to the allocator. We only free the extent in the
3337 * truncated case if we didn't write out the extent at all.
3339 * If we made it past insert_reserved_file_extent before we
3340 * errored out then we don't need to do this as the accounting
3341 * has already been done.
3343 if ((ret || !logical_len) &&
3344 clear_reserved_extent &&
3345 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3346 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3348 * Discard the range before returning it back to the
3351 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3352 btrfs_discard_extent(fs_info,
3353 ordered_extent->disk_bytenr,
3354 ordered_extent->disk_num_bytes,
3356 btrfs_free_reserved_extent(fs_info,
3357 ordered_extent->disk_bytenr,
3358 ordered_extent->disk_num_bytes, 1);
3360 * Actually free the qgroup rsv which was released when
3361 * the ordered extent was created.
3363 btrfs_qgroup_free_refroot(fs_info, inode->root->root_key.objectid,
3364 ordered_extent->qgroup_rsv,
3365 BTRFS_QGROUP_RSV_DATA);
3370 * This needs to be done to make sure anybody waiting knows we are done
3371 * updating everything for this ordered extent.
3373 btrfs_remove_ordered_extent(inode, ordered_extent);
3376 btrfs_put_ordered_extent(ordered_extent);
3377 /* once for the tree */
3378 btrfs_put_ordered_extent(ordered_extent);
3383 int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered)
3385 if (btrfs_is_zoned(btrfs_sb(ordered->inode->i_sb)) &&
3386 !test_bit(BTRFS_ORDERED_IOERR, &ordered->flags))
3387 btrfs_finish_ordered_zoned(ordered);
3388 return btrfs_finish_one_ordered(ordered);
3391 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3392 struct page *page, u64 start,
3393 u64 end, bool uptodate)
3395 trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3397 btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start, uptodate);
3401 * Verify the checksum for a single sector without any extra action that depend
3402 * on the type of I/O.
3404 int btrfs_check_sector_csum(struct btrfs_fs_info *fs_info, struct page *page,
3405 u32 pgoff, u8 *csum, const u8 * const csum_expected)
3407 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3410 ASSERT(pgoff + fs_info->sectorsize <= PAGE_SIZE);
3412 shash->tfm = fs_info->csum_shash;
3414 kaddr = kmap_local_page(page) + pgoff;
3415 crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
3416 kunmap_local(kaddr);
3418 if (memcmp(csum, csum_expected, fs_info->csum_size))
3424 * Verify the checksum of a single data sector.
3426 * @bbio: btrfs_io_bio which contains the csum
3427 * @dev: device the sector is on
3428 * @bio_offset: offset to the beginning of the bio (in bytes)
3429 * @bv: bio_vec to check
3431 * Check if the checksum on a data block is valid. When a checksum mismatch is
3432 * detected, report the error and fill the corrupted range with zero.
3434 * Return %true if the sector is ok or had no checksum to start with, else %false.
3436 bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev,
3437 u32 bio_offset, struct bio_vec *bv)
3439 struct btrfs_inode *inode = bbio->inode;
3440 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3441 u64 file_offset = bbio->file_offset + bio_offset;
3442 u64 end = file_offset + bv->bv_len - 1;
3444 u8 csum[BTRFS_CSUM_SIZE];
3446 ASSERT(bv->bv_len == fs_info->sectorsize);
3451 if (btrfs_is_data_reloc_root(inode->root) &&
3452 test_range_bit(&inode->io_tree, file_offset, end, EXTENT_NODATASUM,
3454 /* Skip the range without csum for data reloc inode */
3455 clear_extent_bits(&inode->io_tree, file_offset, end,
3460 csum_expected = bbio->csum + (bio_offset >> fs_info->sectorsize_bits) *
3462 if (btrfs_check_sector_csum(fs_info, bv->bv_page, bv->bv_offset, csum,
3468 btrfs_print_data_csum_error(inode, file_offset, csum, csum_expected,
3471 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
3477 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3479 * @inode: The inode we want to perform iput on
3481 * This function uses the generic vfs_inode::i_count to track whether we should
3482 * just decrement it (in case it's > 1) or if this is the last iput then link
3483 * the inode to the delayed iput machinery. Delayed iputs are processed at
3484 * transaction commit time/superblock commit/cleaner kthread.
3486 void btrfs_add_delayed_iput(struct btrfs_inode *inode)
3488 struct btrfs_fs_info *fs_info = inode->root->fs_info;
3489 unsigned long flags;
3491 if (atomic_add_unless(&inode->vfs_inode.i_count, -1, 1))
3494 atomic_inc(&fs_info->nr_delayed_iputs);
3496 * Need to be irq safe here because we can be called from either an irq
3497 * context (see bio.c and btrfs_put_ordered_extent()) or a non-irq
3500 spin_lock_irqsave(&fs_info->delayed_iput_lock, flags);
3501 ASSERT(list_empty(&inode->delayed_iput));
3502 list_add_tail(&inode->delayed_iput, &fs_info->delayed_iputs);
3503 spin_unlock_irqrestore(&fs_info->delayed_iput_lock, flags);
3504 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3505 wake_up_process(fs_info->cleaner_kthread);
3508 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3509 struct btrfs_inode *inode)
3511 list_del_init(&inode->delayed_iput);
3512 spin_unlock_irq(&fs_info->delayed_iput_lock);
3513 iput(&inode->vfs_inode);
3514 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3515 wake_up(&fs_info->delayed_iputs_wait);
3516 spin_lock_irq(&fs_info->delayed_iput_lock);
3519 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3520 struct btrfs_inode *inode)
3522 if (!list_empty(&inode->delayed_iput)) {
3523 spin_lock_irq(&fs_info->delayed_iput_lock);
3524 if (!list_empty(&inode->delayed_iput))
3525 run_delayed_iput_locked(fs_info, inode);
3526 spin_unlock_irq(&fs_info->delayed_iput_lock);
3530 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3533 * btrfs_put_ordered_extent() can run in irq context (see bio.c), which
3534 * calls btrfs_add_delayed_iput() and that needs to lock
3535 * fs_info->delayed_iput_lock. So we need to disable irqs here to
3536 * prevent a deadlock.
3538 spin_lock_irq(&fs_info->delayed_iput_lock);
3539 while (!list_empty(&fs_info->delayed_iputs)) {
3540 struct btrfs_inode *inode;
3542 inode = list_first_entry(&fs_info->delayed_iputs,
3543 struct btrfs_inode, delayed_iput);
3544 run_delayed_iput_locked(fs_info, inode);
3545 if (need_resched()) {
3546 spin_unlock_irq(&fs_info->delayed_iput_lock);
3548 spin_lock_irq(&fs_info->delayed_iput_lock);
3551 spin_unlock_irq(&fs_info->delayed_iput_lock);
3555 * Wait for flushing all delayed iputs
3557 * @fs_info: the filesystem
3559 * This will wait on any delayed iputs that are currently running with KILLABLE
3560 * set. Once they are all done running we will return, unless we are killed in
3561 * which case we return EINTR. This helps in user operations like fallocate etc
3562 * that might get blocked on the iputs.
3564 * Return EINTR if we were killed, 0 if nothing's pending
3566 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3568 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3569 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3576 * This creates an orphan entry for the given inode in case something goes wrong
3577 * in the middle of an unlink.
3579 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3580 struct btrfs_inode *inode)
3584 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3585 if (ret && ret != -EEXIST) {
3586 btrfs_abort_transaction(trans, ret);
3594 * We have done the delete so we can go ahead and remove the orphan item for
3595 * this particular inode.
3597 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3598 struct btrfs_inode *inode)
3600 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3604 * this cleans up any orphans that may be left on the list from the last use
3607 int btrfs_orphan_cleanup(struct btrfs_root *root)
3609 struct btrfs_fs_info *fs_info = root->fs_info;
3610 struct btrfs_path *path;
3611 struct extent_buffer *leaf;
3612 struct btrfs_key key, found_key;
3613 struct btrfs_trans_handle *trans;
3614 struct inode *inode;
3615 u64 last_objectid = 0;
3616 int ret = 0, nr_unlink = 0;
3618 if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3621 path = btrfs_alloc_path();
3626 path->reada = READA_BACK;
3628 key.objectid = BTRFS_ORPHAN_OBJECTID;
3629 key.type = BTRFS_ORPHAN_ITEM_KEY;
3630 key.offset = (u64)-1;
3633 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3638 * if ret == 0 means we found what we were searching for, which
3639 * is weird, but possible, so only screw with path if we didn't
3640 * find the key and see if we have stuff that matches
3644 if (path->slots[0] == 0)
3649 /* pull out the item */
3650 leaf = path->nodes[0];
3651 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3653 /* make sure the item matches what we want */
3654 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3656 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3659 /* release the path since we're done with it */
3660 btrfs_release_path(path);
3663 * this is where we are basically btrfs_lookup, without the
3664 * crossing root thing. we store the inode number in the
3665 * offset of the orphan item.
3668 if (found_key.offset == last_objectid) {
3670 "Error removing orphan entry, stopping orphan cleanup");
3675 last_objectid = found_key.offset;
3677 found_key.objectid = found_key.offset;
3678 found_key.type = BTRFS_INODE_ITEM_KEY;
3679 found_key.offset = 0;
3680 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3681 if (IS_ERR(inode)) {
3682 ret = PTR_ERR(inode);
3688 if (!inode && root == fs_info->tree_root) {
3689 struct btrfs_root *dead_root;
3690 int is_dead_root = 0;
3693 * This is an orphan in the tree root. Currently these
3694 * could come from 2 sources:
3695 * a) a root (snapshot/subvolume) deletion in progress
3696 * b) a free space cache inode
3697 * We need to distinguish those two, as the orphan item
3698 * for a root must not get deleted before the deletion
3699 * of the snapshot/subvolume's tree completes.
3701 * btrfs_find_orphan_roots() ran before us, which has
3702 * found all deleted roots and loaded them into
3703 * fs_info->fs_roots_radix. So here we can find if an
3704 * orphan item corresponds to a deleted root by looking
3705 * up the root from that radix tree.
3708 spin_lock(&fs_info->fs_roots_radix_lock);
3709 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3710 (unsigned long)found_key.objectid);
3711 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3713 spin_unlock(&fs_info->fs_roots_radix_lock);
3716 /* prevent this orphan from being found again */
3717 key.offset = found_key.objectid - 1;
3724 * If we have an inode with links, there are a couple of
3727 * 1. We were halfway through creating fsverity metadata for the
3728 * file. In that case, the orphan item represents incomplete
3729 * fsverity metadata which must be cleaned up with
3730 * btrfs_drop_verity_items and deleting the orphan item.
3732 * 2. Old kernels (before v3.12) used to create an
3733 * orphan item for truncate indicating that there were possibly
3734 * extent items past i_size that needed to be deleted. In v3.12,
3735 * truncate was changed to update i_size in sync with the extent
3736 * items, but the (useless) orphan item was still created. Since
3737 * v4.18, we don't create the orphan item for truncate at all.
3739 * So, this item could mean that we need to do a truncate, but
3740 * only if this filesystem was last used on a pre-v3.12 kernel
3741 * and was not cleanly unmounted. The odds of that are quite
3742 * slim, and it's a pain to do the truncate now, so just delete
3745 * It's also possible that this orphan item was supposed to be
3746 * deleted but wasn't. The inode number may have been reused,
3747 * but either way, we can delete the orphan item.
3749 if (!inode || inode->i_nlink) {
3751 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3757 trans = btrfs_start_transaction(root, 1);
3758 if (IS_ERR(trans)) {
3759 ret = PTR_ERR(trans);
3762 btrfs_debug(fs_info, "auto deleting %Lu",
3763 found_key.objectid);
3764 ret = btrfs_del_orphan_item(trans, root,
3765 found_key.objectid);
3766 btrfs_end_transaction(trans);
3774 /* this will do delete_inode and everything for us */
3777 /* release the path since we're done with it */
3778 btrfs_release_path(path);
3780 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3781 trans = btrfs_join_transaction(root);
3783 btrfs_end_transaction(trans);
3787 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3791 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3792 btrfs_free_path(path);
3797 * very simple check to peek ahead in the leaf looking for xattrs. If we
3798 * don't find any xattrs, we know there can't be any acls.
3800 * slot is the slot the inode is in, objectid is the objectid of the inode
3802 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3803 int slot, u64 objectid,
3804 int *first_xattr_slot)
3806 u32 nritems = btrfs_header_nritems(leaf);
3807 struct btrfs_key found_key;
3808 static u64 xattr_access = 0;
3809 static u64 xattr_default = 0;
3812 if (!xattr_access) {
3813 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3814 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3815 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3816 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3820 *first_xattr_slot = -1;
3821 while (slot < nritems) {
3822 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3824 /* we found a different objectid, there must not be acls */
3825 if (found_key.objectid != objectid)
3828 /* we found an xattr, assume we've got an acl */
3829 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3830 if (*first_xattr_slot == -1)
3831 *first_xattr_slot = slot;
3832 if (found_key.offset == xattr_access ||
3833 found_key.offset == xattr_default)
3838 * we found a key greater than an xattr key, there can't
3839 * be any acls later on
3841 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3848 * it goes inode, inode backrefs, xattrs, extents,
3849 * so if there are a ton of hard links to an inode there can
3850 * be a lot of backrefs. Don't waste time searching too hard,
3851 * this is just an optimization
3856 /* we hit the end of the leaf before we found an xattr or
3857 * something larger than an xattr. We have to assume the inode
3860 if (*first_xattr_slot == -1)
3861 *first_xattr_slot = slot;
3866 * read an inode from the btree into the in-memory inode
3868 static int btrfs_read_locked_inode(struct inode *inode,
3869 struct btrfs_path *in_path)
3871 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3872 struct btrfs_path *path = in_path;
3873 struct extent_buffer *leaf;
3874 struct btrfs_inode_item *inode_item;
3875 struct btrfs_root *root = BTRFS_I(inode)->root;
3876 struct btrfs_key location;
3881 bool filled = false;
3882 int first_xattr_slot;
3884 ret = btrfs_fill_inode(inode, &rdev);
3889 path = btrfs_alloc_path();
3894 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3896 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3898 if (path != in_path)
3899 btrfs_free_path(path);
3903 leaf = path->nodes[0];
3908 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3909 struct btrfs_inode_item);
3910 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3911 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3912 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3913 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3914 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3915 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3916 round_up(i_size_read(inode), fs_info->sectorsize));
3918 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3919 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3921 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3922 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3924 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3925 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3927 BTRFS_I(inode)->i_otime.tv_sec =
3928 btrfs_timespec_sec(leaf, &inode_item->otime);
3929 BTRFS_I(inode)->i_otime.tv_nsec =
3930 btrfs_timespec_nsec(leaf, &inode_item->otime);
3932 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3933 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3934 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3936 inode_set_iversion_queried(inode,
3937 btrfs_inode_sequence(leaf, inode_item));
3938 inode->i_generation = BTRFS_I(inode)->generation;
3940 rdev = btrfs_inode_rdev(leaf, inode_item);
3942 BTRFS_I(inode)->index_cnt = (u64)-1;
3943 btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
3944 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
3948 * If we were modified in the current generation and evicted from memory
3949 * and then re-read we need to do a full sync since we don't have any
3950 * idea about which extents were modified before we were evicted from
3953 * This is required for both inode re-read from disk and delayed inode
3954 * in delayed_nodes_tree.
3956 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3957 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3958 &BTRFS_I(inode)->runtime_flags);
3961 * We don't persist the id of the transaction where an unlink operation
3962 * against the inode was last made. So here we assume the inode might
3963 * have been evicted, and therefore the exact value of last_unlink_trans
3964 * lost, and set it to last_trans to avoid metadata inconsistencies
3965 * between the inode and its parent if the inode is fsync'ed and the log
3966 * replayed. For example, in the scenario:
3969 * ln mydir/foo mydir/bar
3972 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3973 * xfs_io -c fsync mydir/foo
3975 * mount fs, triggers fsync log replay
3977 * We must make sure that when we fsync our inode foo we also log its
3978 * parent inode, otherwise after log replay the parent still has the
3979 * dentry with the "bar" name but our inode foo has a link count of 1
3980 * and doesn't have an inode ref with the name "bar" anymore.
3982 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3983 * but it guarantees correctness at the expense of occasional full
3984 * transaction commits on fsync if our inode is a directory, or if our
3985 * inode is not a directory, logging its parent unnecessarily.
3987 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3990 * Same logic as for last_unlink_trans. We don't persist the generation
3991 * of the last transaction where this inode was used for a reflink
3992 * operation, so after eviction and reloading the inode we must be
3993 * pessimistic and assume the last transaction that modified the inode.
3995 BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3998 if (inode->i_nlink != 1 ||
3999 path->slots[0] >= btrfs_header_nritems(leaf))
4002 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4003 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
4006 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4007 if (location.type == BTRFS_INODE_REF_KEY) {
4008 struct btrfs_inode_ref *ref;
4010 ref = (struct btrfs_inode_ref *)ptr;
4011 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
4012 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
4013 struct btrfs_inode_extref *extref;
4015 extref = (struct btrfs_inode_extref *)ptr;
4016 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
4021 * try to precache a NULL acl entry for files that don't have
4022 * any xattrs or acls
4024 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
4025 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
4026 if (first_xattr_slot != -1) {
4027 path->slots[0] = first_xattr_slot;
4028 ret = btrfs_load_inode_props(inode, path);
4031 "error loading props for ino %llu (root %llu): %d",
4032 btrfs_ino(BTRFS_I(inode)),
4033 root->root_key.objectid, ret);
4035 if (path != in_path)
4036 btrfs_free_path(path);
4039 cache_no_acl(inode);
4041 switch (inode->i_mode & S_IFMT) {
4043 inode->i_mapping->a_ops = &btrfs_aops;
4044 inode->i_fop = &btrfs_file_operations;
4045 inode->i_op = &btrfs_file_inode_operations;
4048 inode->i_fop = &btrfs_dir_file_operations;
4049 inode->i_op = &btrfs_dir_inode_operations;
4052 inode->i_op = &btrfs_symlink_inode_operations;
4053 inode_nohighmem(inode);
4054 inode->i_mapping->a_ops = &btrfs_aops;
4057 inode->i_op = &btrfs_special_inode_operations;
4058 init_special_inode(inode, inode->i_mode, rdev);
4062 btrfs_sync_inode_flags_to_i_flags(inode);
4067 * given a leaf and an inode, copy the inode fields into the leaf
4069 static void fill_inode_item(struct btrfs_trans_handle *trans,
4070 struct extent_buffer *leaf,
4071 struct btrfs_inode_item *item,
4072 struct inode *inode)
4074 struct btrfs_map_token token;
4077 btrfs_init_map_token(&token, leaf);
4079 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4080 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4081 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
4082 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4083 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4085 btrfs_set_token_timespec_sec(&token, &item->atime,
4086 inode->i_atime.tv_sec);
4087 btrfs_set_token_timespec_nsec(&token, &item->atime,
4088 inode->i_atime.tv_nsec);
4090 btrfs_set_token_timespec_sec(&token, &item->mtime,
4091 inode->i_mtime.tv_sec);
4092 btrfs_set_token_timespec_nsec(&token, &item->mtime,
4093 inode->i_mtime.tv_nsec);
4095 btrfs_set_token_timespec_sec(&token, &item->ctime,
4096 inode->i_ctime.tv_sec);
4097 btrfs_set_token_timespec_nsec(&token, &item->ctime,
4098 inode->i_ctime.tv_nsec);
4100 btrfs_set_token_timespec_sec(&token, &item->otime,
4101 BTRFS_I(inode)->i_otime.tv_sec);
4102 btrfs_set_token_timespec_nsec(&token, &item->otime,
4103 BTRFS_I(inode)->i_otime.tv_nsec);
4105 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
4106 btrfs_set_token_inode_generation(&token, item,
4107 BTRFS_I(inode)->generation);
4108 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4109 btrfs_set_token_inode_transid(&token, item, trans->transid);
4110 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4111 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4112 BTRFS_I(inode)->ro_flags);
4113 btrfs_set_token_inode_flags(&token, item, flags);
4114 btrfs_set_token_inode_block_group(&token, item, 0);
4118 * copy everything in the in-memory inode into the btree.
4120 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4121 struct btrfs_root *root,
4122 struct btrfs_inode *inode)
4124 struct btrfs_inode_item *inode_item;
4125 struct btrfs_path *path;
4126 struct extent_buffer *leaf;
4129 path = btrfs_alloc_path();
4133 ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
4140 leaf = path->nodes[0];
4141 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4142 struct btrfs_inode_item);
4144 fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4145 btrfs_mark_buffer_dirty(leaf);
4146 btrfs_set_inode_last_trans(trans, inode);
4149 btrfs_free_path(path);
4154 * copy everything in the in-memory inode into the btree.
4156 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4157 struct btrfs_root *root,
4158 struct btrfs_inode *inode)
4160 struct btrfs_fs_info *fs_info = root->fs_info;
4164 * If the inode is a free space inode, we can deadlock during commit
4165 * if we put it into the delayed code.
4167 * The data relocation inode should also be directly updated
4170 if (!btrfs_is_free_space_inode(inode)
4171 && !btrfs_is_data_reloc_root(root)
4172 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4173 btrfs_update_root_times(trans, root);
4175 ret = btrfs_delayed_update_inode(trans, root, inode);
4177 btrfs_set_inode_last_trans(trans, inode);
4181 return btrfs_update_inode_item(trans, root, inode);
4184 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4185 struct btrfs_root *root, struct btrfs_inode *inode)
4189 ret = btrfs_update_inode(trans, root, inode);
4191 return btrfs_update_inode_item(trans, root, inode);
4196 * unlink helper that gets used here in inode.c and in the tree logging
4197 * recovery code. It remove a link in a directory with a given name, and
4198 * also drops the back refs in the inode to the directory
4200 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4201 struct btrfs_inode *dir,
4202 struct btrfs_inode *inode,
4203 const struct fscrypt_str *name,
4204 struct btrfs_rename_ctx *rename_ctx)
4206 struct btrfs_root *root = dir->root;
4207 struct btrfs_fs_info *fs_info = root->fs_info;
4208 struct btrfs_path *path;
4210 struct btrfs_dir_item *di;
4212 u64 ino = btrfs_ino(inode);
4213 u64 dir_ino = btrfs_ino(dir);
4215 path = btrfs_alloc_path();
4221 di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4222 if (IS_ERR_OR_NULL(di)) {
4223 ret = di ? PTR_ERR(di) : -ENOENT;
4226 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4229 btrfs_release_path(path);
4232 * If we don't have dir index, we have to get it by looking up
4233 * the inode ref, since we get the inode ref, remove it directly,
4234 * it is unnecessary to do delayed deletion.
4236 * But if we have dir index, needn't search inode ref to get it.
4237 * Since the inode ref is close to the inode item, it is better
4238 * that we delay to delete it, and just do this deletion when
4239 * we update the inode item.
4241 if (inode->dir_index) {
4242 ret = btrfs_delayed_delete_inode_ref(inode);
4244 index = inode->dir_index;
4249 ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4252 "failed to delete reference to %.*s, inode %llu parent %llu",
4253 name->len, name->name, ino, dir_ino);
4254 btrfs_abort_transaction(trans, ret);
4259 rename_ctx->index = index;
4261 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4263 btrfs_abort_transaction(trans, ret);
4268 * If we are in a rename context, we don't need to update anything in the
4269 * log. That will be done later during the rename by btrfs_log_new_name().
4270 * Besides that, doing it here would only cause extra unnecessary btree
4271 * operations on the log tree, increasing latency for applications.
4274 btrfs_del_inode_ref_in_log(trans, root, name, inode, dir_ino);
4275 btrfs_del_dir_entries_in_log(trans, root, name, dir, index);
4279 * If we have a pending delayed iput we could end up with the final iput
4280 * being run in btrfs-cleaner context. If we have enough of these built
4281 * up we can end up burning a lot of time in btrfs-cleaner without any
4282 * way to throttle the unlinks. Since we're currently holding a ref on
4283 * the inode we can run the delayed iput here without any issues as the
4284 * final iput won't be done until after we drop the ref we're currently
4287 btrfs_run_delayed_iput(fs_info, inode);
4289 btrfs_free_path(path);
4293 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4294 inode_inc_iversion(&inode->vfs_inode);
4295 inode_inc_iversion(&dir->vfs_inode);
4296 inode->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4297 dir->vfs_inode.i_mtime = inode->vfs_inode.i_ctime;
4298 dir->vfs_inode.i_ctime = inode->vfs_inode.i_ctime;
4299 ret = btrfs_update_inode(trans, root, dir);
4304 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4305 struct btrfs_inode *dir, struct btrfs_inode *inode,
4306 const struct fscrypt_str *name)
4310 ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4312 drop_nlink(&inode->vfs_inode);
4313 ret = btrfs_update_inode(trans, inode->root, inode);
4319 * helper to start transaction for unlink and rmdir.
4321 * unlink and rmdir are special in btrfs, they do not always free space, so
4322 * if we cannot make our reservations the normal way try and see if there is
4323 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4324 * allow the unlink to occur.
4326 static struct btrfs_trans_handle *__unlink_start_trans(struct btrfs_inode *dir)
4328 struct btrfs_root *root = dir->root;
4330 return btrfs_start_transaction_fallback_global_rsv(root,
4331 BTRFS_UNLINK_METADATA_UNITS);
4334 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4336 struct btrfs_trans_handle *trans;
4337 struct inode *inode = d_inode(dentry);
4339 struct fscrypt_name fname;
4341 ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4345 /* This needs to handle no-key deletions later on */
4347 trans = __unlink_start_trans(BTRFS_I(dir));
4348 if (IS_ERR(trans)) {
4349 ret = PTR_ERR(trans);
4353 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4356 ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4361 if (inode->i_nlink == 0) {
4362 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4368 btrfs_end_transaction(trans);
4369 btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4371 fscrypt_free_filename(&fname);
4375 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4376 struct btrfs_inode *dir, struct dentry *dentry)
4378 struct btrfs_root *root = dir->root;
4379 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4380 struct btrfs_path *path;
4381 struct extent_buffer *leaf;
4382 struct btrfs_dir_item *di;
4383 struct btrfs_key key;
4387 u64 dir_ino = btrfs_ino(dir);
4388 struct fscrypt_name fname;
4390 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
4394 /* This needs to handle no-key deletions later on */
4396 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4397 objectid = inode->root->root_key.objectid;
4398 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4399 objectid = inode->location.objectid;
4402 fscrypt_free_filename(&fname);
4406 path = btrfs_alloc_path();
4412 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4413 &fname.disk_name, -1);
4414 if (IS_ERR_OR_NULL(di)) {
4415 ret = di ? PTR_ERR(di) : -ENOENT;
4419 leaf = path->nodes[0];
4420 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4421 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4422 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4424 btrfs_abort_transaction(trans, ret);
4427 btrfs_release_path(path);
4430 * This is a placeholder inode for a subvolume we didn't have a
4431 * reference to at the time of the snapshot creation. In the meantime
4432 * we could have renamed the real subvol link into our snapshot, so
4433 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4434 * Instead simply lookup the dir_index_item for this entry so we can
4435 * remove it. Otherwise we know we have a ref to the root and we can
4436 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4438 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4439 di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4440 if (IS_ERR_OR_NULL(di)) {
4445 btrfs_abort_transaction(trans, ret);
4449 leaf = path->nodes[0];
4450 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4452 btrfs_release_path(path);
4454 ret = btrfs_del_root_ref(trans, objectid,
4455 root->root_key.objectid, dir_ino,
4456 &index, &fname.disk_name);
4458 btrfs_abort_transaction(trans, ret);
4463 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4465 btrfs_abort_transaction(trans, ret);
4469 btrfs_i_size_write(dir, dir->vfs_inode.i_size - fname.disk_name.len * 2);
4470 inode_inc_iversion(&dir->vfs_inode);
4471 dir->vfs_inode.i_mtime = current_time(&dir->vfs_inode);
4472 dir->vfs_inode.i_ctime = dir->vfs_inode.i_mtime;
4473 ret = btrfs_update_inode_fallback(trans, root, dir);
4475 btrfs_abort_transaction(trans, ret);
4477 btrfs_free_path(path);
4478 fscrypt_free_filename(&fname);
4483 * Helper to check if the subvolume references other subvolumes or if it's
4486 static noinline int may_destroy_subvol(struct btrfs_root *root)
4488 struct btrfs_fs_info *fs_info = root->fs_info;
4489 struct btrfs_path *path;
4490 struct btrfs_dir_item *di;
4491 struct btrfs_key key;
4492 struct fscrypt_str name = FSTR_INIT("default", 7);
4496 path = btrfs_alloc_path();
4500 /* Make sure this root isn't set as the default subvol */
4501 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4502 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4504 if (di && !IS_ERR(di)) {
4505 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4506 if (key.objectid == root->root_key.objectid) {
4509 "deleting default subvolume %llu is not allowed",
4513 btrfs_release_path(path);
4516 key.objectid = root->root_key.objectid;
4517 key.type = BTRFS_ROOT_REF_KEY;
4518 key.offset = (u64)-1;
4520 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4526 if (path->slots[0] > 0) {
4528 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4529 if (key.objectid == root->root_key.objectid &&
4530 key.type == BTRFS_ROOT_REF_KEY)
4534 btrfs_free_path(path);
4538 /* Delete all dentries for inodes belonging to the root */
4539 static void btrfs_prune_dentries(struct btrfs_root *root)
4541 struct btrfs_fs_info *fs_info = root->fs_info;
4542 struct rb_node *node;
4543 struct rb_node *prev;
4544 struct btrfs_inode *entry;
4545 struct inode *inode;
4548 if (!BTRFS_FS_ERROR(fs_info))
4549 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4551 spin_lock(&root->inode_lock);
4553 node = root->inode_tree.rb_node;
4557 entry = rb_entry(node, struct btrfs_inode, rb_node);
4559 if (objectid < btrfs_ino(entry))
4560 node = node->rb_left;
4561 else if (objectid > btrfs_ino(entry))
4562 node = node->rb_right;
4568 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4569 if (objectid <= btrfs_ino(entry)) {
4573 prev = rb_next(prev);
4577 entry = rb_entry(node, struct btrfs_inode, rb_node);
4578 objectid = btrfs_ino(entry) + 1;
4579 inode = igrab(&entry->vfs_inode);
4581 spin_unlock(&root->inode_lock);
4582 if (atomic_read(&inode->i_count) > 1)
4583 d_prune_aliases(inode);
4585 * btrfs_drop_inode will have it removed from the inode
4586 * cache when its usage count hits zero.
4590 spin_lock(&root->inode_lock);
4594 if (cond_resched_lock(&root->inode_lock))
4597 node = rb_next(node);
4599 spin_unlock(&root->inode_lock);
4602 int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry)
4604 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4605 struct btrfs_root *root = dir->root;
4606 struct inode *inode = d_inode(dentry);
4607 struct btrfs_root *dest = BTRFS_I(inode)->root;
4608 struct btrfs_trans_handle *trans;
4609 struct btrfs_block_rsv block_rsv;
4614 * Don't allow to delete a subvolume with send in progress. This is
4615 * inside the inode lock so the error handling that has to drop the bit
4616 * again is not run concurrently.
4618 spin_lock(&dest->root_item_lock);
4619 if (dest->send_in_progress) {
4620 spin_unlock(&dest->root_item_lock);
4622 "attempt to delete subvolume %llu during send",
4623 dest->root_key.objectid);
4626 if (atomic_read(&dest->nr_swapfiles)) {
4627 spin_unlock(&dest->root_item_lock);
4629 "attempt to delete subvolume %llu with active swapfile",
4630 root->root_key.objectid);
4633 root_flags = btrfs_root_flags(&dest->root_item);
4634 btrfs_set_root_flags(&dest->root_item,
4635 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4636 spin_unlock(&dest->root_item_lock);
4638 down_write(&fs_info->subvol_sem);
4640 ret = may_destroy_subvol(dest);
4644 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4646 * One for dir inode,
4647 * two for dir entries,
4648 * two for root ref/backref.
4650 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4654 trans = btrfs_start_transaction(root, 0);
4655 if (IS_ERR(trans)) {
4656 ret = PTR_ERR(trans);
4659 trans->block_rsv = &block_rsv;
4660 trans->bytes_reserved = block_rsv.size;
4662 btrfs_record_snapshot_destroy(trans, dir);
4664 ret = btrfs_unlink_subvol(trans, dir, dentry);
4666 btrfs_abort_transaction(trans, ret);
4670 ret = btrfs_record_root_in_trans(trans, dest);
4672 btrfs_abort_transaction(trans, ret);
4676 memset(&dest->root_item.drop_progress, 0,
4677 sizeof(dest->root_item.drop_progress));
4678 btrfs_set_root_drop_level(&dest->root_item, 0);
4679 btrfs_set_root_refs(&dest->root_item, 0);
4681 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4682 ret = btrfs_insert_orphan_item(trans,
4684 dest->root_key.objectid);
4686 btrfs_abort_transaction(trans, ret);
4691 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4692 BTRFS_UUID_KEY_SUBVOL,
4693 dest->root_key.objectid);
4694 if (ret && ret != -ENOENT) {
4695 btrfs_abort_transaction(trans, ret);
4698 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4699 ret = btrfs_uuid_tree_remove(trans,
4700 dest->root_item.received_uuid,
4701 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4702 dest->root_key.objectid);
4703 if (ret && ret != -ENOENT) {
4704 btrfs_abort_transaction(trans, ret);
4709 free_anon_bdev(dest->anon_dev);
4712 trans->block_rsv = NULL;
4713 trans->bytes_reserved = 0;
4714 ret = btrfs_end_transaction(trans);
4715 inode->i_flags |= S_DEAD;
4717 btrfs_subvolume_release_metadata(root, &block_rsv);
4719 up_write(&fs_info->subvol_sem);
4721 spin_lock(&dest->root_item_lock);
4722 root_flags = btrfs_root_flags(&dest->root_item);
4723 btrfs_set_root_flags(&dest->root_item,
4724 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4725 spin_unlock(&dest->root_item_lock);
4727 d_invalidate(dentry);
4728 btrfs_prune_dentries(dest);
4729 ASSERT(dest->send_in_progress == 0);
4735 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4737 struct inode *inode = d_inode(dentry);
4738 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
4740 struct btrfs_trans_handle *trans;
4741 u64 last_unlink_trans;
4742 struct fscrypt_name fname;
4744 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4746 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
4747 if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4749 "extent tree v2 doesn't support snapshot deletion yet");
4752 return btrfs_delete_subvolume(BTRFS_I(dir), dentry);
4755 err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4759 /* This needs to handle no-key deletions later on */
4761 trans = __unlink_start_trans(BTRFS_I(dir));
4762 if (IS_ERR(trans)) {
4763 err = PTR_ERR(trans);
4767 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4768 err = btrfs_unlink_subvol(trans, BTRFS_I(dir), dentry);
4772 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4776 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4778 /* now the directory is empty */
4779 err = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4782 btrfs_i_size_write(BTRFS_I(inode), 0);
4784 * Propagate the last_unlink_trans value of the deleted dir to
4785 * its parent directory. This is to prevent an unrecoverable
4786 * log tree in the case we do something like this:
4788 * 2) create snapshot under dir foo
4789 * 3) delete the snapshot
4792 * 6) fsync foo or some file inside foo
4794 if (last_unlink_trans >= trans->transid)
4795 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4798 btrfs_end_transaction(trans);
4800 btrfs_btree_balance_dirty(fs_info);
4801 fscrypt_free_filename(&fname);
4807 * btrfs_truncate_block - read, zero a chunk and write a block
4808 * @inode - inode that we're zeroing
4809 * @from - the offset to start zeroing
4810 * @len - the length to zero, 0 to zero the entire range respective to the
4812 * @front - zero up to the offset instead of from the offset on
4814 * This will find the block for the "from" offset and cow the block and zero the
4815 * part we want to zero. This is used with truncate and hole punching.
4817 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4820 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4821 struct address_space *mapping = inode->vfs_inode.i_mapping;
4822 struct extent_io_tree *io_tree = &inode->io_tree;
4823 struct btrfs_ordered_extent *ordered;
4824 struct extent_state *cached_state = NULL;
4825 struct extent_changeset *data_reserved = NULL;
4826 bool only_release_metadata = false;
4827 u32 blocksize = fs_info->sectorsize;
4828 pgoff_t index = from >> PAGE_SHIFT;
4829 unsigned offset = from & (blocksize - 1);
4831 gfp_t mask = btrfs_alloc_write_mask(mapping);
4832 size_t write_bytes = blocksize;
4837 if (IS_ALIGNED(offset, blocksize) &&
4838 (!len || IS_ALIGNED(len, blocksize)))
4841 block_start = round_down(from, blocksize);
4842 block_end = block_start + blocksize - 1;
4844 ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4847 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
4848 /* For nocow case, no need to reserve data space */
4849 only_release_metadata = true;
4854 ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
4856 if (!only_release_metadata)
4857 btrfs_free_reserved_data_space(inode, data_reserved,
4858 block_start, blocksize);
4862 page = find_or_create_page(mapping, index, mask);
4864 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4866 btrfs_delalloc_release_extents(inode, blocksize);
4871 if (!PageUptodate(page)) {
4872 ret = btrfs_read_folio(NULL, page_folio(page));
4874 if (page->mapping != mapping) {
4879 if (!PageUptodate(page)) {
4886 * We unlock the page after the io is completed and then re-lock it
4887 * above. release_folio() could have come in between that and cleared
4888 * PagePrivate(), but left the page in the mapping. Set the page mapped
4889 * here to make sure it's properly set for the subpage stuff.
4891 ret = set_page_extent_mapped(page);
4895 wait_on_page_writeback(page);
4897 lock_extent(io_tree, block_start, block_end, &cached_state);
4899 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4901 unlock_extent(io_tree, block_start, block_end, &cached_state);
4904 btrfs_start_ordered_extent(ordered);
4905 btrfs_put_ordered_extent(ordered);
4909 clear_extent_bit(&inode->io_tree, block_start, block_end,
4910 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4913 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4916 unlock_extent(io_tree, block_start, block_end, &cached_state);
4920 if (offset != blocksize) {
4922 len = blocksize - offset;
4924 memzero_page(page, (block_start - page_offset(page)),
4927 memzero_page(page, (block_start - page_offset(page)) + offset,
4930 btrfs_page_clear_checked(fs_info, page, block_start,
4931 block_end + 1 - block_start);
4932 btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
4933 unlock_extent(io_tree, block_start, block_end, &cached_state);
4935 if (only_release_metadata)
4936 set_extent_bit(&inode->io_tree, block_start, block_end,
4937 EXTENT_NORESERVE, NULL);
4941 if (only_release_metadata)
4942 btrfs_delalloc_release_metadata(inode, blocksize, true);
4944 btrfs_delalloc_release_space(inode, data_reserved,
4945 block_start, blocksize, true);
4947 btrfs_delalloc_release_extents(inode, blocksize);
4951 if (only_release_metadata)
4952 btrfs_check_nocow_unlock(inode);
4953 extent_changeset_free(data_reserved);
4957 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4958 u64 offset, u64 len)
4960 struct btrfs_fs_info *fs_info = root->fs_info;
4961 struct btrfs_trans_handle *trans;
4962 struct btrfs_drop_extents_args drop_args = { 0 };
4966 * If NO_HOLES is enabled, we don't need to do anything.
4967 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
4968 * or btrfs_update_inode() will be called, which guarantee that the next
4969 * fsync will know this inode was changed and needs to be logged.
4971 if (btrfs_fs_incompat(fs_info, NO_HOLES))
4975 * 1 - for the one we're dropping
4976 * 1 - for the one we're adding
4977 * 1 - for updating the inode.
4979 trans = btrfs_start_transaction(root, 3);
4981 return PTR_ERR(trans);
4983 drop_args.start = offset;
4984 drop_args.end = offset + len;
4985 drop_args.drop_cache = true;
4987 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4989 btrfs_abort_transaction(trans, ret);
4990 btrfs_end_transaction(trans);
4994 ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
4996 btrfs_abort_transaction(trans, ret);
4998 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
4999 btrfs_update_inode(trans, root, inode);
5001 btrfs_end_transaction(trans);
5006 * This function puts in dummy file extents for the area we're creating a hole
5007 * for. So if we are truncating this file to a larger size we need to insert
5008 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5009 * the range between oldsize and size
5011 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5013 struct btrfs_root *root = inode->root;
5014 struct btrfs_fs_info *fs_info = root->fs_info;
5015 struct extent_io_tree *io_tree = &inode->io_tree;
5016 struct extent_map *em = NULL;
5017 struct extent_state *cached_state = NULL;
5018 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5019 u64 block_end = ALIGN(size, fs_info->sectorsize);
5026 * If our size started in the middle of a block we need to zero out the
5027 * rest of the block before we expand the i_size, otherwise we could
5028 * expose stale data.
5030 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5034 if (size <= hole_start)
5037 btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5039 cur_offset = hole_start;
5041 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5042 block_end - cur_offset);
5048 last_byte = min(extent_map_end(em), block_end);
5049 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5050 hole_size = last_byte - cur_offset;
5052 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5053 struct extent_map *hole_em;
5055 err = maybe_insert_hole(root, inode, cur_offset,
5060 err = btrfs_inode_set_file_extent_range(inode,
5061 cur_offset, hole_size);
5065 hole_em = alloc_extent_map();
5067 btrfs_drop_extent_map_range(inode, cur_offset,
5068 cur_offset + hole_size - 1,
5070 btrfs_set_inode_full_sync(inode);
5073 hole_em->start = cur_offset;
5074 hole_em->len = hole_size;
5075 hole_em->orig_start = cur_offset;
5077 hole_em->block_start = EXTENT_MAP_HOLE;
5078 hole_em->block_len = 0;
5079 hole_em->orig_block_len = 0;
5080 hole_em->ram_bytes = hole_size;
5081 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5082 hole_em->generation = fs_info->generation;
5084 err = btrfs_replace_extent_map_range(inode, hole_em, true);
5085 free_extent_map(hole_em);
5087 err = btrfs_inode_set_file_extent_range(inode,
5088 cur_offset, hole_size);
5093 free_extent_map(em);
5095 cur_offset = last_byte;
5096 if (cur_offset >= block_end)
5099 free_extent_map(em);
5100 unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5104 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5106 struct btrfs_root *root = BTRFS_I(inode)->root;
5107 struct btrfs_trans_handle *trans;
5108 loff_t oldsize = i_size_read(inode);
5109 loff_t newsize = attr->ia_size;
5110 int mask = attr->ia_valid;
5114 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5115 * special case where we need to update the times despite not having
5116 * these flags set. For all other operations the VFS set these flags
5117 * explicitly if it wants a timestamp update.
5119 if (newsize != oldsize) {
5120 inode_inc_iversion(inode);
5121 if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5122 inode->i_mtime = current_time(inode);
5123 inode->i_ctime = inode->i_mtime;
5127 if (newsize > oldsize) {
5129 * Don't do an expanding truncate while snapshotting is ongoing.
5130 * This is to ensure the snapshot captures a fully consistent
5131 * state of this file - if the snapshot captures this expanding
5132 * truncation, it must capture all writes that happened before
5135 btrfs_drew_write_lock(&root->snapshot_lock);
5136 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5138 btrfs_drew_write_unlock(&root->snapshot_lock);
5142 trans = btrfs_start_transaction(root, 1);
5143 if (IS_ERR(trans)) {
5144 btrfs_drew_write_unlock(&root->snapshot_lock);
5145 return PTR_ERR(trans);
5148 i_size_write(inode, newsize);
5149 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5150 pagecache_isize_extended(inode, oldsize, newsize);
5151 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5152 btrfs_drew_write_unlock(&root->snapshot_lock);
5153 btrfs_end_transaction(trans);
5155 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5157 if (btrfs_is_zoned(fs_info)) {
5158 ret = btrfs_wait_ordered_range(inode,
5159 ALIGN(newsize, fs_info->sectorsize),
5166 * We're truncating a file that used to have good data down to
5167 * zero. Make sure any new writes to the file get on disk
5171 set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5172 &BTRFS_I(inode)->runtime_flags);
5174 truncate_setsize(inode, newsize);
5176 inode_dio_wait(inode);
5178 ret = btrfs_truncate(BTRFS_I(inode), newsize == oldsize);
5179 if (ret && inode->i_nlink) {
5183 * Truncate failed, so fix up the in-memory size. We
5184 * adjusted disk_i_size down as we removed extents, so
5185 * wait for disk_i_size to be stable and then update the
5186 * in-memory size to match.
5188 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5191 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5198 static int btrfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5201 struct inode *inode = d_inode(dentry);
5202 struct btrfs_root *root = BTRFS_I(inode)->root;
5205 if (btrfs_root_readonly(root))
5208 err = setattr_prepare(idmap, dentry, attr);
5212 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5213 err = btrfs_setsize(inode, attr);
5218 if (attr->ia_valid) {
5219 setattr_copy(idmap, inode, attr);
5220 inode_inc_iversion(inode);
5221 err = btrfs_dirty_inode(BTRFS_I(inode));
5223 if (!err && attr->ia_valid & ATTR_MODE)
5224 err = posix_acl_chmod(idmap, dentry, inode->i_mode);
5231 * While truncating the inode pages during eviction, we get the VFS
5232 * calling btrfs_invalidate_folio() against each folio of the inode. This
5233 * is slow because the calls to btrfs_invalidate_folio() result in a
5234 * huge amount of calls to lock_extent() and clear_extent_bit(),
5235 * which keep merging and splitting extent_state structures over and over,
5236 * wasting lots of time.
5238 * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5239 * skip all those expensive operations on a per folio basis and do only
5240 * the ordered io finishing, while we release here the extent_map and
5241 * extent_state structures, without the excessive merging and splitting.
5243 static void evict_inode_truncate_pages(struct inode *inode)
5245 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5246 struct rb_node *node;
5248 ASSERT(inode->i_state & I_FREEING);
5249 truncate_inode_pages_final(&inode->i_data);
5251 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5254 * Keep looping until we have no more ranges in the io tree.
5255 * We can have ongoing bios started by readahead that have
5256 * their endio callback (extent_io.c:end_bio_extent_readpage)
5257 * still in progress (unlocked the pages in the bio but did not yet
5258 * unlocked the ranges in the io tree). Therefore this means some
5259 * ranges can still be locked and eviction started because before
5260 * submitting those bios, which are executed by a separate task (work
5261 * queue kthread), inode references (inode->i_count) were not taken
5262 * (which would be dropped in the end io callback of each bio).
5263 * Therefore here we effectively end up waiting for those bios and
5264 * anyone else holding locked ranges without having bumped the inode's
5265 * reference count - if we don't do it, when they access the inode's
5266 * io_tree to unlock a range it may be too late, leading to an
5267 * use-after-free issue.
5269 spin_lock(&io_tree->lock);
5270 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5271 struct extent_state *state;
5272 struct extent_state *cached_state = NULL;
5275 unsigned state_flags;
5277 node = rb_first(&io_tree->state);
5278 state = rb_entry(node, struct extent_state, rb_node);
5279 start = state->start;
5281 state_flags = state->state;
5282 spin_unlock(&io_tree->lock);
5284 lock_extent(io_tree, start, end, &cached_state);
5287 * If still has DELALLOC flag, the extent didn't reach disk,
5288 * and its reserved space won't be freed by delayed_ref.
5289 * So we need to free its reserved space here.
5290 * (Refer to comment in btrfs_invalidate_folio, case 2)
5292 * Note, end is the bytenr of last byte, so we need + 1 here.
5294 if (state_flags & EXTENT_DELALLOC)
5295 btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5298 clear_extent_bit(io_tree, start, end,
5299 EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5303 spin_lock(&io_tree->lock);
5305 spin_unlock(&io_tree->lock);
5308 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5309 struct btrfs_block_rsv *rsv)
5311 struct btrfs_fs_info *fs_info = root->fs_info;
5312 struct btrfs_trans_handle *trans;
5313 u64 delayed_refs_extra = btrfs_calc_delayed_ref_bytes(fs_info, 1);
5317 * Eviction should be taking place at some place safe because of our
5318 * delayed iputs. However the normal flushing code will run delayed
5319 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5321 * We reserve the delayed_refs_extra here again because we can't use
5322 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5323 * above. We reserve our extra bit here because we generate a ton of
5324 * delayed refs activity by truncating.
5326 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5327 * if we fail to make this reservation we can re-try without the
5328 * delayed_refs_extra so we can make some forward progress.
5330 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5331 BTRFS_RESERVE_FLUSH_EVICT);
5333 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5334 BTRFS_RESERVE_FLUSH_EVICT);
5337 "could not allocate space for delete; will truncate on mount");
5338 return ERR_PTR(-ENOSPC);
5340 delayed_refs_extra = 0;
5343 trans = btrfs_join_transaction(root);
5347 if (delayed_refs_extra) {
5348 trans->block_rsv = &fs_info->trans_block_rsv;
5349 trans->bytes_reserved = delayed_refs_extra;
5350 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5351 delayed_refs_extra, true);
5356 void btrfs_evict_inode(struct inode *inode)
5358 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5359 struct btrfs_trans_handle *trans;
5360 struct btrfs_root *root = BTRFS_I(inode)->root;
5361 struct btrfs_block_rsv *rsv = NULL;
5364 trace_btrfs_inode_evict(inode);
5367 fsverity_cleanup_inode(inode);
5372 evict_inode_truncate_pages(inode);
5374 if (inode->i_nlink &&
5375 ((btrfs_root_refs(&root->root_item) != 0 &&
5376 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5377 btrfs_is_free_space_inode(BTRFS_I(inode))))
5380 if (is_bad_inode(inode))
5383 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5386 if (inode->i_nlink > 0) {
5387 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5388 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5393 * This makes sure the inode item in tree is uptodate and the space for
5394 * the inode update is released.
5396 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5401 * This drops any pending insert or delete operations we have for this
5402 * inode. We could have a delayed dir index deletion queued up, but
5403 * we're removing the inode completely so that'll be taken care of in
5406 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5408 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5411 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5412 rsv->failfast = true;
5414 btrfs_i_size_write(BTRFS_I(inode), 0);
5417 struct btrfs_truncate_control control = {
5418 .inode = BTRFS_I(inode),
5419 .ino = btrfs_ino(BTRFS_I(inode)),
5424 trans = evict_refill_and_join(root, rsv);
5428 trans->block_rsv = rsv;
5430 ret = btrfs_truncate_inode_items(trans, root, &control);
5431 trans->block_rsv = &fs_info->trans_block_rsv;
5432 btrfs_end_transaction(trans);
5434 * We have not added new delayed items for our inode after we
5435 * have flushed its delayed items, so no need to throttle on
5436 * delayed items. However we have modified extent buffers.
5438 btrfs_btree_balance_dirty_nodelay(fs_info);
5439 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5446 * Errors here aren't a big deal, it just means we leave orphan items in
5447 * the tree. They will be cleaned up on the next mount. If the inode
5448 * number gets reused, cleanup deletes the orphan item without doing
5449 * anything, and unlink reuses the existing orphan item.
5451 * If it turns out that we are dropping too many of these, we might want
5452 * to add a mechanism for retrying these after a commit.
5454 trans = evict_refill_and_join(root, rsv);
5455 if (!IS_ERR(trans)) {
5456 trans->block_rsv = rsv;
5457 btrfs_orphan_del(trans, BTRFS_I(inode));
5458 trans->block_rsv = &fs_info->trans_block_rsv;
5459 btrfs_end_transaction(trans);
5463 btrfs_free_block_rsv(fs_info, rsv);
5465 * If we didn't successfully delete, the orphan item will still be in
5466 * the tree and we'll retry on the next mount. Again, we might also want
5467 * to retry these periodically in the future.
5469 btrfs_remove_delayed_node(BTRFS_I(inode));
5470 fsverity_cleanup_inode(inode);
5475 * Return the key found in the dir entry in the location pointer, fill @type
5476 * with BTRFS_FT_*, and return 0.
5478 * If no dir entries were found, returns -ENOENT.
5479 * If found a corrupted location in dir entry, returns -EUCLEAN.
5481 static int btrfs_inode_by_name(struct btrfs_inode *dir, struct dentry *dentry,
5482 struct btrfs_key *location, u8 *type)
5484 struct btrfs_dir_item *di;
5485 struct btrfs_path *path;
5486 struct btrfs_root *root = dir->root;
5488 struct fscrypt_name fname;
5490 path = btrfs_alloc_path();
5494 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
5498 * fscrypt_setup_filename() should never return a positive value, but
5499 * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
5503 /* This needs to handle no-key deletions later on */
5505 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
5506 &fname.disk_name, 0);
5507 if (IS_ERR_OR_NULL(di)) {
5508 ret = di ? PTR_ERR(di) : -ENOENT;
5512 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5513 if (location->type != BTRFS_INODE_ITEM_KEY &&
5514 location->type != BTRFS_ROOT_ITEM_KEY) {
5516 btrfs_warn(root->fs_info,
5517 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5518 __func__, fname.disk_name.name, btrfs_ino(dir),
5519 location->objectid, location->type, location->offset);
5522 *type = btrfs_dir_ftype(path->nodes[0], di);
5524 fscrypt_free_filename(&fname);
5525 btrfs_free_path(path);
5530 * when we hit a tree root in a directory, the btrfs part of the inode
5531 * needs to be changed to reflect the root directory of the tree root. This
5532 * is kind of like crossing a mount point.
5534 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5535 struct btrfs_inode *dir,
5536 struct dentry *dentry,
5537 struct btrfs_key *location,
5538 struct btrfs_root **sub_root)
5540 struct btrfs_path *path;
5541 struct btrfs_root *new_root;
5542 struct btrfs_root_ref *ref;
5543 struct extent_buffer *leaf;
5544 struct btrfs_key key;
5547 struct fscrypt_name fname;
5549 ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
5553 path = btrfs_alloc_path();
5560 key.objectid = dir->root->root_key.objectid;
5561 key.type = BTRFS_ROOT_REF_KEY;
5562 key.offset = location->objectid;
5564 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5571 leaf = path->nodes[0];
5572 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5573 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5574 btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5577 ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5578 (unsigned long)(ref + 1), fname.disk_name.len);
5582 btrfs_release_path(path);
5584 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5585 if (IS_ERR(new_root)) {
5586 err = PTR_ERR(new_root);
5590 *sub_root = new_root;
5591 location->objectid = btrfs_root_dirid(&new_root->root_item);
5592 location->type = BTRFS_INODE_ITEM_KEY;
5593 location->offset = 0;
5596 btrfs_free_path(path);
5597 fscrypt_free_filename(&fname);
5601 static void inode_tree_add(struct btrfs_inode *inode)
5603 struct btrfs_root *root = inode->root;
5604 struct btrfs_inode *entry;
5606 struct rb_node *parent;
5607 struct rb_node *new = &inode->rb_node;
5608 u64 ino = btrfs_ino(inode);
5610 if (inode_unhashed(&inode->vfs_inode))
5613 spin_lock(&root->inode_lock);
5614 p = &root->inode_tree.rb_node;
5617 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5619 if (ino < btrfs_ino(entry))
5620 p = &parent->rb_left;
5621 else if (ino > btrfs_ino(entry))
5622 p = &parent->rb_right;
5624 WARN_ON(!(entry->vfs_inode.i_state &
5625 (I_WILL_FREE | I_FREEING)));
5626 rb_replace_node(parent, new, &root->inode_tree);
5627 RB_CLEAR_NODE(parent);
5628 spin_unlock(&root->inode_lock);
5632 rb_link_node(new, parent, p);
5633 rb_insert_color(new, &root->inode_tree);
5634 spin_unlock(&root->inode_lock);
5637 static void inode_tree_del(struct btrfs_inode *inode)
5639 struct btrfs_root *root = inode->root;
5642 spin_lock(&root->inode_lock);
5643 if (!RB_EMPTY_NODE(&inode->rb_node)) {
5644 rb_erase(&inode->rb_node, &root->inode_tree);
5645 RB_CLEAR_NODE(&inode->rb_node);
5646 empty = RB_EMPTY_ROOT(&root->inode_tree);
5648 spin_unlock(&root->inode_lock);
5650 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5651 spin_lock(&root->inode_lock);
5652 empty = RB_EMPTY_ROOT(&root->inode_tree);
5653 spin_unlock(&root->inode_lock);
5655 btrfs_add_dead_root(root);
5660 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5662 struct btrfs_iget_args *args = p;
5664 inode->i_ino = args->ino;
5665 BTRFS_I(inode)->location.objectid = args->ino;
5666 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5667 BTRFS_I(inode)->location.offset = 0;
5668 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5669 BUG_ON(args->root && !BTRFS_I(inode)->root);
5671 if (args->root && args->root == args->root->fs_info->tree_root &&
5672 args->ino != BTRFS_BTREE_INODE_OBJECTID)
5673 set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5674 &BTRFS_I(inode)->runtime_flags);
5678 static int btrfs_find_actor(struct inode *inode, void *opaque)
5680 struct btrfs_iget_args *args = opaque;
5682 return args->ino == BTRFS_I(inode)->location.objectid &&
5683 args->root == BTRFS_I(inode)->root;
5686 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5687 struct btrfs_root *root)
5689 struct inode *inode;
5690 struct btrfs_iget_args args;
5691 unsigned long hashval = btrfs_inode_hash(ino, root);
5696 inode = iget5_locked(s, hashval, btrfs_find_actor,
5697 btrfs_init_locked_inode,
5703 * Get an inode object given its inode number and corresponding root.
5704 * Path can be preallocated to prevent recursing back to iget through
5705 * allocator. NULL is also valid but may require an additional allocation
5708 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5709 struct btrfs_root *root, struct btrfs_path *path)
5711 struct inode *inode;
5713 inode = btrfs_iget_locked(s, ino, root);
5715 return ERR_PTR(-ENOMEM);
5717 if (inode->i_state & I_NEW) {
5720 ret = btrfs_read_locked_inode(inode, path);
5722 inode_tree_add(BTRFS_I(inode));
5723 unlock_new_inode(inode);
5727 * ret > 0 can come from btrfs_search_slot called by
5728 * btrfs_read_locked_inode, this means the inode item
5733 inode = ERR_PTR(ret);
5740 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5742 return btrfs_iget_path(s, ino, root, NULL);
5745 static struct inode *new_simple_dir(struct super_block *s,
5746 struct btrfs_key *key,
5747 struct btrfs_root *root)
5749 struct inode *inode = new_inode(s);
5752 return ERR_PTR(-ENOMEM);
5754 BTRFS_I(inode)->root = btrfs_grab_root(root);
5755 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5756 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5758 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5760 * We only need lookup, the rest is read-only and there's no inode
5761 * associated with the dentry
5763 inode->i_op = &simple_dir_inode_operations;
5764 inode->i_opflags &= ~IOP_XATTR;
5765 inode->i_fop = &simple_dir_operations;
5766 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5767 inode->i_mtime = current_time(inode);
5768 inode->i_atime = inode->i_mtime;
5769 inode->i_ctime = inode->i_mtime;
5770 BTRFS_I(inode)->i_otime = inode->i_mtime;
5775 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5776 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5777 static_assert(BTRFS_FT_DIR == FT_DIR);
5778 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5779 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5780 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5781 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5782 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5784 static inline u8 btrfs_inode_type(struct inode *inode)
5786 return fs_umode_to_ftype(inode->i_mode);
5789 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5791 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5792 struct inode *inode;
5793 struct btrfs_root *root = BTRFS_I(dir)->root;
5794 struct btrfs_root *sub_root = root;
5795 struct btrfs_key location;
5799 if (dentry->d_name.len > BTRFS_NAME_LEN)
5800 return ERR_PTR(-ENAMETOOLONG);
5802 ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
5804 return ERR_PTR(ret);
5806 if (location.type == BTRFS_INODE_ITEM_KEY) {
5807 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5811 /* Do extra check against inode mode with di_type */
5812 if (btrfs_inode_type(inode) != di_type) {
5814 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5815 inode->i_mode, btrfs_inode_type(inode),
5818 return ERR_PTR(-EUCLEAN);
5823 ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
5824 &location, &sub_root);
5827 inode = ERR_PTR(ret);
5829 inode = new_simple_dir(dir->i_sb, &location, root);
5831 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5832 btrfs_put_root(sub_root);
5837 down_read(&fs_info->cleanup_work_sem);
5838 if (!sb_rdonly(inode->i_sb))
5839 ret = btrfs_orphan_cleanup(sub_root);
5840 up_read(&fs_info->cleanup_work_sem);
5843 inode = ERR_PTR(ret);
5850 static int btrfs_dentry_delete(const struct dentry *dentry)
5852 struct btrfs_root *root;
5853 struct inode *inode = d_inode(dentry);
5855 if (!inode && !IS_ROOT(dentry))
5856 inode = d_inode(dentry->d_parent);
5859 root = BTRFS_I(inode)->root;
5860 if (btrfs_root_refs(&root->root_item) == 0)
5863 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5869 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5872 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5874 if (inode == ERR_PTR(-ENOENT))
5876 return d_splice_alias(inode, dentry);
5880 * Find the highest existing sequence number in a directory and then set the
5881 * in-memory index_cnt variable to the first free sequence number.
5883 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5885 struct btrfs_root *root = inode->root;
5886 struct btrfs_key key, found_key;
5887 struct btrfs_path *path;
5888 struct extent_buffer *leaf;
5891 key.objectid = btrfs_ino(inode);
5892 key.type = BTRFS_DIR_INDEX_KEY;
5893 key.offset = (u64)-1;
5895 path = btrfs_alloc_path();
5899 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5902 /* FIXME: we should be able to handle this */
5907 if (path->slots[0] == 0) {
5908 inode->index_cnt = BTRFS_DIR_START_INDEX;
5914 leaf = path->nodes[0];
5915 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5917 if (found_key.objectid != btrfs_ino(inode) ||
5918 found_key.type != BTRFS_DIR_INDEX_KEY) {
5919 inode->index_cnt = BTRFS_DIR_START_INDEX;
5923 inode->index_cnt = found_key.offset + 1;
5925 btrfs_free_path(path);
5929 static int btrfs_get_dir_last_index(struct btrfs_inode *dir, u64 *index)
5931 if (dir->index_cnt == (u64)-1) {
5934 ret = btrfs_inode_delayed_dir_index_count(dir);
5936 ret = btrfs_set_inode_index_count(dir);
5942 *index = dir->index_cnt;
5948 * All this infrastructure exists because dir_emit can fault, and we are holding
5949 * the tree lock when doing readdir. For now just allocate a buffer and copy
5950 * our information into that, and then dir_emit from the buffer. This is
5951 * similar to what NFS does, only we don't keep the buffer around in pagecache
5952 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5953 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5956 static int btrfs_opendir(struct inode *inode, struct file *file)
5958 struct btrfs_file_private *private;
5962 ret = btrfs_get_dir_last_index(BTRFS_I(inode), &last_index);
5966 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5969 private->last_index = last_index;
5970 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5971 if (!private->filldir_buf) {
5975 file->private_data = private;
5986 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5989 struct dir_entry *entry = addr;
5990 char *name = (char *)(entry + 1);
5992 ctx->pos = get_unaligned(&entry->offset);
5993 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5994 get_unaligned(&entry->ino),
5995 get_unaligned(&entry->type)))
5997 addr += sizeof(struct dir_entry) +
5998 get_unaligned(&entry->name_len);
6004 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6006 struct inode *inode = file_inode(file);
6007 struct btrfs_root *root = BTRFS_I(inode)->root;
6008 struct btrfs_file_private *private = file->private_data;
6009 struct btrfs_dir_item *di;
6010 struct btrfs_key key;
6011 struct btrfs_key found_key;
6012 struct btrfs_path *path;
6014 struct list_head ins_list;
6015 struct list_head del_list;
6022 struct btrfs_key location;
6024 if (!dir_emit_dots(file, ctx))
6027 path = btrfs_alloc_path();
6031 addr = private->filldir_buf;
6032 path->reada = READA_FORWARD;
6034 INIT_LIST_HEAD(&ins_list);
6035 INIT_LIST_HEAD(&del_list);
6036 put = btrfs_readdir_get_delayed_items(inode, private->last_index,
6037 &ins_list, &del_list);
6040 key.type = BTRFS_DIR_INDEX_KEY;
6041 key.offset = ctx->pos;
6042 key.objectid = btrfs_ino(BTRFS_I(inode));
6044 btrfs_for_each_slot(root, &key, &found_key, path, ret) {
6045 struct dir_entry *entry;
6046 struct extent_buffer *leaf = path->nodes[0];
6049 if (found_key.objectid != key.objectid)
6051 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6053 if (found_key.offset < ctx->pos)
6055 if (found_key.offset > private->last_index)
6057 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6059 di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
6060 name_len = btrfs_dir_name_len(leaf, di);
6061 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6063 btrfs_release_path(path);
6064 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6067 addr = private->filldir_buf;
6073 ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
6075 name_ptr = (char *)(entry + 1);
6076 read_extent_buffer(leaf, name_ptr,
6077 (unsigned long)(di + 1), name_len);
6078 put_unaligned(name_len, &entry->name_len);
6079 put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
6080 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6081 put_unaligned(location.objectid, &entry->ino);
6082 put_unaligned(found_key.offset, &entry->offset);
6084 addr += sizeof(struct dir_entry) + name_len;
6085 total_len += sizeof(struct dir_entry) + name_len;
6087 /* Catch error encountered during iteration */
6091 btrfs_release_path(path);
6093 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6097 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6102 * Stop new entries from being returned after we return the last
6105 * New directory entries are assigned a strictly increasing
6106 * offset. This means that new entries created during readdir
6107 * are *guaranteed* to be seen in the future by that readdir.
6108 * This has broken buggy programs which operate on names as
6109 * they're returned by readdir. Until we re-use freed offsets
6110 * we have this hack to stop new entries from being returned
6111 * under the assumption that they'll never reach this huge
6114 * This is being careful not to overflow 32bit loff_t unless the
6115 * last entry requires it because doing so has broken 32bit apps
6118 if (ctx->pos >= INT_MAX)
6119 ctx->pos = LLONG_MAX;
6126 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6127 btrfs_free_path(path);
6132 * This is somewhat expensive, updating the tree every time the
6133 * inode changes. But, it is most likely to find the inode in cache.
6134 * FIXME, needs more benchmarking...there are no reasons other than performance
6135 * to keep or drop this code.
6137 static int btrfs_dirty_inode(struct btrfs_inode *inode)
6139 struct btrfs_root *root = inode->root;
6140 struct btrfs_fs_info *fs_info = root->fs_info;
6141 struct btrfs_trans_handle *trans;
6144 if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
6147 trans = btrfs_join_transaction(root);
6149 return PTR_ERR(trans);
6151 ret = btrfs_update_inode(trans, root, inode);
6152 if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6153 /* whoops, lets try again with the full transaction */
6154 btrfs_end_transaction(trans);
6155 trans = btrfs_start_transaction(root, 1);
6157 return PTR_ERR(trans);
6159 ret = btrfs_update_inode(trans, root, inode);
6161 btrfs_end_transaction(trans);
6162 if (inode->delayed_node)
6163 btrfs_balance_delayed_items(fs_info);
6169 * This is a copy of file_update_time. We need this so we can return error on
6170 * ENOSPC for updating the inode in the case of file write and mmap writes.
6172 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6175 struct btrfs_root *root = BTRFS_I(inode)->root;
6176 bool dirty = flags & ~S_VERSION;
6178 if (btrfs_root_readonly(root))
6181 if (flags & S_VERSION)
6182 dirty |= inode_maybe_inc_iversion(inode, dirty);
6183 if (flags & S_CTIME)
6184 inode->i_ctime = *now;
6185 if (flags & S_MTIME)
6186 inode->i_mtime = *now;
6187 if (flags & S_ATIME)
6188 inode->i_atime = *now;
6189 return dirty ? btrfs_dirty_inode(BTRFS_I(inode)) : 0;
6193 * helper to find a free sequence number in a given directory. This current
6194 * code is very simple, later versions will do smarter things in the btree
6196 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6200 if (dir->index_cnt == (u64)-1) {
6201 ret = btrfs_inode_delayed_dir_index_count(dir);
6203 ret = btrfs_set_inode_index_count(dir);
6209 *index = dir->index_cnt;
6215 static int btrfs_insert_inode_locked(struct inode *inode)
6217 struct btrfs_iget_args args;
6219 args.ino = BTRFS_I(inode)->location.objectid;
6220 args.root = BTRFS_I(inode)->root;
6222 return insert_inode_locked4(inode,
6223 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6224 btrfs_find_actor, &args);
6227 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6228 unsigned int *trans_num_items)
6230 struct inode *dir = args->dir;
6231 struct inode *inode = args->inode;
6234 if (!args->orphan) {
6235 ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6241 ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6243 fscrypt_free_filename(&args->fname);
6247 /* 1 to add inode item */
6248 *trans_num_items = 1;
6249 /* 1 to add compression property */
6250 if (BTRFS_I(dir)->prop_compress)
6251 (*trans_num_items)++;
6252 /* 1 to add default ACL xattr */
6253 if (args->default_acl)
6254 (*trans_num_items)++;
6255 /* 1 to add access ACL xattr */
6257 (*trans_num_items)++;
6258 #ifdef CONFIG_SECURITY
6259 /* 1 to add LSM xattr */
6260 if (dir->i_security)
6261 (*trans_num_items)++;
6264 /* 1 to add orphan item */
6265 (*trans_num_items)++;
6269 * 1 to add dir index
6270 * 1 to update parent inode item
6272 * No need for 1 unit for the inode ref item because it is
6273 * inserted in a batch together with the inode item at
6274 * btrfs_create_new_inode().
6276 *trans_num_items += 3;
6281 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6283 posix_acl_release(args->acl);
6284 posix_acl_release(args->default_acl);
6285 fscrypt_free_filename(&args->fname);
6289 * Inherit flags from the parent inode.
6291 * Currently only the compression flags and the cow flags are inherited.
6293 static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
6299 if (flags & BTRFS_INODE_NOCOMPRESS) {
6300 inode->flags &= ~BTRFS_INODE_COMPRESS;
6301 inode->flags |= BTRFS_INODE_NOCOMPRESS;
6302 } else if (flags & BTRFS_INODE_COMPRESS) {
6303 inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
6304 inode->flags |= BTRFS_INODE_COMPRESS;
6307 if (flags & BTRFS_INODE_NODATACOW) {
6308 inode->flags |= BTRFS_INODE_NODATACOW;
6309 if (S_ISREG(inode->vfs_inode.i_mode))
6310 inode->flags |= BTRFS_INODE_NODATASUM;
6313 btrfs_sync_inode_flags_to_i_flags(&inode->vfs_inode);
6316 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6317 struct btrfs_new_inode_args *args)
6319 struct inode *dir = args->dir;
6320 struct inode *inode = args->inode;
6321 const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6322 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6323 struct btrfs_root *root;
6324 struct btrfs_inode_item *inode_item;
6325 struct btrfs_key *location;
6326 struct btrfs_path *path;
6328 struct btrfs_inode_ref *ref;
6329 struct btrfs_key key[2];
6331 struct btrfs_item_batch batch;
6335 path = btrfs_alloc_path();
6340 BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6341 root = BTRFS_I(inode)->root;
6343 ret = btrfs_get_free_objectid(root, &objectid);
6346 inode->i_ino = objectid;
6350 * O_TMPFILE, set link count to 0, so that after this point, we
6351 * fill in an inode item with the correct link count.
6353 set_nlink(inode, 0);
6355 trace_btrfs_inode_request(dir);
6357 ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6361 /* index_cnt is ignored for everything but a dir. */
6362 BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6363 BTRFS_I(inode)->generation = trans->transid;
6364 inode->i_generation = BTRFS_I(inode)->generation;
6367 * Subvolumes don't inherit flags from their parent directory.
6368 * Originally this was probably by accident, but we probably can't
6369 * change it now without compatibility issues.
6372 btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
6374 if (S_ISREG(inode->i_mode)) {
6375 if (btrfs_test_opt(fs_info, NODATASUM))
6376 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6377 if (btrfs_test_opt(fs_info, NODATACOW))
6378 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6379 BTRFS_INODE_NODATASUM;
6382 location = &BTRFS_I(inode)->location;
6383 location->objectid = objectid;
6384 location->offset = 0;
6385 location->type = BTRFS_INODE_ITEM_KEY;
6387 ret = btrfs_insert_inode_locked(inode);
6390 BTRFS_I(dir)->index_cnt--;
6395 * We could have gotten an inode number from somebody who was fsynced
6396 * and then removed in this same transaction, so let's just set full
6397 * sync since it will be a full sync anyway and this will blow away the
6398 * old info in the log.
6400 btrfs_set_inode_full_sync(BTRFS_I(inode));
6402 key[0].objectid = objectid;
6403 key[0].type = BTRFS_INODE_ITEM_KEY;
6406 sizes[0] = sizeof(struct btrfs_inode_item);
6408 if (!args->orphan) {
6410 * Start new inodes with an inode_ref. This is slightly more
6411 * efficient for small numbers of hard links since they will
6412 * be packed into one item. Extended refs will kick in if we
6413 * add more hard links than can fit in the ref item.
6415 key[1].objectid = objectid;
6416 key[1].type = BTRFS_INODE_REF_KEY;
6418 key[1].offset = objectid;
6419 sizes[1] = 2 + sizeof(*ref);
6421 key[1].offset = btrfs_ino(BTRFS_I(dir));
6422 sizes[1] = name->len + sizeof(*ref);
6426 batch.keys = &key[0];
6427 batch.data_sizes = &sizes[0];
6428 batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6429 batch.nr = args->orphan ? 1 : 2;
6430 ret = btrfs_insert_empty_items(trans, root, path, &batch);
6432 btrfs_abort_transaction(trans, ret);
6436 inode->i_mtime = current_time(inode);
6437 inode->i_atime = inode->i_mtime;
6438 inode->i_ctime = inode->i_mtime;
6439 BTRFS_I(inode)->i_otime = inode->i_mtime;
6442 * We're going to fill the inode item now, so at this point the inode
6443 * must be fully initialized.
6446 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6447 struct btrfs_inode_item);
6448 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6449 sizeof(*inode_item));
6450 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6452 if (!args->orphan) {
6453 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6454 struct btrfs_inode_ref);
6455 ptr = (unsigned long)(ref + 1);
6457 btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6458 btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6459 write_extent_buffer(path->nodes[0], "..", ptr, 2);
6461 btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6463 btrfs_set_inode_ref_index(path->nodes[0], ref,
6464 BTRFS_I(inode)->dir_index);
6465 write_extent_buffer(path->nodes[0], name->name, ptr,
6470 btrfs_mark_buffer_dirty(path->nodes[0]);
6472 * We don't need the path anymore, plus inheriting properties, adding
6473 * ACLs, security xattrs, orphan item or adding the link, will result in
6474 * allocating yet another path. So just free our path.
6476 btrfs_free_path(path);
6480 struct inode *parent;
6483 * Subvolumes inherit properties from their parent subvolume,
6484 * not the directory they were created in.
6486 parent = btrfs_iget(fs_info->sb, BTRFS_FIRST_FREE_OBJECTID,
6487 BTRFS_I(dir)->root);
6488 if (IS_ERR(parent)) {
6489 ret = PTR_ERR(parent);
6491 ret = btrfs_inode_inherit_props(trans, inode, parent);
6495 ret = btrfs_inode_inherit_props(trans, inode, dir);
6499 "error inheriting props for ino %llu (root %llu): %d",
6500 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid,
6505 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6508 if (!args->subvol) {
6509 ret = btrfs_init_inode_security(trans, args);
6511 btrfs_abort_transaction(trans, ret);
6516 inode_tree_add(BTRFS_I(inode));
6518 trace_btrfs_inode_new(inode);
6519 btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6521 btrfs_update_root_times(trans, root);
6524 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6526 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6527 0, BTRFS_I(inode)->dir_index);
6530 btrfs_abort_transaction(trans, ret);
6538 * discard_new_inode() calls iput(), but the caller owns the reference
6542 discard_new_inode(inode);
6544 btrfs_free_path(path);
6549 * utility function to add 'inode' into 'parent_inode' with
6550 * a give name and a given sequence number.
6551 * if 'add_backref' is true, also insert a backref from the
6552 * inode to the parent directory.
6554 int btrfs_add_link(struct btrfs_trans_handle *trans,
6555 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6556 const struct fscrypt_str *name, int add_backref, u64 index)
6559 struct btrfs_key key;
6560 struct btrfs_root *root = parent_inode->root;
6561 u64 ino = btrfs_ino(inode);
6562 u64 parent_ino = btrfs_ino(parent_inode);
6564 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6565 memcpy(&key, &inode->root->root_key, sizeof(key));
6568 key.type = BTRFS_INODE_ITEM_KEY;
6572 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6573 ret = btrfs_add_root_ref(trans, key.objectid,
6574 root->root_key.objectid, parent_ino,
6576 } else if (add_backref) {
6577 ret = btrfs_insert_inode_ref(trans, root, name,
6578 ino, parent_ino, index);
6581 /* Nothing to clean up yet */
6585 ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6586 btrfs_inode_type(&inode->vfs_inode), index);
6587 if (ret == -EEXIST || ret == -EOVERFLOW)
6590 btrfs_abort_transaction(trans, ret);
6594 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6596 inode_inc_iversion(&parent_inode->vfs_inode);
6598 * If we are replaying a log tree, we do not want to update the mtime
6599 * and ctime of the parent directory with the current time, since the
6600 * log replay procedure is responsible for setting them to their correct
6601 * values (the ones it had when the fsync was done).
6603 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6604 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6606 parent_inode->vfs_inode.i_mtime = now;
6607 parent_inode->vfs_inode.i_ctime = now;
6609 ret = btrfs_update_inode(trans, root, parent_inode);
6611 btrfs_abort_transaction(trans, ret);
6615 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6618 err = btrfs_del_root_ref(trans, key.objectid,
6619 root->root_key.objectid, parent_ino,
6620 &local_index, name);
6622 btrfs_abort_transaction(trans, err);
6623 } else if (add_backref) {
6627 err = btrfs_del_inode_ref(trans, root, name, ino, parent_ino,
6630 btrfs_abort_transaction(trans, err);
6633 /* Return the original error code */
6637 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6638 struct inode *inode)
6640 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6641 struct btrfs_root *root = BTRFS_I(dir)->root;
6642 struct btrfs_new_inode_args new_inode_args = {
6647 unsigned int trans_num_items;
6648 struct btrfs_trans_handle *trans;
6651 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6655 trans = btrfs_start_transaction(root, trans_num_items);
6656 if (IS_ERR(trans)) {
6657 err = PTR_ERR(trans);
6658 goto out_new_inode_args;
6661 err = btrfs_create_new_inode(trans, &new_inode_args);
6663 d_instantiate_new(dentry, inode);
6665 btrfs_end_transaction(trans);
6666 btrfs_btree_balance_dirty(fs_info);
6668 btrfs_new_inode_args_destroy(&new_inode_args);
6675 static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
6676 struct dentry *dentry, umode_t mode, dev_t rdev)
6678 struct inode *inode;
6680 inode = new_inode(dir->i_sb);
6683 inode_init_owner(idmap, inode, dir, mode);
6684 inode->i_op = &btrfs_special_inode_operations;
6685 init_special_inode(inode, inode->i_mode, rdev);
6686 return btrfs_create_common(dir, dentry, inode);
6689 static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
6690 struct dentry *dentry, umode_t mode, bool excl)
6692 struct inode *inode;
6694 inode = new_inode(dir->i_sb);
6697 inode_init_owner(idmap, inode, dir, mode);
6698 inode->i_fop = &btrfs_file_operations;
6699 inode->i_op = &btrfs_file_inode_operations;
6700 inode->i_mapping->a_ops = &btrfs_aops;
6701 return btrfs_create_common(dir, dentry, inode);
6704 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6705 struct dentry *dentry)
6707 struct btrfs_trans_handle *trans = NULL;
6708 struct btrfs_root *root = BTRFS_I(dir)->root;
6709 struct inode *inode = d_inode(old_dentry);
6710 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6711 struct fscrypt_name fname;
6716 /* do not allow sys_link's with other subvols of the same device */
6717 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6720 if (inode->i_nlink >= BTRFS_LINK_MAX)
6723 err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
6727 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6732 * 2 items for inode and inode ref
6733 * 2 items for dir items
6734 * 1 item for parent inode
6735 * 1 item for orphan item deletion if O_TMPFILE
6737 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6738 if (IS_ERR(trans)) {
6739 err = PTR_ERR(trans);
6744 /* There are several dir indexes for this inode, clear the cache. */
6745 BTRFS_I(inode)->dir_index = 0ULL;
6747 inode_inc_iversion(inode);
6748 inode->i_ctime = current_time(inode);
6750 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6752 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6753 &fname.disk_name, 1, index);
6758 struct dentry *parent = dentry->d_parent;
6760 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6763 if (inode->i_nlink == 1) {
6765 * If new hard link count is 1, it's a file created
6766 * with open(2) O_TMPFILE flag.
6768 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6772 d_instantiate(dentry, inode);
6773 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6777 fscrypt_free_filename(&fname);
6779 btrfs_end_transaction(trans);
6781 inode_dec_link_count(inode);
6784 btrfs_btree_balance_dirty(fs_info);
6788 static int btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
6789 struct dentry *dentry, umode_t mode)
6791 struct inode *inode;
6793 inode = new_inode(dir->i_sb);
6796 inode_init_owner(idmap, inode, dir, S_IFDIR | mode);
6797 inode->i_op = &btrfs_dir_inode_operations;
6798 inode->i_fop = &btrfs_dir_file_operations;
6799 return btrfs_create_common(dir, dentry, inode);
6802 static noinline int uncompress_inline(struct btrfs_path *path,
6804 struct btrfs_file_extent_item *item)
6807 struct extent_buffer *leaf = path->nodes[0];
6810 unsigned long inline_size;
6814 compress_type = btrfs_file_extent_compression(leaf, item);
6815 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6816 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6817 tmp = kmalloc(inline_size, GFP_NOFS);
6820 ptr = btrfs_file_extent_inline_start(item);
6822 read_extent_buffer(leaf, tmp, ptr, inline_size);
6824 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6825 ret = btrfs_decompress(compress_type, tmp, page, 0, inline_size, max_size);
6828 * decompression code contains a memset to fill in any space between the end
6829 * of the uncompressed data and the end of max_size in case the decompressed
6830 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6831 * the end of an inline extent and the beginning of the next block, so we
6832 * cover that region here.
6835 if (max_size < PAGE_SIZE)
6836 memzero_page(page, max_size, PAGE_SIZE - max_size);
6841 static int read_inline_extent(struct btrfs_inode *inode, struct btrfs_path *path,
6844 struct btrfs_file_extent_item *fi;
6848 if (!page || PageUptodate(page))
6851 ASSERT(page_offset(page) == 0);
6853 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6854 struct btrfs_file_extent_item);
6855 if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
6856 return uncompress_inline(path, page, fi);
6858 copy_size = min_t(u64, PAGE_SIZE,
6859 btrfs_file_extent_ram_bytes(path->nodes[0], fi));
6860 kaddr = kmap_local_page(page);
6861 read_extent_buffer(path->nodes[0], kaddr,
6862 btrfs_file_extent_inline_start(fi), copy_size);
6863 kunmap_local(kaddr);
6864 if (copy_size < PAGE_SIZE)
6865 memzero_page(page, copy_size, PAGE_SIZE - copy_size);
6870 * Lookup the first extent overlapping a range in a file.
6872 * @inode: file to search in
6873 * @page: page to read extent data into if the extent is inline
6874 * @pg_offset: offset into @page to copy to
6875 * @start: file offset
6876 * @len: length of range starting at @start
6878 * Return the first &struct extent_map which overlaps the given range, reading
6879 * it from the B-tree and caching it if necessary. Note that there may be more
6880 * extents which overlap the given range after the returned extent_map.
6882 * If @page is not NULL and the extent is inline, this also reads the extent
6883 * data directly into the page and marks the extent up to date in the io_tree.
6885 * Return: ERR_PTR on error, non-NULL extent_map on success.
6887 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6888 struct page *page, size_t pg_offset,
6891 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6893 u64 extent_start = 0;
6895 u64 objectid = btrfs_ino(inode);
6896 int extent_type = -1;
6897 struct btrfs_path *path = NULL;
6898 struct btrfs_root *root = inode->root;
6899 struct btrfs_file_extent_item *item;
6900 struct extent_buffer *leaf;
6901 struct btrfs_key found_key;
6902 struct extent_map *em = NULL;
6903 struct extent_map_tree *em_tree = &inode->extent_tree;
6905 read_lock(&em_tree->lock);
6906 em = lookup_extent_mapping(em_tree, start, len);
6907 read_unlock(&em_tree->lock);
6910 if (em->start > start || em->start + em->len <= start)
6911 free_extent_map(em);
6912 else if (em->block_start == EXTENT_MAP_INLINE && page)
6913 free_extent_map(em);
6917 em = alloc_extent_map();
6922 em->start = EXTENT_MAP_HOLE;
6923 em->orig_start = EXTENT_MAP_HOLE;
6925 em->block_len = (u64)-1;
6927 path = btrfs_alloc_path();
6933 /* Chances are we'll be called again, so go ahead and do readahead */
6934 path->reada = READA_FORWARD;
6937 * The same explanation in load_free_space_cache applies here as well,
6938 * we only read when we're loading the free space cache, and at that
6939 * point the commit_root has everything we need.
6941 if (btrfs_is_free_space_inode(inode)) {
6942 path->search_commit_root = 1;
6943 path->skip_locking = 1;
6946 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6949 } else if (ret > 0) {
6950 if (path->slots[0] == 0)
6956 leaf = path->nodes[0];
6957 item = btrfs_item_ptr(leaf, path->slots[0],
6958 struct btrfs_file_extent_item);
6959 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6960 if (found_key.objectid != objectid ||
6961 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6963 * If we backup past the first extent we want to move forward
6964 * and see if there is an extent in front of us, otherwise we'll
6965 * say there is a hole for our whole search range which can
6972 extent_type = btrfs_file_extent_type(leaf, item);
6973 extent_start = found_key.offset;
6974 extent_end = btrfs_file_extent_end(path);
6975 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6976 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6977 /* Only regular file could have regular/prealloc extent */
6978 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6981 "regular/prealloc extent found for non-regular inode %llu",
6985 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6987 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6988 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6993 if (start >= extent_end) {
6995 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6996 ret = btrfs_next_leaf(root, path);
7002 leaf = path->nodes[0];
7004 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7005 if (found_key.objectid != objectid ||
7006 found_key.type != BTRFS_EXTENT_DATA_KEY)
7008 if (start + len <= found_key.offset)
7010 if (start > found_key.offset)
7013 /* New extent overlaps with existing one */
7015 em->orig_start = start;
7016 em->len = found_key.offset - start;
7017 em->block_start = EXTENT_MAP_HOLE;
7021 btrfs_extent_item_to_extent_map(inode, path, item, em);
7023 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7024 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7026 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7028 * Inline extent can only exist at file offset 0. This is
7029 * ensured by tree-checker and inline extent creation path.
7030 * Thus all members representing file offsets should be zero.
7032 ASSERT(pg_offset == 0);
7033 ASSERT(extent_start == 0);
7034 ASSERT(em->start == 0);
7037 * btrfs_extent_item_to_extent_map() should have properly
7038 * initialized em members already.
7040 * Other members are not utilized for inline extents.
7042 ASSERT(em->block_start == EXTENT_MAP_INLINE);
7043 ASSERT(em->len == fs_info->sectorsize);
7045 ret = read_inline_extent(inode, path, page);
7052 em->orig_start = start;
7054 em->block_start = EXTENT_MAP_HOLE;
7057 btrfs_release_path(path);
7058 if (em->start > start || extent_map_end(em) <= start) {
7060 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7061 em->start, em->len, start, len);
7066 write_lock(&em_tree->lock);
7067 ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7068 write_unlock(&em_tree->lock);
7070 btrfs_free_path(path);
7072 trace_btrfs_get_extent(root, inode, em);
7075 free_extent_map(em);
7076 return ERR_PTR(ret);
7081 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7082 struct btrfs_dio_data *dio_data,
7085 const u64 orig_start,
7086 const u64 block_start,
7087 const u64 block_len,
7088 const u64 orig_block_len,
7089 const u64 ram_bytes,
7092 struct extent_map *em = NULL;
7093 struct btrfs_ordered_extent *ordered;
7095 if (type != BTRFS_ORDERED_NOCOW) {
7096 em = create_io_em(inode, start, len, orig_start, block_start,
7097 block_len, orig_block_len, ram_bytes,
7098 BTRFS_COMPRESS_NONE, /* compress_type */
7103 ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
7104 block_start, block_len, 0,
7106 (1 << BTRFS_ORDERED_DIRECT),
7107 BTRFS_COMPRESS_NONE);
7108 if (IS_ERR(ordered)) {
7110 free_extent_map(em);
7111 btrfs_drop_extent_map_range(inode, start,
7112 start + len - 1, false);
7114 em = ERR_CAST(ordered);
7116 ASSERT(!dio_data->ordered);
7117 dio_data->ordered = ordered;
7124 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7125 struct btrfs_dio_data *dio_data,
7128 struct btrfs_root *root = inode->root;
7129 struct btrfs_fs_info *fs_info = root->fs_info;
7130 struct extent_map *em;
7131 struct btrfs_key ins;
7135 alloc_hint = get_extent_allocation_hint(inode, start, len);
7136 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7137 0, alloc_hint, &ins, 1, 1);
7139 return ERR_PTR(ret);
7141 em = btrfs_create_dio_extent(inode, dio_data, start, ins.offset, start,
7142 ins.objectid, ins.offset, ins.offset,
7143 ins.offset, BTRFS_ORDERED_REGULAR);
7144 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7146 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7152 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7154 struct btrfs_block_group *block_group;
7155 bool readonly = false;
7157 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7158 if (!block_group || block_group->ro)
7161 btrfs_put_block_group(block_group);
7166 * Check if we can do nocow write into the range [@offset, @offset + @len)
7168 * @offset: File offset
7169 * @len: The length to write, will be updated to the nocow writeable
7171 * @orig_start: (optional) Return the original file offset of the file extent
7172 * @orig_len: (optional) Return the original on-disk length of the file extent
7173 * @ram_bytes: (optional) Return the ram_bytes of the file extent
7174 * @strict: if true, omit optimizations that might force us into unnecessary
7175 * cow. e.g., don't trust generation number.
7178 * >0 and update @len if we can do nocow write
7179 * 0 if we can't do nocow write
7180 * <0 if error happened
7182 * NOTE: This only checks the file extents, caller is responsible to wait for
7183 * any ordered extents.
7185 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7186 u64 *orig_start, u64 *orig_block_len,
7187 u64 *ram_bytes, bool nowait, bool strict)
7189 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7190 struct can_nocow_file_extent_args nocow_args = { 0 };
7191 struct btrfs_path *path;
7193 struct extent_buffer *leaf;
7194 struct btrfs_root *root = BTRFS_I(inode)->root;
7195 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7196 struct btrfs_file_extent_item *fi;
7197 struct btrfs_key key;
7200 path = btrfs_alloc_path();
7203 path->nowait = nowait;
7205 ret = btrfs_lookup_file_extent(NULL, root, path,
7206 btrfs_ino(BTRFS_I(inode)), offset, 0);
7211 if (path->slots[0] == 0) {
7212 /* can't find the item, must cow */
7219 leaf = path->nodes[0];
7220 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7221 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7222 key.type != BTRFS_EXTENT_DATA_KEY) {
7223 /* not our file or wrong item type, must cow */
7227 if (key.offset > offset) {
7228 /* Wrong offset, must cow */
7232 if (btrfs_file_extent_end(path) <= offset)
7235 fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7236 found_type = btrfs_file_extent_type(leaf, fi);
7238 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7240 nocow_args.start = offset;
7241 nocow_args.end = offset + *len - 1;
7242 nocow_args.strict = strict;
7243 nocow_args.free_path = true;
7245 ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
7246 /* can_nocow_file_extent() has freed the path. */
7250 /* Treat errors as not being able to NOCOW. */
7256 if (btrfs_extent_readonly(fs_info, nocow_args.disk_bytenr))
7259 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7260 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7263 range_end = round_up(offset + nocow_args.num_bytes,
7264 root->fs_info->sectorsize) - 1;
7265 ret = test_range_bit(io_tree, offset, range_end,
7266 EXTENT_DELALLOC, 0, NULL);
7274 *orig_start = key.offset - nocow_args.extent_offset;
7276 *orig_block_len = nocow_args.disk_num_bytes;
7278 *len = nocow_args.num_bytes;
7281 btrfs_free_path(path);
7285 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7286 struct extent_state **cached_state,
7287 unsigned int iomap_flags)
7289 const bool writing = (iomap_flags & IOMAP_WRITE);
7290 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7291 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7292 struct btrfs_ordered_extent *ordered;
7297 if (!try_lock_extent(io_tree, lockstart, lockend,
7301 lock_extent(io_tree, lockstart, lockend, cached_state);
7304 * We're concerned with the entire range that we're going to be
7305 * doing DIO to, so we need to make sure there's no ordered
7306 * extents in this range.
7308 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7309 lockend - lockstart + 1);
7312 * We need to make sure there are no buffered pages in this
7313 * range either, we could have raced between the invalidate in
7314 * generic_file_direct_write and locking the extent. The
7315 * invalidate needs to happen so that reads after a write do not
7319 (!writing || !filemap_range_has_page(inode->i_mapping,
7320 lockstart, lockend)))
7323 unlock_extent(io_tree, lockstart, lockend, cached_state);
7327 btrfs_put_ordered_extent(ordered);
7332 * If we are doing a DIO read and the ordered extent we
7333 * found is for a buffered write, we can not wait for it
7334 * to complete and retry, because if we do so we can
7335 * deadlock with concurrent buffered writes on page
7336 * locks. This happens only if our DIO read covers more
7337 * than one extent map, if at this point has already
7338 * created an ordered extent for a previous extent map
7339 * and locked its range in the inode's io tree, and a
7340 * concurrent write against that previous extent map's
7341 * range and this range started (we unlock the ranges
7342 * in the io tree only when the bios complete and
7343 * buffered writes always lock pages before attempting
7344 * to lock range in the io tree).
7347 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7348 btrfs_start_ordered_extent(ordered);
7350 ret = nowait ? -EAGAIN : -ENOTBLK;
7351 btrfs_put_ordered_extent(ordered);
7354 * We could trigger writeback for this range (and wait
7355 * for it to complete) and then invalidate the pages for
7356 * this range (through invalidate_inode_pages2_range()),
7357 * but that can lead us to a deadlock with a concurrent
7358 * call to readahead (a buffered read or a defrag call
7359 * triggered a readahead) on a page lock due to an
7360 * ordered dio extent we created before but did not have
7361 * yet a corresponding bio submitted (whence it can not
7362 * complete), which makes readahead wait for that
7363 * ordered extent to complete while holding a lock on
7366 ret = nowait ? -EAGAIN : -ENOTBLK;
7378 /* The callers of this must take lock_extent() */
7379 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7380 u64 len, u64 orig_start, u64 block_start,
7381 u64 block_len, u64 orig_block_len,
7382 u64 ram_bytes, int compress_type,
7385 struct extent_map *em;
7388 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7389 type == BTRFS_ORDERED_COMPRESSED ||
7390 type == BTRFS_ORDERED_NOCOW ||
7391 type == BTRFS_ORDERED_REGULAR);
7393 em = alloc_extent_map();
7395 return ERR_PTR(-ENOMEM);
7398 em->orig_start = orig_start;
7400 em->block_len = block_len;
7401 em->block_start = block_start;
7402 em->orig_block_len = orig_block_len;
7403 em->ram_bytes = ram_bytes;
7404 em->generation = -1;
7405 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7406 if (type == BTRFS_ORDERED_PREALLOC) {
7407 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7408 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7409 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7410 em->compress_type = compress_type;
7413 ret = btrfs_replace_extent_map_range(inode, em, true);
7415 free_extent_map(em);
7416 return ERR_PTR(ret);
7419 /* em got 2 refs now, callers needs to do free_extent_map once. */
7424 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7425 struct inode *inode,
7426 struct btrfs_dio_data *dio_data,
7427 u64 start, u64 *lenp,
7428 unsigned int iomap_flags)
7430 const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7431 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7432 struct extent_map *em = *map;
7434 u64 block_start, orig_start, orig_block_len, ram_bytes;
7435 struct btrfs_block_group *bg;
7436 bool can_nocow = false;
7437 bool space_reserved = false;
7443 * We don't allocate a new extent in the following cases
7445 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7447 * 2) The extent is marked as PREALLOC. We're good to go here and can
7448 * just use the extent.
7451 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7452 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7453 em->block_start != EXTENT_MAP_HOLE)) {
7454 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7455 type = BTRFS_ORDERED_PREALLOC;
7457 type = BTRFS_ORDERED_NOCOW;
7458 len = min(len, em->len - (start - em->start));
7459 block_start = em->block_start + (start - em->start);
7461 if (can_nocow_extent(inode, start, &len, &orig_start,
7462 &orig_block_len, &ram_bytes, false, false) == 1) {
7463 bg = btrfs_inc_nocow_writers(fs_info, block_start);
7471 struct extent_map *em2;
7473 /* We can NOCOW, so only need to reserve metadata space. */
7474 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7477 /* Our caller expects us to free the input extent map. */
7478 free_extent_map(em);
7480 btrfs_dec_nocow_writers(bg);
7481 if (nowait && (ret == -ENOSPC || ret == -EDQUOT))
7485 space_reserved = true;
7487 em2 = btrfs_create_dio_extent(BTRFS_I(inode), dio_data, start, len,
7488 orig_start, block_start,
7489 len, orig_block_len,
7491 btrfs_dec_nocow_writers(bg);
7492 if (type == BTRFS_ORDERED_PREALLOC) {
7493 free_extent_map(em);
7503 dio_data->nocow_done = true;
7505 /* Our caller expects us to free the input extent map. */
7506 free_extent_map(em);
7515 * If we could not allocate data space before locking the file
7516 * range and we can't do a NOCOW write, then we have to fail.
7518 if (!dio_data->data_space_reserved) {
7524 * We have to COW and we have already reserved data space before,
7525 * so now we reserve only metadata.
7527 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7531 space_reserved = true;
7533 em = btrfs_new_extent_direct(BTRFS_I(inode), dio_data, start, len);
7539 len = min(len, em->len - (start - em->start));
7541 btrfs_delalloc_release_metadata(BTRFS_I(inode),
7542 prev_len - len, true);
7546 * We have created our ordered extent, so we can now release our reservation
7547 * for an outstanding extent.
7549 btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
7552 * Need to update the i_size under the extent lock so buffered
7553 * readers will get the updated i_size when we unlock.
7555 if (start + len > i_size_read(inode))
7556 i_size_write(inode, start + len);
7558 if (ret && space_reserved) {
7559 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7560 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7566 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7567 loff_t length, unsigned int flags, struct iomap *iomap,
7568 struct iomap *srcmap)
7570 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7571 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7572 struct extent_map *em;
7573 struct extent_state *cached_state = NULL;
7574 struct btrfs_dio_data *dio_data = iter->private;
7575 u64 lockstart, lockend;
7576 const bool write = !!(flags & IOMAP_WRITE);
7579 const u64 data_alloc_len = length;
7580 bool unlock_extents = false;
7583 * We could potentially fault if we have a buffer > PAGE_SIZE, and if
7584 * we're NOWAIT we may submit a bio for a partial range and return
7585 * EIOCBQUEUED, which would result in an errant short read.
7587 * The best way to handle this would be to allow for partial completions
7588 * of iocb's, so we could submit the partial bio, return and fault in
7589 * the rest of the pages, and then submit the io for the rest of the
7590 * range. However we don't have that currently, so simply return
7591 * -EAGAIN at this point so that the normal path is used.
7593 if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE)
7597 * Cap the size of reads to that usually seen in buffered I/O as we need
7598 * to allocate a contiguous array for the checksums.
7601 len = min_t(u64, len, fs_info->sectorsize * BTRFS_MAX_BIO_SECTORS);
7604 lockend = start + len - 1;
7607 * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
7608 * enough if we've written compressed pages to this area, so we need to
7609 * flush the dirty pages again to make absolutely sure that any
7610 * outstanding dirty pages are on disk - the first flush only starts
7611 * compression on the data, while keeping the pages locked, so by the
7612 * time the second flush returns we know bios for the compressed pages
7613 * were submitted and finished, and the pages no longer under writeback.
7615 * If we have a NOWAIT request and we have any pages in the range that
7616 * are locked, likely due to compression still in progress, we don't want
7617 * to block on page locks. We also don't want to block on pages marked as
7618 * dirty or under writeback (same as for the non-compression case).
7619 * iomap_dio_rw() did the same check, but after that and before we got
7620 * here, mmap'ed writes may have happened or buffered reads started
7621 * (readpage() and readahead(), which lock pages), as we haven't locked
7622 * the file range yet.
7624 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7625 &BTRFS_I(inode)->runtime_flags)) {
7626 if (flags & IOMAP_NOWAIT) {
7627 if (filemap_range_needs_writeback(inode->i_mapping,
7628 lockstart, lockend))
7631 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7632 start + length - 1);
7638 memset(dio_data, 0, sizeof(*dio_data));
7641 * We always try to allocate data space and must do it before locking
7642 * the file range, to avoid deadlocks with concurrent writes to the same
7643 * range if the range has several extents and the writes don't expand the
7644 * current i_size (the inode lock is taken in shared mode). If we fail to
7645 * allocate data space here we continue and later, after locking the
7646 * file range, we fail with ENOSPC only if we figure out we can not do a
7649 if (write && !(flags & IOMAP_NOWAIT)) {
7650 ret = btrfs_check_data_free_space(BTRFS_I(inode),
7651 &dio_data->data_reserved,
7652 start, data_alloc_len, false);
7654 dio_data->data_space_reserved = true;
7655 else if (ret && !(BTRFS_I(inode)->flags &
7656 (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
7661 * If this errors out it's because we couldn't invalidate pagecache for
7662 * this range and we need to fallback to buffered IO, or we are doing a
7663 * NOWAIT read/write and we need to block.
7665 ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags);
7669 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7676 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7677 * io. INLINE is special, and we could probably kludge it in here, but
7678 * it's still buffered so for safety lets just fall back to the generic
7681 * For COMPRESSED we _have_ to read the entire extent in so we can
7682 * decompress it, so there will be buffering required no matter what we
7683 * do, so go ahead and fallback to buffered.
7685 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7686 * to buffered IO. Don't blame me, this is the price we pay for using
7689 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7690 em->block_start == EXTENT_MAP_INLINE) {
7691 free_extent_map(em);
7693 * If we are in a NOWAIT context, return -EAGAIN in order to
7694 * fallback to buffered IO. This is not only because we can
7695 * block with buffered IO (no support for NOWAIT semantics at
7696 * the moment) but also to avoid returning short reads to user
7697 * space - this happens if we were able to read some data from
7698 * previous non-compressed extents and then when we fallback to
7699 * buffered IO, at btrfs_file_read_iter() by calling
7700 * filemap_read(), we fail to fault in pages for the read buffer,
7701 * in which case filemap_read() returns a short read (the number
7702 * of bytes previously read is > 0, so it does not return -EFAULT).
7704 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
7708 len = min(len, em->len - (start - em->start));
7711 * If we have a NOWAIT request and the range contains multiple extents
7712 * (or a mix of extents and holes), then we return -EAGAIN to make the
7713 * caller fallback to a context where it can do a blocking (without
7714 * NOWAIT) request. This way we avoid doing partial IO and returning
7715 * success to the caller, which is not optimal for writes and for reads
7716 * it can result in unexpected behaviour for an application.
7718 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7719 * iomap_dio_rw(), we can end up returning less data then what the caller
7720 * asked for, resulting in an unexpected, and incorrect, short read.
7721 * That is, the caller asked to read N bytes and we return less than that,
7722 * which is wrong unless we are crossing EOF. This happens if we get a
7723 * page fault error when trying to fault in pages for the buffer that is
7724 * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7725 * have previously submitted bios for other extents in the range, in
7726 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7727 * those bios have completed by the time we get the page fault error,
7728 * which we return back to our caller - we should only return EIOCBQUEUED
7729 * after we have submitted bios for all the extents in the range.
7731 if ((flags & IOMAP_NOWAIT) && len < length) {
7732 free_extent_map(em);
7738 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7739 start, &len, flags);
7742 unlock_extents = true;
7743 /* Recalc len in case the new em is smaller than requested */
7744 len = min(len, em->len - (start - em->start));
7745 if (dio_data->data_space_reserved) {
7747 u64 release_len = 0;
7749 if (dio_data->nocow_done) {
7750 release_offset = start;
7751 release_len = data_alloc_len;
7752 } else if (len < data_alloc_len) {
7753 release_offset = start + len;
7754 release_len = data_alloc_len - len;
7757 if (release_len > 0)
7758 btrfs_free_reserved_data_space(BTRFS_I(inode),
7759 dio_data->data_reserved,
7765 * We need to unlock only the end area that we aren't using.
7766 * The rest is going to be unlocked by the endio routine.
7768 lockstart = start + len;
7769 if (lockstart < lockend)
7770 unlock_extents = true;
7774 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7777 free_extent_state(cached_state);
7780 * Translate extent map information to iomap.
7781 * We trim the extents (and move the addr) even though iomap code does
7782 * that, since we have locked only the parts we are performing I/O in.
7784 if ((em->block_start == EXTENT_MAP_HOLE) ||
7785 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7786 iomap->addr = IOMAP_NULL_ADDR;
7787 iomap->type = IOMAP_HOLE;
7789 iomap->addr = em->block_start + (start - em->start);
7790 iomap->type = IOMAP_MAPPED;
7792 iomap->offset = start;
7793 iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7794 iomap->length = len;
7795 free_extent_map(em);
7800 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7803 if (dio_data->data_space_reserved) {
7804 btrfs_free_reserved_data_space(BTRFS_I(inode),
7805 dio_data->data_reserved,
7806 start, data_alloc_len);
7807 extent_changeset_free(dio_data->data_reserved);
7813 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7814 ssize_t written, unsigned int flags, struct iomap *iomap)
7816 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7817 struct btrfs_dio_data *dio_data = iter->private;
7818 size_t submitted = dio_data->submitted;
7819 const bool write = !!(flags & IOMAP_WRITE);
7822 if (!write && (iomap->type == IOMAP_HOLE)) {
7823 /* If reading from a hole, unlock and return */
7824 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1,
7829 if (submitted < length) {
7831 length -= submitted;
7833 btrfs_finish_ordered_extent(dio_data->ordered, NULL,
7834 pos, length, false);
7836 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7837 pos + length - 1, NULL);
7841 btrfs_put_ordered_extent(dio_data->ordered);
7842 dio_data->ordered = NULL;
7846 extent_changeset_free(dio_data->data_reserved);
7850 static void btrfs_dio_end_io(struct btrfs_bio *bbio)
7852 struct btrfs_dio_private *dip =
7853 container_of(bbio, struct btrfs_dio_private, bbio);
7854 struct btrfs_inode *inode = bbio->inode;
7855 struct bio *bio = &bbio->bio;
7857 if (bio->bi_status) {
7858 btrfs_warn(inode->root->fs_info,
7859 "direct IO failed ino %llu op 0x%0x offset %#llx len %u err no %d",
7860 btrfs_ino(inode), bio->bi_opf,
7861 dip->file_offset, dip->bytes, bio->bi_status);
7864 if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
7865 btrfs_finish_ordered_extent(bbio->ordered, NULL,
7866 dip->file_offset, dip->bytes,
7869 unlock_extent(&inode->io_tree, dip->file_offset,
7870 dip->file_offset + dip->bytes - 1, NULL);
7873 bbio->bio.bi_private = bbio->private;
7874 iomap_dio_bio_end_io(bio);
7877 static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio,
7880 struct btrfs_bio *bbio = btrfs_bio(bio);
7881 struct btrfs_dio_private *dip =
7882 container_of(bbio, struct btrfs_dio_private, bbio);
7883 struct btrfs_dio_data *dio_data = iter->private;
7885 btrfs_bio_init(bbio, BTRFS_I(iter->inode)->root->fs_info,
7886 btrfs_dio_end_io, bio->bi_private);
7887 bbio->inode = BTRFS_I(iter->inode);
7888 bbio->file_offset = file_offset;
7890 dip->file_offset = file_offset;
7891 dip->bytes = bio->bi_iter.bi_size;
7893 dio_data->submitted += bio->bi_iter.bi_size;
7896 * Check if we are doing a partial write. If we are, we need to split
7897 * the ordered extent to match the submitted bio. Hang on to the
7898 * remaining unfinishable ordered_extent in dio_data so that it can be
7899 * cancelled in iomap_end to avoid a deadlock wherein faulting the
7900 * remaining pages is blocked on the outstanding ordered extent.
7902 if (iter->flags & IOMAP_WRITE) {
7905 ret = btrfs_extract_ordered_extent(bbio, dio_data->ordered);
7907 btrfs_finish_ordered_extent(dio_data->ordered, NULL,
7908 file_offset, dip->bytes,
7910 bio->bi_status = errno_to_blk_status(ret);
7911 iomap_dio_bio_end_io(bio);
7916 btrfs_submit_bio(bbio, 0);
7919 static const struct iomap_ops btrfs_dio_iomap_ops = {
7920 .iomap_begin = btrfs_dio_iomap_begin,
7921 .iomap_end = btrfs_dio_iomap_end,
7924 static const struct iomap_dio_ops btrfs_dio_ops = {
7925 .submit_io = btrfs_dio_submit_io,
7926 .bio_set = &btrfs_dio_bioset,
7929 ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, size_t done_before)
7931 struct btrfs_dio_data data = { 0 };
7933 return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
7934 IOMAP_DIO_PARTIAL, &data, done_before);
7937 struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
7940 struct btrfs_dio_data data = { 0 };
7942 return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
7943 IOMAP_DIO_PARTIAL, &data, done_before);
7946 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7951 ret = fiemap_prep(inode, fieinfo, start, &len, 0);
7956 * fiemap_prep() called filemap_write_and_wait() for the whole possible
7957 * file range (0 to LLONG_MAX), but that is not enough if we have
7958 * compression enabled. The first filemap_fdatawrite_range() only kicks
7959 * in the compression of data (in an async thread) and will return
7960 * before the compression is done and writeback is started. A second
7961 * filemap_fdatawrite_range() is needed to wait for the compression to
7962 * complete and writeback to start. We also need to wait for ordered
7963 * extents to complete, because our fiemap implementation uses mainly
7964 * file extent items to list the extents, searching for extent maps
7965 * only for file ranges with holes or prealloc extents to figure out
7966 * if we have delalloc in those ranges.
7968 if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
7969 ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
7974 return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
7977 static int btrfs_writepages(struct address_space *mapping,
7978 struct writeback_control *wbc)
7980 return extent_writepages(mapping, wbc);
7983 static void btrfs_readahead(struct readahead_control *rac)
7985 extent_readahead(rac);
7989 * For release_folio() and invalidate_folio() we have a race window where
7990 * folio_end_writeback() is called but the subpage spinlock is not yet released.
7991 * If we continue to release/invalidate the page, we could cause use-after-free
7992 * for subpage spinlock. So this function is to spin and wait for subpage
7995 static void wait_subpage_spinlock(struct page *page)
7997 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7998 struct btrfs_subpage *subpage;
8000 if (!btrfs_is_subpage(fs_info, page))
8003 ASSERT(PagePrivate(page) && page->private);
8004 subpage = (struct btrfs_subpage *)page->private;
8007 * This may look insane as we just acquire the spinlock and release it,
8008 * without doing anything. But we just want to make sure no one is
8009 * still holding the subpage spinlock.
8010 * And since the page is not dirty nor writeback, and we have page
8011 * locked, the only possible way to hold a spinlock is from the endio
8012 * function to clear page writeback.
8014 * Here we just acquire the spinlock so that all existing callers
8015 * should exit and we're safe to release/invalidate the page.
8017 spin_lock_irq(&subpage->lock);
8018 spin_unlock_irq(&subpage->lock);
8021 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
8023 int ret = try_release_extent_mapping(&folio->page, gfp_flags);
8026 wait_subpage_spinlock(&folio->page);
8027 clear_page_extent_mapped(&folio->page);
8032 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
8034 if (folio_test_writeback(folio) || folio_test_dirty(folio))
8036 return __btrfs_release_folio(folio, gfp_flags);
8039 #ifdef CONFIG_MIGRATION
8040 static int btrfs_migrate_folio(struct address_space *mapping,
8041 struct folio *dst, struct folio *src,
8042 enum migrate_mode mode)
8044 int ret = filemap_migrate_folio(mapping, dst, src, mode);
8046 if (ret != MIGRATEPAGE_SUCCESS)
8049 if (folio_test_ordered(src)) {
8050 folio_clear_ordered(src);
8051 folio_set_ordered(dst);
8054 return MIGRATEPAGE_SUCCESS;
8057 #define btrfs_migrate_folio NULL
8060 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
8063 struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
8064 struct btrfs_fs_info *fs_info = inode->root->fs_info;
8065 struct extent_io_tree *tree = &inode->io_tree;
8066 struct extent_state *cached_state = NULL;
8067 u64 page_start = folio_pos(folio);
8068 u64 page_end = page_start + folio_size(folio) - 1;
8070 int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8073 * We have folio locked so no new ordered extent can be created on this
8074 * page, nor bio can be submitted for this folio.
8076 * But already submitted bio can still be finished on this folio.
8077 * Furthermore, endio function won't skip folio which has Ordered
8078 * (Private2) already cleared, so it's possible for endio and
8079 * invalidate_folio to do the same ordered extent accounting twice
8082 * So here we wait for any submitted bios to finish, so that we won't
8083 * do double ordered extent accounting on the same folio.
8085 folio_wait_writeback(folio);
8086 wait_subpage_spinlock(&folio->page);
8089 * For subpage case, we have call sites like
8090 * btrfs_punch_hole_lock_range() which passes range not aligned to
8092 * If the range doesn't cover the full folio, we don't need to and
8093 * shouldn't clear page extent mapped, as folio->private can still
8094 * record subpage dirty bits for other part of the range.
8096 * For cases that invalidate the full folio even the range doesn't
8097 * cover the full folio, like invalidating the last folio, we're
8098 * still safe to wait for ordered extent to finish.
8100 if (!(offset == 0 && length == folio_size(folio))) {
8101 btrfs_release_folio(folio, GFP_NOFS);
8105 if (!inode_evicting)
8106 lock_extent(tree, page_start, page_end, &cached_state);
8109 while (cur < page_end) {
8110 struct btrfs_ordered_extent *ordered;
8113 u32 extra_flags = 0;
8115 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8116 page_end + 1 - cur);
8118 range_end = page_end;
8120 * No ordered extent covering this range, we are safe
8121 * to delete all extent states in the range.
8123 extra_flags = EXTENT_CLEAR_ALL_BITS;
8126 if (ordered->file_offset > cur) {
8128 * There is a range between [cur, oe->file_offset) not
8129 * covered by any ordered extent.
8130 * We are safe to delete all extent states, and handle
8131 * the ordered extent in the next iteration.
8133 range_end = ordered->file_offset - 1;
8134 extra_flags = EXTENT_CLEAR_ALL_BITS;
8138 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8140 ASSERT(range_end + 1 - cur < U32_MAX);
8141 range_len = range_end + 1 - cur;
8142 if (!btrfs_page_test_ordered(fs_info, &folio->page, cur, range_len)) {
8144 * If Ordered (Private2) is cleared, it means endio has
8145 * already been executed for the range.
8146 * We can't delete the extent states as
8147 * btrfs_finish_ordered_io() may still use some of them.
8151 btrfs_page_clear_ordered(fs_info, &folio->page, cur, range_len);
8154 * IO on this page will never be started, so we need to account
8155 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8156 * here, must leave that up for the ordered extent completion.
8158 * This will also unlock the range for incoming
8159 * btrfs_finish_ordered_io().
8161 if (!inode_evicting)
8162 clear_extent_bit(tree, cur, range_end,
8164 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8165 EXTENT_DEFRAG, &cached_state);
8167 spin_lock_irq(&inode->ordered_tree.lock);
8168 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8169 ordered->truncated_len = min(ordered->truncated_len,
8170 cur - ordered->file_offset);
8171 spin_unlock_irq(&inode->ordered_tree.lock);
8174 * If the ordered extent has finished, we're safe to delete all
8175 * the extent states of the range, otherwise
8176 * btrfs_finish_ordered_io() will get executed by endio for
8177 * other pages, so we can't delete extent states.
8179 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8180 cur, range_end + 1 - cur)) {
8181 btrfs_finish_ordered_io(ordered);
8183 * The ordered extent has finished, now we're again
8184 * safe to delete all extent states of the range.
8186 extra_flags = EXTENT_CLEAR_ALL_BITS;
8190 btrfs_put_ordered_extent(ordered);
8192 * Qgroup reserved space handler
8193 * Sector(s) here will be either:
8195 * 1) Already written to disk or bio already finished
8196 * Then its QGROUP_RESERVED bit in io_tree is already cleared.
8197 * Qgroup will be handled by its qgroup_record then.
8198 * btrfs_qgroup_free_data() call will do nothing here.
8200 * 2) Not written to disk yet
8201 * Then btrfs_qgroup_free_data() call will clear the
8202 * QGROUP_RESERVED bit of its io_tree, and free the qgroup
8203 * reserved data space.
8204 * Since the IO will never happen for this page.
8206 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
8207 if (!inode_evicting) {
8208 clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8209 EXTENT_DELALLOC | EXTENT_UPTODATE |
8210 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
8211 extra_flags, &cached_state);
8213 cur = range_end + 1;
8216 * We have iterated through all ordered extents of the page, the page
8217 * should not have Ordered (Private2) anymore, or the above iteration
8218 * did something wrong.
8220 ASSERT(!folio_test_ordered(folio));
8221 btrfs_page_clear_checked(fs_info, &folio->page, folio_pos(folio), folio_size(folio));
8222 if (!inode_evicting)
8223 __btrfs_release_folio(folio, GFP_NOFS);
8224 clear_page_extent_mapped(&folio->page);
8228 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8229 * called from a page fault handler when a page is first dirtied. Hence we must
8230 * be careful to check for EOF conditions here. We set the page up correctly
8231 * for a written page which means we get ENOSPC checking when writing into
8232 * holes and correct delalloc and unwritten extent mapping on filesystems that
8233 * support these features.
8235 * We are not allowed to take the i_mutex here so we have to play games to
8236 * protect against truncate races as the page could now be beyond EOF. Because
8237 * truncate_setsize() writes the inode size before removing pages, once we have
8238 * the page lock we can determine safely if the page is beyond EOF. If it is not
8239 * beyond EOF, then the page is guaranteed safe against truncation until we
8242 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8244 struct page *page = vmf->page;
8245 struct inode *inode = file_inode(vmf->vma->vm_file);
8246 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8247 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8248 struct btrfs_ordered_extent *ordered;
8249 struct extent_state *cached_state = NULL;
8250 struct extent_changeset *data_reserved = NULL;
8251 unsigned long zero_start;
8261 reserved_space = PAGE_SIZE;
8263 sb_start_pagefault(inode->i_sb);
8264 page_start = page_offset(page);
8265 page_end = page_start + PAGE_SIZE - 1;
8269 * Reserving delalloc space after obtaining the page lock can lead to
8270 * deadlock. For example, if a dirty page is locked by this function
8271 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8272 * dirty page write out, then the btrfs_writepages() function could
8273 * end up waiting indefinitely to get a lock on the page currently
8274 * being processed by btrfs_page_mkwrite() function.
8276 ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8277 page_start, reserved_space);
8279 ret2 = file_update_time(vmf->vma->vm_file);
8283 ret = vmf_error(ret2);
8289 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8291 down_read(&BTRFS_I(inode)->i_mmap_lock);
8293 size = i_size_read(inode);
8295 if ((page->mapping != inode->i_mapping) ||
8296 (page_start >= size)) {
8297 /* page got truncated out from underneath us */
8300 wait_on_page_writeback(page);
8302 lock_extent(io_tree, page_start, page_end, &cached_state);
8303 ret2 = set_page_extent_mapped(page);
8305 ret = vmf_error(ret2);
8306 unlock_extent(io_tree, page_start, page_end, &cached_state);
8311 * we can't set the delalloc bits if there are pending ordered
8312 * extents. Drop our locks and wait for them to finish
8314 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8317 unlock_extent(io_tree, page_start, page_end, &cached_state);
8319 up_read(&BTRFS_I(inode)->i_mmap_lock);
8320 btrfs_start_ordered_extent(ordered);
8321 btrfs_put_ordered_extent(ordered);
8325 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8326 reserved_space = round_up(size - page_start,
8327 fs_info->sectorsize);
8328 if (reserved_space < PAGE_SIZE) {
8329 end = page_start + reserved_space - 1;
8330 btrfs_delalloc_release_space(BTRFS_I(inode),
8331 data_reserved, page_start,
8332 PAGE_SIZE - reserved_space, true);
8337 * page_mkwrite gets called when the page is firstly dirtied after it's
8338 * faulted in, but write(2) could also dirty a page and set delalloc
8339 * bits, thus in this case for space account reason, we still need to
8340 * clear any delalloc bits within this page range since we have to
8341 * reserve data&meta space before lock_page() (see above comments).
8343 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8344 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8345 EXTENT_DEFRAG, &cached_state);
8347 ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8350 unlock_extent(io_tree, page_start, page_end, &cached_state);
8351 ret = VM_FAULT_SIGBUS;
8355 /* page is wholly or partially inside EOF */
8356 if (page_start + PAGE_SIZE > size)
8357 zero_start = offset_in_page(size);
8359 zero_start = PAGE_SIZE;
8361 if (zero_start != PAGE_SIZE)
8362 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8364 btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
8365 btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8366 btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8368 btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8370 unlock_extent(io_tree, page_start, page_end, &cached_state);
8371 up_read(&BTRFS_I(inode)->i_mmap_lock);
8373 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8374 sb_end_pagefault(inode->i_sb);
8375 extent_changeset_free(data_reserved);
8376 return VM_FAULT_LOCKED;
8380 up_read(&BTRFS_I(inode)->i_mmap_lock);
8382 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8383 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8384 reserved_space, (ret != 0));
8386 sb_end_pagefault(inode->i_sb);
8387 extent_changeset_free(data_reserved);
8391 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
8393 struct btrfs_truncate_control control = {
8395 .ino = btrfs_ino(inode),
8396 .min_type = BTRFS_EXTENT_DATA_KEY,
8397 .clear_extent_range = true,
8399 struct btrfs_root *root = inode->root;
8400 struct btrfs_fs_info *fs_info = root->fs_info;
8401 struct btrfs_block_rsv *rsv;
8403 struct btrfs_trans_handle *trans;
8404 u64 mask = fs_info->sectorsize - 1;
8405 const u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8407 if (!skip_writeback) {
8408 ret = btrfs_wait_ordered_range(&inode->vfs_inode,
8409 inode->vfs_inode.i_size & (~mask),
8416 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8417 * things going on here:
8419 * 1) We need to reserve space to update our inode.
8421 * 2) We need to have something to cache all the space that is going to
8422 * be free'd up by the truncate operation, but also have some slack
8423 * space reserved in case it uses space during the truncate (thank you
8424 * very much snapshotting).
8426 * And we need these to be separate. The fact is we can use a lot of
8427 * space doing the truncate, and we have no earthly idea how much space
8428 * we will use, so we need the truncate reservation to be separate so it
8429 * doesn't end up using space reserved for updating the inode. We also
8430 * need to be able to stop the transaction and start a new one, which
8431 * means we need to be able to update the inode several times, and we
8432 * have no idea of knowing how many times that will be, so we can't just
8433 * reserve 1 item for the entirety of the operation, so that has to be
8434 * done separately as well.
8436 * So that leaves us with
8438 * 1) rsv - for the truncate reservation, which we will steal from the
8439 * transaction reservation.
8440 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8441 * updating the inode.
8443 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8446 rsv->size = min_size;
8447 rsv->failfast = true;
8450 * 1 for the truncate slack space
8451 * 1 for updating the inode.
8453 trans = btrfs_start_transaction(root, 2);
8454 if (IS_ERR(trans)) {
8455 ret = PTR_ERR(trans);
8459 /* Migrate the slack space for the truncate to our reserve */
8460 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8463 * We have reserved 2 metadata units when we started the transaction and
8464 * min_size matches 1 unit, so this should never fail, but if it does,
8465 * it's not critical we just fail truncation.
8468 btrfs_end_transaction(trans);
8472 trans->block_rsv = rsv;
8475 struct extent_state *cached_state = NULL;
8476 const u64 new_size = inode->vfs_inode.i_size;
8477 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8479 control.new_size = new_size;
8480 lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
8482 * We want to drop from the next block forward in case this new
8483 * size is not block aligned since we will be keeping the last
8484 * block of the extent just the way it is.
8486 btrfs_drop_extent_map_range(inode,
8487 ALIGN(new_size, fs_info->sectorsize),
8490 ret = btrfs_truncate_inode_items(trans, root, &control);
8492 inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
8493 btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
8495 unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
8497 trans->block_rsv = &fs_info->trans_block_rsv;
8498 if (ret != -ENOSPC && ret != -EAGAIN)
8501 ret = btrfs_update_inode(trans, root, inode);
8505 btrfs_end_transaction(trans);
8506 btrfs_btree_balance_dirty(fs_info);
8508 trans = btrfs_start_transaction(root, 2);
8509 if (IS_ERR(trans)) {
8510 ret = PTR_ERR(trans);
8515 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8516 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8517 rsv, min_size, false);
8519 * We have reserved 2 metadata units when we started the
8520 * transaction and min_size matches 1 unit, so this should never
8521 * fail, but if it does, it's not critical we just fail truncation.
8526 trans->block_rsv = rsv;
8530 * We can't call btrfs_truncate_block inside a trans handle as we could
8531 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8532 * know we've truncated everything except the last little bit, and can
8533 * do btrfs_truncate_block and then update the disk_i_size.
8535 if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8536 btrfs_end_transaction(trans);
8537 btrfs_btree_balance_dirty(fs_info);
8539 ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size, 0, 0);
8542 trans = btrfs_start_transaction(root, 1);
8543 if (IS_ERR(trans)) {
8544 ret = PTR_ERR(trans);
8547 btrfs_inode_safe_disk_i_size_write(inode, 0);
8553 trans->block_rsv = &fs_info->trans_block_rsv;
8554 ret2 = btrfs_update_inode(trans, root, inode);
8558 ret2 = btrfs_end_transaction(trans);
8561 btrfs_btree_balance_dirty(fs_info);
8564 btrfs_free_block_rsv(fs_info, rsv);
8566 * So if we truncate and then write and fsync we normally would just
8567 * write the extents that changed, which is a problem if we need to
8568 * first truncate that entire inode. So set this flag so we write out
8569 * all of the extents in the inode to the sync log so we're completely
8572 * If no extents were dropped or trimmed we don't need to force the next
8573 * fsync to truncate all the inode's items from the log and re-log them
8574 * all. This means the truncate operation did not change the file size,
8575 * or changed it to a smaller size but there was only an implicit hole
8576 * between the old i_size and the new i_size, and there were no prealloc
8577 * extents beyond i_size to drop.
8579 if (control.extents_found > 0)
8580 btrfs_set_inode_full_sync(inode);
8585 struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
8588 struct inode *inode;
8590 inode = new_inode(dir->i_sb);
8593 * Subvolumes don't inherit the sgid bit or the parent's gid if
8594 * the parent's sgid bit is set. This is probably a bug.
8596 inode_init_owner(idmap, inode, NULL,
8597 S_IFDIR | (~current_umask() & S_IRWXUGO));
8598 inode->i_op = &btrfs_dir_inode_operations;
8599 inode->i_fop = &btrfs_dir_file_operations;
8604 struct inode *btrfs_alloc_inode(struct super_block *sb)
8606 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8607 struct btrfs_inode *ei;
8608 struct inode *inode;
8610 ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8617 ei->last_sub_trans = 0;
8618 ei->logged_trans = 0;
8619 ei->delalloc_bytes = 0;
8620 ei->new_delalloc_bytes = 0;
8621 ei->defrag_bytes = 0;
8622 ei->disk_i_size = 0;
8626 ei->index_cnt = (u64)-1;
8628 ei->last_unlink_trans = 0;
8629 ei->last_reflink_trans = 0;
8630 ei->last_log_commit = 0;
8632 spin_lock_init(&ei->lock);
8633 ei->outstanding_extents = 0;
8634 if (sb->s_magic != BTRFS_TEST_MAGIC)
8635 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8636 BTRFS_BLOCK_RSV_DELALLOC);
8637 ei->runtime_flags = 0;
8638 ei->prop_compress = BTRFS_COMPRESS_NONE;
8639 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8641 ei->delayed_node = NULL;
8643 ei->i_otime.tv_sec = 0;
8644 ei->i_otime.tv_nsec = 0;
8646 inode = &ei->vfs_inode;
8647 extent_map_tree_init(&ei->extent_tree);
8648 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
8649 ei->io_tree.inode = ei;
8650 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8651 IO_TREE_INODE_FILE_EXTENT);
8652 mutex_init(&ei->log_mutex);
8653 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8654 INIT_LIST_HEAD(&ei->delalloc_inodes);
8655 INIT_LIST_HEAD(&ei->delayed_iput);
8656 RB_CLEAR_NODE(&ei->rb_node);
8657 init_rwsem(&ei->i_mmap_lock);
8662 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8663 void btrfs_test_destroy_inode(struct inode *inode)
8665 btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8666 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8670 void btrfs_free_inode(struct inode *inode)
8672 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8675 void btrfs_destroy_inode(struct inode *vfs_inode)
8677 struct btrfs_ordered_extent *ordered;
8678 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8679 struct btrfs_root *root = inode->root;
8680 bool freespace_inode;
8682 WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8683 WARN_ON(vfs_inode->i_data.nrpages);
8684 WARN_ON(inode->block_rsv.reserved);
8685 WARN_ON(inode->block_rsv.size);
8686 WARN_ON(inode->outstanding_extents);
8687 if (!S_ISDIR(vfs_inode->i_mode)) {
8688 WARN_ON(inode->delalloc_bytes);
8689 WARN_ON(inode->new_delalloc_bytes);
8691 WARN_ON(inode->csum_bytes);
8692 WARN_ON(inode->defrag_bytes);
8695 * This can happen where we create an inode, but somebody else also
8696 * created the same inode and we need to destroy the one we already
8703 * If this is a free space inode do not take the ordered extents lockdep
8706 freespace_inode = btrfs_is_free_space_inode(inode);
8709 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8713 btrfs_err(root->fs_info,
8714 "found ordered extent %llu %llu on inode cleanup",
8715 ordered->file_offset, ordered->num_bytes);
8717 if (!freespace_inode)
8718 btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
8720 btrfs_remove_ordered_extent(inode, ordered);
8721 btrfs_put_ordered_extent(ordered);
8722 btrfs_put_ordered_extent(ordered);
8725 btrfs_qgroup_check_reserved_leak(inode);
8726 inode_tree_del(inode);
8727 btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
8728 btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8729 btrfs_put_root(inode->root);
8732 int btrfs_drop_inode(struct inode *inode)
8734 struct btrfs_root *root = BTRFS_I(inode)->root;
8739 /* the snap/subvol tree is on deleting */
8740 if (btrfs_root_refs(&root->root_item) == 0)
8743 return generic_drop_inode(inode);
8746 static void init_once(void *foo)
8748 struct btrfs_inode *ei = foo;
8750 inode_init_once(&ei->vfs_inode);
8753 void __cold btrfs_destroy_cachep(void)
8756 * Make sure all delayed rcu free inodes are flushed before we
8760 bioset_exit(&btrfs_dio_bioset);
8761 kmem_cache_destroy(btrfs_inode_cachep);
8764 int __init btrfs_init_cachep(void)
8766 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8767 sizeof(struct btrfs_inode), 0,
8768 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8770 if (!btrfs_inode_cachep)
8773 if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE,
8774 offsetof(struct btrfs_dio_private, bbio.bio),
8780 btrfs_destroy_cachep();
8784 static int btrfs_getattr(struct mnt_idmap *idmap,
8785 const struct path *path, struct kstat *stat,
8786 u32 request_mask, unsigned int flags)
8790 struct inode *inode = d_inode(path->dentry);
8791 u32 blocksize = inode->i_sb->s_blocksize;
8792 u32 bi_flags = BTRFS_I(inode)->flags;
8793 u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8795 stat->result_mask |= STATX_BTIME;
8796 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8797 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8798 if (bi_flags & BTRFS_INODE_APPEND)
8799 stat->attributes |= STATX_ATTR_APPEND;
8800 if (bi_flags & BTRFS_INODE_COMPRESS)
8801 stat->attributes |= STATX_ATTR_COMPRESSED;
8802 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8803 stat->attributes |= STATX_ATTR_IMMUTABLE;
8804 if (bi_flags & BTRFS_INODE_NODUMP)
8805 stat->attributes |= STATX_ATTR_NODUMP;
8806 if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8807 stat->attributes |= STATX_ATTR_VERITY;
8809 stat->attributes_mask |= (STATX_ATTR_APPEND |
8810 STATX_ATTR_COMPRESSED |
8811 STATX_ATTR_IMMUTABLE |
8814 generic_fillattr(idmap, inode, stat);
8815 stat->dev = BTRFS_I(inode)->root->anon_dev;
8817 spin_lock(&BTRFS_I(inode)->lock);
8818 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8819 inode_bytes = inode_get_bytes(inode);
8820 spin_unlock(&BTRFS_I(inode)->lock);
8821 stat->blocks = (ALIGN(inode_bytes, blocksize) +
8822 ALIGN(delalloc_bytes, blocksize)) >> SECTOR_SHIFT;
8826 static int btrfs_rename_exchange(struct inode *old_dir,
8827 struct dentry *old_dentry,
8828 struct inode *new_dir,
8829 struct dentry *new_dentry)
8831 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8832 struct btrfs_trans_handle *trans;
8833 unsigned int trans_num_items;
8834 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8835 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8836 struct inode *new_inode = new_dentry->d_inode;
8837 struct inode *old_inode = old_dentry->d_inode;
8838 struct timespec64 ctime = current_time(old_inode);
8839 struct btrfs_rename_ctx old_rename_ctx;
8840 struct btrfs_rename_ctx new_rename_ctx;
8841 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8842 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8847 bool need_abort = false;
8848 struct fscrypt_name old_fname, new_fname;
8849 struct fscrypt_str *old_name, *new_name;
8852 * For non-subvolumes allow exchange only within one subvolume, in the
8853 * same inode namespace. Two subvolumes (represented as directory) can
8854 * be exchanged as they're a logical link and have a fixed inode number.
8857 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8858 new_ino != BTRFS_FIRST_FREE_OBJECTID))
8861 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8865 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8867 fscrypt_free_filename(&old_fname);
8871 old_name = &old_fname.disk_name;
8872 new_name = &new_fname.disk_name;
8874 /* close the race window with snapshot create/destroy ioctl */
8875 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8876 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8877 down_read(&fs_info->subvol_sem);
8881 * 1 to remove old dir item
8882 * 1 to remove old dir index
8883 * 1 to add new dir item
8884 * 1 to add new dir index
8885 * 1 to update parent inode
8887 * If the parents are the same, we only need to account for one
8889 trans_num_items = (old_dir == new_dir ? 9 : 10);
8890 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8892 * 1 to remove old root ref
8893 * 1 to remove old root backref
8894 * 1 to add new root ref
8895 * 1 to add new root backref
8897 trans_num_items += 4;
8900 * 1 to update inode item
8901 * 1 to remove old inode ref
8902 * 1 to add new inode ref
8904 trans_num_items += 3;
8906 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
8907 trans_num_items += 4;
8909 trans_num_items += 3;
8910 trans = btrfs_start_transaction(root, trans_num_items);
8911 if (IS_ERR(trans)) {
8912 ret = PTR_ERR(trans);
8917 ret = btrfs_record_root_in_trans(trans, dest);
8923 * We need to find a free sequence number both in the source and
8924 * in the destination directory for the exchange.
8926 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8929 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8933 BTRFS_I(old_inode)->dir_index = 0ULL;
8934 BTRFS_I(new_inode)->dir_index = 0ULL;
8936 /* Reference for the source. */
8937 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8938 /* force full log commit if subvolume involved. */
8939 btrfs_set_log_full_commit(trans);
8941 ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
8942 btrfs_ino(BTRFS_I(new_dir)),
8949 /* And now for the dest. */
8950 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8951 /* force full log commit if subvolume involved. */
8952 btrfs_set_log_full_commit(trans);
8954 ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
8955 btrfs_ino(BTRFS_I(old_dir)),
8959 btrfs_abort_transaction(trans, ret);
8964 /* Update inode version and ctime/mtime. */
8965 inode_inc_iversion(old_dir);
8966 inode_inc_iversion(new_dir);
8967 inode_inc_iversion(old_inode);
8968 inode_inc_iversion(new_inode);
8969 old_dir->i_mtime = ctime;
8970 old_dir->i_ctime = ctime;
8971 new_dir->i_mtime = ctime;
8972 new_dir->i_ctime = ctime;
8973 old_inode->i_ctime = ctime;
8974 new_inode->i_ctime = ctime;
8976 if (old_dentry->d_parent != new_dentry->d_parent) {
8977 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8978 BTRFS_I(old_inode), true);
8979 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8980 BTRFS_I(new_inode), true);
8983 /* src is a subvolume */
8984 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8985 ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8986 } else { /* src is an inode */
8987 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8988 BTRFS_I(old_dentry->d_inode),
8989 old_name, &old_rename_ctx);
8991 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
8994 btrfs_abort_transaction(trans, ret);
8998 /* dest is a subvolume */
8999 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9000 ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
9001 } else { /* dest is an inode */
9002 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9003 BTRFS_I(new_dentry->d_inode),
9004 new_name, &new_rename_ctx);
9006 ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9009 btrfs_abort_transaction(trans, ret);
9013 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9014 new_name, 0, old_idx);
9016 btrfs_abort_transaction(trans, ret);
9020 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9021 old_name, 0, new_idx);
9023 btrfs_abort_transaction(trans, ret);
9027 if (old_inode->i_nlink == 1)
9028 BTRFS_I(old_inode)->dir_index = old_idx;
9029 if (new_inode->i_nlink == 1)
9030 BTRFS_I(new_inode)->dir_index = new_idx;
9033 * Now pin the logs of the roots. We do it to ensure that no other task
9034 * can sync the logs while we are in progress with the rename, because
9035 * that could result in an inconsistency in case any of the inodes that
9036 * are part of this rename operation were logged before.
9038 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9039 btrfs_pin_log_trans(root);
9040 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9041 btrfs_pin_log_trans(dest);
9043 /* Do the log updates for all inodes. */
9044 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9045 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9046 old_rename_ctx.index, new_dentry->d_parent);
9047 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9048 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
9049 new_rename_ctx.index, old_dentry->d_parent);
9051 /* Now unpin the logs. */
9052 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9053 btrfs_end_log_trans(root);
9054 if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9055 btrfs_end_log_trans(dest);
9057 ret2 = btrfs_end_transaction(trans);
9058 ret = ret ? ret : ret2;
9060 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9061 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9062 up_read(&fs_info->subvol_sem);
9064 fscrypt_free_filename(&new_fname);
9065 fscrypt_free_filename(&old_fname);
9069 static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
9072 struct inode *inode;
9074 inode = new_inode(dir->i_sb);
9076 inode_init_owner(idmap, inode, dir,
9077 S_IFCHR | WHITEOUT_MODE);
9078 inode->i_op = &btrfs_special_inode_operations;
9079 init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
9084 static int btrfs_rename(struct mnt_idmap *idmap,
9085 struct inode *old_dir, struct dentry *old_dentry,
9086 struct inode *new_dir, struct dentry *new_dentry,
9089 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9090 struct btrfs_new_inode_args whiteout_args = {
9092 .dentry = old_dentry,
9094 struct btrfs_trans_handle *trans;
9095 unsigned int trans_num_items;
9096 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9097 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9098 struct inode *new_inode = d_inode(new_dentry);
9099 struct inode *old_inode = d_inode(old_dentry);
9100 struct btrfs_rename_ctx rename_ctx;
9104 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9105 struct fscrypt_name old_fname, new_fname;
9107 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9110 /* we only allow rename subvolume link between subvolumes */
9111 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9114 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9115 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9118 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9119 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9122 ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
9126 ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
9128 fscrypt_free_filename(&old_fname);
9132 /* check for collisions, even if the name isn't there */
9133 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
9135 if (ret == -EEXIST) {
9137 * eexist without a new_inode */
9138 if (WARN_ON(!new_inode)) {
9139 goto out_fscrypt_names;
9142 /* maybe -EOVERFLOW */
9143 goto out_fscrypt_names;
9149 * we're using rename to replace one file with another. Start IO on it
9150 * now so we don't add too much work to the end of the transaction
9152 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9153 filemap_flush(old_inode->i_mapping);
9155 if (flags & RENAME_WHITEOUT) {
9156 whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
9157 if (!whiteout_args.inode) {
9159 goto out_fscrypt_names;
9161 ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
9163 goto out_whiteout_inode;
9165 /* 1 to update the old parent inode. */
9166 trans_num_items = 1;
9169 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9170 /* Close the race window with snapshot create/destroy ioctl */
9171 down_read(&fs_info->subvol_sem);
9173 * 1 to remove old root ref
9174 * 1 to remove old root backref
9175 * 1 to add new root ref
9176 * 1 to add new root backref
9178 trans_num_items += 4;
9182 * 1 to remove old inode ref
9183 * 1 to add new inode ref
9185 trans_num_items += 3;
9188 * 1 to remove old dir item
9189 * 1 to remove old dir index
9190 * 1 to add new dir item
9191 * 1 to add new dir index
9193 trans_num_items += 4;
9194 /* 1 to update new parent inode if it's not the same as the old parent */
9195 if (new_dir != old_dir)
9200 * 1 to remove inode ref
9201 * 1 to remove dir item
9202 * 1 to remove dir index
9203 * 1 to possibly add orphan item
9205 trans_num_items += 5;
9207 trans = btrfs_start_transaction(root, trans_num_items);
9208 if (IS_ERR(trans)) {
9209 ret = PTR_ERR(trans);
9214 ret = btrfs_record_root_in_trans(trans, dest);
9219 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9223 BTRFS_I(old_inode)->dir_index = 0ULL;
9224 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9225 /* force full log commit if subvolume involved. */
9226 btrfs_set_log_full_commit(trans);
9228 ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
9229 old_ino, btrfs_ino(BTRFS_I(new_dir)),
9235 inode_inc_iversion(old_dir);
9236 inode_inc_iversion(new_dir);
9237 inode_inc_iversion(old_inode);
9238 old_dir->i_mtime = current_time(old_dir);
9239 old_dir->i_ctime = old_dir->i_mtime;
9240 new_dir->i_mtime = old_dir->i_mtime;
9241 new_dir->i_ctime = old_dir->i_mtime;
9242 old_inode->i_ctime = old_dir->i_mtime;
9244 if (old_dentry->d_parent != new_dentry->d_parent)
9245 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9246 BTRFS_I(old_inode), true);
9248 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9249 ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
9251 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9252 BTRFS_I(d_inode(old_dentry)),
9253 &old_fname.disk_name, &rename_ctx);
9255 ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9258 btrfs_abort_transaction(trans, ret);
9263 inode_inc_iversion(new_inode);
9264 new_inode->i_ctime = current_time(new_inode);
9265 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9266 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9267 ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
9268 BUG_ON(new_inode->i_nlink == 0);
9270 ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9271 BTRFS_I(d_inode(new_dentry)),
9272 &new_fname.disk_name);
9274 if (!ret && new_inode->i_nlink == 0)
9275 ret = btrfs_orphan_add(trans,
9276 BTRFS_I(d_inode(new_dentry)));
9278 btrfs_abort_transaction(trans, ret);
9283 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9284 &new_fname.disk_name, 0, index);
9286 btrfs_abort_transaction(trans, ret);
9290 if (old_inode->i_nlink == 1)
9291 BTRFS_I(old_inode)->dir_index = index;
9293 if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9294 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9295 rename_ctx.index, new_dentry->d_parent);
9297 if (flags & RENAME_WHITEOUT) {
9298 ret = btrfs_create_new_inode(trans, &whiteout_args);
9300 btrfs_abort_transaction(trans, ret);
9303 unlock_new_inode(whiteout_args.inode);
9304 iput(whiteout_args.inode);
9305 whiteout_args.inode = NULL;
9309 ret2 = btrfs_end_transaction(trans);
9310 ret = ret ? ret : ret2;
9312 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9313 up_read(&fs_info->subvol_sem);
9314 if (flags & RENAME_WHITEOUT)
9315 btrfs_new_inode_args_destroy(&whiteout_args);
9317 if (flags & RENAME_WHITEOUT)
9318 iput(whiteout_args.inode);
9320 fscrypt_free_filename(&old_fname);
9321 fscrypt_free_filename(&new_fname);
9325 static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
9326 struct dentry *old_dentry, struct inode *new_dir,
9327 struct dentry *new_dentry, unsigned int flags)
9331 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9334 if (flags & RENAME_EXCHANGE)
9335 ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9338 ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
9341 btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
9346 struct btrfs_delalloc_work {
9347 struct inode *inode;
9348 struct completion completion;
9349 struct list_head list;
9350 struct btrfs_work work;
9353 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9355 struct btrfs_delalloc_work *delalloc_work;
9356 struct inode *inode;
9358 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9360 inode = delalloc_work->inode;
9361 filemap_flush(inode->i_mapping);
9362 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9363 &BTRFS_I(inode)->runtime_flags))
9364 filemap_flush(inode->i_mapping);
9367 complete(&delalloc_work->completion);
9370 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9372 struct btrfs_delalloc_work *work;
9374 work = kmalloc(sizeof(*work), GFP_NOFS);
9378 init_completion(&work->completion);
9379 INIT_LIST_HEAD(&work->list);
9380 work->inode = inode;
9381 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9387 * some fairly slow code that needs optimization. This walks the list
9388 * of all the inodes with pending delalloc and forces them to disk.
9390 static int start_delalloc_inodes(struct btrfs_root *root,
9391 struct writeback_control *wbc, bool snapshot,
9392 bool in_reclaim_context)
9394 struct btrfs_inode *binode;
9395 struct inode *inode;
9396 struct btrfs_delalloc_work *work, *next;
9397 struct list_head works;
9398 struct list_head splice;
9400 bool full_flush = wbc->nr_to_write == LONG_MAX;
9402 INIT_LIST_HEAD(&works);
9403 INIT_LIST_HEAD(&splice);
9405 mutex_lock(&root->delalloc_mutex);
9406 spin_lock(&root->delalloc_lock);
9407 list_splice_init(&root->delalloc_inodes, &splice);
9408 while (!list_empty(&splice)) {
9409 binode = list_entry(splice.next, struct btrfs_inode,
9412 list_move_tail(&binode->delalloc_inodes,
9413 &root->delalloc_inodes);
9415 if (in_reclaim_context &&
9416 test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9419 inode = igrab(&binode->vfs_inode);
9421 cond_resched_lock(&root->delalloc_lock);
9424 spin_unlock(&root->delalloc_lock);
9427 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9428 &binode->runtime_flags);
9430 work = btrfs_alloc_delalloc_work(inode);
9436 list_add_tail(&work->list, &works);
9437 btrfs_queue_work(root->fs_info->flush_workers,
9440 ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9441 btrfs_add_delayed_iput(BTRFS_I(inode));
9442 if (ret || wbc->nr_to_write <= 0)
9446 spin_lock(&root->delalloc_lock);
9448 spin_unlock(&root->delalloc_lock);
9451 list_for_each_entry_safe(work, next, &works, list) {
9452 list_del_init(&work->list);
9453 wait_for_completion(&work->completion);
9457 if (!list_empty(&splice)) {
9458 spin_lock(&root->delalloc_lock);
9459 list_splice_tail(&splice, &root->delalloc_inodes);
9460 spin_unlock(&root->delalloc_lock);
9462 mutex_unlock(&root->delalloc_mutex);
9466 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9468 struct writeback_control wbc = {
9469 .nr_to_write = LONG_MAX,
9470 .sync_mode = WB_SYNC_NONE,
9472 .range_end = LLONG_MAX,
9474 struct btrfs_fs_info *fs_info = root->fs_info;
9476 if (BTRFS_FS_ERROR(fs_info))
9479 return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9482 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9483 bool in_reclaim_context)
9485 struct writeback_control wbc = {
9487 .sync_mode = WB_SYNC_NONE,
9489 .range_end = LLONG_MAX,
9491 struct btrfs_root *root;
9492 struct list_head splice;
9495 if (BTRFS_FS_ERROR(fs_info))
9498 INIT_LIST_HEAD(&splice);
9500 mutex_lock(&fs_info->delalloc_root_mutex);
9501 spin_lock(&fs_info->delalloc_root_lock);
9502 list_splice_init(&fs_info->delalloc_roots, &splice);
9503 while (!list_empty(&splice)) {
9505 * Reset nr_to_write here so we know that we're doing a full
9509 wbc.nr_to_write = LONG_MAX;
9511 root = list_first_entry(&splice, struct btrfs_root,
9513 root = btrfs_grab_root(root);
9515 list_move_tail(&root->delalloc_root,
9516 &fs_info->delalloc_roots);
9517 spin_unlock(&fs_info->delalloc_root_lock);
9519 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9520 btrfs_put_root(root);
9521 if (ret < 0 || wbc.nr_to_write <= 0)
9523 spin_lock(&fs_info->delalloc_root_lock);
9525 spin_unlock(&fs_info->delalloc_root_lock);
9529 if (!list_empty(&splice)) {
9530 spin_lock(&fs_info->delalloc_root_lock);
9531 list_splice_tail(&splice, &fs_info->delalloc_roots);
9532 spin_unlock(&fs_info->delalloc_root_lock);
9534 mutex_unlock(&fs_info->delalloc_root_mutex);
9538 static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
9539 struct dentry *dentry, const char *symname)
9541 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9542 struct btrfs_trans_handle *trans;
9543 struct btrfs_root *root = BTRFS_I(dir)->root;
9544 struct btrfs_path *path;
9545 struct btrfs_key key;
9546 struct inode *inode;
9547 struct btrfs_new_inode_args new_inode_args = {
9551 unsigned int trans_num_items;
9556 struct btrfs_file_extent_item *ei;
9557 struct extent_buffer *leaf;
9559 name_len = strlen(symname);
9560 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9561 return -ENAMETOOLONG;
9563 inode = new_inode(dir->i_sb);
9566 inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
9567 inode->i_op = &btrfs_symlink_inode_operations;
9568 inode_nohighmem(inode);
9569 inode->i_mapping->a_ops = &btrfs_aops;
9570 btrfs_i_size_write(BTRFS_I(inode), name_len);
9571 inode_set_bytes(inode, name_len);
9573 new_inode_args.inode = inode;
9574 err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9577 /* 1 additional item for the inline extent */
9580 trans = btrfs_start_transaction(root, trans_num_items);
9581 if (IS_ERR(trans)) {
9582 err = PTR_ERR(trans);
9583 goto out_new_inode_args;
9586 err = btrfs_create_new_inode(trans, &new_inode_args);
9590 path = btrfs_alloc_path();
9593 btrfs_abort_transaction(trans, err);
9594 discard_new_inode(inode);
9598 key.objectid = btrfs_ino(BTRFS_I(inode));
9600 key.type = BTRFS_EXTENT_DATA_KEY;
9601 datasize = btrfs_file_extent_calc_inline_size(name_len);
9602 err = btrfs_insert_empty_item(trans, root, path, &key,
9605 btrfs_abort_transaction(trans, err);
9606 btrfs_free_path(path);
9607 discard_new_inode(inode);
9611 leaf = path->nodes[0];
9612 ei = btrfs_item_ptr(leaf, path->slots[0],
9613 struct btrfs_file_extent_item);
9614 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9615 btrfs_set_file_extent_type(leaf, ei,
9616 BTRFS_FILE_EXTENT_INLINE);
9617 btrfs_set_file_extent_encryption(leaf, ei, 0);
9618 btrfs_set_file_extent_compression(leaf, ei, 0);
9619 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9620 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9622 ptr = btrfs_file_extent_inline_start(ei);
9623 write_extent_buffer(leaf, symname, ptr, name_len);
9624 btrfs_mark_buffer_dirty(leaf);
9625 btrfs_free_path(path);
9627 d_instantiate_new(dentry, inode);
9630 btrfs_end_transaction(trans);
9631 btrfs_btree_balance_dirty(fs_info);
9633 btrfs_new_inode_args_destroy(&new_inode_args);
9640 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9641 struct btrfs_trans_handle *trans_in,
9642 struct btrfs_inode *inode,
9643 struct btrfs_key *ins,
9646 struct btrfs_file_extent_item stack_fi;
9647 struct btrfs_replace_extent_info extent_info;
9648 struct btrfs_trans_handle *trans = trans_in;
9649 struct btrfs_path *path;
9650 u64 start = ins->objectid;
9651 u64 len = ins->offset;
9652 int qgroup_released;
9655 memset(&stack_fi, 0, sizeof(stack_fi));
9657 btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9658 btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9659 btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9660 btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9661 btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9662 btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9663 /* Encryption and other encoding is reserved and all 0 */
9665 qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9666 if (qgroup_released < 0)
9667 return ERR_PTR(qgroup_released);
9670 ret = insert_reserved_file_extent(trans, inode,
9671 file_offset, &stack_fi,
9672 true, qgroup_released);
9678 extent_info.disk_offset = start;
9679 extent_info.disk_len = len;
9680 extent_info.data_offset = 0;
9681 extent_info.data_len = len;
9682 extent_info.file_offset = file_offset;
9683 extent_info.extent_buf = (char *)&stack_fi;
9684 extent_info.is_new_extent = true;
9685 extent_info.update_times = true;
9686 extent_info.qgroup_reserved = qgroup_released;
9687 extent_info.insertions = 0;
9689 path = btrfs_alloc_path();
9695 ret = btrfs_replace_file_extents(inode, path, file_offset,
9696 file_offset + len - 1, &extent_info,
9698 btrfs_free_path(path);
9705 * We have released qgroup data range at the beginning of the function,
9706 * and normally qgroup_released bytes will be freed when committing
9708 * But if we error out early, we have to free what we have released
9709 * or we leak qgroup data reservation.
9711 btrfs_qgroup_free_refroot(inode->root->fs_info,
9712 inode->root->root_key.objectid, qgroup_released,
9713 BTRFS_QGROUP_RSV_DATA);
9714 return ERR_PTR(ret);
9717 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9718 u64 start, u64 num_bytes, u64 min_size,
9719 loff_t actual_len, u64 *alloc_hint,
9720 struct btrfs_trans_handle *trans)
9722 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9723 struct extent_map *em;
9724 struct btrfs_root *root = BTRFS_I(inode)->root;
9725 struct btrfs_key ins;
9726 u64 cur_offset = start;
9727 u64 clear_offset = start;
9730 u64 last_alloc = (u64)-1;
9732 bool own_trans = true;
9733 u64 end = start + num_bytes - 1;
9737 while (num_bytes > 0) {
9738 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9739 cur_bytes = max(cur_bytes, min_size);
9741 * If we are severely fragmented we could end up with really
9742 * small allocations, so if the allocator is returning small
9743 * chunks lets make its job easier by only searching for those
9746 cur_bytes = min(cur_bytes, last_alloc);
9747 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9748 min_size, 0, *alloc_hint, &ins, 1, 0);
9753 * We've reserved this space, and thus converted it from
9754 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9755 * from here on out we will only need to clear our reservation
9756 * for the remaining unreserved area, so advance our
9757 * clear_offset by our extent size.
9759 clear_offset += ins.offset;
9761 last_alloc = ins.offset;
9762 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9765 * Now that we inserted the prealloc extent we can finally
9766 * decrement the number of reservations in the block group.
9767 * If we did it before, we could race with relocation and have
9768 * relocation miss the reserved extent, making it fail later.
9770 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9771 if (IS_ERR(trans)) {
9772 ret = PTR_ERR(trans);
9773 btrfs_free_reserved_extent(fs_info, ins.objectid,
9778 em = alloc_extent_map();
9780 btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9781 cur_offset + ins.offset - 1, false);
9782 btrfs_set_inode_full_sync(BTRFS_I(inode));
9786 em->start = cur_offset;
9787 em->orig_start = cur_offset;
9788 em->len = ins.offset;
9789 em->block_start = ins.objectid;
9790 em->block_len = ins.offset;
9791 em->orig_block_len = ins.offset;
9792 em->ram_bytes = ins.offset;
9793 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9794 em->generation = trans->transid;
9796 ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9797 free_extent_map(em);
9799 num_bytes -= ins.offset;
9800 cur_offset += ins.offset;
9801 *alloc_hint = ins.objectid + ins.offset;
9803 inode_inc_iversion(inode);
9804 inode->i_ctime = current_time(inode);
9805 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9806 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9807 (actual_len > inode->i_size) &&
9808 (cur_offset > inode->i_size)) {
9809 if (cur_offset > actual_len)
9810 i_size = actual_len;
9812 i_size = cur_offset;
9813 i_size_write(inode, i_size);
9814 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9817 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9820 btrfs_abort_transaction(trans, ret);
9822 btrfs_end_transaction(trans);
9827 btrfs_end_transaction(trans);
9831 if (clear_offset < end)
9832 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9833 end - clear_offset + 1);
9837 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9838 u64 start, u64 num_bytes, u64 min_size,
9839 loff_t actual_len, u64 *alloc_hint)
9841 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9842 min_size, actual_len, alloc_hint,
9846 int btrfs_prealloc_file_range_trans(struct inode *inode,
9847 struct btrfs_trans_handle *trans, int mode,
9848 u64 start, u64 num_bytes, u64 min_size,
9849 loff_t actual_len, u64 *alloc_hint)
9851 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9852 min_size, actual_len, alloc_hint, trans);
9855 static int btrfs_permission(struct mnt_idmap *idmap,
9856 struct inode *inode, int mask)
9858 struct btrfs_root *root = BTRFS_I(inode)->root;
9859 umode_t mode = inode->i_mode;
9861 if (mask & MAY_WRITE &&
9862 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9863 if (btrfs_root_readonly(root))
9865 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9868 return generic_permission(idmap, inode, mask);
9871 static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
9872 struct file *file, umode_t mode)
9874 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9875 struct btrfs_trans_handle *trans;
9876 struct btrfs_root *root = BTRFS_I(dir)->root;
9877 struct inode *inode;
9878 struct btrfs_new_inode_args new_inode_args = {
9880 .dentry = file->f_path.dentry,
9883 unsigned int trans_num_items;
9886 inode = new_inode(dir->i_sb);
9889 inode_init_owner(idmap, inode, dir, mode);
9890 inode->i_fop = &btrfs_file_operations;
9891 inode->i_op = &btrfs_file_inode_operations;
9892 inode->i_mapping->a_ops = &btrfs_aops;
9894 new_inode_args.inode = inode;
9895 ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9899 trans = btrfs_start_transaction(root, trans_num_items);
9900 if (IS_ERR(trans)) {
9901 ret = PTR_ERR(trans);
9902 goto out_new_inode_args;
9905 ret = btrfs_create_new_inode(trans, &new_inode_args);
9908 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9909 * set it to 1 because d_tmpfile() will issue a warning if the count is
9912 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9914 set_nlink(inode, 1);
9917 d_tmpfile(file, inode);
9918 unlock_new_inode(inode);
9919 mark_inode_dirty(inode);
9922 btrfs_end_transaction(trans);
9923 btrfs_btree_balance_dirty(fs_info);
9925 btrfs_new_inode_args_destroy(&new_inode_args);
9929 return finish_open_simple(file, ret);
9932 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
9934 struct btrfs_fs_info *fs_info = inode->root->fs_info;
9935 unsigned long index = start >> PAGE_SHIFT;
9936 unsigned long end_index = end >> PAGE_SHIFT;
9940 ASSERT(end + 1 - start <= U32_MAX);
9941 len = end + 1 - start;
9942 while (index <= end_index) {
9943 page = find_get_page(inode->vfs_inode.i_mapping, index);
9944 ASSERT(page); /* Pages should be in the extent_io_tree */
9946 btrfs_page_set_writeback(fs_info, page, start, len);
9952 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
9955 switch (compress_type) {
9956 case BTRFS_COMPRESS_NONE:
9957 return BTRFS_ENCODED_IO_COMPRESSION_NONE;
9958 case BTRFS_COMPRESS_ZLIB:
9959 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
9960 case BTRFS_COMPRESS_LZO:
9962 * The LZO format depends on the sector size. 64K is the maximum
9963 * sector size that we support.
9965 if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
9967 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
9968 (fs_info->sectorsize_bits - 12);
9969 case BTRFS_COMPRESS_ZSTD:
9970 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
9976 static ssize_t btrfs_encoded_read_inline(
9978 struct iov_iter *iter, u64 start,
9980 struct extent_state **cached_state,
9981 u64 extent_start, size_t count,
9982 struct btrfs_ioctl_encoded_io_args *encoded,
9985 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9986 struct btrfs_root *root = inode->root;
9987 struct btrfs_fs_info *fs_info = root->fs_info;
9988 struct extent_io_tree *io_tree = &inode->io_tree;
9989 struct btrfs_path *path;
9990 struct extent_buffer *leaf;
9991 struct btrfs_file_extent_item *item;
9997 path = btrfs_alloc_path();
10002 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
10006 /* The extent item disappeared? */
10011 leaf = path->nodes[0];
10012 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10014 ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
10015 ptr = btrfs_file_extent_inline_start(item);
10017 encoded->len = min_t(u64, extent_start + ram_bytes,
10018 inode->vfs_inode.i_size) - iocb->ki_pos;
10019 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10020 btrfs_file_extent_compression(leaf, item));
10023 encoded->compression = ret;
10024 if (encoded->compression) {
10025 size_t inline_size;
10027 inline_size = btrfs_file_extent_inline_item_len(leaf,
10029 if (inline_size > count) {
10033 count = inline_size;
10034 encoded->unencoded_len = ram_bytes;
10035 encoded->unencoded_offset = iocb->ki_pos - extent_start;
10037 count = min_t(u64, count, encoded->len);
10038 encoded->len = count;
10039 encoded->unencoded_len = count;
10040 ptr += iocb->ki_pos - extent_start;
10043 tmp = kmalloc(count, GFP_NOFS);
10048 read_extent_buffer(leaf, tmp, ptr, count);
10049 btrfs_release_path(path);
10050 unlock_extent(io_tree, start, lockend, cached_state);
10051 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10054 ret = copy_to_iter(tmp, count, iter);
10059 btrfs_free_path(path);
10063 struct btrfs_encoded_read_private {
10064 wait_queue_head_t wait;
10066 blk_status_t status;
10069 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
10071 struct btrfs_encoded_read_private *priv = bbio->private;
10073 if (bbio->bio.bi_status) {
10075 * The memory barrier implied by the atomic_dec_return() here
10076 * pairs with the memory barrier implied by the
10077 * atomic_dec_return() or io_wait_event() in
10078 * btrfs_encoded_read_regular_fill_pages() to ensure that this
10079 * write is observed before the load of status in
10080 * btrfs_encoded_read_regular_fill_pages().
10082 WRITE_ONCE(priv->status, bbio->bio.bi_status);
10084 if (!atomic_dec_return(&priv->pending))
10085 wake_up(&priv->wait);
10086 bio_put(&bbio->bio);
10089 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
10090 u64 file_offset, u64 disk_bytenr,
10091 u64 disk_io_size, struct page **pages)
10093 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10094 struct btrfs_encoded_read_private priv = {
10095 .pending = ATOMIC_INIT(1),
10097 unsigned long i = 0;
10098 struct btrfs_bio *bbio;
10100 init_waitqueue_head(&priv.wait);
10102 bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, fs_info,
10103 btrfs_encoded_read_endio, &priv);
10104 bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
10105 bbio->inode = inode;
10108 size_t bytes = min_t(u64, disk_io_size, PAGE_SIZE);
10110 if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
10111 atomic_inc(&priv.pending);
10112 btrfs_submit_bio(bbio, 0);
10114 bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, fs_info,
10115 btrfs_encoded_read_endio, &priv);
10116 bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
10117 bbio->inode = inode;
10122 disk_bytenr += bytes;
10123 disk_io_size -= bytes;
10124 } while (disk_io_size);
10126 atomic_inc(&priv.pending);
10127 btrfs_submit_bio(bbio, 0);
10129 if (atomic_dec_return(&priv.pending))
10130 io_wait_event(priv.wait, !atomic_read(&priv.pending));
10131 /* See btrfs_encoded_read_endio() for ordering. */
10132 return blk_status_to_errno(READ_ONCE(priv.status));
10135 static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
10136 struct iov_iter *iter,
10137 u64 start, u64 lockend,
10138 struct extent_state **cached_state,
10139 u64 disk_bytenr, u64 disk_io_size,
10140 size_t count, bool compressed,
10143 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10144 struct extent_io_tree *io_tree = &inode->io_tree;
10145 struct page **pages;
10146 unsigned long nr_pages, i;
10148 size_t page_offset;
10151 nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
10152 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
10155 ret = btrfs_alloc_page_array(nr_pages, pages);
10161 ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
10162 disk_io_size, pages);
10166 unlock_extent(io_tree, start, lockend, cached_state);
10167 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10174 i = (iocb->ki_pos - start) >> PAGE_SHIFT;
10175 page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
10178 while (cur < count) {
10179 size_t bytes = min_t(size_t, count - cur,
10180 PAGE_SIZE - page_offset);
10182 if (copy_page_to_iter(pages[i], page_offset, bytes,
10193 for (i = 0; i < nr_pages; i++) {
10195 __free_page(pages[i]);
10201 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
10202 struct btrfs_ioctl_encoded_io_args *encoded)
10204 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10205 struct btrfs_fs_info *fs_info = inode->root->fs_info;
10206 struct extent_io_tree *io_tree = &inode->io_tree;
10208 size_t count = iov_iter_count(iter);
10209 u64 start, lockend, disk_bytenr, disk_io_size;
10210 struct extent_state *cached_state = NULL;
10211 struct extent_map *em;
10212 bool unlocked = false;
10214 file_accessed(iocb->ki_filp);
10216 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
10218 if (iocb->ki_pos >= inode->vfs_inode.i_size) {
10219 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10222 start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
10224 * We don't know how long the extent containing iocb->ki_pos is, but if
10225 * it's compressed we know that it won't be longer than this.
10227 lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
10230 struct btrfs_ordered_extent *ordered;
10232 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
10233 lockend - start + 1);
10235 goto out_unlock_inode;
10236 lock_extent(io_tree, start, lockend, &cached_state);
10237 ordered = btrfs_lookup_ordered_range(inode, start,
10238 lockend - start + 1);
10241 btrfs_put_ordered_extent(ordered);
10242 unlock_extent(io_tree, start, lockend, &cached_state);
10246 em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
10249 goto out_unlock_extent;
10252 if (em->block_start == EXTENT_MAP_INLINE) {
10253 u64 extent_start = em->start;
10256 * For inline extents we get everything we need out of the
10259 free_extent_map(em);
10261 ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
10262 &cached_state, extent_start,
10263 count, encoded, &unlocked);
10268 * We only want to return up to EOF even if the extent extends beyond
10271 encoded->len = min_t(u64, extent_map_end(em),
10272 inode->vfs_inode.i_size) - iocb->ki_pos;
10273 if (em->block_start == EXTENT_MAP_HOLE ||
10274 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
10275 disk_bytenr = EXTENT_MAP_HOLE;
10276 count = min_t(u64, count, encoded->len);
10277 encoded->len = count;
10278 encoded->unencoded_len = count;
10279 } else if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10280 disk_bytenr = em->block_start;
10282 * Bail if the buffer isn't large enough to return the whole
10283 * compressed extent.
10285 if (em->block_len > count) {
10289 disk_io_size = em->block_len;
10290 count = em->block_len;
10291 encoded->unencoded_len = em->ram_bytes;
10292 encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
10293 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10294 em->compress_type);
10297 encoded->compression = ret;
10299 disk_bytenr = em->block_start + (start - em->start);
10300 if (encoded->len > count)
10301 encoded->len = count;
10303 * Don't read beyond what we locked. This also limits the page
10304 * allocations that we'll do.
10306 disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
10307 count = start + disk_io_size - iocb->ki_pos;
10308 encoded->len = count;
10309 encoded->unencoded_len = count;
10310 disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
10312 free_extent_map(em);
10315 if (disk_bytenr == EXTENT_MAP_HOLE) {
10316 unlock_extent(io_tree, start, lockend, &cached_state);
10317 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10319 ret = iov_iter_zero(count, iter);
10323 ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
10324 &cached_state, disk_bytenr,
10325 disk_io_size, count,
10326 encoded->compression,
10332 iocb->ki_pos += encoded->len;
10334 free_extent_map(em);
10337 unlock_extent(io_tree, start, lockend, &cached_state);
10340 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
10344 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
10345 const struct btrfs_ioctl_encoded_io_args *encoded)
10347 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10348 struct btrfs_root *root = inode->root;
10349 struct btrfs_fs_info *fs_info = root->fs_info;
10350 struct extent_io_tree *io_tree = &inode->io_tree;
10351 struct extent_changeset *data_reserved = NULL;
10352 struct extent_state *cached_state = NULL;
10353 struct btrfs_ordered_extent *ordered;
10357 u64 num_bytes, ram_bytes, disk_num_bytes;
10358 unsigned long nr_pages, i;
10359 struct page **pages;
10360 struct btrfs_key ins;
10361 bool extent_reserved = false;
10362 struct extent_map *em;
10365 switch (encoded->compression) {
10366 case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
10367 compression = BTRFS_COMPRESS_ZLIB;
10369 case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
10370 compression = BTRFS_COMPRESS_ZSTD;
10372 case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
10373 case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
10374 case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
10375 case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
10376 case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
10377 /* The sector size must match for LZO. */
10378 if (encoded->compression -
10379 BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
10380 fs_info->sectorsize_bits)
10382 compression = BTRFS_COMPRESS_LZO;
10387 if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
10390 orig_count = iov_iter_count(from);
10392 /* The extent size must be sane. */
10393 if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
10394 orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
10398 * The compressed data must be smaller than the decompressed data.
10400 * It's of course possible for data to compress to larger or the same
10401 * size, but the buffered I/O path falls back to no compression for such
10402 * data, and we don't want to break any assumptions by creating these
10405 * Note that this is less strict than the current check we have that the
10406 * compressed data must be at least one sector smaller than the
10407 * decompressed data. We only want to enforce the weaker requirement
10408 * from old kernels that it is at least one byte smaller.
10410 if (orig_count >= encoded->unencoded_len)
10413 /* The extent must start on a sector boundary. */
10414 start = iocb->ki_pos;
10415 if (!IS_ALIGNED(start, fs_info->sectorsize))
10419 * The extent must end on a sector boundary. However, we allow a write
10420 * which ends at or extends i_size to have an unaligned length; we round
10421 * up the extent size and set i_size to the unaligned end.
10423 if (start + encoded->len < inode->vfs_inode.i_size &&
10424 !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
10427 /* Finally, the offset in the unencoded data must be sector-aligned. */
10428 if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
10431 num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10432 ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10433 end = start + num_bytes - 1;
10436 * If the extent cannot be inline, the compressed data on disk must be
10437 * sector-aligned. For convenience, we extend it with zeroes if it
10440 disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10441 nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
10442 pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
10445 for (i = 0; i < nr_pages; i++) {
10446 size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
10449 pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
10454 kaddr = kmap_local_page(pages[i]);
10455 if (copy_from_iter(kaddr, bytes, from) != bytes) {
10456 kunmap_local(kaddr);
10460 if (bytes < PAGE_SIZE)
10461 memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
10462 kunmap_local(kaddr);
10466 struct btrfs_ordered_extent *ordered;
10468 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
10471 ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10472 start >> PAGE_SHIFT,
10473 end >> PAGE_SHIFT);
10476 lock_extent(io_tree, start, end, &cached_state);
10477 ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10479 !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10482 btrfs_put_ordered_extent(ordered);
10483 unlock_extent(io_tree, start, end, &cached_state);
10488 * We don't use the higher-level delalloc space functions because our
10489 * num_bytes and disk_num_bytes are different.
10491 ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10494 ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10496 goto out_free_data_space;
10497 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10500 goto out_qgroup_free_data;
10502 /* Try an inline extent first. */
10503 if (start == 0 && encoded->unencoded_len == encoded->len &&
10504 encoded->unencoded_offset == 0) {
10505 ret = cow_file_range_inline(inode, encoded->len, orig_count,
10506 compression, pages, true);
10510 goto out_delalloc_release;
10514 ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10515 disk_num_bytes, 0, 0, &ins, 1, 1);
10517 goto out_delalloc_release;
10518 extent_reserved = true;
10520 em = create_io_em(inode, start, num_bytes,
10521 start - encoded->unencoded_offset, ins.objectid,
10522 ins.offset, ins.offset, ram_bytes, compression,
10523 BTRFS_ORDERED_COMPRESSED);
10526 goto out_free_reserved;
10528 free_extent_map(em);
10530 ordered = btrfs_alloc_ordered_extent(inode, start, num_bytes, ram_bytes,
10531 ins.objectid, ins.offset,
10532 encoded->unencoded_offset,
10533 (1 << BTRFS_ORDERED_ENCODED) |
10534 (1 << BTRFS_ORDERED_COMPRESSED),
10536 if (IS_ERR(ordered)) {
10537 btrfs_drop_extent_map_range(inode, start, end, false);
10538 ret = PTR_ERR(ordered);
10539 goto out_free_reserved;
10541 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10543 if (start + encoded->len > inode->vfs_inode.i_size)
10544 i_size_write(&inode->vfs_inode, start + encoded->len);
10546 unlock_extent(io_tree, start, end, &cached_state);
10548 btrfs_delalloc_release_extents(inode, num_bytes);
10550 btrfs_submit_compressed_write(ordered, pages, nr_pages, 0, false);
10555 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10556 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
10557 out_delalloc_release:
10558 btrfs_delalloc_release_extents(inode, num_bytes);
10559 btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10560 out_qgroup_free_data:
10562 btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes);
10563 out_free_data_space:
10565 * If btrfs_reserve_extent() succeeded, then we already decremented
10568 if (!extent_reserved)
10569 btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
10571 unlock_extent(io_tree, start, end, &cached_state);
10573 for (i = 0; i < nr_pages; i++) {
10575 __free_page(pages[i]);
10580 iocb->ki_pos += encoded->len;
10586 * Add an entry indicating a block group or device which is pinned by a
10587 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10588 * negative errno on failure.
10590 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10591 bool is_block_group)
10593 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10594 struct btrfs_swapfile_pin *sp, *entry;
10595 struct rb_node **p;
10596 struct rb_node *parent = NULL;
10598 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10603 sp->is_block_group = is_block_group;
10604 sp->bg_extent_count = 1;
10606 spin_lock(&fs_info->swapfile_pins_lock);
10607 p = &fs_info->swapfile_pins.rb_node;
10610 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10611 if (sp->ptr < entry->ptr ||
10612 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10613 p = &(*p)->rb_left;
10614 } else if (sp->ptr > entry->ptr ||
10615 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10616 p = &(*p)->rb_right;
10618 if (is_block_group)
10619 entry->bg_extent_count++;
10620 spin_unlock(&fs_info->swapfile_pins_lock);
10625 rb_link_node(&sp->node, parent, p);
10626 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10627 spin_unlock(&fs_info->swapfile_pins_lock);
10631 /* Free all of the entries pinned by this swapfile. */
10632 static void btrfs_free_swapfile_pins(struct inode *inode)
10634 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10635 struct btrfs_swapfile_pin *sp;
10636 struct rb_node *node, *next;
10638 spin_lock(&fs_info->swapfile_pins_lock);
10639 node = rb_first(&fs_info->swapfile_pins);
10641 next = rb_next(node);
10642 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10643 if (sp->inode == inode) {
10644 rb_erase(&sp->node, &fs_info->swapfile_pins);
10645 if (sp->is_block_group) {
10646 btrfs_dec_block_group_swap_extents(sp->ptr,
10647 sp->bg_extent_count);
10648 btrfs_put_block_group(sp->ptr);
10654 spin_unlock(&fs_info->swapfile_pins_lock);
10657 struct btrfs_swap_info {
10663 unsigned long nr_pages;
10667 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10668 struct btrfs_swap_info *bsi)
10670 unsigned long nr_pages;
10671 unsigned long max_pages;
10672 u64 first_ppage, first_ppage_reported, next_ppage;
10676 * Our swapfile may have had its size extended after the swap header was
10677 * written. In that case activating the swapfile should not go beyond
10678 * the max size set in the swap header.
10680 if (bsi->nr_pages >= sis->max)
10683 max_pages = sis->max - bsi->nr_pages;
10684 first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
10685 next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
10687 if (first_ppage >= next_ppage)
10689 nr_pages = next_ppage - first_ppage;
10690 nr_pages = min(nr_pages, max_pages);
10692 first_ppage_reported = first_ppage;
10693 if (bsi->start == 0)
10694 first_ppage_reported++;
10695 if (bsi->lowest_ppage > first_ppage_reported)
10696 bsi->lowest_ppage = first_ppage_reported;
10697 if (bsi->highest_ppage < (next_ppage - 1))
10698 bsi->highest_ppage = next_ppage - 1;
10700 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10703 bsi->nr_extents += ret;
10704 bsi->nr_pages += nr_pages;
10708 static void btrfs_swap_deactivate(struct file *file)
10710 struct inode *inode = file_inode(file);
10712 btrfs_free_swapfile_pins(inode);
10713 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10716 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10719 struct inode *inode = file_inode(file);
10720 struct btrfs_root *root = BTRFS_I(inode)->root;
10721 struct btrfs_fs_info *fs_info = root->fs_info;
10722 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10723 struct extent_state *cached_state = NULL;
10724 struct extent_map *em = NULL;
10725 struct btrfs_device *device = NULL;
10726 struct btrfs_swap_info bsi = {
10727 .lowest_ppage = (sector_t)-1ULL,
10734 * If the swap file was just created, make sure delalloc is done. If the
10735 * file changes again after this, the user is doing something stupid and
10736 * we don't really care.
10738 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10743 * The inode is locked, so these flags won't change after we check them.
10745 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10746 btrfs_warn(fs_info, "swapfile must not be compressed");
10749 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10750 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10753 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10754 btrfs_warn(fs_info, "swapfile must not be checksummed");
10759 * Balance or device remove/replace/resize can move stuff around from
10760 * under us. The exclop protection makes sure they aren't running/won't
10761 * run concurrently while we are mapping the swap extents, and
10762 * fs_info->swapfile_pins prevents them from running while the swap
10763 * file is active and moving the extents. Note that this also prevents
10764 * a concurrent device add which isn't actually necessary, but it's not
10765 * really worth the trouble to allow it.
10767 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10768 btrfs_warn(fs_info,
10769 "cannot activate swapfile while exclusive operation is running");
10774 * Prevent snapshot creation while we are activating the swap file.
10775 * We do not want to race with snapshot creation. If snapshot creation
10776 * already started before we bumped nr_swapfiles from 0 to 1 and
10777 * completes before the first write into the swap file after it is
10778 * activated, than that write would fallback to COW.
10780 if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10781 btrfs_exclop_finish(fs_info);
10782 btrfs_warn(fs_info,
10783 "cannot activate swapfile because snapshot creation is in progress");
10787 * Snapshots can create extents which require COW even if NODATACOW is
10788 * set. We use this counter to prevent snapshots. We must increment it
10789 * before walking the extents because we don't want a concurrent
10790 * snapshot to run after we've already checked the extents.
10792 * It is possible that subvolume is marked for deletion but still not
10793 * removed yet. To prevent this race, we check the root status before
10794 * activating the swapfile.
10796 spin_lock(&root->root_item_lock);
10797 if (btrfs_root_dead(root)) {
10798 spin_unlock(&root->root_item_lock);
10800 btrfs_exclop_finish(fs_info);
10801 btrfs_warn(fs_info,
10802 "cannot activate swapfile because subvolume %llu is being deleted",
10803 root->root_key.objectid);
10806 atomic_inc(&root->nr_swapfiles);
10807 spin_unlock(&root->root_item_lock);
10809 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10811 lock_extent(io_tree, 0, isize - 1, &cached_state);
10813 while (start < isize) {
10814 u64 logical_block_start, physical_block_start;
10815 struct btrfs_block_group *bg;
10816 u64 len = isize - start;
10818 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10824 if (em->block_start == EXTENT_MAP_HOLE) {
10825 btrfs_warn(fs_info, "swapfile must not have holes");
10829 if (em->block_start == EXTENT_MAP_INLINE) {
10831 * It's unlikely we'll ever actually find ourselves
10832 * here, as a file small enough to fit inline won't be
10833 * big enough to store more than the swap header, but in
10834 * case something changes in the future, let's catch it
10835 * here rather than later.
10837 btrfs_warn(fs_info, "swapfile must not be inline");
10841 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10842 btrfs_warn(fs_info, "swapfile must not be compressed");
10847 logical_block_start = em->block_start + (start - em->start);
10848 len = min(len, em->len - (start - em->start));
10849 free_extent_map(em);
10852 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, false, true);
10858 btrfs_warn(fs_info,
10859 "swapfile must not be copy-on-write");
10864 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10870 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10871 btrfs_warn(fs_info,
10872 "swapfile must have single data profile");
10877 if (device == NULL) {
10878 device = em->map_lookup->stripes[0].dev;
10879 ret = btrfs_add_swapfile_pin(inode, device, false);
10884 } else if (device != em->map_lookup->stripes[0].dev) {
10885 btrfs_warn(fs_info, "swapfile must be on one device");
10890 physical_block_start = (em->map_lookup->stripes[0].physical +
10891 (logical_block_start - em->start));
10892 len = min(len, em->len - (logical_block_start - em->start));
10893 free_extent_map(em);
10896 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10898 btrfs_warn(fs_info,
10899 "could not find block group containing swapfile");
10904 if (!btrfs_inc_block_group_swap_extents(bg)) {
10905 btrfs_warn(fs_info,
10906 "block group for swapfile at %llu is read-only%s",
10908 atomic_read(&fs_info->scrubs_running) ?
10909 " (scrub running)" : "");
10910 btrfs_put_block_group(bg);
10915 ret = btrfs_add_swapfile_pin(inode, bg, true);
10917 btrfs_put_block_group(bg);
10924 if (bsi.block_len &&
10925 bsi.block_start + bsi.block_len == physical_block_start) {
10926 bsi.block_len += len;
10928 if (bsi.block_len) {
10929 ret = btrfs_add_swap_extent(sis, &bsi);
10934 bsi.block_start = physical_block_start;
10935 bsi.block_len = len;
10942 ret = btrfs_add_swap_extent(sis, &bsi);
10945 if (!IS_ERR_OR_NULL(em))
10946 free_extent_map(em);
10948 unlock_extent(io_tree, 0, isize - 1, &cached_state);
10951 btrfs_swap_deactivate(file);
10953 btrfs_drew_write_unlock(&root->snapshot_lock);
10955 btrfs_exclop_finish(fs_info);
10961 sis->bdev = device->bdev;
10962 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10963 sis->max = bsi.nr_pages;
10964 sis->pages = bsi.nr_pages - 1;
10965 sis->highest_bit = bsi.nr_pages - 1;
10966 return bsi.nr_extents;
10969 static void btrfs_swap_deactivate(struct file *file)
10973 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10976 return -EOPNOTSUPP;
10981 * Update the number of bytes used in the VFS' inode. When we replace extents in
10982 * a range (clone, dedupe, fallocate's zero range), we must update the number of
10983 * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10984 * always get a correct value.
10986 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10987 const u64 add_bytes,
10988 const u64 del_bytes)
10990 if (add_bytes == del_bytes)
10993 spin_lock(&inode->lock);
10995 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10997 inode_add_bytes(&inode->vfs_inode, add_bytes);
10998 spin_unlock(&inode->lock);
11002 * Verify that there are no ordered extents for a given file range.
11004 * @inode: The target inode.
11005 * @start: Start offset of the file range, should be sector size aligned.
11006 * @end: End offset (inclusive) of the file range, its value +1 should be
11007 * sector size aligned.
11009 * This should typically be used for cases where we locked an inode's VFS lock in
11010 * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
11011 * we have flushed all delalloc in the range, we have waited for all ordered
11012 * extents in the range to complete and finally we have locked the file range in
11013 * the inode's io_tree.
11015 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
11017 struct btrfs_root *root = inode->root;
11018 struct btrfs_ordered_extent *ordered;
11020 if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
11023 ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
11025 btrfs_err(root->fs_info,
11026 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
11027 start, end, btrfs_ino(inode), root->root_key.objectid,
11028 ordered->file_offset,
11029 ordered->file_offset + ordered->num_bytes - 1);
11030 btrfs_put_ordered_extent(ordered);
11033 ASSERT(ordered == NULL);
11036 static const struct inode_operations btrfs_dir_inode_operations = {
11037 .getattr = btrfs_getattr,
11038 .lookup = btrfs_lookup,
11039 .create = btrfs_create,
11040 .unlink = btrfs_unlink,
11041 .link = btrfs_link,
11042 .mkdir = btrfs_mkdir,
11043 .rmdir = btrfs_rmdir,
11044 .rename = btrfs_rename2,
11045 .symlink = btrfs_symlink,
11046 .setattr = btrfs_setattr,
11047 .mknod = btrfs_mknod,
11048 .listxattr = btrfs_listxattr,
11049 .permission = btrfs_permission,
11050 .get_inode_acl = btrfs_get_acl,
11051 .set_acl = btrfs_set_acl,
11052 .update_time = btrfs_update_time,
11053 .tmpfile = btrfs_tmpfile,
11054 .fileattr_get = btrfs_fileattr_get,
11055 .fileattr_set = btrfs_fileattr_set,
11058 static const struct file_operations btrfs_dir_file_operations = {
11059 .llseek = generic_file_llseek,
11060 .read = generic_read_dir,
11061 .iterate_shared = btrfs_real_readdir,
11062 .open = btrfs_opendir,
11063 .unlocked_ioctl = btrfs_ioctl,
11064 #ifdef CONFIG_COMPAT
11065 .compat_ioctl = btrfs_compat_ioctl,
11067 .release = btrfs_release_file,
11068 .fsync = btrfs_sync_file,
11072 * btrfs doesn't support the bmap operation because swapfiles
11073 * use bmap to make a mapping of extents in the file. They assume
11074 * these extents won't change over the life of the file and they
11075 * use the bmap result to do IO directly to the drive.
11077 * the btrfs bmap call would return logical addresses that aren't
11078 * suitable for IO and they also will change frequently as COW
11079 * operations happen. So, swapfile + btrfs == corruption.
11081 * For now we're avoiding this by dropping bmap.
11083 static const struct address_space_operations btrfs_aops = {
11084 .read_folio = btrfs_read_folio,
11085 .writepages = btrfs_writepages,
11086 .readahead = btrfs_readahead,
11087 .invalidate_folio = btrfs_invalidate_folio,
11088 .release_folio = btrfs_release_folio,
11089 .migrate_folio = btrfs_migrate_folio,
11090 .dirty_folio = filemap_dirty_folio,
11091 .error_remove_page = generic_error_remove_page,
11092 .swap_activate = btrfs_swap_activate,
11093 .swap_deactivate = btrfs_swap_deactivate,
11096 static const struct inode_operations btrfs_file_inode_operations = {
11097 .getattr = btrfs_getattr,
11098 .setattr = btrfs_setattr,
11099 .listxattr = btrfs_listxattr,
11100 .permission = btrfs_permission,
11101 .fiemap = btrfs_fiemap,
11102 .get_inode_acl = btrfs_get_acl,
11103 .set_acl = btrfs_set_acl,
11104 .update_time = btrfs_update_time,
11105 .fileattr_get = btrfs_fileattr_get,
11106 .fileattr_set = btrfs_fileattr_set,
11108 static const struct inode_operations btrfs_special_inode_operations = {
11109 .getattr = btrfs_getattr,
11110 .setattr = btrfs_setattr,
11111 .permission = btrfs_permission,
11112 .listxattr = btrfs_listxattr,
11113 .get_inode_acl = btrfs_get_acl,
11114 .set_acl = btrfs_set_acl,
11115 .update_time = btrfs_update_time,
11117 static const struct inode_operations btrfs_symlink_inode_operations = {
11118 .get_link = page_get_link,
11119 .getattr = btrfs_getattr,
11120 .setattr = btrfs_setattr,
11121 .permission = btrfs_permission,
11122 .listxattr = btrfs_listxattr,
11123 .update_time = btrfs_update_time,
11126 const struct dentry_operations btrfs_dentry_operations = {
11127 .d_delete = btrfs_dentry_delete,