1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/file.h>
10 #include <linux/fsnotify.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/string.h>
15 #include <linux/backing-dev.h>
16 #include <linux/mount.h>
17 #include <linux/namei.h>
18 #include <linux/writeback.h>
19 #include <linux/compat.h>
20 #include <linux/security.h>
21 #include <linux/xattr.h>
23 #include <linux/slab.h>
24 #include <linux/blkdev.h>
25 #include <linux/uuid.h>
26 #include <linux/btrfs.h>
27 #include <linux/uaccess.h>
28 #include <linux/iversion.h>
29 #include <linux/fileattr.h>
30 #include <linux/fsverity.h>
31 #include <linux/sched/xacct.h>
35 #include "transaction.h"
36 #include "btrfs_inode.h"
37 #include "print-tree.h"
41 #include "rcu-string.h"
43 #include "dev-replace.h"
48 #include "compression.h"
49 #include "space-info.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
55 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
56 * structures are incorrect, as the timespec structure from userspace
57 * is 4 bytes too small. We define these alternatives here to teach
58 * the kernel about the 32-bit struct packing.
60 struct btrfs_ioctl_timespec_32 {
63 } __attribute__ ((__packed__));
65 struct btrfs_ioctl_received_subvol_args_32 {
66 char uuid[BTRFS_UUID_SIZE]; /* in */
67 __u64 stransid; /* in */
68 __u64 rtransid; /* out */
69 struct btrfs_ioctl_timespec_32 stime; /* in */
70 struct btrfs_ioctl_timespec_32 rtime; /* out */
72 __u64 reserved[16]; /* in */
73 } __attribute__ ((__packed__));
75 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
76 struct btrfs_ioctl_received_subvol_args_32)
79 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
80 struct btrfs_ioctl_send_args_32 {
81 __s64 send_fd; /* in */
82 __u64 clone_sources_count; /* in */
83 compat_uptr_t clone_sources; /* in */
84 __u64 parent_root; /* in */
86 __u32 version; /* in */
87 __u8 reserved[28]; /* in */
88 } __attribute__ ((__packed__));
90 #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
91 struct btrfs_ioctl_send_args_32)
93 struct btrfs_ioctl_encoded_io_args_32 {
95 compat_ulong_t iovcnt;
100 __u64 unencoded_offset;
106 #define BTRFS_IOC_ENCODED_READ_32 _IOR(BTRFS_IOCTL_MAGIC, 64, \
107 struct btrfs_ioctl_encoded_io_args_32)
108 #define BTRFS_IOC_ENCODED_WRITE_32 _IOW(BTRFS_IOCTL_MAGIC, 64, \
109 struct btrfs_ioctl_encoded_io_args_32)
112 /* Mask out flags that are inappropriate for the given type of inode. */
113 static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
116 if (S_ISDIR(inode->i_mode))
118 else if (S_ISREG(inode->i_mode))
119 return flags & ~FS_DIRSYNC_FL;
121 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
125 * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
128 static unsigned int btrfs_inode_flags_to_fsflags(struct btrfs_inode *binode)
130 unsigned int iflags = 0;
131 u32 flags = binode->flags;
132 u32 ro_flags = binode->ro_flags;
134 if (flags & BTRFS_INODE_SYNC)
135 iflags |= FS_SYNC_FL;
136 if (flags & BTRFS_INODE_IMMUTABLE)
137 iflags |= FS_IMMUTABLE_FL;
138 if (flags & BTRFS_INODE_APPEND)
139 iflags |= FS_APPEND_FL;
140 if (flags & BTRFS_INODE_NODUMP)
141 iflags |= FS_NODUMP_FL;
142 if (flags & BTRFS_INODE_NOATIME)
143 iflags |= FS_NOATIME_FL;
144 if (flags & BTRFS_INODE_DIRSYNC)
145 iflags |= FS_DIRSYNC_FL;
146 if (flags & BTRFS_INODE_NODATACOW)
147 iflags |= FS_NOCOW_FL;
148 if (ro_flags & BTRFS_INODE_RO_VERITY)
149 iflags |= FS_VERITY_FL;
151 if (flags & BTRFS_INODE_NOCOMPRESS)
152 iflags |= FS_NOCOMP_FL;
153 else if (flags & BTRFS_INODE_COMPRESS)
154 iflags |= FS_COMPR_FL;
160 * Update inode->i_flags based on the btrfs internal flags.
162 void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
164 struct btrfs_inode *binode = BTRFS_I(inode);
165 unsigned int new_fl = 0;
167 if (binode->flags & BTRFS_INODE_SYNC)
169 if (binode->flags & BTRFS_INODE_IMMUTABLE)
170 new_fl |= S_IMMUTABLE;
171 if (binode->flags & BTRFS_INODE_APPEND)
173 if (binode->flags & BTRFS_INODE_NOATIME)
175 if (binode->flags & BTRFS_INODE_DIRSYNC)
177 if (binode->ro_flags & BTRFS_INODE_RO_VERITY)
180 set_mask_bits(&inode->i_flags,
181 S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC |
186 * Check if @flags are a supported and valid set of FS_*_FL flags and that
187 * the old and new flags are not conflicting
189 static int check_fsflags(unsigned int old_flags, unsigned int flags)
191 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
192 FS_NOATIME_FL | FS_NODUMP_FL | \
193 FS_SYNC_FL | FS_DIRSYNC_FL | \
194 FS_NOCOMP_FL | FS_COMPR_FL |
198 /* COMPR and NOCOMP on new/old are valid */
199 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
202 if ((flags & FS_COMPR_FL) && (flags & FS_NOCOW_FL))
205 /* NOCOW and compression options are mutually exclusive */
206 if ((old_flags & FS_NOCOW_FL) && (flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
208 if ((flags & FS_NOCOW_FL) && (old_flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
214 static int check_fsflags_compatible(struct btrfs_fs_info *fs_info,
217 if (btrfs_is_zoned(fs_info) && (flags & FS_NOCOW_FL))
224 * Set flags/xflags from the internal inode flags. The remaining items of
225 * fsxattr are zeroed.
227 int btrfs_fileattr_get(struct dentry *dentry, struct fileattr *fa)
229 struct btrfs_inode *binode = BTRFS_I(d_inode(dentry));
231 fileattr_fill_flags(fa, btrfs_inode_flags_to_fsflags(binode));
235 int btrfs_fileattr_set(struct user_namespace *mnt_userns,
236 struct dentry *dentry, struct fileattr *fa)
238 struct inode *inode = d_inode(dentry);
239 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
240 struct btrfs_inode *binode = BTRFS_I(inode);
241 struct btrfs_root *root = binode->root;
242 struct btrfs_trans_handle *trans;
243 unsigned int fsflags, old_fsflags;
245 const char *comp = NULL;
248 if (btrfs_root_readonly(root))
251 if (fileattr_has_fsx(fa))
254 fsflags = btrfs_mask_fsflags_for_type(inode, fa->flags);
255 old_fsflags = btrfs_inode_flags_to_fsflags(binode);
256 ret = check_fsflags(old_fsflags, fsflags);
260 ret = check_fsflags_compatible(fs_info, fsflags);
264 binode_flags = binode->flags;
265 if (fsflags & FS_SYNC_FL)
266 binode_flags |= BTRFS_INODE_SYNC;
268 binode_flags &= ~BTRFS_INODE_SYNC;
269 if (fsflags & FS_IMMUTABLE_FL)
270 binode_flags |= BTRFS_INODE_IMMUTABLE;
272 binode_flags &= ~BTRFS_INODE_IMMUTABLE;
273 if (fsflags & FS_APPEND_FL)
274 binode_flags |= BTRFS_INODE_APPEND;
276 binode_flags &= ~BTRFS_INODE_APPEND;
277 if (fsflags & FS_NODUMP_FL)
278 binode_flags |= BTRFS_INODE_NODUMP;
280 binode_flags &= ~BTRFS_INODE_NODUMP;
281 if (fsflags & FS_NOATIME_FL)
282 binode_flags |= BTRFS_INODE_NOATIME;
284 binode_flags &= ~BTRFS_INODE_NOATIME;
286 /* If coming from FS_IOC_FSSETXATTR then skip unconverted flags */
287 if (!fa->flags_valid) {
288 /* 1 item for the inode */
289 trans = btrfs_start_transaction(root, 1);
291 return PTR_ERR(trans);
295 if (fsflags & FS_DIRSYNC_FL)
296 binode_flags |= BTRFS_INODE_DIRSYNC;
298 binode_flags &= ~BTRFS_INODE_DIRSYNC;
299 if (fsflags & FS_NOCOW_FL) {
300 if (S_ISREG(inode->i_mode)) {
302 * It's safe to turn csums off here, no extents exist.
303 * Otherwise we want the flag to reflect the real COW
304 * status of the file and will not set it.
306 if (inode->i_size == 0)
307 binode_flags |= BTRFS_INODE_NODATACOW |
308 BTRFS_INODE_NODATASUM;
310 binode_flags |= BTRFS_INODE_NODATACOW;
314 * Revert back under same assumptions as above
316 if (S_ISREG(inode->i_mode)) {
317 if (inode->i_size == 0)
318 binode_flags &= ~(BTRFS_INODE_NODATACOW |
319 BTRFS_INODE_NODATASUM);
321 binode_flags &= ~BTRFS_INODE_NODATACOW;
326 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
327 * flag may be changed automatically if compression code won't make
330 if (fsflags & FS_NOCOMP_FL) {
331 binode_flags &= ~BTRFS_INODE_COMPRESS;
332 binode_flags |= BTRFS_INODE_NOCOMPRESS;
333 } else if (fsflags & FS_COMPR_FL) {
335 if (IS_SWAPFILE(inode))
338 binode_flags |= BTRFS_INODE_COMPRESS;
339 binode_flags &= ~BTRFS_INODE_NOCOMPRESS;
341 comp = btrfs_compress_type2str(fs_info->compress_type);
342 if (!comp || comp[0] == 0)
343 comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
345 binode_flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
352 trans = btrfs_start_transaction(root, 3);
354 return PTR_ERR(trans);
357 ret = btrfs_set_prop(trans, inode, "btrfs.compression", comp,
360 btrfs_abort_transaction(trans, ret);
364 ret = btrfs_set_prop(trans, inode, "btrfs.compression", NULL,
366 if (ret && ret != -ENODATA) {
367 btrfs_abort_transaction(trans, ret);
373 binode->flags = binode_flags;
374 btrfs_sync_inode_flags_to_i_flags(inode);
375 inode_inc_iversion(inode);
376 inode->i_ctime = current_time(inode);
377 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
380 btrfs_end_transaction(trans);
385 * Start exclusive operation @type, return true on success
387 bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
388 enum btrfs_exclusive_operation type)
392 spin_lock(&fs_info->super_lock);
393 if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
394 fs_info->exclusive_operation = type;
397 spin_unlock(&fs_info->super_lock);
403 * Conditionally allow to enter the exclusive operation in case it's compatible
404 * with the running one. This must be paired with btrfs_exclop_start_unlock and
405 * btrfs_exclop_finish.
408 * - the same type is already running
409 * - when trying to add a device and balance has been paused
410 * - not BTRFS_EXCLOP_NONE - this is intentionally incompatible and the caller
411 * must check the condition first that would allow none -> @type
413 bool btrfs_exclop_start_try_lock(struct btrfs_fs_info *fs_info,
414 enum btrfs_exclusive_operation type)
416 spin_lock(&fs_info->super_lock);
417 if (fs_info->exclusive_operation == type ||
418 (fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED &&
419 type == BTRFS_EXCLOP_DEV_ADD))
422 spin_unlock(&fs_info->super_lock);
426 void btrfs_exclop_start_unlock(struct btrfs_fs_info *fs_info)
428 spin_unlock(&fs_info->super_lock);
431 void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
433 spin_lock(&fs_info->super_lock);
434 WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
435 spin_unlock(&fs_info->super_lock);
436 sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
439 void btrfs_exclop_balance(struct btrfs_fs_info *fs_info,
440 enum btrfs_exclusive_operation op)
443 case BTRFS_EXCLOP_BALANCE_PAUSED:
444 spin_lock(&fs_info->super_lock);
445 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE ||
446 fs_info->exclusive_operation == BTRFS_EXCLOP_DEV_ADD);
447 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE_PAUSED;
448 spin_unlock(&fs_info->super_lock);
450 case BTRFS_EXCLOP_BALANCE:
451 spin_lock(&fs_info->super_lock);
452 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED);
453 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
454 spin_unlock(&fs_info->super_lock);
458 "invalid exclop balance operation %d requested", op);
462 static int btrfs_ioctl_getversion(struct inode *inode, int __user *arg)
464 return put_user(inode->i_generation, arg);
467 static noinline int btrfs_ioctl_fitrim(struct btrfs_fs_info *fs_info,
470 struct btrfs_device *device;
471 struct fstrim_range range;
472 u64 minlen = ULLONG_MAX;
476 if (!capable(CAP_SYS_ADMIN))
480 * btrfs_trim_block_group() depends on space cache, which is not
481 * available in zoned filesystem. So, disallow fitrim on a zoned
482 * filesystem for now.
484 if (btrfs_is_zoned(fs_info))
488 * If the fs is mounted with nologreplay, which requires it to be
489 * mounted in RO mode as well, we can not allow discard on free space
490 * inside block groups, because log trees refer to extents that are not
491 * pinned in a block group's free space cache (pinning the extents is
492 * precisely the first phase of replaying a log tree).
494 if (btrfs_test_opt(fs_info, NOLOGREPLAY))
498 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
500 if (!device->bdev || !bdev_max_discard_sectors(device->bdev))
503 minlen = min_t(u64, bdev_discard_granularity(device->bdev),
510 if (copy_from_user(&range, arg, sizeof(range)))
514 * NOTE: Don't truncate the range using super->total_bytes. Bytenr of
515 * block group is in the logical address space, which can be any
516 * sectorsize aligned bytenr in the range [0, U64_MAX].
518 if (range.len < fs_info->sb->s_blocksize)
521 range.minlen = max(range.minlen, minlen);
522 ret = btrfs_trim_fs(fs_info, &range);
526 if (copy_to_user(arg, &range, sizeof(range)))
532 int __pure btrfs_is_empty_uuid(u8 *uuid)
536 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
543 static noinline int create_subvol(struct user_namespace *mnt_userns,
544 struct inode *dir, struct dentry *dentry,
545 const char *name, int namelen,
546 struct btrfs_qgroup_inherit *inherit)
548 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
549 struct btrfs_trans_handle *trans;
550 struct btrfs_key key;
551 struct btrfs_root_item *root_item;
552 struct btrfs_inode_item *inode_item;
553 struct extent_buffer *leaf;
554 struct btrfs_root *root = BTRFS_I(dir)->root;
555 struct btrfs_root *new_root;
556 struct btrfs_block_rsv block_rsv;
557 struct timespec64 cur_time = current_time(dir);
564 root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
568 ret = btrfs_get_free_objectid(fs_info->tree_root, &objectid);
572 ret = get_anon_bdev(&anon_dev);
577 * Don't create subvolume whose level is not zero. Or qgroup will be
578 * screwed up since it assumes subvolume qgroup's level to be 0.
580 if (btrfs_qgroup_level(objectid)) {
585 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
587 * The same as the snapshot creation, please see the comment
588 * of create_snapshot().
590 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
594 trans = btrfs_start_transaction(root, 0);
596 ret = PTR_ERR(trans);
597 btrfs_subvolume_release_metadata(root, &block_rsv);
600 trans->block_rsv = &block_rsv;
601 trans->bytes_reserved = block_rsv.size;
603 ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
607 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
608 BTRFS_NESTING_NORMAL);
614 btrfs_mark_buffer_dirty(leaf);
616 inode_item = &root_item->inode;
617 btrfs_set_stack_inode_generation(inode_item, 1);
618 btrfs_set_stack_inode_size(inode_item, 3);
619 btrfs_set_stack_inode_nlink(inode_item, 1);
620 btrfs_set_stack_inode_nbytes(inode_item,
622 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
624 btrfs_set_root_flags(root_item, 0);
625 btrfs_set_root_limit(root_item, 0);
626 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
628 btrfs_set_root_bytenr(root_item, leaf->start);
629 btrfs_set_root_generation(root_item, trans->transid);
630 btrfs_set_root_level(root_item, 0);
631 btrfs_set_root_refs(root_item, 1);
632 btrfs_set_root_used(root_item, leaf->len);
633 btrfs_set_root_last_snapshot(root_item, 0);
635 btrfs_set_root_generation_v2(root_item,
636 btrfs_root_generation(root_item));
637 generate_random_guid(root_item->uuid);
638 btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
639 btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
640 root_item->ctime = root_item->otime;
641 btrfs_set_root_ctransid(root_item, trans->transid);
642 btrfs_set_root_otransid(root_item, trans->transid);
644 btrfs_tree_unlock(leaf);
646 btrfs_set_root_dirid(root_item, BTRFS_FIRST_FREE_OBJECTID);
648 key.objectid = objectid;
650 key.type = BTRFS_ROOT_ITEM_KEY;
651 ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
655 * Since we don't abort the transaction in this case, free the
656 * tree block so that we don't leak space and leave the
657 * filesystem in an inconsistent state (an extent item in the
658 * extent tree with a backreference for a root that does not
661 btrfs_tree_lock(leaf);
662 btrfs_clean_tree_block(leaf);
663 btrfs_tree_unlock(leaf);
664 btrfs_free_tree_block(trans, objectid, leaf, 0, 1);
665 free_extent_buffer(leaf);
669 free_extent_buffer(leaf);
672 key.offset = (u64)-1;
673 new_root = btrfs_get_new_fs_root(fs_info, objectid, anon_dev);
674 if (IS_ERR(new_root)) {
675 free_anon_bdev(anon_dev);
676 ret = PTR_ERR(new_root);
677 btrfs_abort_transaction(trans, ret);
680 /* Freeing will be done in btrfs_put_root() of new_root */
683 ret = btrfs_record_root_in_trans(trans, new_root);
685 btrfs_put_root(new_root);
686 btrfs_abort_transaction(trans, ret);
690 ret = btrfs_create_subvol_root(trans, new_root, root, mnt_userns);
691 btrfs_put_root(new_root);
693 /* We potentially lose an unused inode item here */
694 btrfs_abort_transaction(trans, ret);
699 * insert the directory item
701 ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
703 btrfs_abort_transaction(trans, ret);
707 ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
708 BTRFS_FT_DIR, index);
710 btrfs_abort_transaction(trans, ret);
714 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
715 ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
717 btrfs_abort_transaction(trans, ret);
721 ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
722 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
724 btrfs_abort_transaction(trans, ret);
728 ret = btrfs_uuid_tree_add(trans, root_item->uuid,
729 BTRFS_UUID_KEY_SUBVOL, objectid);
731 btrfs_abort_transaction(trans, ret);
735 trans->block_rsv = NULL;
736 trans->bytes_reserved = 0;
737 btrfs_subvolume_release_metadata(root, &block_rsv);
740 btrfs_end_transaction(trans);
742 ret = btrfs_commit_transaction(trans);
745 inode = btrfs_lookup_dentry(dir, dentry);
747 return PTR_ERR(inode);
748 d_instantiate(dentry, inode);
754 free_anon_bdev(anon_dev);
759 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
760 struct dentry *dentry, bool readonly,
761 struct btrfs_qgroup_inherit *inherit)
763 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
765 struct btrfs_pending_snapshot *pending_snapshot;
766 struct btrfs_trans_handle *trans;
769 /* We do not support snapshotting right now. */
770 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
772 "extent tree v2 doesn't support snapshotting yet");
776 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
779 if (atomic_read(&root->nr_swapfiles)) {
781 "cannot snapshot subvolume with active swapfile");
785 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
786 if (!pending_snapshot)
789 ret = get_anon_bdev(&pending_snapshot->anon_dev);
792 pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
794 pending_snapshot->path = btrfs_alloc_path();
795 if (!pending_snapshot->root_item || !pending_snapshot->path) {
800 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
801 BTRFS_BLOCK_RSV_TEMP);
803 * 1 - parent dir inode
806 * 2 - root ref/backref
807 * 1 - root of snapshot
810 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
811 &pending_snapshot->block_rsv, 8,
816 pending_snapshot->dentry = dentry;
817 pending_snapshot->root = root;
818 pending_snapshot->readonly = readonly;
819 pending_snapshot->dir = dir;
820 pending_snapshot->inherit = inherit;
822 trans = btrfs_start_transaction(root, 0);
824 ret = PTR_ERR(trans);
828 trans->pending_snapshot = pending_snapshot;
830 ret = btrfs_commit_transaction(trans);
834 ret = pending_snapshot->error;
838 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
842 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
844 ret = PTR_ERR(inode);
848 d_instantiate(dentry, inode);
850 pending_snapshot->anon_dev = 0;
852 /* Prevent double freeing of anon_dev */
853 if (ret && pending_snapshot->snap)
854 pending_snapshot->snap->anon_dev = 0;
855 btrfs_put_root(pending_snapshot->snap);
856 btrfs_subvolume_release_metadata(root, &pending_snapshot->block_rsv);
858 if (pending_snapshot->anon_dev)
859 free_anon_bdev(pending_snapshot->anon_dev);
860 kfree(pending_snapshot->root_item);
861 btrfs_free_path(pending_snapshot->path);
862 kfree(pending_snapshot);
867 /* copy of may_delete in fs/namei.c()
868 * Check whether we can remove a link victim from directory dir, check
869 * whether the type of victim is right.
870 * 1. We can't do it if dir is read-only (done in permission())
871 * 2. We should have write and exec permissions on dir
872 * 3. We can't remove anything from append-only dir
873 * 4. We can't do anything with immutable dir (done in permission())
874 * 5. If the sticky bit on dir is set we should either
875 * a. be owner of dir, or
876 * b. be owner of victim, or
877 * c. have CAP_FOWNER capability
878 * 6. If the victim is append-only or immutable we can't do anything with
879 * links pointing to it.
880 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
881 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
882 * 9. We can't remove a root or mountpoint.
883 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
884 * nfs_async_unlink().
887 static int btrfs_may_delete(struct user_namespace *mnt_userns,
888 struct inode *dir, struct dentry *victim, int isdir)
892 if (d_really_is_negative(victim))
895 BUG_ON(d_inode(victim->d_parent) != dir);
896 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
898 error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
903 if (check_sticky(mnt_userns, dir, d_inode(victim)) ||
904 IS_APPEND(d_inode(victim)) || IS_IMMUTABLE(d_inode(victim)) ||
905 IS_SWAPFILE(d_inode(victim)))
908 if (!d_is_dir(victim))
912 } else if (d_is_dir(victim))
916 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
921 /* copy of may_create in fs/namei.c() */
922 static inline int btrfs_may_create(struct user_namespace *mnt_userns,
923 struct inode *dir, struct dentry *child)
925 if (d_really_is_positive(child))
929 if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
931 return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
935 * Create a new subvolume below @parent. This is largely modeled after
936 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
937 * inside this filesystem so it's quite a bit simpler.
939 static noinline int btrfs_mksubvol(const struct path *parent,
940 struct user_namespace *mnt_userns,
941 const char *name, int namelen,
942 struct btrfs_root *snap_src,
944 struct btrfs_qgroup_inherit *inherit)
946 struct inode *dir = d_inode(parent->dentry);
947 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
948 struct dentry *dentry;
951 error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
955 dentry = lookup_one(mnt_userns, name, parent->dentry, namelen);
956 error = PTR_ERR(dentry);
960 error = btrfs_may_create(mnt_userns, dir, dentry);
965 * even if this name doesn't exist, we may get hash collisions.
966 * check for them now when we can safely fail
968 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
974 down_read(&fs_info->subvol_sem);
976 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
980 error = create_snapshot(snap_src, dir, dentry, readonly, inherit);
982 error = create_subvol(mnt_userns, dir, dentry, name, namelen, inherit);
985 fsnotify_mkdir(dir, dentry);
987 up_read(&fs_info->subvol_sem);
991 btrfs_inode_unlock(dir, 0);
995 static noinline int btrfs_mksnapshot(const struct path *parent,
996 struct user_namespace *mnt_userns,
997 const char *name, int namelen,
998 struct btrfs_root *root,
1000 struct btrfs_qgroup_inherit *inherit)
1003 bool snapshot_force_cow = false;
1006 * Force new buffered writes to reserve space even when NOCOW is
1007 * possible. This is to avoid later writeback (running dealloc) to
1008 * fallback to COW mode and unexpectedly fail with ENOSPC.
1010 btrfs_drew_read_lock(&root->snapshot_lock);
1012 ret = btrfs_start_delalloc_snapshot(root, false);
1017 * All previous writes have started writeback in NOCOW mode, so now
1018 * we force future writes to fallback to COW mode during snapshot
1021 atomic_inc(&root->snapshot_force_cow);
1022 snapshot_force_cow = true;
1024 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
1026 ret = btrfs_mksubvol(parent, mnt_userns, name, namelen,
1027 root, readonly, inherit);
1029 if (snapshot_force_cow)
1030 atomic_dec(&root->snapshot_force_cow);
1031 btrfs_drew_read_unlock(&root->snapshot_lock);
1036 * Defrag specific helper to get an extent map.
1038 * Differences between this and btrfs_get_extent() are:
1040 * - No extent_map will be added to inode->extent_tree
1041 * To reduce memory usage in the long run.
1043 * - Extra optimization to skip file extents older than @newer_than
1044 * By using btrfs_search_forward() we can skip entire file ranges that
1045 * have extents created in past transactions, because btrfs_search_forward()
1046 * will not visit leaves and nodes with a generation smaller than given
1047 * minimal generation threshold (@newer_than).
1049 * Return valid em if we find a file extent matching the requirement.
1050 * Return NULL if we can not find a file extent matching the requirement.
1052 * Return ERR_PTR() for error.
1054 static struct extent_map *defrag_get_extent(struct btrfs_inode *inode,
1055 u64 start, u64 newer_than)
1057 struct btrfs_root *root = inode->root;
1058 struct btrfs_file_extent_item *fi;
1059 struct btrfs_path path = { 0 };
1060 struct extent_map *em;
1061 struct btrfs_key key;
1062 u64 ino = btrfs_ino(inode);
1065 em = alloc_extent_map();
1072 key.type = BTRFS_EXTENT_DATA_KEY;
1076 ret = btrfs_search_forward(root, &key, &path, newer_than);
1079 /* Can't find anything newer */
1083 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1087 if (path.slots[0] >= btrfs_header_nritems(path.nodes[0])) {
1089 * If btrfs_search_slot() makes path to point beyond nritems,
1090 * we should not have an empty leaf, as this inode must at
1091 * least have its INODE_ITEM.
1093 ASSERT(btrfs_header_nritems(path.nodes[0]));
1094 path.slots[0] = btrfs_header_nritems(path.nodes[0]) - 1;
1096 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1097 /* Perfect match, no need to go one slot back */
1098 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY &&
1099 key.offset == start)
1102 /* We didn't find a perfect match, needs to go one slot back */
1103 if (path.slots[0] > 0) {
1104 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1105 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
1110 /* Iterate through the path to find a file extent covering @start */
1114 if (path.slots[0] >= btrfs_header_nritems(path.nodes[0]))
1117 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1120 * We may go one slot back to INODE_REF/XATTR item, then
1121 * need to go forward until we reach an EXTENT_DATA.
1122 * But we should still has the correct ino as key.objectid.
1124 if (WARN_ON(key.objectid < ino) || key.type < BTRFS_EXTENT_DATA_KEY)
1127 /* It's beyond our target range, definitely not extent found */
1128 if (key.objectid > ino || key.type > BTRFS_EXTENT_DATA_KEY)
1132 * | |<- File extent ->|
1135 * This means there is a hole between start and key.offset.
1137 if (key.offset > start) {
1139 em->orig_start = start;
1140 em->block_start = EXTENT_MAP_HOLE;
1141 em->len = key.offset - start;
1145 fi = btrfs_item_ptr(path.nodes[0], path.slots[0],
1146 struct btrfs_file_extent_item);
1147 extent_end = btrfs_file_extent_end(&path);
1150 * |<- file extent ->| |
1153 * We haven't reached start, search next slot.
1155 if (extent_end <= start)
1158 /* Now this extent covers @start, convert it to em */
1159 btrfs_extent_item_to_extent_map(inode, &path, fi, false, em);
1162 ret = btrfs_next_item(root, &path);
1168 btrfs_release_path(&path);
1172 btrfs_release_path(&path);
1173 free_extent_map(em);
1177 btrfs_release_path(&path);
1178 free_extent_map(em);
1179 return ERR_PTR(ret);
1182 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start,
1183 u64 newer_than, bool locked)
1185 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1186 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1187 struct extent_map *em;
1188 const u32 sectorsize = BTRFS_I(inode)->root->fs_info->sectorsize;
1191 * hopefully we have this extent in the tree already, try without
1192 * the full extent lock
1194 read_lock(&em_tree->lock);
1195 em = lookup_extent_mapping(em_tree, start, sectorsize);
1196 read_unlock(&em_tree->lock);
1199 * We can get a merged extent, in that case, we need to re-search
1200 * tree to get the original em for defrag.
1202 * If @newer_than is 0 or em::generation < newer_than, we can trust
1203 * this em, as either we don't care about the generation, or the
1204 * merged extent map will be rejected anyway.
1206 if (em && test_bit(EXTENT_FLAG_MERGED, &em->flags) &&
1207 newer_than && em->generation >= newer_than) {
1208 free_extent_map(em);
1213 struct extent_state *cached = NULL;
1214 u64 end = start + sectorsize - 1;
1216 /* get the big lock and read metadata off disk */
1218 lock_extent_bits(io_tree, start, end, &cached);
1219 em = defrag_get_extent(BTRFS_I(inode), start, newer_than);
1221 unlock_extent_cached(io_tree, start, end, &cached);
1230 static u32 get_extent_max_capacity(const struct extent_map *em)
1232 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1233 return BTRFS_MAX_COMPRESSED;
1234 return BTRFS_MAX_EXTENT_SIZE;
1237 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em,
1238 u32 extent_thresh, u64 newer_than, bool locked)
1240 struct extent_map *next;
1243 /* this is the last extent */
1244 if (em->start + em->len >= i_size_read(inode))
1248 * Here we need to pass @newer_then when checking the next extent, or
1249 * we will hit a case we mark current extent for defrag, but the next
1250 * one will not be a target.
1251 * This will just cause extra IO without really reducing the fragments.
1253 next = defrag_lookup_extent(inode, em->start + em->len, newer_than, locked);
1254 /* No more em or hole */
1255 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1257 if (test_bit(EXTENT_FLAG_PREALLOC, &next->flags))
1260 * If the next extent is at its max capacity, defragging current extent
1261 * makes no sense, as the total number of extents won't change.
1263 if (next->len >= get_extent_max_capacity(em))
1265 /* Skip older extent */
1266 if (next->generation < newer_than)
1268 /* Also check extent size */
1269 if (next->len >= extent_thresh)
1274 free_extent_map(next);
1279 * Prepare one page to be defragged.
1283 * - Returned page is locked and has been set up properly.
1284 * - No ordered extent exists in the page.
1285 * - The page is uptodate.
1287 * NOTE: Caller should also wait for page writeback after the cluster is
1288 * prepared, here we don't do writeback wait for each page.
1290 static struct page *defrag_prepare_one_page(struct btrfs_inode *inode,
1293 struct address_space *mapping = inode->vfs_inode.i_mapping;
1294 gfp_t mask = btrfs_alloc_write_mask(mapping);
1295 u64 page_start = (u64)index << PAGE_SHIFT;
1296 u64 page_end = page_start + PAGE_SIZE - 1;
1297 struct extent_state *cached_state = NULL;
1302 page = find_or_create_page(mapping, index, mask);
1304 return ERR_PTR(-ENOMEM);
1307 * Since we can defragment files opened read-only, we can encounter
1308 * transparent huge pages here (see CONFIG_READ_ONLY_THP_FOR_FS). We
1309 * can't do I/O using huge pages yet, so return an error for now.
1310 * Filesystem transparent huge pages are typically only used for
1311 * executables that explicitly enable them, so this isn't very
1314 if (PageCompound(page)) {
1317 return ERR_PTR(-ETXTBSY);
1320 ret = set_page_extent_mapped(page);
1324 return ERR_PTR(ret);
1327 /* Wait for any existing ordered extent in the range */
1329 struct btrfs_ordered_extent *ordered;
1331 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
1332 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
1333 unlock_extent_cached(&inode->io_tree, page_start, page_end,
1339 btrfs_start_ordered_extent(ordered, 1);
1340 btrfs_put_ordered_extent(ordered);
1343 * We unlocked the page above, so we need check if it was
1346 if (page->mapping != mapping || !PagePrivate(page)) {
1354 * Now the page range has no ordered extent any more. Read the page to
1357 if (!PageUptodate(page)) {
1358 btrfs_readpage(NULL, page);
1360 if (page->mapping != mapping || !PagePrivate(page)) {
1365 if (!PageUptodate(page)) {
1368 return ERR_PTR(-EIO);
1374 struct defrag_target_range {
1375 struct list_head list;
1381 * Collect all valid target extents.
1383 * @start: file offset to lookup
1384 * @len: length to lookup
1385 * @extent_thresh: file extent size threshold, any extent size >= this value
1387 * @newer_than: only defrag extents newer than this value
1388 * @do_compress: whether the defrag is doing compression
1389 * if true, @extent_thresh will be ignored and all regular
1390 * file extents meeting @newer_than will be targets.
1391 * @locked: if the range has already held extent lock
1392 * @target_list: list of targets file extents
1394 static int defrag_collect_targets(struct btrfs_inode *inode,
1395 u64 start, u64 len, u32 extent_thresh,
1396 u64 newer_than, bool do_compress,
1397 bool locked, struct list_head *target_list,
1398 u64 *last_scanned_ret)
1400 bool last_is_target = false;
1404 while (cur < start + len) {
1405 struct extent_map *em;
1406 struct defrag_target_range *new;
1407 bool next_mergeable = true;
1410 last_is_target = false;
1411 em = defrag_lookup_extent(&inode->vfs_inode, cur,
1412 newer_than, locked);
1416 /* Skip hole/inline/preallocated extents */
1417 if (em->block_start >= EXTENT_MAP_LAST_BYTE ||
1418 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1421 /* Skip older extent */
1422 if (em->generation < newer_than)
1425 /* This em is under writeback, no need to defrag */
1426 if (em->generation == (u64)-1)
1430 * Our start offset might be in the middle of an existing extent
1431 * map, so take that into account.
1433 range_len = em->len - (cur - em->start);
1435 * If this range of the extent map is already flagged for delalloc,
1438 * 1) We could deadlock later, when trying to reserve space for
1439 * delalloc, because in case we can't immediately reserve space
1440 * the flusher can start delalloc and wait for the respective
1441 * ordered extents to complete. The deadlock would happen
1442 * because we do the space reservation while holding the range
1443 * locked, and starting writeback, or finishing an ordered
1444 * extent, requires locking the range;
1446 * 2) If there's delalloc there, it means there's dirty pages for
1447 * which writeback has not started yet (we clean the delalloc
1448 * flag when starting writeback and after creating an ordered
1449 * extent). If we mark pages in an adjacent range for defrag,
1450 * then we will have a larger contiguous range for delalloc,
1451 * very likely resulting in a larger extent after writeback is
1452 * triggered (except in a case of free space fragmentation).
1454 if (test_range_bit(&inode->io_tree, cur, cur + range_len - 1,
1455 EXTENT_DELALLOC, 0, NULL))
1459 * For do_compress case, we want to compress all valid file
1460 * extents, thus no @extent_thresh or mergeable check.
1465 /* Skip too large extent */
1466 if (range_len >= extent_thresh)
1470 * Skip extents already at its max capacity, this is mostly for
1471 * compressed extents, which max cap is only 128K.
1473 if (em->len >= get_extent_max_capacity(em))
1476 next_mergeable = defrag_check_next_extent(&inode->vfs_inode, em,
1477 extent_thresh, newer_than, locked);
1478 if (!next_mergeable) {
1479 struct defrag_target_range *last;
1481 /* Empty target list, no way to merge with last entry */
1482 if (list_empty(target_list))
1484 last = list_entry(target_list->prev,
1485 struct defrag_target_range, list);
1486 /* Not mergeable with last entry */
1487 if (last->start + last->len != cur)
1490 /* Mergeable, fall through to add it to @target_list. */
1494 last_is_target = true;
1495 range_len = min(extent_map_end(em), start + len) - cur;
1497 * This one is a good target, check if it can be merged into
1498 * last range of the target list.
1500 if (!list_empty(target_list)) {
1501 struct defrag_target_range *last;
1503 last = list_entry(target_list->prev,
1504 struct defrag_target_range, list);
1505 ASSERT(last->start + last->len <= cur);
1506 if (last->start + last->len == cur) {
1507 /* Mergeable, enlarge the last entry */
1508 last->len += range_len;
1511 /* Fall through to allocate a new entry */
1514 /* Allocate new defrag_target_range */
1515 new = kmalloc(sizeof(*new), GFP_NOFS);
1517 free_extent_map(em);
1522 new->len = range_len;
1523 list_add_tail(&new->list, target_list);
1526 cur = extent_map_end(em);
1527 free_extent_map(em);
1530 struct defrag_target_range *entry;
1531 struct defrag_target_range *tmp;
1533 list_for_each_entry_safe(entry, tmp, target_list, list) {
1534 list_del_init(&entry->list);
1538 if (!ret && last_scanned_ret) {
1540 * If the last extent is not a target, the caller can skip to
1541 * the end of that extent.
1542 * Otherwise, we can only go the end of the specified range.
1544 if (!last_is_target)
1545 *last_scanned_ret = max(cur, *last_scanned_ret);
1547 *last_scanned_ret = max(start + len, *last_scanned_ret);
1552 #define CLUSTER_SIZE (SZ_256K)
1553 static_assert(IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
1556 * Defrag one contiguous target range.
1558 * @inode: target inode
1559 * @target: target range to defrag
1560 * @pages: locked pages covering the defrag range
1561 * @nr_pages: number of locked pages
1563 * Caller should ensure:
1565 * - Pages are prepared
1566 * Pages should be locked, no ordered extent in the pages range,
1569 * - Extent bits are locked
1571 static int defrag_one_locked_target(struct btrfs_inode *inode,
1572 struct defrag_target_range *target,
1573 struct page **pages, int nr_pages,
1574 struct extent_state **cached_state)
1576 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1577 struct extent_changeset *data_reserved = NULL;
1578 const u64 start = target->start;
1579 const u64 len = target->len;
1580 unsigned long last_index = (start + len - 1) >> PAGE_SHIFT;
1581 unsigned long start_index = start >> PAGE_SHIFT;
1582 unsigned long first_index = page_index(pages[0]);
1586 ASSERT(last_index - first_index + 1 <= nr_pages);
1588 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, start, len);
1591 clear_extent_bit(&inode->io_tree, start, start + len - 1,
1592 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
1593 EXTENT_DEFRAG, 0, 0, cached_state);
1594 set_extent_defrag(&inode->io_tree, start, start + len - 1, cached_state);
1596 /* Update the page status */
1597 for (i = start_index - first_index; i <= last_index - first_index; i++) {
1598 ClearPageChecked(pages[i]);
1599 btrfs_page_clamp_set_dirty(fs_info, pages[i], start, len);
1601 btrfs_delalloc_release_extents(inode, len);
1602 extent_changeset_free(data_reserved);
1607 static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
1608 u32 extent_thresh, u64 newer_than, bool do_compress,
1609 u64 *last_scanned_ret)
1611 struct extent_state *cached_state = NULL;
1612 struct defrag_target_range *entry;
1613 struct defrag_target_range *tmp;
1614 LIST_HEAD(target_list);
1615 struct page **pages;
1616 const u32 sectorsize = inode->root->fs_info->sectorsize;
1617 u64 last_index = (start + len - 1) >> PAGE_SHIFT;
1618 u64 start_index = start >> PAGE_SHIFT;
1619 unsigned int nr_pages = last_index - start_index + 1;
1623 ASSERT(nr_pages <= CLUSTER_SIZE / PAGE_SIZE);
1624 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(len, sectorsize));
1626 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
1630 /* Prepare all pages */
1631 for (i = 0; i < nr_pages; i++) {
1632 pages[i] = defrag_prepare_one_page(inode, start_index + i);
1633 if (IS_ERR(pages[i])) {
1634 ret = PTR_ERR(pages[i]);
1639 for (i = 0; i < nr_pages; i++)
1640 wait_on_page_writeback(pages[i]);
1642 /* Lock the pages range */
1643 lock_extent_bits(&inode->io_tree, start_index << PAGE_SHIFT,
1644 (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1647 * Now we have a consistent view about the extent map, re-check
1648 * which range really needs to be defragged.
1650 * And this time we have extent locked already, pass @locked = true
1651 * so that we won't relock the extent range and cause deadlock.
1653 ret = defrag_collect_targets(inode, start, len, extent_thresh,
1654 newer_than, do_compress, true,
1655 &target_list, last_scanned_ret);
1659 list_for_each_entry(entry, &target_list, list) {
1660 ret = defrag_one_locked_target(inode, entry, pages, nr_pages,
1666 list_for_each_entry_safe(entry, tmp, &target_list, list) {
1667 list_del_init(&entry->list);
1671 unlock_extent_cached(&inode->io_tree, start_index << PAGE_SHIFT,
1672 (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1675 for (i = 0; i < nr_pages; i++) {
1677 unlock_page(pages[i]);
1685 static int defrag_one_cluster(struct btrfs_inode *inode,
1686 struct file_ra_state *ra,
1687 u64 start, u32 len, u32 extent_thresh,
1688 u64 newer_than, bool do_compress,
1689 unsigned long *sectors_defragged,
1690 unsigned long max_sectors,
1691 u64 *last_scanned_ret)
1693 const u32 sectorsize = inode->root->fs_info->sectorsize;
1694 struct defrag_target_range *entry;
1695 struct defrag_target_range *tmp;
1696 LIST_HEAD(target_list);
1699 ret = defrag_collect_targets(inode, start, len, extent_thresh,
1700 newer_than, do_compress, false,
1701 &target_list, NULL);
1705 list_for_each_entry(entry, &target_list, list) {
1706 u32 range_len = entry->len;
1708 /* Reached or beyond the limit */
1709 if (max_sectors && *sectors_defragged >= max_sectors) {
1715 range_len = min_t(u32, range_len,
1716 (max_sectors - *sectors_defragged) * sectorsize);
1719 * If defrag_one_range() has updated last_scanned_ret,
1720 * our range may already be invalid (e.g. hole punched).
1721 * Skip if our range is before last_scanned_ret, as there is
1722 * no need to defrag the range anymore.
1724 if (entry->start + range_len <= *last_scanned_ret)
1728 page_cache_sync_readahead(inode->vfs_inode.i_mapping,
1729 ra, NULL, entry->start >> PAGE_SHIFT,
1730 ((entry->start + range_len - 1) >> PAGE_SHIFT) -
1731 (entry->start >> PAGE_SHIFT) + 1);
1733 * Here we may not defrag any range if holes are punched before
1734 * we locked the pages.
1735 * But that's fine, it only affects the @sectors_defragged
1738 ret = defrag_one_range(inode, entry->start, range_len,
1739 extent_thresh, newer_than, do_compress,
1743 *sectors_defragged += range_len >>
1744 inode->root->fs_info->sectorsize_bits;
1747 list_for_each_entry_safe(entry, tmp, &target_list, list) {
1748 list_del_init(&entry->list);
1752 *last_scanned_ret = max(*last_scanned_ret, start + len);
1757 * Entry point to file defragmentation.
1759 * @inode: inode to be defragged
1760 * @ra: readahead state (can be NUL)
1761 * @range: defrag options including range and flags
1762 * @newer_than: minimum transid to defrag
1763 * @max_to_defrag: max number of sectors to be defragged, if 0, the whole inode
1764 * will be defragged.
1766 * Return <0 for error.
1767 * Return >=0 for the number of sectors defragged, and range->start will be updated
1768 * to indicate the file offset where next defrag should be started at.
1769 * (Mostly for autodefrag, which sets @max_to_defrag thus we may exit early without
1770 * defragging all the range).
1772 int btrfs_defrag_file(struct inode *inode, struct file_ra_state *ra,
1773 struct btrfs_ioctl_defrag_range_args *range,
1774 u64 newer_than, unsigned long max_to_defrag)
1776 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1777 unsigned long sectors_defragged = 0;
1778 u64 isize = i_size_read(inode);
1781 bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1782 bool ra_allocated = false;
1783 int compress_type = BTRFS_COMPRESS_ZLIB;
1785 u32 extent_thresh = range->extent_thresh;
1786 pgoff_t start_index;
1791 if (range->start >= isize)
1795 if (range->compress_type >= BTRFS_NR_COMPRESS_TYPES)
1797 if (range->compress_type)
1798 compress_type = range->compress_type;
1801 if (extent_thresh == 0)
1802 extent_thresh = SZ_256K;
1804 if (range->start + range->len > range->start) {
1805 /* Got a specific range */
1806 last_byte = min(isize, range->start + range->len);
1808 /* Defrag until file end */
1812 /* Align the range */
1813 cur = round_down(range->start, fs_info->sectorsize);
1814 last_byte = round_up(last_byte, fs_info->sectorsize) - 1;
1817 * If we were not given a ra, allocate a readahead context. As
1818 * readahead is just an optimization, defrag will work without it so
1819 * we don't error out.
1822 ra_allocated = true;
1823 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1825 file_ra_state_init(ra, inode->i_mapping);
1829 * Make writeback start from the beginning of the range, so that the
1830 * defrag range can be written sequentially.
1832 start_index = cur >> PAGE_SHIFT;
1833 if (start_index < inode->i_mapping->writeback_index)
1834 inode->i_mapping->writeback_index = start_index;
1836 while (cur < last_byte) {
1837 const unsigned long prev_sectors_defragged = sectors_defragged;
1838 u64 last_scanned = cur;
1841 if (btrfs_defrag_cancelled(fs_info)) {
1846 /* We want the cluster end at page boundary when possible */
1847 cluster_end = (((cur >> PAGE_SHIFT) +
1848 (SZ_256K >> PAGE_SHIFT)) << PAGE_SHIFT) - 1;
1849 cluster_end = min(cluster_end, last_byte);
1851 btrfs_inode_lock(inode, 0);
1852 if (IS_SWAPFILE(inode)) {
1854 btrfs_inode_unlock(inode, 0);
1857 if (!(inode->i_sb->s_flags & SB_ACTIVE)) {
1858 btrfs_inode_unlock(inode, 0);
1862 BTRFS_I(inode)->defrag_compress = compress_type;
1863 ret = defrag_one_cluster(BTRFS_I(inode), ra, cur,
1864 cluster_end + 1 - cur, extent_thresh,
1865 newer_than, do_compress, §ors_defragged,
1866 max_to_defrag, &last_scanned);
1868 if (sectors_defragged > prev_sectors_defragged)
1869 balance_dirty_pages_ratelimited(inode->i_mapping);
1871 btrfs_inode_unlock(inode, 0);
1874 cur = max(cluster_end + 1, last_scanned);
1885 * Update range.start for autodefrag, this will indicate where to start
1889 if (sectors_defragged) {
1891 * We have defragged some sectors, for compression case they
1892 * need to be written back immediately.
1894 if (range->flags & BTRFS_DEFRAG_RANGE_START_IO) {
1895 filemap_flush(inode->i_mapping);
1896 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1897 &BTRFS_I(inode)->runtime_flags))
1898 filemap_flush(inode->i_mapping);
1900 if (range->compress_type == BTRFS_COMPRESS_LZO)
1901 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1902 else if (range->compress_type == BTRFS_COMPRESS_ZSTD)
1903 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1904 ret = sectors_defragged;
1907 btrfs_inode_lock(inode, 0);
1908 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1909 btrfs_inode_unlock(inode, 0);
1915 * Try to start exclusive operation @type or cancel it if it's running.
1918 * 0 - normal mode, newly claimed op started
1919 * >0 - normal mode, something else is running,
1920 * return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS to user space
1921 * ECANCELED - cancel mode, successful cancel
1922 * ENOTCONN - cancel mode, operation not running anymore
1924 static int exclop_start_or_cancel_reloc(struct btrfs_fs_info *fs_info,
1925 enum btrfs_exclusive_operation type, bool cancel)
1928 /* Start normal op */
1929 if (!btrfs_exclop_start(fs_info, type))
1930 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1931 /* Exclusive operation is now claimed */
1935 /* Cancel running op */
1936 if (btrfs_exclop_start_try_lock(fs_info, type)) {
1938 * This blocks any exclop finish from setting it to NONE, so we
1939 * request cancellation. Either it runs and we will wait for it,
1940 * or it has finished and no waiting will happen.
1942 atomic_inc(&fs_info->reloc_cancel_req);
1943 btrfs_exclop_start_unlock(fs_info);
1945 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
1946 wait_on_bit(&fs_info->flags, BTRFS_FS_RELOC_RUNNING,
1947 TASK_INTERRUPTIBLE);
1952 /* Something else is running or none */
1956 static noinline int btrfs_ioctl_resize(struct file *file,
1959 BTRFS_DEV_LOOKUP_ARGS(args);
1960 struct inode *inode = file_inode(file);
1961 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1965 struct btrfs_root *root = BTRFS_I(inode)->root;
1966 struct btrfs_ioctl_vol_args *vol_args;
1967 struct btrfs_trans_handle *trans;
1968 struct btrfs_device *device = NULL;
1971 char *devstr = NULL;
1976 if (!capable(CAP_SYS_ADMIN))
1979 ret = mnt_want_write_file(file);
1984 * Read the arguments before checking exclusivity to be able to
1985 * distinguish regular resize and cancel
1987 vol_args = memdup_user(arg, sizeof(*vol_args));
1988 if (IS_ERR(vol_args)) {
1989 ret = PTR_ERR(vol_args);
1992 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1993 sizestr = vol_args->name;
1994 cancel = (strcmp("cancel", sizestr) == 0);
1995 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_RESIZE, cancel);
1998 /* Exclusive operation is now claimed */
2000 devstr = strchr(sizestr, ':');
2002 sizestr = devstr + 1;
2004 devstr = vol_args->name;
2005 ret = kstrtoull(devstr, 10, &devid);
2012 btrfs_info(fs_info, "resizing devid %llu", devid);
2016 device = btrfs_find_device(fs_info->fs_devices, &args);
2018 btrfs_info(fs_info, "resizer unable to find device %llu",
2024 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2026 "resizer unable to apply on readonly device %llu",
2032 if (!strcmp(sizestr, "max"))
2033 new_size = bdev_nr_bytes(device->bdev);
2035 if (sizestr[0] == '-') {
2038 } else if (sizestr[0] == '+') {
2042 new_size = memparse(sizestr, &retptr);
2043 if (*retptr != '\0' || new_size == 0) {
2049 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2054 old_size = btrfs_device_get_total_bytes(device);
2057 if (new_size > old_size) {
2061 new_size = old_size - new_size;
2062 } else if (mod > 0) {
2063 if (new_size > ULLONG_MAX - old_size) {
2067 new_size = old_size + new_size;
2070 if (new_size < SZ_256M) {
2074 if (new_size > bdev_nr_bytes(device->bdev)) {
2079 new_size = round_down(new_size, fs_info->sectorsize);
2081 if (new_size > old_size) {
2082 trans = btrfs_start_transaction(root, 0);
2083 if (IS_ERR(trans)) {
2084 ret = PTR_ERR(trans);
2087 ret = btrfs_grow_device(trans, device, new_size);
2088 btrfs_commit_transaction(trans);
2089 } else if (new_size < old_size) {
2090 ret = btrfs_shrink_device(device, new_size);
2091 } /* equal, nothing need to do */
2093 if (ret == 0 && new_size != old_size)
2094 btrfs_info_in_rcu(fs_info,
2095 "resize device %s (devid %llu) from %llu to %llu",
2096 rcu_str_deref(device->name), device->devid,
2097 old_size, new_size);
2099 btrfs_exclop_finish(fs_info);
2103 mnt_drop_write_file(file);
2107 static noinline int __btrfs_ioctl_snap_create(struct file *file,
2108 struct user_namespace *mnt_userns,
2109 const char *name, unsigned long fd, int subvol,
2111 struct btrfs_qgroup_inherit *inherit)
2116 if (!S_ISDIR(file_inode(file)->i_mode))
2119 ret = mnt_want_write_file(file);
2123 namelen = strlen(name);
2124 if (strchr(name, '/')) {
2126 goto out_drop_write;
2129 if (name[0] == '.' &&
2130 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
2132 goto out_drop_write;
2136 ret = btrfs_mksubvol(&file->f_path, mnt_userns, name,
2137 namelen, NULL, readonly, inherit);
2139 struct fd src = fdget(fd);
2140 struct inode *src_inode;
2143 goto out_drop_write;
2146 src_inode = file_inode(src.file);
2147 if (src_inode->i_sb != file_inode(file)->i_sb) {
2148 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
2149 "Snapshot src from another FS");
2151 } else if (!inode_owner_or_capable(mnt_userns, src_inode)) {
2153 * Subvolume creation is not restricted, but snapshots
2154 * are limited to own subvolumes only
2158 ret = btrfs_mksnapshot(&file->f_path, mnt_userns,
2160 BTRFS_I(src_inode)->root,
2166 mnt_drop_write_file(file);
2171 static noinline int btrfs_ioctl_snap_create(struct file *file,
2172 void __user *arg, int subvol)
2174 struct btrfs_ioctl_vol_args *vol_args;
2177 if (!S_ISDIR(file_inode(file)->i_mode))
2180 vol_args = memdup_user(arg, sizeof(*vol_args));
2181 if (IS_ERR(vol_args))
2182 return PTR_ERR(vol_args);
2183 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2185 ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
2186 vol_args->name, vol_args->fd, subvol,
2193 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
2194 void __user *arg, int subvol)
2196 struct btrfs_ioctl_vol_args_v2 *vol_args;
2198 bool readonly = false;
2199 struct btrfs_qgroup_inherit *inherit = NULL;
2201 if (!S_ISDIR(file_inode(file)->i_mode))
2204 vol_args = memdup_user(arg, sizeof(*vol_args));
2205 if (IS_ERR(vol_args))
2206 return PTR_ERR(vol_args);
2207 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
2209 if (vol_args->flags & ~BTRFS_SUBVOL_CREATE_ARGS_MASK) {
2214 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
2216 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
2219 if (vol_args->size < sizeof(*inherit) ||
2220 vol_args->size > PAGE_SIZE) {
2224 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
2225 if (IS_ERR(inherit)) {
2226 ret = PTR_ERR(inherit);
2230 if (inherit->num_qgroups > PAGE_SIZE ||
2231 inherit->num_ref_copies > PAGE_SIZE ||
2232 inherit->num_excl_copies > PAGE_SIZE) {
2237 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
2238 2 * inherit->num_excl_copies;
2239 if (vol_args->size != struct_size(inherit, qgroups, nums)) {
2245 ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
2246 vol_args->name, vol_args->fd, subvol,
2257 static noinline int btrfs_ioctl_subvol_getflags(struct inode *inode,
2260 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2261 struct btrfs_root *root = BTRFS_I(inode)->root;
2265 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
2268 down_read(&fs_info->subvol_sem);
2269 if (btrfs_root_readonly(root))
2270 flags |= BTRFS_SUBVOL_RDONLY;
2271 up_read(&fs_info->subvol_sem);
2273 if (copy_to_user(arg, &flags, sizeof(flags)))
2279 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
2282 struct inode *inode = file_inode(file);
2283 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2284 struct btrfs_root *root = BTRFS_I(inode)->root;
2285 struct btrfs_trans_handle *trans;
2290 if (!inode_owner_or_capable(file_mnt_user_ns(file), inode))
2293 ret = mnt_want_write_file(file);
2297 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2299 goto out_drop_write;
2302 if (copy_from_user(&flags, arg, sizeof(flags))) {
2304 goto out_drop_write;
2307 if (flags & ~BTRFS_SUBVOL_RDONLY) {
2309 goto out_drop_write;
2312 down_write(&fs_info->subvol_sem);
2315 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
2318 root_flags = btrfs_root_flags(&root->root_item);
2319 if (flags & BTRFS_SUBVOL_RDONLY) {
2320 btrfs_set_root_flags(&root->root_item,
2321 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
2324 * Block RO -> RW transition if this subvolume is involved in
2327 spin_lock(&root->root_item_lock);
2328 if (root->send_in_progress == 0) {
2329 btrfs_set_root_flags(&root->root_item,
2330 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
2331 spin_unlock(&root->root_item_lock);
2333 spin_unlock(&root->root_item_lock);
2335 "Attempt to set subvolume %llu read-write during send",
2336 root->root_key.objectid);
2342 trans = btrfs_start_transaction(root, 1);
2343 if (IS_ERR(trans)) {
2344 ret = PTR_ERR(trans);
2348 ret = btrfs_update_root(trans, fs_info->tree_root,
2349 &root->root_key, &root->root_item);
2351 btrfs_end_transaction(trans);
2355 ret = btrfs_commit_transaction(trans);
2359 btrfs_set_root_flags(&root->root_item, root_flags);
2361 up_write(&fs_info->subvol_sem);
2363 mnt_drop_write_file(file);
2368 static noinline int key_in_sk(struct btrfs_key *key,
2369 struct btrfs_ioctl_search_key *sk)
2371 struct btrfs_key test;
2374 test.objectid = sk->min_objectid;
2375 test.type = sk->min_type;
2376 test.offset = sk->min_offset;
2378 ret = btrfs_comp_cpu_keys(key, &test);
2382 test.objectid = sk->max_objectid;
2383 test.type = sk->max_type;
2384 test.offset = sk->max_offset;
2386 ret = btrfs_comp_cpu_keys(key, &test);
2392 static noinline int copy_to_sk(struct btrfs_path *path,
2393 struct btrfs_key *key,
2394 struct btrfs_ioctl_search_key *sk,
2397 unsigned long *sk_offset,
2401 struct extent_buffer *leaf;
2402 struct btrfs_ioctl_search_header sh;
2403 struct btrfs_key test;
2404 unsigned long item_off;
2405 unsigned long item_len;
2411 leaf = path->nodes[0];
2412 slot = path->slots[0];
2413 nritems = btrfs_header_nritems(leaf);
2415 if (btrfs_header_generation(leaf) > sk->max_transid) {
2419 found_transid = btrfs_header_generation(leaf);
2421 for (i = slot; i < nritems; i++) {
2422 item_off = btrfs_item_ptr_offset(leaf, i);
2423 item_len = btrfs_item_size(leaf, i);
2425 btrfs_item_key_to_cpu(leaf, key, i);
2426 if (!key_in_sk(key, sk))
2429 if (sizeof(sh) + item_len > *buf_size) {
2436 * return one empty item back for v1, which does not
2440 *buf_size = sizeof(sh) + item_len;
2445 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2450 sh.objectid = key->objectid;
2451 sh.offset = key->offset;
2452 sh.type = key->type;
2454 sh.transid = found_transid;
2457 * Copy search result header. If we fault then loop again so we
2458 * can fault in the pages and -EFAULT there if there's a
2459 * problem. Otherwise we'll fault and then copy the buffer in
2460 * properly this next time through
2462 if (copy_to_user_nofault(ubuf + *sk_offset, &sh, sizeof(sh))) {
2467 *sk_offset += sizeof(sh);
2470 char __user *up = ubuf + *sk_offset;
2472 * Copy the item, same behavior as above, but reset the
2473 * * sk_offset so we copy the full thing again.
2475 if (read_extent_buffer_to_user_nofault(leaf, up,
2476 item_off, item_len)) {
2478 *sk_offset -= sizeof(sh);
2482 *sk_offset += item_len;
2486 if (ret) /* -EOVERFLOW from above */
2489 if (*num_found >= sk->nr_items) {
2496 test.objectid = sk->max_objectid;
2497 test.type = sk->max_type;
2498 test.offset = sk->max_offset;
2499 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2501 else if (key->offset < (u64)-1)
2503 else if (key->type < (u8)-1) {
2506 } else if (key->objectid < (u64)-1) {
2514 * 0: all items from this leaf copied, continue with next
2515 * 1: * more items can be copied, but unused buffer is too small
2516 * * all items were found
2517 * Either way, it will stops the loop which iterates to the next
2519 * -EOVERFLOW: item was to large for buffer
2520 * -EFAULT: could not copy extent buffer back to userspace
2525 static noinline int search_ioctl(struct inode *inode,
2526 struct btrfs_ioctl_search_key *sk,
2530 struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2531 struct btrfs_root *root;
2532 struct btrfs_key key;
2533 struct btrfs_path *path;
2536 unsigned long sk_offset = 0;
2538 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2539 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2543 path = btrfs_alloc_path();
2547 if (sk->tree_id == 0) {
2548 /* search the root of the inode that was passed */
2549 root = btrfs_grab_root(BTRFS_I(inode)->root);
2551 root = btrfs_get_fs_root(info, sk->tree_id, true);
2553 btrfs_free_path(path);
2554 return PTR_ERR(root);
2558 key.objectid = sk->min_objectid;
2559 key.type = sk->min_type;
2560 key.offset = sk->min_offset;
2565 * Ensure that the whole user buffer is faulted in at sub-page
2566 * granularity, otherwise the loop may live-lock.
2568 if (fault_in_subpage_writeable(ubuf + sk_offset,
2569 *buf_size - sk_offset))
2572 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2578 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2579 &sk_offset, &num_found);
2580 btrfs_release_path(path);
2588 sk->nr_items = num_found;
2589 btrfs_put_root(root);
2590 btrfs_free_path(path);
2594 static noinline int btrfs_ioctl_tree_search(struct inode *inode,
2597 struct btrfs_ioctl_search_args __user *uargs;
2598 struct btrfs_ioctl_search_key sk;
2602 if (!capable(CAP_SYS_ADMIN))
2605 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2607 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2610 buf_size = sizeof(uargs->buf);
2612 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2615 * In the origin implementation an overflow is handled by returning a
2616 * search header with a len of zero, so reset ret.
2618 if (ret == -EOVERFLOW)
2621 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2626 static noinline int btrfs_ioctl_tree_search_v2(struct inode *inode,
2629 struct btrfs_ioctl_search_args_v2 __user *uarg;
2630 struct btrfs_ioctl_search_args_v2 args;
2633 const size_t buf_limit = SZ_16M;
2635 if (!capable(CAP_SYS_ADMIN))
2638 /* copy search header and buffer size */
2639 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2640 if (copy_from_user(&args, uarg, sizeof(args)))
2643 buf_size = args.buf_size;
2645 /* limit result size to 16MB */
2646 if (buf_size > buf_limit)
2647 buf_size = buf_limit;
2649 ret = search_ioctl(inode, &args.key, &buf_size,
2650 (char __user *)(&uarg->buf[0]));
2651 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2653 else if (ret == -EOVERFLOW &&
2654 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2661 * Search INODE_REFs to identify path name of 'dirid' directory
2662 * in a 'tree_id' tree. and sets path name to 'name'.
2664 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2665 u64 tree_id, u64 dirid, char *name)
2667 struct btrfs_root *root;
2668 struct btrfs_key key;
2674 struct btrfs_inode_ref *iref;
2675 struct extent_buffer *l;
2676 struct btrfs_path *path;
2678 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2683 path = btrfs_alloc_path();
2687 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2689 root = btrfs_get_fs_root(info, tree_id, true);
2691 ret = PTR_ERR(root);
2696 key.objectid = dirid;
2697 key.type = BTRFS_INODE_REF_KEY;
2698 key.offset = (u64)-1;
2701 ret = btrfs_search_backwards(root, &key, path);
2710 slot = path->slots[0];
2712 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2713 len = btrfs_inode_ref_name_len(l, iref);
2715 total_len += len + 1;
2717 ret = -ENAMETOOLONG;
2722 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2724 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2727 btrfs_release_path(path);
2728 key.objectid = key.offset;
2729 key.offset = (u64)-1;
2730 dirid = key.objectid;
2732 memmove(name, ptr, total_len);
2733 name[total_len] = '\0';
2736 btrfs_put_root(root);
2737 btrfs_free_path(path);
2741 static int btrfs_search_path_in_tree_user(struct user_namespace *mnt_userns,
2742 struct inode *inode,
2743 struct btrfs_ioctl_ino_lookup_user_args *args)
2745 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2746 struct super_block *sb = inode->i_sb;
2747 struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2748 u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2749 u64 dirid = args->dirid;
2750 unsigned long item_off;
2751 unsigned long item_len;
2752 struct btrfs_inode_ref *iref;
2753 struct btrfs_root_ref *rref;
2754 struct btrfs_root *root = NULL;
2755 struct btrfs_path *path;
2756 struct btrfs_key key, key2;
2757 struct extent_buffer *leaf;
2758 struct inode *temp_inode;
2765 path = btrfs_alloc_path();
2770 * If the bottom subvolume does not exist directly under upper_limit,
2771 * construct the path in from the bottom up.
2773 if (dirid != upper_limit.objectid) {
2774 ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2776 root = btrfs_get_fs_root(fs_info, treeid, true);
2778 ret = PTR_ERR(root);
2782 key.objectid = dirid;
2783 key.type = BTRFS_INODE_REF_KEY;
2784 key.offset = (u64)-1;
2786 ret = btrfs_search_backwards(root, &key, path);
2794 leaf = path->nodes[0];
2795 slot = path->slots[0];
2797 iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2798 len = btrfs_inode_ref_name_len(leaf, iref);
2800 total_len += len + 1;
2801 if (ptr < args->path) {
2802 ret = -ENAMETOOLONG;
2807 read_extent_buffer(leaf, ptr,
2808 (unsigned long)(iref + 1), len);
2810 /* Check the read+exec permission of this directory */
2811 ret = btrfs_previous_item(root, path, dirid,
2812 BTRFS_INODE_ITEM_KEY);
2815 } else if (ret > 0) {
2820 leaf = path->nodes[0];
2821 slot = path->slots[0];
2822 btrfs_item_key_to_cpu(leaf, &key2, slot);
2823 if (key2.objectid != dirid) {
2828 temp_inode = btrfs_iget(sb, key2.objectid, root);
2829 if (IS_ERR(temp_inode)) {
2830 ret = PTR_ERR(temp_inode);
2833 ret = inode_permission(mnt_userns, temp_inode,
2834 MAY_READ | MAY_EXEC);
2841 if (key.offset == upper_limit.objectid)
2843 if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2848 btrfs_release_path(path);
2849 key.objectid = key.offset;
2850 key.offset = (u64)-1;
2851 dirid = key.objectid;
2854 memmove(args->path, ptr, total_len);
2855 args->path[total_len] = '\0';
2856 btrfs_put_root(root);
2858 btrfs_release_path(path);
2861 /* Get the bottom subvolume's name from ROOT_REF */
2862 key.objectid = treeid;
2863 key.type = BTRFS_ROOT_REF_KEY;
2864 key.offset = args->treeid;
2865 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2868 } else if (ret > 0) {
2873 leaf = path->nodes[0];
2874 slot = path->slots[0];
2875 btrfs_item_key_to_cpu(leaf, &key, slot);
2877 item_off = btrfs_item_ptr_offset(leaf, slot);
2878 item_len = btrfs_item_size(leaf, slot);
2879 /* Check if dirid in ROOT_REF corresponds to passed dirid */
2880 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2881 if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2886 /* Copy subvolume's name */
2887 item_off += sizeof(struct btrfs_root_ref);
2888 item_len -= sizeof(struct btrfs_root_ref);
2889 read_extent_buffer(leaf, args->name, item_off, item_len);
2890 args->name[item_len] = 0;
2893 btrfs_put_root(root);
2895 btrfs_free_path(path);
2899 static noinline int btrfs_ioctl_ino_lookup(struct btrfs_root *root,
2902 struct btrfs_ioctl_ino_lookup_args *args;
2905 args = memdup_user(argp, sizeof(*args));
2907 return PTR_ERR(args);
2910 * Unprivileged query to obtain the containing subvolume root id. The
2911 * path is reset so it's consistent with btrfs_search_path_in_tree.
2913 if (args->treeid == 0)
2914 args->treeid = root->root_key.objectid;
2916 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2921 if (!capable(CAP_SYS_ADMIN)) {
2926 ret = btrfs_search_path_in_tree(root->fs_info,
2927 args->treeid, args->objectid,
2931 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2939 * Version of ino_lookup ioctl (unprivileged)
2941 * The main differences from ino_lookup ioctl are:
2943 * 1. Read + Exec permission will be checked using inode_permission() during
2944 * path construction. -EACCES will be returned in case of failure.
2945 * 2. Path construction will be stopped at the inode number which corresponds
2946 * to the fd with which this ioctl is called. If constructed path does not
2947 * exist under fd's inode, -EACCES will be returned.
2948 * 3. The name of bottom subvolume is also searched and filled.
2950 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2952 struct btrfs_ioctl_ino_lookup_user_args *args;
2953 struct inode *inode;
2956 args = memdup_user(argp, sizeof(*args));
2958 return PTR_ERR(args);
2960 inode = file_inode(file);
2962 if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2963 BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2965 * The subvolume does not exist under fd with which this is
2972 ret = btrfs_search_path_in_tree_user(file_mnt_user_ns(file), inode, args);
2974 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2981 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2982 static int btrfs_ioctl_get_subvol_info(struct inode *inode, void __user *argp)
2984 struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2985 struct btrfs_fs_info *fs_info;
2986 struct btrfs_root *root;
2987 struct btrfs_path *path;
2988 struct btrfs_key key;
2989 struct btrfs_root_item *root_item;
2990 struct btrfs_root_ref *rref;
2991 struct extent_buffer *leaf;
2992 unsigned long item_off;
2993 unsigned long item_len;
2997 path = btrfs_alloc_path();
3001 subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
3003 btrfs_free_path(path);
3007 fs_info = BTRFS_I(inode)->root->fs_info;
3009 /* Get root_item of inode's subvolume */
3010 key.objectid = BTRFS_I(inode)->root->root_key.objectid;
3011 root = btrfs_get_fs_root(fs_info, key.objectid, true);
3013 ret = PTR_ERR(root);
3016 root_item = &root->root_item;
3018 subvol_info->treeid = key.objectid;
3020 subvol_info->generation = btrfs_root_generation(root_item);
3021 subvol_info->flags = btrfs_root_flags(root_item);
3023 memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
3024 memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
3026 memcpy(subvol_info->received_uuid, root_item->received_uuid,
3029 subvol_info->ctransid = btrfs_root_ctransid(root_item);
3030 subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
3031 subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
3033 subvol_info->otransid = btrfs_root_otransid(root_item);
3034 subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
3035 subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
3037 subvol_info->stransid = btrfs_root_stransid(root_item);
3038 subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
3039 subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
3041 subvol_info->rtransid = btrfs_root_rtransid(root_item);
3042 subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
3043 subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
3045 if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
3046 /* Search root tree for ROOT_BACKREF of this subvolume */
3047 key.type = BTRFS_ROOT_BACKREF_KEY;
3049 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3052 } else if (path->slots[0] >=
3053 btrfs_header_nritems(path->nodes[0])) {
3054 ret = btrfs_next_leaf(fs_info->tree_root, path);
3057 } else if (ret > 0) {
3063 leaf = path->nodes[0];
3064 slot = path->slots[0];
3065 btrfs_item_key_to_cpu(leaf, &key, slot);
3066 if (key.objectid == subvol_info->treeid &&
3067 key.type == BTRFS_ROOT_BACKREF_KEY) {
3068 subvol_info->parent_id = key.offset;
3070 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
3071 subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
3073 item_off = btrfs_item_ptr_offset(leaf, slot)
3074 + sizeof(struct btrfs_root_ref);
3075 item_len = btrfs_item_size(leaf, slot)
3076 - sizeof(struct btrfs_root_ref);
3077 read_extent_buffer(leaf, subvol_info->name,
3078 item_off, item_len);
3085 if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
3089 btrfs_put_root(root);
3091 btrfs_free_path(path);
3097 * Return ROOT_REF information of the subvolume containing this inode
3098 * except the subvolume name.
3100 static int btrfs_ioctl_get_subvol_rootref(struct btrfs_root *root,
3103 struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
3104 struct btrfs_root_ref *rref;
3105 struct btrfs_path *path;
3106 struct btrfs_key key;
3107 struct extent_buffer *leaf;
3113 path = btrfs_alloc_path();
3117 rootrefs = memdup_user(argp, sizeof(*rootrefs));
3118 if (IS_ERR(rootrefs)) {
3119 btrfs_free_path(path);
3120 return PTR_ERR(rootrefs);
3123 objectid = root->root_key.objectid;
3124 key.objectid = objectid;
3125 key.type = BTRFS_ROOT_REF_KEY;
3126 key.offset = rootrefs->min_treeid;
3129 root = root->fs_info->tree_root;
3130 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3133 } else if (path->slots[0] >=
3134 btrfs_header_nritems(path->nodes[0])) {
3135 ret = btrfs_next_leaf(root, path);
3138 } else if (ret > 0) {
3144 leaf = path->nodes[0];
3145 slot = path->slots[0];
3147 btrfs_item_key_to_cpu(leaf, &key, slot);
3148 if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
3153 if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
3158 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
3159 rootrefs->rootref[found].treeid = key.offset;
3160 rootrefs->rootref[found].dirid =
3161 btrfs_root_ref_dirid(leaf, rref);
3164 ret = btrfs_next_item(root, path);
3167 } else if (ret > 0) {
3174 if (!ret || ret == -EOVERFLOW) {
3175 rootrefs->num_items = found;
3176 /* update min_treeid for next search */
3178 rootrefs->min_treeid =
3179 rootrefs->rootref[found - 1].treeid + 1;
3180 if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
3185 btrfs_free_path(path);
3190 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
3194 struct dentry *parent = file->f_path.dentry;
3195 struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
3196 struct dentry *dentry;
3197 struct inode *dir = d_inode(parent);
3198 struct inode *inode;
3199 struct btrfs_root *root = BTRFS_I(dir)->root;
3200 struct btrfs_root *dest = NULL;
3201 struct btrfs_ioctl_vol_args *vol_args = NULL;
3202 struct btrfs_ioctl_vol_args_v2 *vol_args2 = NULL;
3203 struct user_namespace *mnt_userns = file_mnt_user_ns(file);
3204 char *subvol_name, *subvol_name_ptr = NULL;
3207 bool destroy_parent = false;
3209 /* We don't support snapshots with extent tree v2 yet. */
3210 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3212 "extent tree v2 doesn't support snapshot deletion yet");
3217 vol_args2 = memdup_user(arg, sizeof(*vol_args2));
3218 if (IS_ERR(vol_args2))
3219 return PTR_ERR(vol_args2);
3221 if (vol_args2->flags & ~BTRFS_SUBVOL_DELETE_ARGS_MASK) {
3227 * If SPEC_BY_ID is not set, we are looking for the subvolume by
3228 * name, same as v1 currently does.
3230 if (!(vol_args2->flags & BTRFS_SUBVOL_SPEC_BY_ID)) {
3231 vol_args2->name[BTRFS_SUBVOL_NAME_MAX] = 0;
3232 subvol_name = vol_args2->name;
3234 err = mnt_want_write_file(file);
3238 struct inode *old_dir;
3240 if (vol_args2->subvolid < BTRFS_FIRST_FREE_OBJECTID) {
3245 err = mnt_want_write_file(file);
3249 dentry = btrfs_get_dentry(fs_info->sb,
3250 BTRFS_FIRST_FREE_OBJECTID,
3251 vol_args2->subvolid, 0, 0);
3252 if (IS_ERR(dentry)) {
3253 err = PTR_ERR(dentry);
3254 goto out_drop_write;
3258 * Change the default parent since the subvolume being
3259 * deleted can be outside of the current mount point.
3261 parent = btrfs_get_parent(dentry);
3264 * At this point dentry->d_name can point to '/' if the
3265 * subvolume we want to destroy is outsite of the
3266 * current mount point, so we need to release the
3267 * current dentry and execute the lookup to return a new
3268 * one with ->d_name pointing to the
3269 * <mount point>/subvol_name.
3272 if (IS_ERR(parent)) {
3273 err = PTR_ERR(parent);
3274 goto out_drop_write;
3277 dir = d_inode(parent);
3280 * If v2 was used with SPEC_BY_ID, a new parent was
3281 * allocated since the subvolume can be outside of the
3282 * current mount point. Later on we need to release this
3283 * new parent dentry.
3285 destroy_parent = true;
3288 * On idmapped mounts, deletion via subvolid is
3289 * restricted to subvolumes that are immediate
3290 * ancestors of the inode referenced by the file
3291 * descriptor in the ioctl. Otherwise the idmapping
3292 * could potentially be abused to delete subvolumes
3293 * anywhere in the filesystem the user wouldn't be able
3294 * to delete without an idmapped mount.
3296 if (old_dir != dir && mnt_userns != &init_user_ns) {
3301 subvol_name_ptr = btrfs_get_subvol_name_from_objectid(
3302 fs_info, vol_args2->subvolid);
3303 if (IS_ERR(subvol_name_ptr)) {
3304 err = PTR_ERR(subvol_name_ptr);
3307 /* subvol_name_ptr is already nul terminated */
3308 subvol_name = (char *)kbasename(subvol_name_ptr);
3311 vol_args = memdup_user(arg, sizeof(*vol_args));
3312 if (IS_ERR(vol_args))
3313 return PTR_ERR(vol_args);
3315 vol_args->name[BTRFS_PATH_NAME_MAX] = 0;
3316 subvol_name = vol_args->name;
3318 err = mnt_want_write_file(file);
3323 subvol_namelen = strlen(subvol_name);
3325 if (strchr(subvol_name, '/') ||
3326 strncmp(subvol_name, "..", subvol_namelen) == 0) {
3328 goto free_subvol_name;
3331 if (!S_ISDIR(dir->i_mode)) {
3333 goto free_subvol_name;
3336 err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
3338 goto free_subvol_name;
3339 dentry = lookup_one(mnt_userns, subvol_name, parent, subvol_namelen);
3340 if (IS_ERR(dentry)) {
3341 err = PTR_ERR(dentry);
3342 goto out_unlock_dir;
3345 if (d_really_is_negative(dentry)) {
3350 inode = d_inode(dentry);
3351 dest = BTRFS_I(inode)->root;
3352 if (!capable(CAP_SYS_ADMIN)) {
3354 * Regular user. Only allow this with a special mount
3355 * option, when the user has write+exec access to the
3356 * subvol root, and when rmdir(2) would have been
3359 * Note that this is _not_ check that the subvol is
3360 * empty or doesn't contain data that we wouldn't
3361 * otherwise be able to delete.
3363 * Users who want to delete empty subvols should try
3367 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
3371 * Do not allow deletion if the parent dir is the same
3372 * as the dir to be deleted. That means the ioctl
3373 * must be called on the dentry referencing the root
3374 * of the subvol, not a random directory contained
3381 err = inode_permission(mnt_userns, inode, MAY_WRITE | MAY_EXEC);
3386 /* check if subvolume may be deleted by a user */
3387 err = btrfs_may_delete(mnt_userns, dir, dentry, 1);
3391 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
3396 btrfs_inode_lock(inode, 0);
3397 err = btrfs_delete_subvolume(dir, dentry);
3398 btrfs_inode_unlock(inode, 0);
3400 d_delete_notify(dir, dentry);
3405 btrfs_inode_unlock(dir, 0);
3407 kfree(subvol_name_ptr);
3412 mnt_drop_write_file(file);
3419 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
3421 struct inode *inode = file_inode(file);
3422 struct btrfs_root *root = BTRFS_I(inode)->root;
3423 struct btrfs_ioctl_defrag_range_args range = {0};
3426 ret = mnt_want_write_file(file);
3430 if (btrfs_root_readonly(root)) {
3435 switch (inode->i_mode & S_IFMT) {
3437 if (!capable(CAP_SYS_ADMIN)) {
3441 ret = btrfs_defrag_root(root);
3445 * Note that this does not check the file descriptor for write
3446 * access. This prevents defragmenting executables that are
3447 * running and allows defrag on files open in read-only mode.
3449 if (!capable(CAP_SYS_ADMIN) &&
3450 inode_permission(&init_user_ns, inode, MAY_WRITE)) {
3456 if (copy_from_user(&range, argp, sizeof(range))) {
3460 /* compression requires us to start the IO */
3461 if ((range.flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3462 range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
3463 range.extent_thresh = (u32)-1;
3466 /* the rest are all set to zero by kzalloc */
3467 range.len = (u64)-1;
3469 ret = btrfs_defrag_file(file_inode(file), &file->f_ra,
3470 &range, BTRFS_OLDEST_GENERATION, 0);
3478 mnt_drop_write_file(file);
3482 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3484 struct btrfs_ioctl_vol_args *vol_args;
3485 bool restore_op = false;
3488 if (!capable(CAP_SYS_ADMIN))
3491 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3492 btrfs_err(fs_info, "device add not supported on extent tree v2 yet");
3496 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_ADD)) {
3497 if (!btrfs_exclop_start_try_lock(fs_info, BTRFS_EXCLOP_DEV_ADD))
3498 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3501 * We can do the device add because we have a paused balanced,
3502 * change the exclusive op type and remember we should bring
3503 * back the paused balance
3505 fs_info->exclusive_operation = BTRFS_EXCLOP_DEV_ADD;
3506 btrfs_exclop_start_unlock(fs_info);
3510 vol_args = memdup_user(arg, sizeof(*vol_args));
3511 if (IS_ERR(vol_args)) {
3512 ret = PTR_ERR(vol_args);
3516 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3517 ret = btrfs_init_new_device(fs_info, vol_args->name);
3520 btrfs_info(fs_info, "disk added %s", vol_args->name);
3525 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
3527 btrfs_exclop_finish(fs_info);
3531 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3533 BTRFS_DEV_LOOKUP_ARGS(args);
3534 struct inode *inode = file_inode(file);
3535 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3536 struct btrfs_ioctl_vol_args_v2 *vol_args;
3537 struct block_device *bdev = NULL;
3540 bool cancel = false;
3542 if (!capable(CAP_SYS_ADMIN))
3545 vol_args = memdup_user(arg, sizeof(*vol_args));
3546 if (IS_ERR(vol_args))
3547 return PTR_ERR(vol_args);
3549 if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
3554 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3555 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3556 args.devid = vol_args->devid;
3557 } else if (!strcmp("cancel", vol_args->name)) {
3560 ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3565 ret = mnt_want_write_file(file);
3569 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3574 /* Exclusive operation is now claimed */
3575 ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3577 btrfs_exclop_finish(fs_info);
3580 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3581 btrfs_info(fs_info, "device deleted: id %llu",
3584 btrfs_info(fs_info, "device deleted: %s",
3588 mnt_drop_write_file(file);
3590 blkdev_put(bdev, mode);
3592 btrfs_put_dev_args_from_path(&args);
3597 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3599 BTRFS_DEV_LOOKUP_ARGS(args);
3600 struct inode *inode = file_inode(file);
3601 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3602 struct btrfs_ioctl_vol_args *vol_args;
3603 struct block_device *bdev = NULL;
3606 bool cancel = false;
3608 if (!capable(CAP_SYS_ADMIN))
3611 vol_args = memdup_user(arg, sizeof(*vol_args));
3612 if (IS_ERR(vol_args))
3613 return PTR_ERR(vol_args);
3615 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3616 if (!strcmp("cancel", vol_args->name)) {
3619 ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3624 ret = mnt_want_write_file(file);
3628 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3631 ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3633 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3634 btrfs_exclop_finish(fs_info);
3637 mnt_drop_write_file(file);
3639 blkdev_put(bdev, mode);
3641 btrfs_put_dev_args_from_path(&args);
3646 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3649 struct btrfs_ioctl_fs_info_args *fi_args;
3650 struct btrfs_device *device;
3651 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3655 fi_args = memdup_user(arg, sizeof(*fi_args));
3656 if (IS_ERR(fi_args))
3657 return PTR_ERR(fi_args);
3659 flags_in = fi_args->flags;
3660 memset(fi_args, 0, sizeof(*fi_args));
3663 fi_args->num_devices = fs_devices->num_devices;
3665 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3666 if (device->devid > fi_args->max_id)
3667 fi_args->max_id = device->devid;
3671 memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3672 fi_args->nodesize = fs_info->nodesize;
3673 fi_args->sectorsize = fs_info->sectorsize;
3674 fi_args->clone_alignment = fs_info->sectorsize;
3676 if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3677 fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3678 fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3679 fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3682 if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
3683 fi_args->generation = fs_info->generation;
3684 fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
3687 if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
3688 memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
3689 sizeof(fi_args->metadata_uuid));
3690 fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
3693 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3700 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3703 BTRFS_DEV_LOOKUP_ARGS(args);
3704 struct btrfs_ioctl_dev_info_args *di_args;
3705 struct btrfs_device *dev;
3708 di_args = memdup_user(arg, sizeof(*di_args));
3709 if (IS_ERR(di_args))
3710 return PTR_ERR(di_args);
3712 args.devid = di_args->devid;
3713 if (!btrfs_is_empty_uuid(di_args->uuid))
3714 args.uuid = di_args->uuid;
3717 dev = btrfs_find_device(fs_info->fs_devices, &args);
3723 di_args->devid = dev->devid;
3724 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3725 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3726 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3728 strncpy(di_args->path, rcu_str_deref(dev->name),
3729 sizeof(di_args->path) - 1);
3730 di_args->path[sizeof(di_args->path) - 1] = 0;
3732 di_args->path[0] = '\0';
3737 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3744 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3746 struct inode *inode = file_inode(file);
3747 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3748 struct btrfs_root *root = BTRFS_I(inode)->root;
3749 struct btrfs_root *new_root;
3750 struct btrfs_dir_item *di;
3751 struct btrfs_trans_handle *trans;
3752 struct btrfs_path *path = NULL;
3753 struct btrfs_disk_key disk_key;
3758 if (!capable(CAP_SYS_ADMIN))
3761 ret = mnt_want_write_file(file);
3765 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3771 objectid = BTRFS_FS_TREE_OBJECTID;
3773 new_root = btrfs_get_fs_root(fs_info, objectid, true);
3774 if (IS_ERR(new_root)) {
3775 ret = PTR_ERR(new_root);
3778 if (!is_fstree(new_root->root_key.objectid)) {
3783 path = btrfs_alloc_path();
3789 trans = btrfs_start_transaction(root, 1);
3790 if (IS_ERR(trans)) {
3791 ret = PTR_ERR(trans);
3795 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3796 di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
3797 dir_id, "default", 7, 1);
3798 if (IS_ERR_OR_NULL(di)) {
3799 btrfs_release_path(path);
3800 btrfs_end_transaction(trans);
3802 "Umm, you don't have the default diritem, this isn't going to work");
3807 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3808 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3809 btrfs_mark_buffer_dirty(path->nodes[0]);
3810 btrfs_release_path(path);
3812 btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
3813 btrfs_end_transaction(trans);
3815 btrfs_put_root(new_root);
3816 btrfs_free_path(path);
3818 mnt_drop_write_file(file);
3822 static void get_block_group_info(struct list_head *groups_list,
3823 struct btrfs_ioctl_space_info *space)
3825 struct btrfs_block_group *block_group;
3827 space->total_bytes = 0;
3828 space->used_bytes = 0;
3830 list_for_each_entry(block_group, groups_list, list) {
3831 space->flags = block_group->flags;
3832 space->total_bytes += block_group->length;
3833 space->used_bytes += block_group->used;
3837 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
3840 struct btrfs_ioctl_space_args space_args;
3841 struct btrfs_ioctl_space_info space;
3842 struct btrfs_ioctl_space_info *dest;
3843 struct btrfs_ioctl_space_info *dest_orig;
3844 struct btrfs_ioctl_space_info __user *user_dest;
3845 struct btrfs_space_info *info;
3846 static const u64 types[] = {
3847 BTRFS_BLOCK_GROUP_DATA,
3848 BTRFS_BLOCK_GROUP_SYSTEM,
3849 BTRFS_BLOCK_GROUP_METADATA,
3850 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3858 if (copy_from_user(&space_args,
3859 (struct btrfs_ioctl_space_args __user *)arg,
3860 sizeof(space_args)))
3863 for (i = 0; i < num_types; i++) {
3864 struct btrfs_space_info *tmp;
3867 list_for_each_entry(tmp, &fs_info->space_info, list) {
3868 if (tmp->flags == types[i]) {
3877 down_read(&info->groups_sem);
3878 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3879 if (!list_empty(&info->block_groups[c]))
3882 up_read(&info->groups_sem);
3886 * Global block reserve, exported as a space_info
3890 /* space_slots == 0 means they are asking for a count */
3891 if (space_args.space_slots == 0) {
3892 space_args.total_spaces = slot_count;
3896 slot_count = min_t(u64, space_args.space_slots, slot_count);
3898 alloc_size = sizeof(*dest) * slot_count;
3900 /* we generally have at most 6 or so space infos, one for each raid
3901 * level. So, a whole page should be more than enough for everyone
3903 if (alloc_size > PAGE_SIZE)
3906 space_args.total_spaces = 0;
3907 dest = kmalloc(alloc_size, GFP_KERNEL);
3912 /* now we have a buffer to copy into */
3913 for (i = 0; i < num_types; i++) {
3914 struct btrfs_space_info *tmp;
3920 list_for_each_entry(tmp, &fs_info->space_info, list) {
3921 if (tmp->flags == types[i]) {
3929 down_read(&info->groups_sem);
3930 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3931 if (!list_empty(&info->block_groups[c])) {
3932 get_block_group_info(&info->block_groups[c],
3934 memcpy(dest, &space, sizeof(space));
3936 space_args.total_spaces++;
3942 up_read(&info->groups_sem);
3946 * Add global block reserve
3949 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3951 spin_lock(&block_rsv->lock);
3952 space.total_bytes = block_rsv->size;
3953 space.used_bytes = block_rsv->size - block_rsv->reserved;
3954 spin_unlock(&block_rsv->lock);
3955 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
3956 memcpy(dest, &space, sizeof(space));
3957 space_args.total_spaces++;
3960 user_dest = (struct btrfs_ioctl_space_info __user *)
3961 (arg + sizeof(struct btrfs_ioctl_space_args));
3963 if (copy_to_user(user_dest, dest_orig, alloc_size))
3968 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3974 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3977 struct btrfs_trans_handle *trans;
3980 trans = btrfs_attach_transaction_barrier(root);
3981 if (IS_ERR(trans)) {
3982 if (PTR_ERR(trans) != -ENOENT)
3983 return PTR_ERR(trans);
3985 /* No running transaction, don't bother */
3986 transid = root->fs_info->last_trans_committed;
3989 transid = trans->transid;
3990 btrfs_commit_transaction_async(trans);
3993 if (copy_to_user(argp, &transid, sizeof(transid)))
3998 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
4004 if (copy_from_user(&transid, argp, sizeof(transid)))
4007 transid = 0; /* current trans */
4009 return btrfs_wait_for_commit(fs_info, transid);
4012 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4014 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4015 struct btrfs_ioctl_scrub_args *sa;
4018 if (!capable(CAP_SYS_ADMIN))
4021 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
4022 btrfs_err(fs_info, "scrub is not supported on extent tree v2 yet");
4026 sa = memdup_user(arg, sizeof(*sa));
4030 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4031 ret = mnt_want_write_file(file);
4036 ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
4037 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4041 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
4042 * error. This is important as it allows user space to know how much
4043 * progress scrub has done. For example, if scrub is canceled we get
4044 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
4045 * space. Later user space can inspect the progress from the structure
4046 * btrfs_ioctl_scrub_args and resume scrub from where it left off
4047 * previously (btrfs-progs does this).
4048 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
4049 * then return -EFAULT to signal the structure was not copied or it may
4050 * be corrupt and unreliable due to a partial copy.
4052 if (copy_to_user(arg, sa, sizeof(*sa)))
4055 if (!(sa->flags & BTRFS_SCRUB_READONLY))
4056 mnt_drop_write_file(file);
4062 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4064 if (!capable(CAP_SYS_ADMIN))
4067 return btrfs_scrub_cancel(fs_info);
4070 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4073 struct btrfs_ioctl_scrub_args *sa;
4076 if (!capable(CAP_SYS_ADMIN))
4079 sa = memdup_user(arg, sizeof(*sa));
4083 ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4085 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4092 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4095 struct btrfs_ioctl_get_dev_stats *sa;
4098 sa = memdup_user(arg, sizeof(*sa));
4102 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4107 ret = btrfs_get_dev_stats(fs_info, sa);
4109 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4116 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
4119 struct btrfs_ioctl_dev_replace_args *p;
4122 if (!capable(CAP_SYS_ADMIN))
4125 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
4126 btrfs_err(fs_info, "device replace not supported on extent tree v2 yet");
4130 p = memdup_user(arg, sizeof(*p));
4135 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4136 if (sb_rdonly(fs_info->sb)) {
4140 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
4141 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4143 ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4144 btrfs_exclop_finish(fs_info);
4147 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4148 btrfs_dev_replace_status(fs_info, p);
4151 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4152 p->result = btrfs_dev_replace_cancel(fs_info);
4160 if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
4167 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4173 struct btrfs_ioctl_ino_path_args *ipa = NULL;
4174 struct inode_fs_paths *ipath = NULL;
4175 struct btrfs_path *path;
4177 if (!capable(CAP_DAC_READ_SEARCH))
4180 path = btrfs_alloc_path();
4186 ipa = memdup_user(arg, sizeof(*ipa));
4193 size = min_t(u32, ipa->size, 4096);
4194 ipath = init_ipath(size, root, path);
4195 if (IS_ERR(ipath)) {
4196 ret = PTR_ERR(ipath);
4201 ret = paths_from_inode(ipa->inum, ipath);
4205 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4206 rel_ptr = ipath->fspath->val[i] -
4207 (u64)(unsigned long)ipath->fspath->val;
4208 ipath->fspath->val[i] = rel_ptr;
4211 ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4212 ipath->fspath, size);
4219 btrfs_free_path(path);
4226 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4228 struct btrfs_data_container *inodes = ctx;
4229 const size_t c = 3 * sizeof(u64);
4231 if (inodes->bytes_left >= c) {
4232 inodes->bytes_left -= c;
4233 inodes->val[inodes->elem_cnt] = inum;
4234 inodes->val[inodes->elem_cnt + 1] = offset;
4235 inodes->val[inodes->elem_cnt + 2] = root;
4236 inodes->elem_cnt += 3;
4238 inodes->bytes_missing += c - inodes->bytes_left;
4239 inodes->bytes_left = 0;
4240 inodes->elem_missed += 3;
4246 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4247 void __user *arg, int version)
4251 struct btrfs_ioctl_logical_ino_args *loi;
4252 struct btrfs_data_container *inodes = NULL;
4253 struct btrfs_path *path = NULL;
4256 if (!capable(CAP_SYS_ADMIN))
4259 loi = memdup_user(arg, sizeof(*loi));
4261 return PTR_ERR(loi);
4264 ignore_offset = false;
4265 size = min_t(u32, loi->size, SZ_64K);
4267 /* All reserved bits must be 0 for now */
4268 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4272 /* Only accept flags we have defined so far */
4273 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4277 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4278 size = min_t(u32, loi->size, SZ_16M);
4281 path = btrfs_alloc_path();
4287 inodes = init_data_container(size);
4288 if (IS_ERR(inodes)) {
4289 ret = PTR_ERR(inodes);
4294 ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4295 build_ino_list, inodes, ignore_offset);
4301 ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4307 btrfs_free_path(path);
4315 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4316 struct btrfs_ioctl_balance_args *bargs)
4318 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4320 bargs->flags = bctl->flags;
4322 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4323 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4324 if (atomic_read(&fs_info->balance_pause_req))
4325 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4326 if (atomic_read(&fs_info->balance_cancel_req))
4327 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4329 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4330 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4331 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4333 spin_lock(&fs_info->balance_lock);
4334 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4335 spin_unlock(&fs_info->balance_lock);
4338 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4340 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4341 struct btrfs_fs_info *fs_info = root->fs_info;
4342 struct btrfs_ioctl_balance_args *bargs;
4343 struct btrfs_balance_control *bctl;
4344 bool need_unlock; /* for mut. excl. ops lock */
4349 "IOC_BALANCE ioctl (v1) is deprecated and will be removed in kernel 5.18");
4351 if (!capable(CAP_SYS_ADMIN))
4354 ret = mnt_want_write_file(file);
4359 if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
4360 mutex_lock(&fs_info->balance_mutex);
4366 * mut. excl. ops lock is locked. Three possibilities:
4367 * (1) some other op is running
4368 * (2) balance is running
4369 * (3) balance is paused -- special case (think resume)
4371 mutex_lock(&fs_info->balance_mutex);
4372 if (fs_info->balance_ctl) {
4373 /* this is either (2) or (3) */
4374 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4375 mutex_unlock(&fs_info->balance_mutex);
4377 * Lock released to allow other waiters to continue,
4378 * we'll reexamine the status again.
4380 mutex_lock(&fs_info->balance_mutex);
4382 if (fs_info->balance_ctl &&
4383 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4385 need_unlock = false;
4389 mutex_unlock(&fs_info->balance_mutex);
4393 mutex_unlock(&fs_info->balance_mutex);
4399 mutex_unlock(&fs_info->balance_mutex);
4400 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4407 bargs = memdup_user(arg, sizeof(*bargs));
4408 if (IS_ERR(bargs)) {
4409 ret = PTR_ERR(bargs);
4413 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4414 if (!fs_info->balance_ctl) {
4419 bctl = fs_info->balance_ctl;
4420 spin_lock(&fs_info->balance_lock);
4421 bctl->flags |= BTRFS_BALANCE_RESUME;
4422 spin_unlock(&fs_info->balance_lock);
4423 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE);
4431 if (fs_info->balance_ctl) {
4436 bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4443 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4444 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4445 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4447 bctl->flags = bargs->flags;
4449 /* balance everything - no filters */
4450 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4453 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4460 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4461 * bctl is freed in reset_balance_state, or, if restriper was paused
4462 * all the way until unmount, in free_fs_info. The flag should be
4463 * cleared after reset_balance_state.
4465 need_unlock = false;
4467 ret = btrfs_balance(fs_info, bctl, bargs);
4470 if ((ret == 0 || ret == -ECANCELED) && arg) {
4471 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4480 mutex_unlock(&fs_info->balance_mutex);
4482 btrfs_exclop_finish(fs_info);
4484 mnt_drop_write_file(file);
4488 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4490 if (!capable(CAP_SYS_ADMIN))
4494 case BTRFS_BALANCE_CTL_PAUSE:
4495 return btrfs_pause_balance(fs_info);
4496 case BTRFS_BALANCE_CTL_CANCEL:
4497 return btrfs_cancel_balance(fs_info);
4503 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4506 struct btrfs_ioctl_balance_args *bargs;
4509 if (!capable(CAP_SYS_ADMIN))
4512 mutex_lock(&fs_info->balance_mutex);
4513 if (!fs_info->balance_ctl) {
4518 bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4524 btrfs_update_ioctl_balance_args(fs_info, bargs);
4526 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4531 mutex_unlock(&fs_info->balance_mutex);
4535 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4537 struct inode *inode = file_inode(file);
4538 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4539 struct btrfs_ioctl_quota_ctl_args *sa;
4542 if (!capable(CAP_SYS_ADMIN))
4545 ret = mnt_want_write_file(file);
4549 sa = memdup_user(arg, sizeof(*sa));
4555 down_write(&fs_info->subvol_sem);
4558 case BTRFS_QUOTA_CTL_ENABLE:
4559 ret = btrfs_quota_enable(fs_info);
4561 case BTRFS_QUOTA_CTL_DISABLE:
4562 ret = btrfs_quota_disable(fs_info);
4570 up_write(&fs_info->subvol_sem);
4572 mnt_drop_write_file(file);
4576 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4578 struct inode *inode = file_inode(file);
4579 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4580 struct btrfs_root *root = BTRFS_I(inode)->root;
4581 struct btrfs_ioctl_qgroup_assign_args *sa;
4582 struct btrfs_trans_handle *trans;
4586 if (!capable(CAP_SYS_ADMIN))
4589 ret = mnt_want_write_file(file);
4593 sa = memdup_user(arg, sizeof(*sa));
4599 trans = btrfs_join_transaction(root);
4600 if (IS_ERR(trans)) {
4601 ret = PTR_ERR(trans);
4606 ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
4608 ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
4611 /* update qgroup status and info */
4612 err = btrfs_run_qgroups(trans);
4614 btrfs_handle_fs_error(fs_info, err,
4615 "failed to update qgroup status and info");
4616 err = btrfs_end_transaction(trans);
4623 mnt_drop_write_file(file);
4627 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4629 struct inode *inode = file_inode(file);
4630 struct btrfs_root *root = BTRFS_I(inode)->root;
4631 struct btrfs_ioctl_qgroup_create_args *sa;
4632 struct btrfs_trans_handle *trans;
4636 if (!capable(CAP_SYS_ADMIN))
4639 ret = mnt_want_write_file(file);
4643 sa = memdup_user(arg, sizeof(*sa));
4649 if (!sa->qgroupid) {
4654 trans = btrfs_join_transaction(root);
4655 if (IS_ERR(trans)) {
4656 ret = PTR_ERR(trans);
4661 ret = btrfs_create_qgroup(trans, sa->qgroupid);
4663 ret = btrfs_remove_qgroup(trans, sa->qgroupid);
4666 err = btrfs_end_transaction(trans);
4673 mnt_drop_write_file(file);
4677 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4679 struct inode *inode = file_inode(file);
4680 struct btrfs_root *root = BTRFS_I(inode)->root;
4681 struct btrfs_ioctl_qgroup_limit_args *sa;
4682 struct btrfs_trans_handle *trans;
4687 if (!capable(CAP_SYS_ADMIN))
4690 ret = mnt_want_write_file(file);
4694 sa = memdup_user(arg, sizeof(*sa));
4700 trans = btrfs_join_transaction(root);
4701 if (IS_ERR(trans)) {
4702 ret = PTR_ERR(trans);
4706 qgroupid = sa->qgroupid;
4708 /* take the current subvol as qgroup */
4709 qgroupid = root->root_key.objectid;
4712 ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
4714 err = btrfs_end_transaction(trans);
4721 mnt_drop_write_file(file);
4725 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4727 struct inode *inode = file_inode(file);
4728 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4729 struct btrfs_ioctl_quota_rescan_args *qsa;
4732 if (!capable(CAP_SYS_ADMIN))
4735 ret = mnt_want_write_file(file);
4739 qsa = memdup_user(arg, sizeof(*qsa));
4750 ret = btrfs_qgroup_rescan(fs_info);
4755 mnt_drop_write_file(file);
4759 static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4762 struct btrfs_ioctl_quota_rescan_args qsa = {0};
4764 if (!capable(CAP_SYS_ADMIN))
4767 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4769 qsa.progress = fs_info->qgroup_rescan_progress.objectid;
4772 if (copy_to_user(arg, &qsa, sizeof(qsa)))
4778 static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4781 if (!capable(CAP_SYS_ADMIN))
4784 return btrfs_qgroup_wait_for_completion(fs_info, true);
4787 static long _btrfs_ioctl_set_received_subvol(struct file *file,
4788 struct user_namespace *mnt_userns,
4789 struct btrfs_ioctl_received_subvol_args *sa)
4791 struct inode *inode = file_inode(file);
4792 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4793 struct btrfs_root *root = BTRFS_I(inode)->root;
4794 struct btrfs_root_item *root_item = &root->root_item;
4795 struct btrfs_trans_handle *trans;
4796 struct timespec64 ct = current_time(inode);
4798 int received_uuid_changed;
4800 if (!inode_owner_or_capable(mnt_userns, inode))
4803 ret = mnt_want_write_file(file);
4807 down_write(&fs_info->subvol_sem);
4809 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
4814 if (btrfs_root_readonly(root)) {
4821 * 2 - uuid items (received uuid + subvol uuid)
4823 trans = btrfs_start_transaction(root, 3);
4824 if (IS_ERR(trans)) {
4825 ret = PTR_ERR(trans);
4830 sa->rtransid = trans->transid;
4831 sa->rtime.sec = ct.tv_sec;
4832 sa->rtime.nsec = ct.tv_nsec;
4834 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4836 if (received_uuid_changed &&
4837 !btrfs_is_empty_uuid(root_item->received_uuid)) {
4838 ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
4839 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4840 root->root_key.objectid);
4841 if (ret && ret != -ENOENT) {
4842 btrfs_abort_transaction(trans, ret);
4843 btrfs_end_transaction(trans);
4847 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4848 btrfs_set_root_stransid(root_item, sa->stransid);
4849 btrfs_set_root_rtransid(root_item, sa->rtransid);
4850 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4851 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4852 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4853 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4855 ret = btrfs_update_root(trans, fs_info->tree_root,
4856 &root->root_key, &root->root_item);
4858 btrfs_end_transaction(trans);
4861 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4862 ret = btrfs_uuid_tree_add(trans, sa->uuid,
4863 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4864 root->root_key.objectid);
4865 if (ret < 0 && ret != -EEXIST) {
4866 btrfs_abort_transaction(trans, ret);
4867 btrfs_end_transaction(trans);
4871 ret = btrfs_commit_transaction(trans);
4873 up_write(&fs_info->subvol_sem);
4874 mnt_drop_write_file(file);
4879 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4882 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4883 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4886 args32 = memdup_user(arg, sizeof(*args32));
4888 return PTR_ERR(args32);
4890 args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
4896 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4897 args64->stransid = args32->stransid;
4898 args64->rtransid = args32->rtransid;
4899 args64->stime.sec = args32->stime.sec;
4900 args64->stime.nsec = args32->stime.nsec;
4901 args64->rtime.sec = args32->rtime.sec;
4902 args64->rtime.nsec = args32->rtime.nsec;
4903 args64->flags = args32->flags;
4905 ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), args64);
4909 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4910 args32->stransid = args64->stransid;
4911 args32->rtransid = args64->rtransid;
4912 args32->stime.sec = args64->stime.sec;
4913 args32->stime.nsec = args64->stime.nsec;
4914 args32->rtime.sec = args64->rtime.sec;
4915 args32->rtime.nsec = args64->rtime.nsec;
4916 args32->flags = args64->flags;
4918 ret = copy_to_user(arg, args32, sizeof(*args32));
4929 static long btrfs_ioctl_set_received_subvol(struct file *file,
4932 struct btrfs_ioctl_received_subvol_args *sa = NULL;
4935 sa = memdup_user(arg, sizeof(*sa));
4939 ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), sa);
4944 ret = copy_to_user(arg, sa, sizeof(*sa));
4953 static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4958 char label[BTRFS_LABEL_SIZE];
4960 spin_lock(&fs_info->super_lock);
4961 memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4962 spin_unlock(&fs_info->super_lock);
4964 len = strnlen(label, BTRFS_LABEL_SIZE);
4966 if (len == BTRFS_LABEL_SIZE) {
4968 "label is too long, return the first %zu bytes",
4972 ret = copy_to_user(arg, label, len);
4974 return ret ? -EFAULT : 0;
4977 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4979 struct inode *inode = file_inode(file);
4980 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4981 struct btrfs_root *root = BTRFS_I(inode)->root;
4982 struct btrfs_super_block *super_block = fs_info->super_copy;
4983 struct btrfs_trans_handle *trans;
4984 char label[BTRFS_LABEL_SIZE];
4987 if (!capable(CAP_SYS_ADMIN))
4990 if (copy_from_user(label, arg, sizeof(label)))
4993 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4995 "unable to set label with more than %d bytes",
4996 BTRFS_LABEL_SIZE - 1);
5000 ret = mnt_want_write_file(file);
5004 trans = btrfs_start_transaction(root, 0);
5005 if (IS_ERR(trans)) {
5006 ret = PTR_ERR(trans);
5010 spin_lock(&fs_info->super_lock);
5011 strcpy(super_block->label, label);
5012 spin_unlock(&fs_info->super_lock);
5013 ret = btrfs_commit_transaction(trans);
5016 mnt_drop_write_file(file);
5020 #define INIT_FEATURE_FLAGS(suffix) \
5021 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5022 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5023 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5025 int btrfs_ioctl_get_supported_features(void __user *arg)
5027 static const struct btrfs_ioctl_feature_flags features[3] = {
5028 INIT_FEATURE_FLAGS(SUPP),
5029 INIT_FEATURE_FLAGS(SAFE_SET),
5030 INIT_FEATURE_FLAGS(SAFE_CLEAR)
5033 if (copy_to_user(arg, &features, sizeof(features)))
5039 static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
5042 struct btrfs_super_block *super_block = fs_info->super_copy;
5043 struct btrfs_ioctl_feature_flags features;
5045 features.compat_flags = btrfs_super_compat_flags(super_block);
5046 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5047 features.incompat_flags = btrfs_super_incompat_flags(super_block);
5049 if (copy_to_user(arg, &features, sizeof(features)))
5055 static int check_feature_bits(struct btrfs_fs_info *fs_info,
5056 enum btrfs_feature_set set,
5057 u64 change_mask, u64 flags, u64 supported_flags,
5058 u64 safe_set, u64 safe_clear)
5060 const char *type = btrfs_feature_set_name(set);
5062 u64 disallowed, unsupported;
5063 u64 set_mask = flags & change_mask;
5064 u64 clear_mask = ~flags & change_mask;
5066 unsupported = set_mask & ~supported_flags;
5068 names = btrfs_printable_features(set, unsupported);
5071 "this kernel does not support the %s feature bit%s",
5072 names, strchr(names, ',') ? "s" : "");
5076 "this kernel does not support %s bits 0x%llx",
5081 disallowed = set_mask & ~safe_set;
5083 names = btrfs_printable_features(set, disallowed);
5086 "can't set the %s feature bit%s while mounted",
5087 names, strchr(names, ',') ? "s" : "");
5091 "can't set %s bits 0x%llx while mounted",
5096 disallowed = clear_mask & ~safe_clear;
5098 names = btrfs_printable_features(set, disallowed);
5101 "can't clear the %s feature bit%s while mounted",
5102 names, strchr(names, ',') ? "s" : "");
5106 "can't clear %s bits 0x%llx while mounted",
5114 #define check_feature(fs_info, change_mask, flags, mask_base) \
5115 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \
5116 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
5117 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
5118 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5120 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5122 struct inode *inode = file_inode(file);
5123 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5124 struct btrfs_root *root = BTRFS_I(inode)->root;
5125 struct btrfs_super_block *super_block = fs_info->super_copy;
5126 struct btrfs_ioctl_feature_flags flags[2];
5127 struct btrfs_trans_handle *trans;
5131 if (!capable(CAP_SYS_ADMIN))
5134 if (copy_from_user(flags, arg, sizeof(flags)))
5138 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5139 !flags[0].incompat_flags)
5142 ret = check_feature(fs_info, flags[0].compat_flags,
5143 flags[1].compat_flags, COMPAT);
5147 ret = check_feature(fs_info, flags[0].compat_ro_flags,
5148 flags[1].compat_ro_flags, COMPAT_RO);
5152 ret = check_feature(fs_info, flags[0].incompat_flags,
5153 flags[1].incompat_flags, INCOMPAT);
5157 ret = mnt_want_write_file(file);
5161 trans = btrfs_start_transaction(root, 0);
5162 if (IS_ERR(trans)) {
5163 ret = PTR_ERR(trans);
5164 goto out_drop_write;
5167 spin_lock(&fs_info->super_lock);
5168 newflags = btrfs_super_compat_flags(super_block);
5169 newflags |= flags[0].compat_flags & flags[1].compat_flags;
5170 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5171 btrfs_set_super_compat_flags(super_block, newflags);
5173 newflags = btrfs_super_compat_ro_flags(super_block);
5174 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5175 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5176 btrfs_set_super_compat_ro_flags(super_block, newflags);
5178 newflags = btrfs_super_incompat_flags(super_block);
5179 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5180 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5181 btrfs_set_super_incompat_flags(super_block, newflags);
5182 spin_unlock(&fs_info->super_lock);
5184 ret = btrfs_commit_transaction(trans);
5186 mnt_drop_write_file(file);
5191 static int _btrfs_ioctl_send(struct inode *inode, void __user *argp, bool compat)
5193 struct btrfs_ioctl_send_args *arg;
5197 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5198 struct btrfs_ioctl_send_args_32 args32;
5200 ret = copy_from_user(&args32, argp, sizeof(args32));
5203 arg = kzalloc(sizeof(*arg), GFP_KERNEL);
5206 arg->send_fd = args32.send_fd;
5207 arg->clone_sources_count = args32.clone_sources_count;
5208 arg->clone_sources = compat_ptr(args32.clone_sources);
5209 arg->parent_root = args32.parent_root;
5210 arg->flags = args32.flags;
5211 memcpy(arg->reserved, args32.reserved,
5212 sizeof(args32.reserved));
5217 arg = memdup_user(argp, sizeof(*arg));
5219 return PTR_ERR(arg);
5221 ret = btrfs_ioctl_send(inode, arg);
5226 static int btrfs_ioctl_encoded_read(struct file *file, void __user *argp,
5229 struct btrfs_ioctl_encoded_io_args args = { 0 };
5230 size_t copy_end_kernel = offsetofend(struct btrfs_ioctl_encoded_io_args,
5233 struct iovec iovstack[UIO_FASTIOV];
5234 struct iovec *iov = iovstack;
5235 struct iov_iter iter;
5240 if (!capable(CAP_SYS_ADMIN)) {
5246 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5247 struct btrfs_ioctl_encoded_io_args_32 args32;
5249 copy_end = offsetofend(struct btrfs_ioctl_encoded_io_args_32,
5251 if (copy_from_user(&args32, argp, copy_end)) {
5255 args.iov = compat_ptr(args32.iov);
5256 args.iovcnt = args32.iovcnt;
5257 args.offset = args32.offset;
5258 args.flags = args32.flags;
5263 copy_end = copy_end_kernel;
5264 if (copy_from_user(&args, argp, copy_end)) {
5269 if (args.flags != 0) {
5274 ret = import_iovec(READ, args.iov, args.iovcnt, ARRAY_SIZE(iovstack),
5279 if (iov_iter_count(&iter) == 0) {
5284 ret = rw_verify_area(READ, file, &pos, args.len);
5288 init_sync_kiocb(&kiocb, file);
5291 ret = btrfs_encoded_read(&kiocb, &iter, &args);
5293 fsnotify_access(file);
5294 if (copy_to_user(argp + copy_end,
5295 (char *)&args + copy_end_kernel,
5296 sizeof(args) - copy_end_kernel))
5304 add_rchar(current, ret);
5309 static int btrfs_ioctl_encoded_write(struct file *file, void __user *argp, bool compat)
5311 struct btrfs_ioctl_encoded_io_args args;
5312 struct iovec iovstack[UIO_FASTIOV];
5313 struct iovec *iov = iovstack;
5314 struct iov_iter iter;
5319 if (!capable(CAP_SYS_ADMIN)) {
5324 if (!(file->f_mode & FMODE_WRITE)) {
5330 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5331 struct btrfs_ioctl_encoded_io_args_32 args32;
5333 if (copy_from_user(&args32, argp, sizeof(args32))) {
5337 args.iov = compat_ptr(args32.iov);
5338 args.iovcnt = args32.iovcnt;
5339 args.offset = args32.offset;
5340 args.flags = args32.flags;
5341 args.len = args32.len;
5342 args.unencoded_len = args32.unencoded_len;
5343 args.unencoded_offset = args32.unencoded_offset;
5344 args.compression = args32.compression;
5345 args.encryption = args32.encryption;
5346 memcpy(args.reserved, args32.reserved, sizeof(args.reserved));
5351 if (copy_from_user(&args, argp, sizeof(args))) {
5358 if (args.flags != 0)
5360 if (memchr_inv(args.reserved, 0, sizeof(args.reserved)))
5362 if (args.compression == BTRFS_ENCODED_IO_COMPRESSION_NONE &&
5363 args.encryption == BTRFS_ENCODED_IO_ENCRYPTION_NONE)
5365 if (args.compression >= BTRFS_ENCODED_IO_COMPRESSION_TYPES ||
5366 args.encryption >= BTRFS_ENCODED_IO_ENCRYPTION_TYPES)
5368 if (args.unencoded_offset > args.unencoded_len)
5370 if (args.len > args.unencoded_len - args.unencoded_offset)
5373 ret = import_iovec(WRITE, args.iov, args.iovcnt, ARRAY_SIZE(iovstack),
5378 file_start_write(file);
5380 if (iov_iter_count(&iter) == 0) {
5385 ret = rw_verify_area(WRITE, file, &pos, args.len);
5389 init_sync_kiocb(&kiocb, file);
5390 ret = kiocb_set_rw_flags(&kiocb, 0);
5395 ret = btrfs_do_write_iter(&kiocb, &iter, &args);
5397 fsnotify_modify(file);
5400 file_end_write(file);
5404 add_wchar(current, ret);
5409 long btrfs_ioctl(struct file *file, unsigned int
5410 cmd, unsigned long arg)
5412 struct inode *inode = file_inode(file);
5413 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5414 struct btrfs_root *root = BTRFS_I(inode)->root;
5415 void __user *argp = (void __user *)arg;
5418 case FS_IOC_GETVERSION:
5419 return btrfs_ioctl_getversion(inode, argp);
5420 case FS_IOC_GETFSLABEL:
5421 return btrfs_ioctl_get_fslabel(fs_info, argp);
5422 case FS_IOC_SETFSLABEL:
5423 return btrfs_ioctl_set_fslabel(file, argp);
5425 return btrfs_ioctl_fitrim(fs_info, argp);
5426 case BTRFS_IOC_SNAP_CREATE:
5427 return btrfs_ioctl_snap_create(file, argp, 0);
5428 case BTRFS_IOC_SNAP_CREATE_V2:
5429 return btrfs_ioctl_snap_create_v2(file, argp, 0);
5430 case BTRFS_IOC_SUBVOL_CREATE:
5431 return btrfs_ioctl_snap_create(file, argp, 1);
5432 case BTRFS_IOC_SUBVOL_CREATE_V2:
5433 return btrfs_ioctl_snap_create_v2(file, argp, 1);
5434 case BTRFS_IOC_SNAP_DESTROY:
5435 return btrfs_ioctl_snap_destroy(file, argp, false);
5436 case BTRFS_IOC_SNAP_DESTROY_V2:
5437 return btrfs_ioctl_snap_destroy(file, argp, true);
5438 case BTRFS_IOC_SUBVOL_GETFLAGS:
5439 return btrfs_ioctl_subvol_getflags(inode, argp);
5440 case BTRFS_IOC_SUBVOL_SETFLAGS:
5441 return btrfs_ioctl_subvol_setflags(file, argp);
5442 case BTRFS_IOC_DEFAULT_SUBVOL:
5443 return btrfs_ioctl_default_subvol(file, argp);
5444 case BTRFS_IOC_DEFRAG:
5445 return btrfs_ioctl_defrag(file, NULL);
5446 case BTRFS_IOC_DEFRAG_RANGE:
5447 return btrfs_ioctl_defrag(file, argp);
5448 case BTRFS_IOC_RESIZE:
5449 return btrfs_ioctl_resize(file, argp);
5450 case BTRFS_IOC_ADD_DEV:
5451 return btrfs_ioctl_add_dev(fs_info, argp);
5452 case BTRFS_IOC_RM_DEV:
5453 return btrfs_ioctl_rm_dev(file, argp);
5454 case BTRFS_IOC_RM_DEV_V2:
5455 return btrfs_ioctl_rm_dev_v2(file, argp);
5456 case BTRFS_IOC_FS_INFO:
5457 return btrfs_ioctl_fs_info(fs_info, argp);
5458 case BTRFS_IOC_DEV_INFO:
5459 return btrfs_ioctl_dev_info(fs_info, argp);
5460 case BTRFS_IOC_TREE_SEARCH:
5461 return btrfs_ioctl_tree_search(inode, argp);
5462 case BTRFS_IOC_TREE_SEARCH_V2:
5463 return btrfs_ioctl_tree_search_v2(inode, argp);
5464 case BTRFS_IOC_INO_LOOKUP:
5465 return btrfs_ioctl_ino_lookup(root, argp);
5466 case BTRFS_IOC_INO_PATHS:
5467 return btrfs_ioctl_ino_to_path(root, argp);
5468 case BTRFS_IOC_LOGICAL_INO:
5469 return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5470 case BTRFS_IOC_LOGICAL_INO_V2:
5471 return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
5472 case BTRFS_IOC_SPACE_INFO:
5473 return btrfs_ioctl_space_info(fs_info, argp);
5474 case BTRFS_IOC_SYNC: {
5477 ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
5480 ret = btrfs_sync_fs(inode->i_sb, 1);
5482 * The transaction thread may want to do more work,
5483 * namely it pokes the cleaner kthread that will start
5484 * processing uncleaned subvols.
5486 wake_up_process(fs_info->transaction_kthread);
5489 case BTRFS_IOC_START_SYNC:
5490 return btrfs_ioctl_start_sync(root, argp);
5491 case BTRFS_IOC_WAIT_SYNC:
5492 return btrfs_ioctl_wait_sync(fs_info, argp);
5493 case BTRFS_IOC_SCRUB:
5494 return btrfs_ioctl_scrub(file, argp);
5495 case BTRFS_IOC_SCRUB_CANCEL:
5496 return btrfs_ioctl_scrub_cancel(fs_info);
5497 case BTRFS_IOC_SCRUB_PROGRESS:
5498 return btrfs_ioctl_scrub_progress(fs_info, argp);
5499 case BTRFS_IOC_BALANCE_V2:
5500 return btrfs_ioctl_balance(file, argp);
5501 case BTRFS_IOC_BALANCE_CTL:
5502 return btrfs_ioctl_balance_ctl(fs_info, arg);
5503 case BTRFS_IOC_BALANCE_PROGRESS:
5504 return btrfs_ioctl_balance_progress(fs_info, argp);
5505 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5506 return btrfs_ioctl_set_received_subvol(file, argp);
5508 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5509 return btrfs_ioctl_set_received_subvol_32(file, argp);
5511 case BTRFS_IOC_SEND:
5512 return _btrfs_ioctl_send(inode, argp, false);
5513 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5514 case BTRFS_IOC_SEND_32:
5515 return _btrfs_ioctl_send(inode, argp, true);
5517 case BTRFS_IOC_GET_DEV_STATS:
5518 return btrfs_ioctl_get_dev_stats(fs_info, argp);
5519 case BTRFS_IOC_QUOTA_CTL:
5520 return btrfs_ioctl_quota_ctl(file, argp);
5521 case BTRFS_IOC_QGROUP_ASSIGN:
5522 return btrfs_ioctl_qgroup_assign(file, argp);
5523 case BTRFS_IOC_QGROUP_CREATE:
5524 return btrfs_ioctl_qgroup_create(file, argp);
5525 case BTRFS_IOC_QGROUP_LIMIT:
5526 return btrfs_ioctl_qgroup_limit(file, argp);
5527 case BTRFS_IOC_QUOTA_RESCAN:
5528 return btrfs_ioctl_quota_rescan(file, argp);
5529 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5530 return btrfs_ioctl_quota_rescan_status(fs_info, argp);
5531 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5532 return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
5533 case BTRFS_IOC_DEV_REPLACE:
5534 return btrfs_ioctl_dev_replace(fs_info, argp);
5535 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5536 return btrfs_ioctl_get_supported_features(argp);
5537 case BTRFS_IOC_GET_FEATURES:
5538 return btrfs_ioctl_get_features(fs_info, argp);
5539 case BTRFS_IOC_SET_FEATURES:
5540 return btrfs_ioctl_set_features(file, argp);
5541 case BTRFS_IOC_GET_SUBVOL_INFO:
5542 return btrfs_ioctl_get_subvol_info(inode, argp);
5543 case BTRFS_IOC_GET_SUBVOL_ROOTREF:
5544 return btrfs_ioctl_get_subvol_rootref(root, argp);
5545 case BTRFS_IOC_INO_LOOKUP_USER:
5546 return btrfs_ioctl_ino_lookup_user(file, argp);
5547 case FS_IOC_ENABLE_VERITY:
5548 return fsverity_ioctl_enable(file, (const void __user *)argp);
5549 case FS_IOC_MEASURE_VERITY:
5550 return fsverity_ioctl_measure(file, argp);
5551 case BTRFS_IOC_ENCODED_READ:
5552 return btrfs_ioctl_encoded_read(file, argp, false);
5553 case BTRFS_IOC_ENCODED_WRITE:
5554 return btrfs_ioctl_encoded_write(file, argp, false);
5555 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5556 case BTRFS_IOC_ENCODED_READ_32:
5557 return btrfs_ioctl_encoded_read(file, argp, true);
5558 case BTRFS_IOC_ENCODED_WRITE_32:
5559 return btrfs_ioctl_encoded_write(file, argp, true);
5566 #ifdef CONFIG_COMPAT
5567 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5570 * These all access 32-bit values anyway so no further
5571 * handling is necessary.
5574 case FS_IOC32_GETVERSION:
5575 cmd = FS_IOC_GETVERSION;
5579 return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));