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>
34 #include "transaction.h"
35 #include "btrfs_inode.h"
36 #include "print-tree.h"
40 #include "rcu-string.h"
42 #include "dev-replace.h"
47 #include "compression.h"
48 #include "space-info.h"
49 #include "delalloc-space.h"
50 #include "block-group.h"
54 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
55 * structures are incorrect, as the timespec structure from userspace
56 * is 4 bytes too small. We define these alternatives here to teach
57 * the kernel about the 32-bit struct packing.
59 struct btrfs_ioctl_timespec_32 {
62 } __attribute__ ((__packed__));
64 struct btrfs_ioctl_received_subvol_args_32 {
65 char uuid[BTRFS_UUID_SIZE]; /* in */
66 __u64 stransid; /* in */
67 __u64 rtransid; /* out */
68 struct btrfs_ioctl_timespec_32 stime; /* in */
69 struct btrfs_ioctl_timespec_32 rtime; /* out */
71 __u64 reserved[16]; /* in */
72 } __attribute__ ((__packed__));
74 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
75 struct btrfs_ioctl_received_subvol_args_32)
78 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
79 struct btrfs_ioctl_send_args_32 {
80 __s64 send_fd; /* in */
81 __u64 clone_sources_count; /* in */
82 compat_uptr_t clone_sources; /* in */
83 __u64 parent_root; /* in */
85 __u32 version; /* in */
86 __u8 reserved[28]; /* in */
87 } __attribute__ ((__packed__));
89 #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
90 struct btrfs_ioctl_send_args_32)
93 /* Mask out flags that are inappropriate for the given type of inode. */
94 static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
97 if (S_ISDIR(inode->i_mode))
99 else if (S_ISREG(inode->i_mode))
100 return flags & ~FS_DIRSYNC_FL;
102 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
106 * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
109 static unsigned int btrfs_inode_flags_to_fsflags(struct btrfs_inode *binode)
111 unsigned int iflags = 0;
112 u32 flags = binode->flags;
113 u32 ro_flags = binode->ro_flags;
115 if (flags & BTRFS_INODE_SYNC)
116 iflags |= FS_SYNC_FL;
117 if (flags & BTRFS_INODE_IMMUTABLE)
118 iflags |= FS_IMMUTABLE_FL;
119 if (flags & BTRFS_INODE_APPEND)
120 iflags |= FS_APPEND_FL;
121 if (flags & BTRFS_INODE_NODUMP)
122 iflags |= FS_NODUMP_FL;
123 if (flags & BTRFS_INODE_NOATIME)
124 iflags |= FS_NOATIME_FL;
125 if (flags & BTRFS_INODE_DIRSYNC)
126 iflags |= FS_DIRSYNC_FL;
127 if (flags & BTRFS_INODE_NODATACOW)
128 iflags |= FS_NOCOW_FL;
129 if (ro_flags & BTRFS_INODE_RO_VERITY)
130 iflags |= FS_VERITY_FL;
132 if (flags & BTRFS_INODE_NOCOMPRESS)
133 iflags |= FS_NOCOMP_FL;
134 else if (flags & BTRFS_INODE_COMPRESS)
135 iflags |= FS_COMPR_FL;
141 * Update inode->i_flags based on the btrfs internal flags.
143 void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
145 struct btrfs_inode *binode = BTRFS_I(inode);
146 unsigned int new_fl = 0;
148 if (binode->flags & BTRFS_INODE_SYNC)
150 if (binode->flags & BTRFS_INODE_IMMUTABLE)
151 new_fl |= S_IMMUTABLE;
152 if (binode->flags & BTRFS_INODE_APPEND)
154 if (binode->flags & BTRFS_INODE_NOATIME)
156 if (binode->flags & BTRFS_INODE_DIRSYNC)
158 if (binode->ro_flags & BTRFS_INODE_RO_VERITY)
161 set_mask_bits(&inode->i_flags,
162 S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC |
167 * Check if @flags are a supported and valid set of FS_*_FL flags and that
168 * the old and new flags are not conflicting
170 static int check_fsflags(unsigned int old_flags, unsigned int flags)
172 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
173 FS_NOATIME_FL | FS_NODUMP_FL | \
174 FS_SYNC_FL | FS_DIRSYNC_FL | \
175 FS_NOCOMP_FL | FS_COMPR_FL |
179 /* COMPR and NOCOMP on new/old are valid */
180 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
183 if ((flags & FS_COMPR_FL) && (flags & FS_NOCOW_FL))
186 /* NOCOW and compression options are mutually exclusive */
187 if ((old_flags & FS_NOCOW_FL) && (flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
189 if ((flags & FS_NOCOW_FL) && (old_flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
195 static int check_fsflags_compatible(struct btrfs_fs_info *fs_info,
198 if (btrfs_is_zoned(fs_info) && (flags & FS_NOCOW_FL))
205 * Set flags/xflags from the internal inode flags. The remaining items of
206 * fsxattr are zeroed.
208 int btrfs_fileattr_get(struct dentry *dentry, struct fileattr *fa)
210 struct btrfs_inode *binode = BTRFS_I(d_inode(dentry));
212 fileattr_fill_flags(fa, btrfs_inode_flags_to_fsflags(binode));
216 int btrfs_fileattr_set(struct user_namespace *mnt_userns,
217 struct dentry *dentry, struct fileattr *fa)
219 struct inode *inode = d_inode(dentry);
220 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
221 struct btrfs_inode *binode = BTRFS_I(inode);
222 struct btrfs_root *root = binode->root;
223 struct btrfs_trans_handle *trans;
224 unsigned int fsflags, old_fsflags;
226 const char *comp = NULL;
229 if (btrfs_root_readonly(root))
232 if (fileattr_has_fsx(fa))
235 fsflags = btrfs_mask_fsflags_for_type(inode, fa->flags);
236 old_fsflags = btrfs_inode_flags_to_fsflags(binode);
237 ret = check_fsflags(old_fsflags, fsflags);
241 ret = check_fsflags_compatible(fs_info, fsflags);
245 binode_flags = binode->flags;
246 if (fsflags & FS_SYNC_FL)
247 binode_flags |= BTRFS_INODE_SYNC;
249 binode_flags &= ~BTRFS_INODE_SYNC;
250 if (fsflags & FS_IMMUTABLE_FL)
251 binode_flags |= BTRFS_INODE_IMMUTABLE;
253 binode_flags &= ~BTRFS_INODE_IMMUTABLE;
254 if (fsflags & FS_APPEND_FL)
255 binode_flags |= BTRFS_INODE_APPEND;
257 binode_flags &= ~BTRFS_INODE_APPEND;
258 if (fsflags & FS_NODUMP_FL)
259 binode_flags |= BTRFS_INODE_NODUMP;
261 binode_flags &= ~BTRFS_INODE_NODUMP;
262 if (fsflags & FS_NOATIME_FL)
263 binode_flags |= BTRFS_INODE_NOATIME;
265 binode_flags &= ~BTRFS_INODE_NOATIME;
267 /* If coming from FS_IOC_FSSETXATTR then skip unconverted flags */
268 if (!fa->flags_valid) {
269 /* 1 item for the inode */
270 trans = btrfs_start_transaction(root, 1);
272 return PTR_ERR(trans);
276 if (fsflags & FS_DIRSYNC_FL)
277 binode_flags |= BTRFS_INODE_DIRSYNC;
279 binode_flags &= ~BTRFS_INODE_DIRSYNC;
280 if (fsflags & FS_NOCOW_FL) {
281 if (S_ISREG(inode->i_mode)) {
283 * It's safe to turn csums off here, no extents exist.
284 * Otherwise we want the flag to reflect the real COW
285 * status of the file and will not set it.
287 if (inode->i_size == 0)
288 binode_flags |= BTRFS_INODE_NODATACOW |
289 BTRFS_INODE_NODATASUM;
291 binode_flags |= BTRFS_INODE_NODATACOW;
295 * Revert back under same assumptions as above
297 if (S_ISREG(inode->i_mode)) {
298 if (inode->i_size == 0)
299 binode_flags &= ~(BTRFS_INODE_NODATACOW |
300 BTRFS_INODE_NODATASUM);
302 binode_flags &= ~BTRFS_INODE_NODATACOW;
307 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
308 * flag may be changed automatically if compression code won't make
311 if (fsflags & FS_NOCOMP_FL) {
312 binode_flags &= ~BTRFS_INODE_COMPRESS;
313 binode_flags |= BTRFS_INODE_NOCOMPRESS;
314 } else if (fsflags & FS_COMPR_FL) {
316 if (IS_SWAPFILE(inode))
319 binode_flags |= BTRFS_INODE_COMPRESS;
320 binode_flags &= ~BTRFS_INODE_NOCOMPRESS;
322 comp = btrfs_compress_type2str(fs_info->compress_type);
323 if (!comp || comp[0] == 0)
324 comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
326 binode_flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
333 trans = btrfs_start_transaction(root, 3);
335 return PTR_ERR(trans);
338 ret = btrfs_set_prop(trans, inode, "btrfs.compression", comp,
341 btrfs_abort_transaction(trans, ret);
345 ret = btrfs_set_prop(trans, inode, "btrfs.compression", NULL,
347 if (ret && ret != -ENODATA) {
348 btrfs_abort_transaction(trans, ret);
354 binode->flags = binode_flags;
355 btrfs_sync_inode_flags_to_i_flags(inode);
356 inode_inc_iversion(inode);
357 inode->i_ctime = current_time(inode);
358 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
361 btrfs_end_transaction(trans);
366 * Start exclusive operation @type, return true on success
368 bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
369 enum btrfs_exclusive_operation type)
373 spin_lock(&fs_info->super_lock);
374 if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
375 fs_info->exclusive_operation = type;
378 spin_unlock(&fs_info->super_lock);
384 * Conditionally allow to enter the exclusive operation in case it's compatible
385 * with the running one. This must be paired with btrfs_exclop_start_unlock and
386 * btrfs_exclop_finish.
389 * - the same type is already running
390 * - when trying to add a device and balance has been paused
391 * - not BTRFS_EXCLOP_NONE - this is intentionally incompatible and the caller
392 * must check the condition first that would allow none -> @type
394 bool btrfs_exclop_start_try_lock(struct btrfs_fs_info *fs_info,
395 enum btrfs_exclusive_operation type)
397 spin_lock(&fs_info->super_lock);
398 if (fs_info->exclusive_operation == type ||
399 (fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED &&
400 type == BTRFS_EXCLOP_DEV_ADD))
403 spin_unlock(&fs_info->super_lock);
407 void btrfs_exclop_start_unlock(struct btrfs_fs_info *fs_info)
409 spin_unlock(&fs_info->super_lock);
412 void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
414 spin_lock(&fs_info->super_lock);
415 WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
416 spin_unlock(&fs_info->super_lock);
417 sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
420 void btrfs_exclop_balance(struct btrfs_fs_info *fs_info,
421 enum btrfs_exclusive_operation op)
424 case BTRFS_EXCLOP_BALANCE_PAUSED:
425 spin_lock(&fs_info->super_lock);
426 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE ||
427 fs_info->exclusive_operation == BTRFS_EXCLOP_DEV_ADD);
428 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE_PAUSED;
429 spin_unlock(&fs_info->super_lock);
431 case BTRFS_EXCLOP_BALANCE:
432 spin_lock(&fs_info->super_lock);
433 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED);
434 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
435 spin_unlock(&fs_info->super_lock);
439 "invalid exclop balance operation %d requested", op);
443 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
445 struct inode *inode = file_inode(file);
447 return put_user(inode->i_generation, arg);
450 static noinline int btrfs_ioctl_fitrim(struct btrfs_fs_info *fs_info,
453 struct btrfs_device *device;
454 struct request_queue *q;
455 struct fstrim_range range;
456 u64 minlen = ULLONG_MAX;
460 if (!capable(CAP_SYS_ADMIN))
464 * btrfs_trim_block_group() depends on space cache, which is not
465 * available in zoned filesystem. So, disallow fitrim on a zoned
466 * filesystem for now.
468 if (btrfs_is_zoned(fs_info))
472 * If the fs is mounted with nologreplay, which requires it to be
473 * mounted in RO mode as well, we can not allow discard on free space
474 * inside block groups, because log trees refer to extents that are not
475 * pinned in a block group's free space cache (pinning the extents is
476 * precisely the first phase of replaying a log tree).
478 if (btrfs_test_opt(fs_info, NOLOGREPLAY))
482 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
486 q = bdev_get_queue(device->bdev);
487 if (blk_queue_discard(q)) {
489 minlen = min_t(u64, q->limits.discard_granularity,
497 if (copy_from_user(&range, arg, sizeof(range)))
501 * NOTE: Don't truncate the range using super->total_bytes. Bytenr of
502 * block group is in the logical address space, which can be any
503 * sectorsize aligned bytenr in the range [0, U64_MAX].
505 if (range.len < fs_info->sb->s_blocksize)
508 range.minlen = max(range.minlen, minlen);
509 ret = btrfs_trim_fs(fs_info, &range);
513 if (copy_to_user(arg, &range, sizeof(range)))
519 int __pure btrfs_is_empty_uuid(u8 *uuid)
523 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
530 static noinline int create_subvol(struct user_namespace *mnt_userns,
531 struct inode *dir, struct dentry *dentry,
532 const char *name, int namelen,
533 struct btrfs_qgroup_inherit *inherit)
535 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
536 struct btrfs_trans_handle *trans;
537 struct btrfs_key key;
538 struct btrfs_root_item *root_item;
539 struct btrfs_inode_item *inode_item;
540 struct extent_buffer *leaf;
541 struct btrfs_root *root = BTRFS_I(dir)->root;
542 struct btrfs_root *new_root;
543 struct btrfs_block_rsv block_rsv;
544 struct timespec64 cur_time = current_time(dir);
551 root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
555 ret = btrfs_get_free_objectid(fs_info->tree_root, &objectid);
559 ret = get_anon_bdev(&anon_dev);
564 * Don't create subvolume whose level is not zero. Or qgroup will be
565 * screwed up since it assumes subvolume qgroup's level to be 0.
567 if (btrfs_qgroup_level(objectid)) {
572 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
574 * The same as the snapshot creation, please see the comment
575 * of create_snapshot().
577 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
581 trans = btrfs_start_transaction(root, 0);
583 ret = PTR_ERR(trans);
584 btrfs_subvolume_release_metadata(root, &block_rsv);
587 trans->block_rsv = &block_rsv;
588 trans->bytes_reserved = block_rsv.size;
590 ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
594 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
595 BTRFS_NESTING_NORMAL);
601 btrfs_mark_buffer_dirty(leaf);
603 inode_item = &root_item->inode;
604 btrfs_set_stack_inode_generation(inode_item, 1);
605 btrfs_set_stack_inode_size(inode_item, 3);
606 btrfs_set_stack_inode_nlink(inode_item, 1);
607 btrfs_set_stack_inode_nbytes(inode_item,
609 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
611 btrfs_set_root_flags(root_item, 0);
612 btrfs_set_root_limit(root_item, 0);
613 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
615 btrfs_set_root_bytenr(root_item, leaf->start);
616 btrfs_set_root_generation(root_item, trans->transid);
617 btrfs_set_root_level(root_item, 0);
618 btrfs_set_root_refs(root_item, 1);
619 btrfs_set_root_used(root_item, leaf->len);
620 btrfs_set_root_last_snapshot(root_item, 0);
622 btrfs_set_root_generation_v2(root_item,
623 btrfs_root_generation(root_item));
624 generate_random_guid(root_item->uuid);
625 btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
626 btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
627 root_item->ctime = root_item->otime;
628 btrfs_set_root_ctransid(root_item, trans->transid);
629 btrfs_set_root_otransid(root_item, trans->transid);
631 btrfs_tree_unlock(leaf);
633 btrfs_set_root_dirid(root_item, BTRFS_FIRST_FREE_OBJECTID);
635 key.objectid = objectid;
637 key.type = BTRFS_ROOT_ITEM_KEY;
638 ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
642 * Since we don't abort the transaction in this case, free the
643 * tree block so that we don't leak space and leave the
644 * filesystem in an inconsistent state (an extent item in the
645 * extent tree with a backreference for a root that does not
648 btrfs_tree_lock(leaf);
649 btrfs_clean_tree_block(leaf);
650 btrfs_tree_unlock(leaf);
651 btrfs_free_tree_block(trans, objectid, leaf, 0, 1);
652 free_extent_buffer(leaf);
656 free_extent_buffer(leaf);
659 key.offset = (u64)-1;
660 new_root = btrfs_get_new_fs_root(fs_info, objectid, anon_dev);
661 if (IS_ERR(new_root)) {
662 free_anon_bdev(anon_dev);
663 ret = PTR_ERR(new_root);
664 btrfs_abort_transaction(trans, ret);
667 /* Freeing will be done in btrfs_put_root() of new_root */
670 ret = btrfs_record_root_in_trans(trans, new_root);
672 btrfs_put_root(new_root);
673 btrfs_abort_transaction(trans, ret);
677 ret = btrfs_create_subvol_root(trans, new_root, root, mnt_userns);
678 btrfs_put_root(new_root);
680 /* We potentially lose an unused inode item here */
681 btrfs_abort_transaction(trans, ret);
686 * insert the directory item
688 ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
690 btrfs_abort_transaction(trans, ret);
694 ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
695 BTRFS_FT_DIR, index);
697 btrfs_abort_transaction(trans, ret);
701 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
702 ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
704 btrfs_abort_transaction(trans, ret);
708 ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
709 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
711 btrfs_abort_transaction(trans, ret);
715 ret = btrfs_uuid_tree_add(trans, root_item->uuid,
716 BTRFS_UUID_KEY_SUBVOL, objectid);
718 btrfs_abort_transaction(trans, ret);
722 trans->block_rsv = NULL;
723 trans->bytes_reserved = 0;
724 btrfs_subvolume_release_metadata(root, &block_rsv);
727 btrfs_end_transaction(trans);
729 ret = btrfs_commit_transaction(trans);
732 inode = btrfs_lookup_dentry(dir, dentry);
734 return PTR_ERR(inode);
735 d_instantiate(dentry, inode);
741 free_anon_bdev(anon_dev);
746 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
747 struct dentry *dentry, bool readonly,
748 struct btrfs_qgroup_inherit *inherit)
750 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
752 struct btrfs_pending_snapshot *pending_snapshot;
753 struct btrfs_trans_handle *trans;
756 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
759 if (atomic_read(&root->nr_swapfiles)) {
761 "cannot snapshot subvolume with active swapfile");
765 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
766 if (!pending_snapshot)
769 ret = get_anon_bdev(&pending_snapshot->anon_dev);
772 pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
774 pending_snapshot->path = btrfs_alloc_path();
775 if (!pending_snapshot->root_item || !pending_snapshot->path) {
780 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
781 BTRFS_BLOCK_RSV_TEMP);
783 * 1 - parent dir inode
786 * 2 - root ref/backref
787 * 1 - root of snapshot
790 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
791 &pending_snapshot->block_rsv, 8,
796 pending_snapshot->dentry = dentry;
797 pending_snapshot->root = root;
798 pending_snapshot->readonly = readonly;
799 pending_snapshot->dir = dir;
800 pending_snapshot->inherit = inherit;
802 trans = btrfs_start_transaction(root, 0);
804 ret = PTR_ERR(trans);
808 trans->pending_snapshot = pending_snapshot;
810 ret = btrfs_commit_transaction(trans);
814 ret = pending_snapshot->error;
818 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
822 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
824 ret = PTR_ERR(inode);
828 d_instantiate(dentry, inode);
830 pending_snapshot->anon_dev = 0;
832 /* Prevent double freeing of anon_dev */
833 if (ret && pending_snapshot->snap)
834 pending_snapshot->snap->anon_dev = 0;
835 btrfs_put_root(pending_snapshot->snap);
836 btrfs_subvolume_release_metadata(root, &pending_snapshot->block_rsv);
838 if (pending_snapshot->anon_dev)
839 free_anon_bdev(pending_snapshot->anon_dev);
840 kfree(pending_snapshot->root_item);
841 btrfs_free_path(pending_snapshot->path);
842 kfree(pending_snapshot);
847 /* copy of may_delete in fs/namei.c()
848 * Check whether we can remove a link victim from directory dir, check
849 * whether the type of victim is right.
850 * 1. We can't do it if dir is read-only (done in permission())
851 * 2. We should have write and exec permissions on dir
852 * 3. We can't remove anything from append-only dir
853 * 4. We can't do anything with immutable dir (done in permission())
854 * 5. If the sticky bit on dir is set we should either
855 * a. be owner of dir, or
856 * b. be owner of victim, or
857 * c. have CAP_FOWNER capability
858 * 6. If the victim is append-only or immutable we can't do anything with
859 * links pointing to it.
860 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
861 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
862 * 9. We can't remove a root or mountpoint.
863 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
864 * nfs_async_unlink().
867 static int btrfs_may_delete(struct user_namespace *mnt_userns,
868 struct inode *dir, struct dentry *victim, int isdir)
872 if (d_really_is_negative(victim))
875 BUG_ON(d_inode(victim->d_parent) != dir);
876 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
878 error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
883 if (check_sticky(mnt_userns, dir, d_inode(victim)) ||
884 IS_APPEND(d_inode(victim)) || IS_IMMUTABLE(d_inode(victim)) ||
885 IS_SWAPFILE(d_inode(victim)))
888 if (!d_is_dir(victim))
892 } else if (d_is_dir(victim))
896 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
901 /* copy of may_create in fs/namei.c() */
902 static inline int btrfs_may_create(struct user_namespace *mnt_userns,
903 struct inode *dir, struct dentry *child)
905 if (d_really_is_positive(child))
909 if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
911 return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
915 * Create a new subvolume below @parent. This is largely modeled after
916 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
917 * inside this filesystem so it's quite a bit simpler.
919 static noinline int btrfs_mksubvol(const struct path *parent,
920 struct user_namespace *mnt_userns,
921 const char *name, int namelen,
922 struct btrfs_root *snap_src,
924 struct btrfs_qgroup_inherit *inherit)
926 struct inode *dir = d_inode(parent->dentry);
927 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
928 struct dentry *dentry;
931 error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
935 dentry = lookup_one(mnt_userns, name, parent->dentry, namelen);
936 error = PTR_ERR(dentry);
940 error = btrfs_may_create(mnt_userns, dir, dentry);
945 * even if this name doesn't exist, we may get hash collisions.
946 * check for them now when we can safely fail
948 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
954 down_read(&fs_info->subvol_sem);
956 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
960 error = create_snapshot(snap_src, dir, dentry, readonly, inherit);
962 error = create_subvol(mnt_userns, dir, dentry, name, namelen, inherit);
965 fsnotify_mkdir(dir, dentry);
967 up_read(&fs_info->subvol_sem);
971 btrfs_inode_unlock(dir, 0);
975 static noinline int btrfs_mksnapshot(const struct path *parent,
976 struct user_namespace *mnt_userns,
977 const char *name, int namelen,
978 struct btrfs_root *root,
980 struct btrfs_qgroup_inherit *inherit)
983 bool snapshot_force_cow = false;
986 * Force new buffered writes to reserve space even when NOCOW is
987 * possible. This is to avoid later writeback (running dealloc) to
988 * fallback to COW mode and unexpectedly fail with ENOSPC.
990 btrfs_drew_read_lock(&root->snapshot_lock);
992 ret = btrfs_start_delalloc_snapshot(root, false);
997 * All previous writes have started writeback in NOCOW mode, so now
998 * we force future writes to fallback to COW mode during snapshot
1001 atomic_inc(&root->snapshot_force_cow);
1002 snapshot_force_cow = true;
1004 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
1006 ret = btrfs_mksubvol(parent, mnt_userns, name, namelen,
1007 root, readonly, inherit);
1009 if (snapshot_force_cow)
1010 atomic_dec(&root->snapshot_force_cow);
1011 btrfs_drew_read_unlock(&root->snapshot_lock);
1015 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start,
1018 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1019 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1020 struct extent_map *em;
1021 const u32 sectorsize = BTRFS_I(inode)->root->fs_info->sectorsize;
1024 * hopefully we have this extent in the tree already, try without
1025 * the full extent lock
1027 read_lock(&em_tree->lock);
1028 em = lookup_extent_mapping(em_tree, start, sectorsize);
1029 read_unlock(&em_tree->lock);
1032 struct extent_state *cached = NULL;
1033 u64 end = start + sectorsize - 1;
1035 /* get the big lock and read metadata off disk */
1037 lock_extent_bits(io_tree, start, end, &cached);
1038 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, sectorsize);
1040 unlock_extent_cached(io_tree, start, end, &cached);
1049 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em,
1052 struct extent_map *next;
1055 /* this is the last extent */
1056 if (em->start + em->len >= i_size_read(inode))
1059 next = defrag_lookup_extent(inode, em->start + em->len, locked);
1060 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1062 else if ((em->block_start + em->block_len == next->block_start) &&
1063 (em->block_len > SZ_128K && next->block_len > SZ_128K))
1066 free_extent_map(next);
1071 * Prepare one page to be defragged.
1075 * - Returned page is locked and has been set up properly.
1076 * - No ordered extent exists in the page.
1077 * - The page is uptodate.
1079 * NOTE: Caller should also wait for page writeback after the cluster is
1080 * prepared, here we don't do writeback wait for each page.
1082 static struct page *defrag_prepare_one_page(struct btrfs_inode *inode,
1085 struct address_space *mapping = inode->vfs_inode.i_mapping;
1086 gfp_t mask = btrfs_alloc_write_mask(mapping);
1087 u64 page_start = (u64)index << PAGE_SHIFT;
1088 u64 page_end = page_start + PAGE_SIZE - 1;
1089 struct extent_state *cached_state = NULL;
1094 page = find_or_create_page(mapping, index, mask);
1096 return ERR_PTR(-ENOMEM);
1099 * Since we can defragment files opened read-only, we can encounter
1100 * transparent huge pages here (see CONFIG_READ_ONLY_THP_FOR_FS). We
1101 * can't do I/O using huge pages yet, so return an error for now.
1102 * Filesystem transparent huge pages are typically only used for
1103 * executables that explicitly enable them, so this isn't very
1106 if (PageCompound(page)) {
1109 return ERR_PTR(-ETXTBSY);
1112 ret = set_page_extent_mapped(page);
1116 return ERR_PTR(ret);
1119 /* Wait for any existing ordered extent in the range */
1121 struct btrfs_ordered_extent *ordered;
1123 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
1124 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
1125 unlock_extent_cached(&inode->io_tree, page_start, page_end,
1131 btrfs_start_ordered_extent(ordered, 1);
1132 btrfs_put_ordered_extent(ordered);
1135 * We unlocked the page above, so we need check if it was
1138 if (page->mapping != mapping || !PagePrivate(page)) {
1146 * Now the page range has no ordered extent any more. Read the page to
1149 if (!PageUptodate(page)) {
1150 btrfs_readpage(NULL, page);
1152 if (page->mapping != mapping || !PagePrivate(page)) {
1157 if (!PageUptodate(page)) {
1160 return ERR_PTR(-EIO);
1166 struct defrag_target_range {
1167 struct list_head list;
1173 * Collect all valid target extents.
1175 * @start: file offset to lookup
1176 * @len: length to lookup
1177 * @extent_thresh: file extent size threshold, any extent size >= this value
1179 * @newer_than: only defrag extents newer than this value
1180 * @do_compress: whether the defrag is doing compression
1181 * if true, @extent_thresh will be ignored and all regular
1182 * file extents meeting @newer_than will be targets.
1183 * @locked: if the range has already held extent lock
1184 * @target_list: list of targets file extents
1186 static int defrag_collect_targets(struct btrfs_inode *inode,
1187 u64 start, u64 len, u32 extent_thresh,
1188 u64 newer_than, bool do_compress,
1189 bool locked, struct list_head *target_list)
1194 while (cur < start + len) {
1195 struct extent_map *em;
1196 struct defrag_target_range *new;
1197 bool next_mergeable = true;
1200 em = defrag_lookup_extent(&inode->vfs_inode, cur, locked);
1204 /* Skip hole/inline/preallocated extents */
1205 if (em->block_start >= EXTENT_MAP_LAST_BYTE ||
1206 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1209 /* Skip older extent */
1210 if (em->generation < newer_than)
1213 /* This em is under writeback, no need to defrag */
1214 if (em->generation == (u64)-1)
1218 * Our start offset might be in the middle of an existing extent
1219 * map, so take that into account.
1221 range_len = em->len - (cur - em->start);
1223 * If this range of the extent map is already flagged for delalloc,
1226 * 1) We could deadlock later, when trying to reserve space for
1227 * delalloc, because in case we can't immediately reserve space
1228 * the flusher can start delalloc and wait for the respective
1229 * ordered extents to complete. The deadlock would happen
1230 * because we do the space reservation while holding the range
1231 * locked, and starting writeback, or finishing an ordered
1232 * extent, requires locking the range;
1234 * 2) If there's delalloc there, it means there's dirty pages for
1235 * which writeback has not started yet (we clean the delalloc
1236 * flag when starting writeback and after creating an ordered
1237 * extent). If we mark pages in an adjacent range for defrag,
1238 * then we will have a larger contiguous range for delalloc,
1239 * very likely resulting in a larger extent after writeback is
1240 * triggered (except in a case of free space fragmentation).
1242 if (test_range_bit(&inode->io_tree, cur, cur + range_len - 1,
1243 EXTENT_DELALLOC, 0, NULL))
1247 * For do_compress case, we want to compress all valid file
1248 * extents, thus no @extent_thresh or mergeable check.
1253 /* Skip too large extent */
1254 if (range_len >= extent_thresh)
1257 next_mergeable = defrag_check_next_extent(&inode->vfs_inode, em,
1259 if (!next_mergeable) {
1260 struct defrag_target_range *last;
1262 /* Empty target list, no way to merge with last entry */
1263 if (list_empty(target_list))
1265 last = list_entry(target_list->prev,
1266 struct defrag_target_range, list);
1267 /* Not mergeable with last entry */
1268 if (last->start + last->len != cur)
1271 /* Mergeable, fall through to add it to @target_list. */
1275 range_len = min(extent_map_end(em), start + len) - cur;
1277 * This one is a good target, check if it can be merged into
1278 * last range of the target list.
1280 if (!list_empty(target_list)) {
1281 struct defrag_target_range *last;
1283 last = list_entry(target_list->prev,
1284 struct defrag_target_range, list);
1285 ASSERT(last->start + last->len <= cur);
1286 if (last->start + last->len == cur) {
1287 /* Mergeable, enlarge the last entry */
1288 last->len += range_len;
1291 /* Fall through to allocate a new entry */
1294 /* Allocate new defrag_target_range */
1295 new = kmalloc(sizeof(*new), GFP_NOFS);
1297 free_extent_map(em);
1302 new->len = range_len;
1303 list_add_tail(&new->list, target_list);
1306 cur = extent_map_end(em);
1307 free_extent_map(em);
1310 struct defrag_target_range *entry;
1311 struct defrag_target_range *tmp;
1313 list_for_each_entry_safe(entry, tmp, target_list, list) {
1314 list_del_init(&entry->list);
1321 #define CLUSTER_SIZE (SZ_256K)
1324 * Defrag one contiguous target range.
1326 * @inode: target inode
1327 * @target: target range to defrag
1328 * @pages: locked pages covering the defrag range
1329 * @nr_pages: number of locked pages
1331 * Caller should ensure:
1333 * - Pages are prepared
1334 * Pages should be locked, no ordered extent in the pages range,
1337 * - Extent bits are locked
1339 static int defrag_one_locked_target(struct btrfs_inode *inode,
1340 struct defrag_target_range *target,
1341 struct page **pages, int nr_pages,
1342 struct extent_state **cached_state)
1344 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1345 struct extent_changeset *data_reserved = NULL;
1346 const u64 start = target->start;
1347 const u64 len = target->len;
1348 unsigned long last_index = (start + len - 1) >> PAGE_SHIFT;
1349 unsigned long start_index = start >> PAGE_SHIFT;
1350 unsigned long first_index = page_index(pages[0]);
1354 ASSERT(last_index - first_index + 1 <= nr_pages);
1356 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, start, len);
1359 clear_extent_bit(&inode->io_tree, start, start + len - 1,
1360 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
1361 EXTENT_DEFRAG, 0, 0, cached_state);
1362 set_extent_defrag(&inode->io_tree, start, start + len - 1, cached_state);
1364 /* Update the page status */
1365 for (i = start_index - first_index; i <= last_index - first_index; i++) {
1366 ClearPageChecked(pages[i]);
1367 btrfs_page_clamp_set_dirty(fs_info, pages[i], start, len);
1369 btrfs_delalloc_release_extents(inode, len);
1370 extent_changeset_free(data_reserved);
1375 static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
1376 u32 extent_thresh, u64 newer_than, bool do_compress)
1378 struct extent_state *cached_state = NULL;
1379 struct defrag_target_range *entry;
1380 struct defrag_target_range *tmp;
1381 LIST_HEAD(target_list);
1382 struct page **pages;
1383 const u32 sectorsize = inode->root->fs_info->sectorsize;
1384 u64 last_index = (start + len - 1) >> PAGE_SHIFT;
1385 u64 start_index = start >> PAGE_SHIFT;
1386 unsigned int nr_pages = last_index - start_index + 1;
1390 ASSERT(nr_pages <= CLUSTER_SIZE / PAGE_SIZE);
1391 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(len, sectorsize));
1393 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
1397 /* Prepare all pages */
1398 for (i = 0; i < nr_pages; i++) {
1399 pages[i] = defrag_prepare_one_page(inode, start_index + i);
1400 if (IS_ERR(pages[i])) {
1401 ret = PTR_ERR(pages[i]);
1406 for (i = 0; i < nr_pages; i++)
1407 wait_on_page_writeback(pages[i]);
1409 /* Lock the pages range */
1410 lock_extent_bits(&inode->io_tree, start_index << PAGE_SHIFT,
1411 (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1414 * Now we have a consistent view about the extent map, re-check
1415 * which range really needs to be defragged.
1417 * And this time we have extent locked already, pass @locked = true
1418 * so that we won't relock the extent range and cause deadlock.
1420 ret = defrag_collect_targets(inode, start, len, extent_thresh,
1421 newer_than, do_compress, true,
1426 list_for_each_entry(entry, &target_list, list) {
1427 ret = defrag_one_locked_target(inode, entry, pages, nr_pages,
1433 list_for_each_entry_safe(entry, tmp, &target_list, list) {
1434 list_del_init(&entry->list);
1438 unlock_extent_cached(&inode->io_tree, start_index << PAGE_SHIFT,
1439 (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1442 for (i = 0; i < nr_pages; i++) {
1444 unlock_page(pages[i]);
1452 static int defrag_one_cluster(struct btrfs_inode *inode,
1453 struct file_ra_state *ra,
1454 u64 start, u32 len, u32 extent_thresh,
1455 u64 newer_than, bool do_compress,
1456 unsigned long *sectors_defragged,
1457 unsigned long max_sectors)
1459 const u32 sectorsize = inode->root->fs_info->sectorsize;
1460 struct defrag_target_range *entry;
1461 struct defrag_target_range *tmp;
1462 LIST_HEAD(target_list);
1465 BUILD_BUG_ON(!IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
1466 ret = defrag_collect_targets(inode, start, len, extent_thresh,
1467 newer_than, do_compress, false,
1472 list_for_each_entry(entry, &target_list, list) {
1473 u32 range_len = entry->len;
1475 /* Reached or beyond the limit */
1476 if (max_sectors && *sectors_defragged >= max_sectors) {
1482 range_len = min_t(u32, range_len,
1483 (max_sectors - *sectors_defragged) * sectorsize);
1486 page_cache_sync_readahead(inode->vfs_inode.i_mapping,
1487 ra, NULL, entry->start >> PAGE_SHIFT,
1488 ((entry->start + range_len - 1) >> PAGE_SHIFT) -
1489 (entry->start >> PAGE_SHIFT) + 1);
1491 * Here we may not defrag any range if holes are punched before
1492 * we locked the pages.
1493 * But that's fine, it only affects the @sectors_defragged
1496 ret = defrag_one_range(inode, entry->start, range_len,
1497 extent_thresh, newer_than, do_compress);
1500 *sectors_defragged += range_len >>
1501 inode->root->fs_info->sectorsize_bits;
1504 list_for_each_entry_safe(entry, tmp, &target_list, list) {
1505 list_del_init(&entry->list);
1512 * Entry point to file defragmentation.
1514 * @inode: inode to be defragged
1515 * @ra: readahead state (can be NUL)
1516 * @range: defrag options including range and flags
1517 * @newer_than: minimum transid to defrag
1518 * @max_to_defrag: max number of sectors to be defragged, if 0, the whole inode
1519 * will be defragged.
1521 * Return <0 for error.
1522 * Return >=0 for the number of sectors defragged, and range->start will be updated
1523 * to indicate the file offset where next defrag should be started at.
1524 * (Mostly for autodefrag, which sets @max_to_defrag thus we may exit early without
1525 * defragging all the range).
1527 int btrfs_defrag_file(struct inode *inode, struct file_ra_state *ra,
1528 struct btrfs_ioctl_defrag_range_args *range,
1529 u64 newer_than, unsigned long max_to_defrag)
1531 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1532 unsigned long sectors_defragged = 0;
1533 u64 isize = i_size_read(inode);
1536 bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1537 bool ra_allocated = false;
1538 int compress_type = BTRFS_COMPRESS_ZLIB;
1540 u32 extent_thresh = range->extent_thresh;
1541 pgoff_t start_index;
1546 if (range->start >= isize)
1550 if (range->compress_type >= BTRFS_NR_COMPRESS_TYPES)
1552 if (range->compress_type)
1553 compress_type = range->compress_type;
1556 if (extent_thresh == 0)
1557 extent_thresh = SZ_256K;
1559 if (range->start + range->len > range->start) {
1560 /* Got a specific range */
1561 last_byte = min(isize, range->start + range->len);
1563 /* Defrag until file end */
1567 /* Align the range */
1568 cur = round_down(range->start, fs_info->sectorsize);
1569 last_byte = round_up(last_byte, fs_info->sectorsize) - 1;
1572 * If we were not given a ra, allocate a readahead context. As
1573 * readahead is just an optimization, defrag will work without it so
1574 * we don't error out.
1577 ra_allocated = true;
1578 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1580 file_ra_state_init(ra, inode->i_mapping);
1584 * Make writeback start from the beginning of the range, so that the
1585 * defrag range can be written sequentially.
1587 start_index = cur >> PAGE_SHIFT;
1588 if (start_index < inode->i_mapping->writeback_index)
1589 inode->i_mapping->writeback_index = start_index;
1591 while (cur < last_byte) {
1592 const unsigned long prev_sectors_defragged = sectors_defragged;
1595 /* The cluster size 256K should always be page aligned */
1596 BUILD_BUG_ON(!IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
1598 if (btrfs_defrag_cancelled(fs_info)) {
1603 /* We want the cluster end at page boundary when possible */
1604 cluster_end = (((cur >> PAGE_SHIFT) +
1605 (SZ_256K >> PAGE_SHIFT)) << PAGE_SHIFT) - 1;
1606 cluster_end = min(cluster_end, last_byte);
1608 btrfs_inode_lock(inode, 0);
1609 if (IS_SWAPFILE(inode)) {
1611 btrfs_inode_unlock(inode, 0);
1614 if (!(inode->i_sb->s_flags & SB_ACTIVE)) {
1615 btrfs_inode_unlock(inode, 0);
1619 BTRFS_I(inode)->defrag_compress = compress_type;
1620 ret = defrag_one_cluster(BTRFS_I(inode), ra, cur,
1621 cluster_end + 1 - cur, extent_thresh,
1622 newer_than, do_compress,
1623 §ors_defragged, max_to_defrag);
1625 if (sectors_defragged > prev_sectors_defragged)
1626 balance_dirty_pages_ratelimited(inode->i_mapping);
1628 btrfs_inode_unlock(inode, 0);
1631 cur = cluster_end + 1;
1642 * Update range.start for autodefrag, this will indicate where to start
1646 if (sectors_defragged) {
1648 * We have defragged some sectors, for compression case they
1649 * need to be written back immediately.
1651 if (range->flags & BTRFS_DEFRAG_RANGE_START_IO) {
1652 filemap_flush(inode->i_mapping);
1653 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1654 &BTRFS_I(inode)->runtime_flags))
1655 filemap_flush(inode->i_mapping);
1657 if (range->compress_type == BTRFS_COMPRESS_LZO)
1658 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1659 else if (range->compress_type == BTRFS_COMPRESS_ZSTD)
1660 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1661 ret = sectors_defragged;
1664 btrfs_inode_lock(inode, 0);
1665 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1666 btrfs_inode_unlock(inode, 0);
1672 * Try to start exclusive operation @type or cancel it if it's running.
1675 * 0 - normal mode, newly claimed op started
1676 * >0 - normal mode, something else is running,
1677 * return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS to user space
1678 * ECANCELED - cancel mode, successful cancel
1679 * ENOTCONN - cancel mode, operation not running anymore
1681 static int exclop_start_or_cancel_reloc(struct btrfs_fs_info *fs_info,
1682 enum btrfs_exclusive_operation type, bool cancel)
1685 /* Start normal op */
1686 if (!btrfs_exclop_start(fs_info, type))
1687 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1688 /* Exclusive operation is now claimed */
1692 /* Cancel running op */
1693 if (btrfs_exclop_start_try_lock(fs_info, type)) {
1695 * This blocks any exclop finish from setting it to NONE, so we
1696 * request cancellation. Either it runs and we will wait for it,
1697 * or it has finished and no waiting will happen.
1699 atomic_inc(&fs_info->reloc_cancel_req);
1700 btrfs_exclop_start_unlock(fs_info);
1702 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
1703 wait_on_bit(&fs_info->flags, BTRFS_FS_RELOC_RUNNING,
1704 TASK_INTERRUPTIBLE);
1709 /* Something else is running or none */
1713 static noinline int btrfs_ioctl_resize(struct file *file,
1716 BTRFS_DEV_LOOKUP_ARGS(args);
1717 struct inode *inode = file_inode(file);
1718 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1722 struct btrfs_root *root = BTRFS_I(inode)->root;
1723 struct btrfs_ioctl_vol_args *vol_args;
1724 struct btrfs_trans_handle *trans;
1725 struct btrfs_device *device = NULL;
1728 char *devstr = NULL;
1733 if (!capable(CAP_SYS_ADMIN))
1736 ret = mnt_want_write_file(file);
1741 * Read the arguments before checking exclusivity to be able to
1742 * distinguish regular resize and cancel
1744 vol_args = memdup_user(arg, sizeof(*vol_args));
1745 if (IS_ERR(vol_args)) {
1746 ret = PTR_ERR(vol_args);
1749 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1750 sizestr = vol_args->name;
1751 cancel = (strcmp("cancel", sizestr) == 0);
1752 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_RESIZE, cancel);
1755 /* Exclusive operation is now claimed */
1757 devstr = strchr(sizestr, ':');
1759 sizestr = devstr + 1;
1761 devstr = vol_args->name;
1762 ret = kstrtoull(devstr, 10, &devid);
1769 btrfs_info(fs_info, "resizing devid %llu", devid);
1773 device = btrfs_find_device(fs_info->fs_devices, &args);
1775 btrfs_info(fs_info, "resizer unable to find device %llu",
1781 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1783 "resizer unable to apply on readonly device %llu",
1789 if (!strcmp(sizestr, "max"))
1790 new_size = bdev_nr_bytes(device->bdev);
1792 if (sizestr[0] == '-') {
1795 } else if (sizestr[0] == '+') {
1799 new_size = memparse(sizestr, &retptr);
1800 if (*retptr != '\0' || new_size == 0) {
1806 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1811 old_size = btrfs_device_get_total_bytes(device);
1814 if (new_size > old_size) {
1818 new_size = old_size - new_size;
1819 } else if (mod > 0) {
1820 if (new_size > ULLONG_MAX - old_size) {
1824 new_size = old_size + new_size;
1827 if (new_size < SZ_256M) {
1831 if (new_size > bdev_nr_bytes(device->bdev)) {
1836 new_size = round_down(new_size, fs_info->sectorsize);
1838 if (new_size > old_size) {
1839 trans = btrfs_start_transaction(root, 0);
1840 if (IS_ERR(trans)) {
1841 ret = PTR_ERR(trans);
1844 ret = btrfs_grow_device(trans, device, new_size);
1845 btrfs_commit_transaction(trans);
1846 } else if (new_size < old_size) {
1847 ret = btrfs_shrink_device(device, new_size);
1848 } /* equal, nothing need to do */
1850 if (ret == 0 && new_size != old_size)
1851 btrfs_info_in_rcu(fs_info,
1852 "resize device %s (devid %llu) from %llu to %llu",
1853 rcu_str_deref(device->name), device->devid,
1854 old_size, new_size);
1856 btrfs_exclop_finish(fs_info);
1860 mnt_drop_write_file(file);
1864 static noinline int __btrfs_ioctl_snap_create(struct file *file,
1865 struct user_namespace *mnt_userns,
1866 const char *name, unsigned long fd, int subvol,
1868 struct btrfs_qgroup_inherit *inherit)
1873 if (!S_ISDIR(file_inode(file)->i_mode))
1876 ret = mnt_want_write_file(file);
1880 namelen = strlen(name);
1881 if (strchr(name, '/')) {
1883 goto out_drop_write;
1886 if (name[0] == '.' &&
1887 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1889 goto out_drop_write;
1893 ret = btrfs_mksubvol(&file->f_path, mnt_userns, name,
1894 namelen, NULL, readonly, inherit);
1896 struct fd src = fdget(fd);
1897 struct inode *src_inode;
1900 goto out_drop_write;
1903 src_inode = file_inode(src.file);
1904 if (src_inode->i_sb != file_inode(file)->i_sb) {
1905 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1906 "Snapshot src from another FS");
1908 } else if (!inode_owner_or_capable(mnt_userns, src_inode)) {
1910 * Subvolume creation is not restricted, but snapshots
1911 * are limited to own subvolumes only
1915 ret = btrfs_mksnapshot(&file->f_path, mnt_userns,
1917 BTRFS_I(src_inode)->root,
1923 mnt_drop_write_file(file);
1928 static noinline int btrfs_ioctl_snap_create(struct file *file,
1929 void __user *arg, int subvol)
1931 struct btrfs_ioctl_vol_args *vol_args;
1934 if (!S_ISDIR(file_inode(file)->i_mode))
1937 vol_args = memdup_user(arg, sizeof(*vol_args));
1938 if (IS_ERR(vol_args))
1939 return PTR_ERR(vol_args);
1940 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1942 ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
1943 vol_args->name, vol_args->fd, subvol,
1950 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1951 void __user *arg, int subvol)
1953 struct btrfs_ioctl_vol_args_v2 *vol_args;
1955 bool readonly = false;
1956 struct btrfs_qgroup_inherit *inherit = NULL;
1958 if (!S_ISDIR(file_inode(file)->i_mode))
1961 vol_args = memdup_user(arg, sizeof(*vol_args));
1962 if (IS_ERR(vol_args))
1963 return PTR_ERR(vol_args);
1964 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1966 if (vol_args->flags & ~BTRFS_SUBVOL_CREATE_ARGS_MASK) {
1971 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1973 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1976 if (vol_args->size < sizeof(*inherit) ||
1977 vol_args->size > PAGE_SIZE) {
1981 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1982 if (IS_ERR(inherit)) {
1983 ret = PTR_ERR(inherit);
1987 if (inherit->num_qgroups > PAGE_SIZE ||
1988 inherit->num_ref_copies > PAGE_SIZE ||
1989 inherit->num_excl_copies > PAGE_SIZE) {
1994 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
1995 2 * inherit->num_excl_copies;
1996 if (vol_args->size != struct_size(inherit, qgroups, nums)) {
2002 ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
2003 vol_args->name, vol_args->fd, subvol,
2014 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
2017 struct inode *inode = file_inode(file);
2018 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2019 struct btrfs_root *root = BTRFS_I(inode)->root;
2023 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
2026 down_read(&fs_info->subvol_sem);
2027 if (btrfs_root_readonly(root))
2028 flags |= BTRFS_SUBVOL_RDONLY;
2029 up_read(&fs_info->subvol_sem);
2031 if (copy_to_user(arg, &flags, sizeof(flags)))
2037 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
2040 struct inode *inode = file_inode(file);
2041 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2042 struct btrfs_root *root = BTRFS_I(inode)->root;
2043 struct btrfs_trans_handle *trans;
2048 if (!inode_owner_or_capable(file_mnt_user_ns(file), inode))
2051 ret = mnt_want_write_file(file);
2055 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2057 goto out_drop_write;
2060 if (copy_from_user(&flags, arg, sizeof(flags))) {
2062 goto out_drop_write;
2065 if (flags & ~BTRFS_SUBVOL_RDONLY) {
2067 goto out_drop_write;
2070 down_write(&fs_info->subvol_sem);
2073 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
2076 root_flags = btrfs_root_flags(&root->root_item);
2077 if (flags & BTRFS_SUBVOL_RDONLY) {
2078 btrfs_set_root_flags(&root->root_item,
2079 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
2082 * Block RO -> RW transition if this subvolume is involved in
2085 spin_lock(&root->root_item_lock);
2086 if (root->send_in_progress == 0) {
2087 btrfs_set_root_flags(&root->root_item,
2088 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
2089 spin_unlock(&root->root_item_lock);
2091 spin_unlock(&root->root_item_lock);
2093 "Attempt to set subvolume %llu read-write during send",
2094 root->root_key.objectid);
2100 trans = btrfs_start_transaction(root, 1);
2101 if (IS_ERR(trans)) {
2102 ret = PTR_ERR(trans);
2106 ret = btrfs_update_root(trans, fs_info->tree_root,
2107 &root->root_key, &root->root_item);
2109 btrfs_end_transaction(trans);
2113 ret = btrfs_commit_transaction(trans);
2117 btrfs_set_root_flags(&root->root_item, root_flags);
2119 up_write(&fs_info->subvol_sem);
2121 mnt_drop_write_file(file);
2126 static noinline int key_in_sk(struct btrfs_key *key,
2127 struct btrfs_ioctl_search_key *sk)
2129 struct btrfs_key test;
2132 test.objectid = sk->min_objectid;
2133 test.type = sk->min_type;
2134 test.offset = sk->min_offset;
2136 ret = btrfs_comp_cpu_keys(key, &test);
2140 test.objectid = sk->max_objectid;
2141 test.type = sk->max_type;
2142 test.offset = sk->max_offset;
2144 ret = btrfs_comp_cpu_keys(key, &test);
2150 static noinline int copy_to_sk(struct btrfs_path *path,
2151 struct btrfs_key *key,
2152 struct btrfs_ioctl_search_key *sk,
2155 unsigned long *sk_offset,
2159 struct extent_buffer *leaf;
2160 struct btrfs_ioctl_search_header sh;
2161 struct btrfs_key test;
2162 unsigned long item_off;
2163 unsigned long item_len;
2169 leaf = path->nodes[0];
2170 slot = path->slots[0];
2171 nritems = btrfs_header_nritems(leaf);
2173 if (btrfs_header_generation(leaf) > sk->max_transid) {
2177 found_transid = btrfs_header_generation(leaf);
2179 for (i = slot; i < nritems; i++) {
2180 item_off = btrfs_item_ptr_offset(leaf, i);
2181 item_len = btrfs_item_size(leaf, i);
2183 btrfs_item_key_to_cpu(leaf, key, i);
2184 if (!key_in_sk(key, sk))
2187 if (sizeof(sh) + item_len > *buf_size) {
2194 * return one empty item back for v1, which does not
2198 *buf_size = sizeof(sh) + item_len;
2203 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2208 sh.objectid = key->objectid;
2209 sh.offset = key->offset;
2210 sh.type = key->type;
2212 sh.transid = found_transid;
2215 * Copy search result header. If we fault then loop again so we
2216 * can fault in the pages and -EFAULT there if there's a
2217 * problem. Otherwise we'll fault and then copy the buffer in
2218 * properly this next time through
2220 if (copy_to_user_nofault(ubuf + *sk_offset, &sh, sizeof(sh))) {
2225 *sk_offset += sizeof(sh);
2228 char __user *up = ubuf + *sk_offset;
2230 * Copy the item, same behavior as above, but reset the
2231 * * sk_offset so we copy the full thing again.
2233 if (read_extent_buffer_to_user_nofault(leaf, up,
2234 item_off, item_len)) {
2236 *sk_offset -= sizeof(sh);
2240 *sk_offset += item_len;
2244 if (ret) /* -EOVERFLOW from above */
2247 if (*num_found >= sk->nr_items) {
2254 test.objectid = sk->max_objectid;
2255 test.type = sk->max_type;
2256 test.offset = sk->max_offset;
2257 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2259 else if (key->offset < (u64)-1)
2261 else if (key->type < (u8)-1) {
2264 } else if (key->objectid < (u64)-1) {
2272 * 0: all items from this leaf copied, continue with next
2273 * 1: * more items can be copied, but unused buffer is too small
2274 * * all items were found
2275 * Either way, it will stops the loop which iterates to the next
2277 * -EOVERFLOW: item was to large for buffer
2278 * -EFAULT: could not copy extent buffer back to userspace
2283 static noinline int search_ioctl(struct inode *inode,
2284 struct btrfs_ioctl_search_key *sk,
2288 struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2289 struct btrfs_root *root;
2290 struct btrfs_key key;
2291 struct btrfs_path *path;
2294 unsigned long sk_offset = 0;
2296 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2297 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2301 path = btrfs_alloc_path();
2305 if (sk->tree_id == 0) {
2306 /* search the root of the inode that was passed */
2307 root = btrfs_grab_root(BTRFS_I(inode)->root);
2309 root = btrfs_get_fs_root(info, sk->tree_id, true);
2311 btrfs_free_path(path);
2312 return PTR_ERR(root);
2316 key.objectid = sk->min_objectid;
2317 key.type = sk->min_type;
2318 key.offset = sk->min_offset;
2322 if (fault_in_writeable(ubuf + sk_offset, *buf_size - sk_offset))
2325 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2331 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2332 &sk_offset, &num_found);
2333 btrfs_release_path(path);
2341 sk->nr_items = num_found;
2342 btrfs_put_root(root);
2343 btrfs_free_path(path);
2347 static noinline int btrfs_ioctl_tree_search(struct file *file,
2350 struct btrfs_ioctl_search_args __user *uargs;
2351 struct btrfs_ioctl_search_key sk;
2352 struct inode *inode;
2356 if (!capable(CAP_SYS_ADMIN))
2359 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2361 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2364 buf_size = sizeof(uargs->buf);
2366 inode = file_inode(file);
2367 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2370 * In the origin implementation an overflow is handled by returning a
2371 * search header with a len of zero, so reset ret.
2373 if (ret == -EOVERFLOW)
2376 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2381 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2384 struct btrfs_ioctl_search_args_v2 __user *uarg;
2385 struct btrfs_ioctl_search_args_v2 args;
2386 struct inode *inode;
2389 const size_t buf_limit = SZ_16M;
2391 if (!capable(CAP_SYS_ADMIN))
2394 /* copy search header and buffer size */
2395 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2396 if (copy_from_user(&args, uarg, sizeof(args)))
2399 buf_size = args.buf_size;
2401 /* limit result size to 16MB */
2402 if (buf_size > buf_limit)
2403 buf_size = buf_limit;
2405 inode = file_inode(file);
2406 ret = search_ioctl(inode, &args.key, &buf_size,
2407 (char __user *)(&uarg->buf[0]));
2408 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2410 else if (ret == -EOVERFLOW &&
2411 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2418 * Search INODE_REFs to identify path name of 'dirid' directory
2419 * in a 'tree_id' tree. and sets path name to 'name'.
2421 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2422 u64 tree_id, u64 dirid, char *name)
2424 struct btrfs_root *root;
2425 struct btrfs_key key;
2431 struct btrfs_inode_ref *iref;
2432 struct extent_buffer *l;
2433 struct btrfs_path *path;
2435 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2440 path = btrfs_alloc_path();
2444 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2446 root = btrfs_get_fs_root(info, tree_id, true);
2448 ret = PTR_ERR(root);
2453 key.objectid = dirid;
2454 key.type = BTRFS_INODE_REF_KEY;
2455 key.offset = (u64)-1;
2458 ret = btrfs_search_backwards(root, &key, path);
2467 slot = path->slots[0];
2469 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2470 len = btrfs_inode_ref_name_len(l, iref);
2472 total_len += len + 1;
2474 ret = -ENAMETOOLONG;
2479 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2481 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2484 btrfs_release_path(path);
2485 key.objectid = key.offset;
2486 key.offset = (u64)-1;
2487 dirid = key.objectid;
2489 memmove(name, ptr, total_len);
2490 name[total_len] = '\0';
2493 btrfs_put_root(root);
2494 btrfs_free_path(path);
2498 static int btrfs_search_path_in_tree_user(struct user_namespace *mnt_userns,
2499 struct inode *inode,
2500 struct btrfs_ioctl_ino_lookup_user_args *args)
2502 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2503 struct super_block *sb = inode->i_sb;
2504 struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2505 u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2506 u64 dirid = args->dirid;
2507 unsigned long item_off;
2508 unsigned long item_len;
2509 struct btrfs_inode_ref *iref;
2510 struct btrfs_root_ref *rref;
2511 struct btrfs_root *root = NULL;
2512 struct btrfs_path *path;
2513 struct btrfs_key key, key2;
2514 struct extent_buffer *leaf;
2515 struct inode *temp_inode;
2522 path = btrfs_alloc_path();
2527 * If the bottom subvolume does not exist directly under upper_limit,
2528 * construct the path in from the bottom up.
2530 if (dirid != upper_limit.objectid) {
2531 ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2533 root = btrfs_get_fs_root(fs_info, treeid, true);
2535 ret = PTR_ERR(root);
2539 key.objectid = dirid;
2540 key.type = BTRFS_INODE_REF_KEY;
2541 key.offset = (u64)-1;
2543 ret = btrfs_search_backwards(root, &key, path);
2551 leaf = path->nodes[0];
2552 slot = path->slots[0];
2554 iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2555 len = btrfs_inode_ref_name_len(leaf, iref);
2557 total_len += len + 1;
2558 if (ptr < args->path) {
2559 ret = -ENAMETOOLONG;
2564 read_extent_buffer(leaf, ptr,
2565 (unsigned long)(iref + 1), len);
2567 /* Check the read+exec permission of this directory */
2568 ret = btrfs_previous_item(root, path, dirid,
2569 BTRFS_INODE_ITEM_KEY);
2572 } else if (ret > 0) {
2577 leaf = path->nodes[0];
2578 slot = path->slots[0];
2579 btrfs_item_key_to_cpu(leaf, &key2, slot);
2580 if (key2.objectid != dirid) {
2585 temp_inode = btrfs_iget(sb, key2.objectid, root);
2586 if (IS_ERR(temp_inode)) {
2587 ret = PTR_ERR(temp_inode);
2590 ret = inode_permission(mnt_userns, temp_inode,
2591 MAY_READ | MAY_EXEC);
2598 if (key.offset == upper_limit.objectid)
2600 if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2605 btrfs_release_path(path);
2606 key.objectid = key.offset;
2607 key.offset = (u64)-1;
2608 dirid = key.objectid;
2611 memmove(args->path, ptr, total_len);
2612 args->path[total_len] = '\0';
2613 btrfs_put_root(root);
2615 btrfs_release_path(path);
2618 /* Get the bottom subvolume's name from ROOT_REF */
2619 key.objectid = treeid;
2620 key.type = BTRFS_ROOT_REF_KEY;
2621 key.offset = args->treeid;
2622 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2625 } else if (ret > 0) {
2630 leaf = path->nodes[0];
2631 slot = path->slots[0];
2632 btrfs_item_key_to_cpu(leaf, &key, slot);
2634 item_off = btrfs_item_ptr_offset(leaf, slot);
2635 item_len = btrfs_item_size(leaf, slot);
2636 /* Check if dirid in ROOT_REF corresponds to passed dirid */
2637 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2638 if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2643 /* Copy subvolume's name */
2644 item_off += sizeof(struct btrfs_root_ref);
2645 item_len -= sizeof(struct btrfs_root_ref);
2646 read_extent_buffer(leaf, args->name, item_off, item_len);
2647 args->name[item_len] = 0;
2650 btrfs_put_root(root);
2652 btrfs_free_path(path);
2656 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2659 struct btrfs_ioctl_ino_lookup_args *args;
2660 struct inode *inode;
2663 args = memdup_user(argp, sizeof(*args));
2665 return PTR_ERR(args);
2667 inode = file_inode(file);
2670 * Unprivileged query to obtain the containing subvolume root id. The
2671 * path is reset so it's consistent with btrfs_search_path_in_tree.
2673 if (args->treeid == 0)
2674 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2676 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2681 if (!capable(CAP_SYS_ADMIN)) {
2686 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2687 args->treeid, args->objectid,
2691 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2699 * Version of ino_lookup ioctl (unprivileged)
2701 * The main differences from ino_lookup ioctl are:
2703 * 1. Read + Exec permission will be checked using inode_permission() during
2704 * path construction. -EACCES will be returned in case of failure.
2705 * 2. Path construction will be stopped at the inode number which corresponds
2706 * to the fd with which this ioctl is called. If constructed path does not
2707 * exist under fd's inode, -EACCES will be returned.
2708 * 3. The name of bottom subvolume is also searched and filled.
2710 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2712 struct btrfs_ioctl_ino_lookup_user_args *args;
2713 struct inode *inode;
2716 args = memdup_user(argp, sizeof(*args));
2718 return PTR_ERR(args);
2720 inode = file_inode(file);
2722 if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2723 BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2725 * The subvolume does not exist under fd with which this is
2732 ret = btrfs_search_path_in_tree_user(file_mnt_user_ns(file), inode, args);
2734 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2741 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2742 static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2744 struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2745 struct btrfs_fs_info *fs_info;
2746 struct btrfs_root *root;
2747 struct btrfs_path *path;
2748 struct btrfs_key key;
2749 struct btrfs_root_item *root_item;
2750 struct btrfs_root_ref *rref;
2751 struct extent_buffer *leaf;
2752 unsigned long item_off;
2753 unsigned long item_len;
2754 struct inode *inode;
2758 path = btrfs_alloc_path();
2762 subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2764 btrfs_free_path(path);
2768 inode = file_inode(file);
2769 fs_info = BTRFS_I(inode)->root->fs_info;
2771 /* Get root_item of inode's subvolume */
2772 key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2773 root = btrfs_get_fs_root(fs_info, key.objectid, true);
2775 ret = PTR_ERR(root);
2778 root_item = &root->root_item;
2780 subvol_info->treeid = key.objectid;
2782 subvol_info->generation = btrfs_root_generation(root_item);
2783 subvol_info->flags = btrfs_root_flags(root_item);
2785 memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2786 memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2788 memcpy(subvol_info->received_uuid, root_item->received_uuid,
2791 subvol_info->ctransid = btrfs_root_ctransid(root_item);
2792 subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2793 subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2795 subvol_info->otransid = btrfs_root_otransid(root_item);
2796 subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2797 subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2799 subvol_info->stransid = btrfs_root_stransid(root_item);
2800 subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2801 subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2803 subvol_info->rtransid = btrfs_root_rtransid(root_item);
2804 subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2805 subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2807 if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2808 /* Search root tree for ROOT_BACKREF of this subvolume */
2809 key.type = BTRFS_ROOT_BACKREF_KEY;
2811 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2814 } else if (path->slots[0] >=
2815 btrfs_header_nritems(path->nodes[0])) {
2816 ret = btrfs_next_leaf(fs_info->tree_root, path);
2819 } else if (ret > 0) {
2825 leaf = path->nodes[0];
2826 slot = path->slots[0];
2827 btrfs_item_key_to_cpu(leaf, &key, slot);
2828 if (key.objectid == subvol_info->treeid &&
2829 key.type == BTRFS_ROOT_BACKREF_KEY) {
2830 subvol_info->parent_id = key.offset;
2832 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2833 subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2835 item_off = btrfs_item_ptr_offset(leaf, slot)
2836 + sizeof(struct btrfs_root_ref);
2837 item_len = btrfs_item_size(leaf, slot)
2838 - sizeof(struct btrfs_root_ref);
2839 read_extent_buffer(leaf, subvol_info->name,
2840 item_off, item_len);
2847 if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2851 btrfs_put_root(root);
2853 btrfs_free_path(path);
2859 * Return ROOT_REF information of the subvolume containing this inode
2860 * except the subvolume name.
2862 static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
2864 struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
2865 struct btrfs_root_ref *rref;
2866 struct btrfs_root *root;
2867 struct btrfs_path *path;
2868 struct btrfs_key key;
2869 struct extent_buffer *leaf;
2870 struct inode *inode;
2876 path = btrfs_alloc_path();
2880 rootrefs = memdup_user(argp, sizeof(*rootrefs));
2881 if (IS_ERR(rootrefs)) {
2882 btrfs_free_path(path);
2883 return PTR_ERR(rootrefs);
2886 inode = file_inode(file);
2887 root = BTRFS_I(inode)->root->fs_info->tree_root;
2888 objectid = BTRFS_I(inode)->root->root_key.objectid;
2890 key.objectid = objectid;
2891 key.type = BTRFS_ROOT_REF_KEY;
2892 key.offset = rootrefs->min_treeid;
2895 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2898 } else if (path->slots[0] >=
2899 btrfs_header_nritems(path->nodes[0])) {
2900 ret = btrfs_next_leaf(root, path);
2903 } else if (ret > 0) {
2909 leaf = path->nodes[0];
2910 slot = path->slots[0];
2912 btrfs_item_key_to_cpu(leaf, &key, slot);
2913 if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
2918 if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
2923 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2924 rootrefs->rootref[found].treeid = key.offset;
2925 rootrefs->rootref[found].dirid =
2926 btrfs_root_ref_dirid(leaf, rref);
2929 ret = btrfs_next_item(root, path);
2932 } else if (ret > 0) {
2939 if (!ret || ret == -EOVERFLOW) {
2940 rootrefs->num_items = found;
2941 /* update min_treeid for next search */
2943 rootrefs->min_treeid =
2944 rootrefs->rootref[found - 1].treeid + 1;
2945 if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
2950 btrfs_free_path(path);
2955 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2959 struct dentry *parent = file->f_path.dentry;
2960 struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2961 struct dentry *dentry;
2962 struct inode *dir = d_inode(parent);
2963 struct inode *inode;
2964 struct btrfs_root *root = BTRFS_I(dir)->root;
2965 struct btrfs_root *dest = NULL;
2966 struct btrfs_ioctl_vol_args *vol_args = NULL;
2967 struct btrfs_ioctl_vol_args_v2 *vol_args2 = NULL;
2968 struct user_namespace *mnt_userns = file_mnt_user_ns(file);
2969 char *subvol_name, *subvol_name_ptr = NULL;
2972 bool destroy_parent = false;
2975 vol_args2 = memdup_user(arg, sizeof(*vol_args2));
2976 if (IS_ERR(vol_args2))
2977 return PTR_ERR(vol_args2);
2979 if (vol_args2->flags & ~BTRFS_SUBVOL_DELETE_ARGS_MASK) {
2985 * If SPEC_BY_ID is not set, we are looking for the subvolume by
2986 * name, same as v1 currently does.
2988 if (!(vol_args2->flags & BTRFS_SUBVOL_SPEC_BY_ID)) {
2989 vol_args2->name[BTRFS_SUBVOL_NAME_MAX] = 0;
2990 subvol_name = vol_args2->name;
2992 err = mnt_want_write_file(file);
2996 struct inode *old_dir;
2998 if (vol_args2->subvolid < BTRFS_FIRST_FREE_OBJECTID) {
3003 err = mnt_want_write_file(file);
3007 dentry = btrfs_get_dentry(fs_info->sb,
3008 BTRFS_FIRST_FREE_OBJECTID,
3009 vol_args2->subvolid, 0, 0);
3010 if (IS_ERR(dentry)) {
3011 err = PTR_ERR(dentry);
3012 goto out_drop_write;
3016 * Change the default parent since the subvolume being
3017 * deleted can be outside of the current mount point.
3019 parent = btrfs_get_parent(dentry);
3022 * At this point dentry->d_name can point to '/' if the
3023 * subvolume we want to destroy is outsite of the
3024 * current mount point, so we need to release the
3025 * current dentry and execute the lookup to return a new
3026 * one with ->d_name pointing to the
3027 * <mount point>/subvol_name.
3030 if (IS_ERR(parent)) {
3031 err = PTR_ERR(parent);
3032 goto out_drop_write;
3035 dir = d_inode(parent);
3038 * If v2 was used with SPEC_BY_ID, a new parent was
3039 * allocated since the subvolume can be outside of the
3040 * current mount point. Later on we need to release this
3041 * new parent dentry.
3043 destroy_parent = true;
3046 * On idmapped mounts, deletion via subvolid is
3047 * restricted to subvolumes that are immediate
3048 * ancestors of the inode referenced by the file
3049 * descriptor in the ioctl. Otherwise the idmapping
3050 * could potentially be abused to delete subvolumes
3051 * anywhere in the filesystem the user wouldn't be able
3052 * to delete without an idmapped mount.
3054 if (old_dir != dir && mnt_userns != &init_user_ns) {
3059 subvol_name_ptr = btrfs_get_subvol_name_from_objectid(
3060 fs_info, vol_args2->subvolid);
3061 if (IS_ERR(subvol_name_ptr)) {
3062 err = PTR_ERR(subvol_name_ptr);
3065 /* subvol_name_ptr is already nul terminated */
3066 subvol_name = (char *)kbasename(subvol_name_ptr);
3069 vol_args = memdup_user(arg, sizeof(*vol_args));
3070 if (IS_ERR(vol_args))
3071 return PTR_ERR(vol_args);
3073 vol_args->name[BTRFS_PATH_NAME_MAX] = 0;
3074 subvol_name = vol_args->name;
3076 err = mnt_want_write_file(file);
3081 subvol_namelen = strlen(subvol_name);
3083 if (strchr(subvol_name, '/') ||
3084 strncmp(subvol_name, "..", subvol_namelen) == 0) {
3086 goto free_subvol_name;
3089 if (!S_ISDIR(dir->i_mode)) {
3091 goto free_subvol_name;
3094 err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
3096 goto free_subvol_name;
3097 dentry = lookup_one(mnt_userns, subvol_name, parent, subvol_namelen);
3098 if (IS_ERR(dentry)) {
3099 err = PTR_ERR(dentry);
3100 goto out_unlock_dir;
3103 if (d_really_is_negative(dentry)) {
3108 inode = d_inode(dentry);
3109 dest = BTRFS_I(inode)->root;
3110 if (!capable(CAP_SYS_ADMIN)) {
3112 * Regular user. Only allow this with a special mount
3113 * option, when the user has write+exec access to the
3114 * subvol root, and when rmdir(2) would have been
3117 * Note that this is _not_ check that the subvol is
3118 * empty or doesn't contain data that we wouldn't
3119 * otherwise be able to delete.
3121 * Users who want to delete empty subvols should try
3125 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
3129 * Do not allow deletion if the parent dir is the same
3130 * as the dir to be deleted. That means the ioctl
3131 * must be called on the dentry referencing the root
3132 * of the subvol, not a random directory contained
3139 err = inode_permission(mnt_userns, inode, MAY_WRITE | MAY_EXEC);
3144 /* check if subvolume may be deleted by a user */
3145 err = btrfs_may_delete(mnt_userns, dir, dentry, 1);
3149 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
3154 btrfs_inode_lock(inode, 0);
3155 err = btrfs_delete_subvolume(dir, dentry);
3156 btrfs_inode_unlock(inode, 0);
3158 d_delete_notify(dir, dentry);
3163 btrfs_inode_unlock(dir, 0);
3165 kfree(subvol_name_ptr);
3170 mnt_drop_write_file(file);
3177 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
3179 struct inode *inode = file_inode(file);
3180 struct btrfs_root *root = BTRFS_I(inode)->root;
3181 struct btrfs_ioctl_defrag_range_args range = {0};
3184 ret = mnt_want_write_file(file);
3188 if (btrfs_root_readonly(root)) {
3193 switch (inode->i_mode & S_IFMT) {
3195 if (!capable(CAP_SYS_ADMIN)) {
3199 ret = btrfs_defrag_root(root);
3203 * Note that this does not check the file descriptor for write
3204 * access. This prevents defragmenting executables that are
3205 * running and allows defrag on files open in read-only mode.
3207 if (!capable(CAP_SYS_ADMIN) &&
3208 inode_permission(&init_user_ns, inode, MAY_WRITE)) {
3214 if (copy_from_user(&range, argp, sizeof(range))) {
3218 /* compression requires us to start the IO */
3219 if ((range.flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3220 range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
3221 range.extent_thresh = (u32)-1;
3224 /* the rest are all set to zero by kzalloc */
3225 range.len = (u64)-1;
3227 ret = btrfs_defrag_file(file_inode(file), &file->f_ra,
3228 &range, BTRFS_OLDEST_GENERATION, 0);
3236 mnt_drop_write_file(file);
3240 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3242 struct btrfs_ioctl_vol_args *vol_args;
3243 bool restore_op = false;
3246 if (!capable(CAP_SYS_ADMIN))
3249 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_ADD)) {
3250 if (!btrfs_exclop_start_try_lock(fs_info, BTRFS_EXCLOP_DEV_ADD))
3251 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3254 * We can do the device add because we have a paused balanced,
3255 * change the exclusive op type and remember we should bring
3256 * back the paused balance
3258 fs_info->exclusive_operation = BTRFS_EXCLOP_DEV_ADD;
3259 btrfs_exclop_start_unlock(fs_info);
3263 vol_args = memdup_user(arg, sizeof(*vol_args));
3264 if (IS_ERR(vol_args)) {
3265 ret = PTR_ERR(vol_args);
3269 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3270 ret = btrfs_init_new_device(fs_info, vol_args->name);
3273 btrfs_info(fs_info, "disk added %s", vol_args->name);
3278 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
3280 btrfs_exclop_finish(fs_info);
3284 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3286 BTRFS_DEV_LOOKUP_ARGS(args);
3287 struct inode *inode = file_inode(file);
3288 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3289 struct btrfs_ioctl_vol_args_v2 *vol_args;
3290 struct block_device *bdev = NULL;
3293 bool cancel = false;
3295 if (!capable(CAP_SYS_ADMIN))
3298 vol_args = memdup_user(arg, sizeof(*vol_args));
3299 if (IS_ERR(vol_args))
3300 return PTR_ERR(vol_args);
3302 if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
3307 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3308 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3309 args.devid = vol_args->devid;
3310 } else if (!strcmp("cancel", vol_args->name)) {
3313 ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3318 ret = mnt_want_write_file(file);
3322 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3327 /* Exclusive operation is now claimed */
3328 ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3330 btrfs_exclop_finish(fs_info);
3333 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3334 btrfs_info(fs_info, "device deleted: id %llu",
3337 btrfs_info(fs_info, "device deleted: %s",
3341 mnt_drop_write_file(file);
3343 blkdev_put(bdev, mode);
3345 btrfs_put_dev_args_from_path(&args);
3350 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3352 BTRFS_DEV_LOOKUP_ARGS(args);
3353 struct inode *inode = file_inode(file);
3354 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3355 struct btrfs_ioctl_vol_args *vol_args;
3356 struct block_device *bdev = NULL;
3359 bool cancel = false;
3361 if (!capable(CAP_SYS_ADMIN))
3364 vol_args = memdup_user(arg, sizeof(*vol_args));
3365 if (IS_ERR(vol_args))
3366 return PTR_ERR(vol_args);
3368 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3369 if (!strcmp("cancel", vol_args->name)) {
3372 ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3377 ret = mnt_want_write_file(file);
3381 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3384 ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3386 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3387 btrfs_exclop_finish(fs_info);
3390 mnt_drop_write_file(file);
3392 blkdev_put(bdev, mode);
3394 btrfs_put_dev_args_from_path(&args);
3399 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3402 struct btrfs_ioctl_fs_info_args *fi_args;
3403 struct btrfs_device *device;
3404 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3408 fi_args = memdup_user(arg, sizeof(*fi_args));
3409 if (IS_ERR(fi_args))
3410 return PTR_ERR(fi_args);
3412 flags_in = fi_args->flags;
3413 memset(fi_args, 0, sizeof(*fi_args));
3416 fi_args->num_devices = fs_devices->num_devices;
3418 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3419 if (device->devid > fi_args->max_id)
3420 fi_args->max_id = device->devid;
3424 memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3425 fi_args->nodesize = fs_info->nodesize;
3426 fi_args->sectorsize = fs_info->sectorsize;
3427 fi_args->clone_alignment = fs_info->sectorsize;
3429 if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3430 fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3431 fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3432 fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3435 if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
3436 fi_args->generation = fs_info->generation;
3437 fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
3440 if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
3441 memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
3442 sizeof(fi_args->metadata_uuid));
3443 fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
3446 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3453 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3456 BTRFS_DEV_LOOKUP_ARGS(args);
3457 struct btrfs_ioctl_dev_info_args *di_args;
3458 struct btrfs_device *dev;
3461 di_args = memdup_user(arg, sizeof(*di_args));
3462 if (IS_ERR(di_args))
3463 return PTR_ERR(di_args);
3465 args.devid = di_args->devid;
3466 if (!btrfs_is_empty_uuid(di_args->uuid))
3467 args.uuid = di_args->uuid;
3470 dev = btrfs_find_device(fs_info->fs_devices, &args);
3476 di_args->devid = dev->devid;
3477 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3478 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3479 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3481 strncpy(di_args->path, rcu_str_deref(dev->name),
3482 sizeof(di_args->path) - 1);
3483 di_args->path[sizeof(di_args->path) - 1] = 0;
3485 di_args->path[0] = '\0';
3490 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3497 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3499 struct inode *inode = file_inode(file);
3500 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3501 struct btrfs_root *root = BTRFS_I(inode)->root;
3502 struct btrfs_root *new_root;
3503 struct btrfs_dir_item *di;
3504 struct btrfs_trans_handle *trans;
3505 struct btrfs_path *path = NULL;
3506 struct btrfs_disk_key disk_key;
3511 if (!capable(CAP_SYS_ADMIN))
3514 ret = mnt_want_write_file(file);
3518 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3524 objectid = BTRFS_FS_TREE_OBJECTID;
3526 new_root = btrfs_get_fs_root(fs_info, objectid, true);
3527 if (IS_ERR(new_root)) {
3528 ret = PTR_ERR(new_root);
3531 if (!is_fstree(new_root->root_key.objectid)) {
3536 path = btrfs_alloc_path();
3542 trans = btrfs_start_transaction(root, 1);
3543 if (IS_ERR(trans)) {
3544 ret = PTR_ERR(trans);
3548 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3549 di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
3550 dir_id, "default", 7, 1);
3551 if (IS_ERR_OR_NULL(di)) {
3552 btrfs_release_path(path);
3553 btrfs_end_transaction(trans);
3555 "Umm, you don't have the default diritem, this isn't going to work");
3560 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3561 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3562 btrfs_mark_buffer_dirty(path->nodes[0]);
3563 btrfs_release_path(path);
3565 btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
3566 btrfs_end_transaction(trans);
3568 btrfs_put_root(new_root);
3569 btrfs_free_path(path);
3571 mnt_drop_write_file(file);
3575 static void get_block_group_info(struct list_head *groups_list,
3576 struct btrfs_ioctl_space_info *space)
3578 struct btrfs_block_group *block_group;
3580 space->total_bytes = 0;
3581 space->used_bytes = 0;
3583 list_for_each_entry(block_group, groups_list, list) {
3584 space->flags = block_group->flags;
3585 space->total_bytes += block_group->length;
3586 space->used_bytes += block_group->used;
3590 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
3593 struct btrfs_ioctl_space_args space_args;
3594 struct btrfs_ioctl_space_info space;
3595 struct btrfs_ioctl_space_info *dest;
3596 struct btrfs_ioctl_space_info *dest_orig;
3597 struct btrfs_ioctl_space_info __user *user_dest;
3598 struct btrfs_space_info *info;
3599 static const u64 types[] = {
3600 BTRFS_BLOCK_GROUP_DATA,
3601 BTRFS_BLOCK_GROUP_SYSTEM,
3602 BTRFS_BLOCK_GROUP_METADATA,
3603 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3611 if (copy_from_user(&space_args,
3612 (struct btrfs_ioctl_space_args __user *)arg,
3613 sizeof(space_args)))
3616 for (i = 0; i < num_types; i++) {
3617 struct btrfs_space_info *tmp;
3620 list_for_each_entry(tmp, &fs_info->space_info, list) {
3621 if (tmp->flags == types[i]) {
3630 down_read(&info->groups_sem);
3631 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3632 if (!list_empty(&info->block_groups[c]))
3635 up_read(&info->groups_sem);
3639 * Global block reserve, exported as a space_info
3643 /* space_slots == 0 means they are asking for a count */
3644 if (space_args.space_slots == 0) {
3645 space_args.total_spaces = slot_count;
3649 slot_count = min_t(u64, space_args.space_slots, slot_count);
3651 alloc_size = sizeof(*dest) * slot_count;
3653 /* we generally have at most 6 or so space infos, one for each raid
3654 * level. So, a whole page should be more than enough for everyone
3656 if (alloc_size > PAGE_SIZE)
3659 space_args.total_spaces = 0;
3660 dest = kmalloc(alloc_size, GFP_KERNEL);
3665 /* now we have a buffer to copy into */
3666 for (i = 0; i < num_types; i++) {
3667 struct btrfs_space_info *tmp;
3673 list_for_each_entry(tmp, &fs_info->space_info, list) {
3674 if (tmp->flags == types[i]) {
3682 down_read(&info->groups_sem);
3683 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3684 if (!list_empty(&info->block_groups[c])) {
3685 get_block_group_info(&info->block_groups[c],
3687 memcpy(dest, &space, sizeof(space));
3689 space_args.total_spaces++;
3695 up_read(&info->groups_sem);
3699 * Add global block reserve
3702 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3704 spin_lock(&block_rsv->lock);
3705 space.total_bytes = block_rsv->size;
3706 space.used_bytes = block_rsv->size - block_rsv->reserved;
3707 spin_unlock(&block_rsv->lock);
3708 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
3709 memcpy(dest, &space, sizeof(space));
3710 space_args.total_spaces++;
3713 user_dest = (struct btrfs_ioctl_space_info __user *)
3714 (arg + sizeof(struct btrfs_ioctl_space_args));
3716 if (copy_to_user(user_dest, dest_orig, alloc_size))
3721 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3727 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3730 struct btrfs_trans_handle *trans;
3733 trans = btrfs_attach_transaction_barrier(root);
3734 if (IS_ERR(trans)) {
3735 if (PTR_ERR(trans) != -ENOENT)
3736 return PTR_ERR(trans);
3738 /* No running transaction, don't bother */
3739 transid = root->fs_info->last_trans_committed;
3742 transid = trans->transid;
3743 btrfs_commit_transaction_async(trans);
3746 if (copy_to_user(argp, &transid, sizeof(transid)))
3751 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
3757 if (copy_from_user(&transid, argp, sizeof(transid)))
3760 transid = 0; /* current trans */
3762 return btrfs_wait_for_commit(fs_info, transid);
3765 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3767 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
3768 struct btrfs_ioctl_scrub_args *sa;
3771 if (!capable(CAP_SYS_ADMIN))
3774 sa = memdup_user(arg, sizeof(*sa));
3778 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3779 ret = mnt_want_write_file(file);
3784 ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
3785 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3789 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
3790 * error. This is important as it allows user space to know how much
3791 * progress scrub has done. For example, if scrub is canceled we get
3792 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
3793 * space. Later user space can inspect the progress from the structure
3794 * btrfs_ioctl_scrub_args and resume scrub from where it left off
3795 * previously (btrfs-progs does this).
3796 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
3797 * then return -EFAULT to signal the structure was not copied or it may
3798 * be corrupt and unreliable due to a partial copy.
3800 if (copy_to_user(arg, sa, sizeof(*sa)))
3803 if (!(sa->flags & BTRFS_SCRUB_READONLY))
3804 mnt_drop_write_file(file);
3810 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
3812 if (!capable(CAP_SYS_ADMIN))
3815 return btrfs_scrub_cancel(fs_info);
3818 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
3821 struct btrfs_ioctl_scrub_args *sa;
3824 if (!capable(CAP_SYS_ADMIN))
3827 sa = memdup_user(arg, sizeof(*sa));
3831 ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
3833 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3840 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
3843 struct btrfs_ioctl_get_dev_stats *sa;
3846 sa = memdup_user(arg, sizeof(*sa));
3850 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3855 ret = btrfs_get_dev_stats(fs_info, sa);
3857 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3864 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
3867 struct btrfs_ioctl_dev_replace_args *p;
3870 if (!capable(CAP_SYS_ADMIN))
3873 p = memdup_user(arg, sizeof(*p));
3878 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3879 if (sb_rdonly(fs_info->sb)) {
3883 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
3884 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3886 ret = btrfs_dev_replace_by_ioctl(fs_info, p);
3887 btrfs_exclop_finish(fs_info);
3890 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3891 btrfs_dev_replace_status(fs_info, p);
3894 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3895 p->result = btrfs_dev_replace_cancel(fs_info);
3903 if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
3910 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3916 struct btrfs_ioctl_ino_path_args *ipa = NULL;
3917 struct inode_fs_paths *ipath = NULL;
3918 struct btrfs_path *path;
3920 if (!capable(CAP_DAC_READ_SEARCH))
3923 path = btrfs_alloc_path();
3929 ipa = memdup_user(arg, sizeof(*ipa));
3936 size = min_t(u32, ipa->size, 4096);
3937 ipath = init_ipath(size, root, path);
3938 if (IS_ERR(ipath)) {
3939 ret = PTR_ERR(ipath);
3944 ret = paths_from_inode(ipa->inum, ipath);
3948 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3949 rel_ptr = ipath->fspath->val[i] -
3950 (u64)(unsigned long)ipath->fspath->val;
3951 ipath->fspath->val[i] = rel_ptr;
3954 ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
3955 ipath->fspath, size);
3962 btrfs_free_path(path);
3969 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3971 struct btrfs_data_container *inodes = ctx;
3972 const size_t c = 3 * sizeof(u64);
3974 if (inodes->bytes_left >= c) {
3975 inodes->bytes_left -= c;
3976 inodes->val[inodes->elem_cnt] = inum;
3977 inodes->val[inodes->elem_cnt + 1] = offset;
3978 inodes->val[inodes->elem_cnt + 2] = root;
3979 inodes->elem_cnt += 3;
3981 inodes->bytes_missing += c - inodes->bytes_left;
3982 inodes->bytes_left = 0;
3983 inodes->elem_missed += 3;
3989 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
3990 void __user *arg, int version)
3994 struct btrfs_ioctl_logical_ino_args *loi;
3995 struct btrfs_data_container *inodes = NULL;
3996 struct btrfs_path *path = NULL;
3999 if (!capable(CAP_SYS_ADMIN))
4002 loi = memdup_user(arg, sizeof(*loi));
4004 return PTR_ERR(loi);
4007 ignore_offset = false;
4008 size = min_t(u32, loi->size, SZ_64K);
4010 /* All reserved bits must be 0 for now */
4011 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4015 /* Only accept flags we have defined so far */
4016 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4020 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4021 size = min_t(u32, loi->size, SZ_16M);
4024 path = btrfs_alloc_path();
4030 inodes = init_data_container(size);
4031 if (IS_ERR(inodes)) {
4032 ret = PTR_ERR(inodes);
4037 ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4038 build_ino_list, inodes, ignore_offset);
4044 ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4050 btrfs_free_path(path);
4058 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4059 struct btrfs_ioctl_balance_args *bargs)
4061 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4063 bargs->flags = bctl->flags;
4065 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4066 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4067 if (atomic_read(&fs_info->balance_pause_req))
4068 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4069 if (atomic_read(&fs_info->balance_cancel_req))
4070 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4072 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4073 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4074 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4076 spin_lock(&fs_info->balance_lock);
4077 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4078 spin_unlock(&fs_info->balance_lock);
4081 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4083 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4084 struct btrfs_fs_info *fs_info = root->fs_info;
4085 struct btrfs_ioctl_balance_args *bargs;
4086 struct btrfs_balance_control *bctl;
4087 bool need_unlock; /* for mut. excl. ops lock */
4092 "IOC_BALANCE ioctl (v1) is deprecated and will be removed in kernel 5.18");
4094 if (!capable(CAP_SYS_ADMIN))
4097 ret = mnt_want_write_file(file);
4102 if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
4103 mutex_lock(&fs_info->balance_mutex);
4109 * mut. excl. ops lock is locked. Three possibilities:
4110 * (1) some other op is running
4111 * (2) balance is running
4112 * (3) balance is paused -- special case (think resume)
4114 mutex_lock(&fs_info->balance_mutex);
4115 if (fs_info->balance_ctl) {
4116 /* this is either (2) or (3) */
4117 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4118 mutex_unlock(&fs_info->balance_mutex);
4120 * Lock released to allow other waiters to continue,
4121 * we'll reexamine the status again.
4123 mutex_lock(&fs_info->balance_mutex);
4125 if (fs_info->balance_ctl &&
4126 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4128 need_unlock = false;
4132 mutex_unlock(&fs_info->balance_mutex);
4136 mutex_unlock(&fs_info->balance_mutex);
4142 mutex_unlock(&fs_info->balance_mutex);
4143 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4150 bargs = memdup_user(arg, sizeof(*bargs));
4151 if (IS_ERR(bargs)) {
4152 ret = PTR_ERR(bargs);
4156 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4157 if (!fs_info->balance_ctl) {
4162 bctl = fs_info->balance_ctl;
4163 spin_lock(&fs_info->balance_lock);
4164 bctl->flags |= BTRFS_BALANCE_RESUME;
4165 spin_unlock(&fs_info->balance_lock);
4166 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE);
4174 if (fs_info->balance_ctl) {
4179 bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4186 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4187 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4188 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4190 bctl->flags = bargs->flags;
4192 /* balance everything - no filters */
4193 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4196 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4203 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4204 * bctl is freed in reset_balance_state, or, if restriper was paused
4205 * all the way until unmount, in free_fs_info. The flag should be
4206 * cleared after reset_balance_state.
4208 need_unlock = false;
4210 ret = btrfs_balance(fs_info, bctl, bargs);
4213 if ((ret == 0 || ret == -ECANCELED) && arg) {
4214 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4223 mutex_unlock(&fs_info->balance_mutex);
4225 btrfs_exclop_finish(fs_info);
4227 mnt_drop_write_file(file);
4231 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4233 if (!capable(CAP_SYS_ADMIN))
4237 case BTRFS_BALANCE_CTL_PAUSE:
4238 return btrfs_pause_balance(fs_info);
4239 case BTRFS_BALANCE_CTL_CANCEL:
4240 return btrfs_cancel_balance(fs_info);
4246 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4249 struct btrfs_ioctl_balance_args *bargs;
4252 if (!capable(CAP_SYS_ADMIN))
4255 mutex_lock(&fs_info->balance_mutex);
4256 if (!fs_info->balance_ctl) {
4261 bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4267 btrfs_update_ioctl_balance_args(fs_info, bargs);
4269 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4274 mutex_unlock(&fs_info->balance_mutex);
4278 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4280 struct inode *inode = file_inode(file);
4281 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4282 struct btrfs_ioctl_quota_ctl_args *sa;
4285 if (!capable(CAP_SYS_ADMIN))
4288 ret = mnt_want_write_file(file);
4292 sa = memdup_user(arg, sizeof(*sa));
4298 down_write(&fs_info->subvol_sem);
4301 case BTRFS_QUOTA_CTL_ENABLE:
4302 ret = btrfs_quota_enable(fs_info);
4304 case BTRFS_QUOTA_CTL_DISABLE:
4305 ret = btrfs_quota_disable(fs_info);
4313 up_write(&fs_info->subvol_sem);
4315 mnt_drop_write_file(file);
4319 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4321 struct inode *inode = file_inode(file);
4322 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4323 struct btrfs_root *root = BTRFS_I(inode)->root;
4324 struct btrfs_ioctl_qgroup_assign_args *sa;
4325 struct btrfs_trans_handle *trans;
4329 if (!capable(CAP_SYS_ADMIN))
4332 ret = mnt_want_write_file(file);
4336 sa = memdup_user(arg, sizeof(*sa));
4342 trans = btrfs_join_transaction(root);
4343 if (IS_ERR(trans)) {
4344 ret = PTR_ERR(trans);
4349 ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
4351 ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
4354 /* update qgroup status and info */
4355 err = btrfs_run_qgroups(trans);
4357 btrfs_handle_fs_error(fs_info, err,
4358 "failed to update qgroup status and info");
4359 err = btrfs_end_transaction(trans);
4366 mnt_drop_write_file(file);
4370 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4372 struct inode *inode = file_inode(file);
4373 struct btrfs_root *root = BTRFS_I(inode)->root;
4374 struct btrfs_ioctl_qgroup_create_args *sa;
4375 struct btrfs_trans_handle *trans;
4379 if (!capable(CAP_SYS_ADMIN))
4382 ret = mnt_want_write_file(file);
4386 sa = memdup_user(arg, sizeof(*sa));
4392 if (!sa->qgroupid) {
4397 trans = btrfs_join_transaction(root);
4398 if (IS_ERR(trans)) {
4399 ret = PTR_ERR(trans);
4404 ret = btrfs_create_qgroup(trans, sa->qgroupid);
4406 ret = btrfs_remove_qgroup(trans, sa->qgroupid);
4409 err = btrfs_end_transaction(trans);
4416 mnt_drop_write_file(file);
4420 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4422 struct inode *inode = file_inode(file);
4423 struct btrfs_root *root = BTRFS_I(inode)->root;
4424 struct btrfs_ioctl_qgroup_limit_args *sa;
4425 struct btrfs_trans_handle *trans;
4430 if (!capable(CAP_SYS_ADMIN))
4433 ret = mnt_want_write_file(file);
4437 sa = memdup_user(arg, sizeof(*sa));
4443 trans = btrfs_join_transaction(root);
4444 if (IS_ERR(trans)) {
4445 ret = PTR_ERR(trans);
4449 qgroupid = sa->qgroupid;
4451 /* take the current subvol as qgroup */
4452 qgroupid = root->root_key.objectid;
4455 ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
4457 err = btrfs_end_transaction(trans);
4464 mnt_drop_write_file(file);
4468 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4470 struct inode *inode = file_inode(file);
4471 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4472 struct btrfs_ioctl_quota_rescan_args *qsa;
4475 if (!capable(CAP_SYS_ADMIN))
4478 ret = mnt_want_write_file(file);
4482 qsa = memdup_user(arg, sizeof(*qsa));
4493 ret = btrfs_qgroup_rescan(fs_info);
4498 mnt_drop_write_file(file);
4502 static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4505 struct btrfs_ioctl_quota_rescan_args qsa = {0};
4507 if (!capable(CAP_SYS_ADMIN))
4510 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4512 qsa.progress = fs_info->qgroup_rescan_progress.objectid;
4515 if (copy_to_user(arg, &qsa, sizeof(qsa)))
4521 static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4524 if (!capable(CAP_SYS_ADMIN))
4527 return btrfs_qgroup_wait_for_completion(fs_info, true);
4530 static long _btrfs_ioctl_set_received_subvol(struct file *file,
4531 struct user_namespace *mnt_userns,
4532 struct btrfs_ioctl_received_subvol_args *sa)
4534 struct inode *inode = file_inode(file);
4535 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4536 struct btrfs_root *root = BTRFS_I(inode)->root;
4537 struct btrfs_root_item *root_item = &root->root_item;
4538 struct btrfs_trans_handle *trans;
4539 struct timespec64 ct = current_time(inode);
4541 int received_uuid_changed;
4543 if (!inode_owner_or_capable(mnt_userns, inode))
4546 ret = mnt_want_write_file(file);
4550 down_write(&fs_info->subvol_sem);
4552 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
4557 if (btrfs_root_readonly(root)) {
4564 * 2 - uuid items (received uuid + subvol uuid)
4566 trans = btrfs_start_transaction(root, 3);
4567 if (IS_ERR(trans)) {
4568 ret = PTR_ERR(trans);
4573 sa->rtransid = trans->transid;
4574 sa->rtime.sec = ct.tv_sec;
4575 sa->rtime.nsec = ct.tv_nsec;
4577 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4579 if (received_uuid_changed &&
4580 !btrfs_is_empty_uuid(root_item->received_uuid)) {
4581 ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
4582 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4583 root->root_key.objectid);
4584 if (ret && ret != -ENOENT) {
4585 btrfs_abort_transaction(trans, ret);
4586 btrfs_end_transaction(trans);
4590 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4591 btrfs_set_root_stransid(root_item, sa->stransid);
4592 btrfs_set_root_rtransid(root_item, sa->rtransid);
4593 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4594 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4595 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4596 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4598 ret = btrfs_update_root(trans, fs_info->tree_root,
4599 &root->root_key, &root->root_item);
4601 btrfs_end_transaction(trans);
4604 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4605 ret = btrfs_uuid_tree_add(trans, sa->uuid,
4606 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4607 root->root_key.objectid);
4608 if (ret < 0 && ret != -EEXIST) {
4609 btrfs_abort_transaction(trans, ret);
4610 btrfs_end_transaction(trans);
4614 ret = btrfs_commit_transaction(trans);
4616 up_write(&fs_info->subvol_sem);
4617 mnt_drop_write_file(file);
4622 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4625 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4626 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4629 args32 = memdup_user(arg, sizeof(*args32));
4631 return PTR_ERR(args32);
4633 args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
4639 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4640 args64->stransid = args32->stransid;
4641 args64->rtransid = args32->rtransid;
4642 args64->stime.sec = args32->stime.sec;
4643 args64->stime.nsec = args32->stime.nsec;
4644 args64->rtime.sec = args32->rtime.sec;
4645 args64->rtime.nsec = args32->rtime.nsec;
4646 args64->flags = args32->flags;
4648 ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), args64);
4652 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4653 args32->stransid = args64->stransid;
4654 args32->rtransid = args64->rtransid;
4655 args32->stime.sec = args64->stime.sec;
4656 args32->stime.nsec = args64->stime.nsec;
4657 args32->rtime.sec = args64->rtime.sec;
4658 args32->rtime.nsec = args64->rtime.nsec;
4659 args32->flags = args64->flags;
4661 ret = copy_to_user(arg, args32, sizeof(*args32));
4672 static long btrfs_ioctl_set_received_subvol(struct file *file,
4675 struct btrfs_ioctl_received_subvol_args *sa = NULL;
4678 sa = memdup_user(arg, sizeof(*sa));
4682 ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), sa);
4687 ret = copy_to_user(arg, sa, sizeof(*sa));
4696 static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4701 char label[BTRFS_LABEL_SIZE];
4703 spin_lock(&fs_info->super_lock);
4704 memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4705 spin_unlock(&fs_info->super_lock);
4707 len = strnlen(label, BTRFS_LABEL_SIZE);
4709 if (len == BTRFS_LABEL_SIZE) {
4711 "label is too long, return the first %zu bytes",
4715 ret = copy_to_user(arg, label, len);
4717 return ret ? -EFAULT : 0;
4720 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4722 struct inode *inode = file_inode(file);
4723 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4724 struct btrfs_root *root = BTRFS_I(inode)->root;
4725 struct btrfs_super_block *super_block = fs_info->super_copy;
4726 struct btrfs_trans_handle *trans;
4727 char label[BTRFS_LABEL_SIZE];
4730 if (!capable(CAP_SYS_ADMIN))
4733 if (copy_from_user(label, arg, sizeof(label)))
4736 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4738 "unable to set label with more than %d bytes",
4739 BTRFS_LABEL_SIZE - 1);
4743 ret = mnt_want_write_file(file);
4747 trans = btrfs_start_transaction(root, 0);
4748 if (IS_ERR(trans)) {
4749 ret = PTR_ERR(trans);
4753 spin_lock(&fs_info->super_lock);
4754 strcpy(super_block->label, label);
4755 spin_unlock(&fs_info->super_lock);
4756 ret = btrfs_commit_transaction(trans);
4759 mnt_drop_write_file(file);
4763 #define INIT_FEATURE_FLAGS(suffix) \
4764 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
4765 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
4766 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
4768 int btrfs_ioctl_get_supported_features(void __user *arg)
4770 static const struct btrfs_ioctl_feature_flags features[3] = {
4771 INIT_FEATURE_FLAGS(SUPP),
4772 INIT_FEATURE_FLAGS(SAFE_SET),
4773 INIT_FEATURE_FLAGS(SAFE_CLEAR)
4776 if (copy_to_user(arg, &features, sizeof(features)))
4782 static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
4785 struct btrfs_super_block *super_block = fs_info->super_copy;
4786 struct btrfs_ioctl_feature_flags features;
4788 features.compat_flags = btrfs_super_compat_flags(super_block);
4789 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
4790 features.incompat_flags = btrfs_super_incompat_flags(super_block);
4792 if (copy_to_user(arg, &features, sizeof(features)))
4798 static int check_feature_bits(struct btrfs_fs_info *fs_info,
4799 enum btrfs_feature_set set,
4800 u64 change_mask, u64 flags, u64 supported_flags,
4801 u64 safe_set, u64 safe_clear)
4803 const char *type = btrfs_feature_set_name(set);
4805 u64 disallowed, unsupported;
4806 u64 set_mask = flags & change_mask;
4807 u64 clear_mask = ~flags & change_mask;
4809 unsupported = set_mask & ~supported_flags;
4811 names = btrfs_printable_features(set, unsupported);
4814 "this kernel does not support the %s feature bit%s",
4815 names, strchr(names, ',') ? "s" : "");
4819 "this kernel does not support %s bits 0x%llx",
4824 disallowed = set_mask & ~safe_set;
4826 names = btrfs_printable_features(set, disallowed);
4829 "can't set the %s feature bit%s while mounted",
4830 names, strchr(names, ',') ? "s" : "");
4834 "can't set %s bits 0x%llx while mounted",
4839 disallowed = clear_mask & ~safe_clear;
4841 names = btrfs_printable_features(set, disallowed);
4844 "can't clear the %s feature bit%s while mounted",
4845 names, strchr(names, ',') ? "s" : "");
4849 "can't clear %s bits 0x%llx while mounted",
4857 #define check_feature(fs_info, change_mask, flags, mask_base) \
4858 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \
4859 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
4860 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
4861 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
4863 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
4865 struct inode *inode = file_inode(file);
4866 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4867 struct btrfs_root *root = BTRFS_I(inode)->root;
4868 struct btrfs_super_block *super_block = fs_info->super_copy;
4869 struct btrfs_ioctl_feature_flags flags[2];
4870 struct btrfs_trans_handle *trans;
4874 if (!capable(CAP_SYS_ADMIN))
4877 if (copy_from_user(flags, arg, sizeof(flags)))
4881 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
4882 !flags[0].incompat_flags)
4885 ret = check_feature(fs_info, flags[0].compat_flags,
4886 flags[1].compat_flags, COMPAT);
4890 ret = check_feature(fs_info, flags[0].compat_ro_flags,
4891 flags[1].compat_ro_flags, COMPAT_RO);
4895 ret = check_feature(fs_info, flags[0].incompat_flags,
4896 flags[1].incompat_flags, INCOMPAT);
4900 ret = mnt_want_write_file(file);
4904 trans = btrfs_start_transaction(root, 0);
4905 if (IS_ERR(trans)) {
4906 ret = PTR_ERR(trans);
4907 goto out_drop_write;
4910 spin_lock(&fs_info->super_lock);
4911 newflags = btrfs_super_compat_flags(super_block);
4912 newflags |= flags[0].compat_flags & flags[1].compat_flags;
4913 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
4914 btrfs_set_super_compat_flags(super_block, newflags);
4916 newflags = btrfs_super_compat_ro_flags(super_block);
4917 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
4918 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
4919 btrfs_set_super_compat_ro_flags(super_block, newflags);
4921 newflags = btrfs_super_incompat_flags(super_block);
4922 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
4923 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
4924 btrfs_set_super_incompat_flags(super_block, newflags);
4925 spin_unlock(&fs_info->super_lock);
4927 ret = btrfs_commit_transaction(trans);
4929 mnt_drop_write_file(file);
4934 static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
4936 struct btrfs_ioctl_send_args *arg;
4940 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
4941 struct btrfs_ioctl_send_args_32 args32;
4943 ret = copy_from_user(&args32, argp, sizeof(args32));
4946 arg = kzalloc(sizeof(*arg), GFP_KERNEL);
4949 arg->send_fd = args32.send_fd;
4950 arg->clone_sources_count = args32.clone_sources_count;
4951 arg->clone_sources = compat_ptr(args32.clone_sources);
4952 arg->parent_root = args32.parent_root;
4953 arg->flags = args32.flags;
4954 memcpy(arg->reserved, args32.reserved,
4955 sizeof(args32.reserved));
4960 arg = memdup_user(argp, sizeof(*arg));
4962 return PTR_ERR(arg);
4964 ret = btrfs_ioctl_send(file, arg);
4969 long btrfs_ioctl(struct file *file, unsigned int
4970 cmd, unsigned long arg)
4972 struct inode *inode = file_inode(file);
4973 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4974 struct btrfs_root *root = BTRFS_I(inode)->root;
4975 void __user *argp = (void __user *)arg;
4978 case FS_IOC_GETVERSION:
4979 return btrfs_ioctl_getversion(file, argp);
4980 case FS_IOC_GETFSLABEL:
4981 return btrfs_ioctl_get_fslabel(fs_info, argp);
4982 case FS_IOC_SETFSLABEL:
4983 return btrfs_ioctl_set_fslabel(file, argp);
4985 return btrfs_ioctl_fitrim(fs_info, argp);
4986 case BTRFS_IOC_SNAP_CREATE:
4987 return btrfs_ioctl_snap_create(file, argp, 0);
4988 case BTRFS_IOC_SNAP_CREATE_V2:
4989 return btrfs_ioctl_snap_create_v2(file, argp, 0);
4990 case BTRFS_IOC_SUBVOL_CREATE:
4991 return btrfs_ioctl_snap_create(file, argp, 1);
4992 case BTRFS_IOC_SUBVOL_CREATE_V2:
4993 return btrfs_ioctl_snap_create_v2(file, argp, 1);
4994 case BTRFS_IOC_SNAP_DESTROY:
4995 return btrfs_ioctl_snap_destroy(file, argp, false);
4996 case BTRFS_IOC_SNAP_DESTROY_V2:
4997 return btrfs_ioctl_snap_destroy(file, argp, true);
4998 case BTRFS_IOC_SUBVOL_GETFLAGS:
4999 return btrfs_ioctl_subvol_getflags(file, argp);
5000 case BTRFS_IOC_SUBVOL_SETFLAGS:
5001 return btrfs_ioctl_subvol_setflags(file, argp);
5002 case BTRFS_IOC_DEFAULT_SUBVOL:
5003 return btrfs_ioctl_default_subvol(file, argp);
5004 case BTRFS_IOC_DEFRAG:
5005 return btrfs_ioctl_defrag(file, NULL);
5006 case BTRFS_IOC_DEFRAG_RANGE:
5007 return btrfs_ioctl_defrag(file, argp);
5008 case BTRFS_IOC_RESIZE:
5009 return btrfs_ioctl_resize(file, argp);
5010 case BTRFS_IOC_ADD_DEV:
5011 return btrfs_ioctl_add_dev(fs_info, argp);
5012 case BTRFS_IOC_RM_DEV:
5013 return btrfs_ioctl_rm_dev(file, argp);
5014 case BTRFS_IOC_RM_DEV_V2:
5015 return btrfs_ioctl_rm_dev_v2(file, argp);
5016 case BTRFS_IOC_FS_INFO:
5017 return btrfs_ioctl_fs_info(fs_info, argp);
5018 case BTRFS_IOC_DEV_INFO:
5019 return btrfs_ioctl_dev_info(fs_info, argp);
5020 case BTRFS_IOC_BALANCE:
5021 return btrfs_ioctl_balance(file, NULL);
5022 case BTRFS_IOC_TREE_SEARCH:
5023 return btrfs_ioctl_tree_search(file, argp);
5024 case BTRFS_IOC_TREE_SEARCH_V2:
5025 return btrfs_ioctl_tree_search_v2(file, argp);
5026 case BTRFS_IOC_INO_LOOKUP:
5027 return btrfs_ioctl_ino_lookup(file, argp);
5028 case BTRFS_IOC_INO_PATHS:
5029 return btrfs_ioctl_ino_to_path(root, argp);
5030 case BTRFS_IOC_LOGICAL_INO:
5031 return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5032 case BTRFS_IOC_LOGICAL_INO_V2:
5033 return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
5034 case BTRFS_IOC_SPACE_INFO:
5035 return btrfs_ioctl_space_info(fs_info, argp);
5036 case BTRFS_IOC_SYNC: {
5039 ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
5042 ret = btrfs_sync_fs(inode->i_sb, 1);
5044 * The transaction thread may want to do more work,
5045 * namely it pokes the cleaner kthread that will start
5046 * processing uncleaned subvols.
5048 wake_up_process(fs_info->transaction_kthread);
5051 case BTRFS_IOC_START_SYNC:
5052 return btrfs_ioctl_start_sync(root, argp);
5053 case BTRFS_IOC_WAIT_SYNC:
5054 return btrfs_ioctl_wait_sync(fs_info, argp);
5055 case BTRFS_IOC_SCRUB:
5056 return btrfs_ioctl_scrub(file, argp);
5057 case BTRFS_IOC_SCRUB_CANCEL:
5058 return btrfs_ioctl_scrub_cancel(fs_info);
5059 case BTRFS_IOC_SCRUB_PROGRESS:
5060 return btrfs_ioctl_scrub_progress(fs_info, argp);
5061 case BTRFS_IOC_BALANCE_V2:
5062 return btrfs_ioctl_balance(file, argp);
5063 case BTRFS_IOC_BALANCE_CTL:
5064 return btrfs_ioctl_balance_ctl(fs_info, arg);
5065 case BTRFS_IOC_BALANCE_PROGRESS:
5066 return btrfs_ioctl_balance_progress(fs_info, argp);
5067 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5068 return btrfs_ioctl_set_received_subvol(file, argp);
5070 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5071 return btrfs_ioctl_set_received_subvol_32(file, argp);
5073 case BTRFS_IOC_SEND:
5074 return _btrfs_ioctl_send(file, argp, false);
5075 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5076 case BTRFS_IOC_SEND_32:
5077 return _btrfs_ioctl_send(file, argp, true);
5079 case BTRFS_IOC_GET_DEV_STATS:
5080 return btrfs_ioctl_get_dev_stats(fs_info, argp);
5081 case BTRFS_IOC_QUOTA_CTL:
5082 return btrfs_ioctl_quota_ctl(file, argp);
5083 case BTRFS_IOC_QGROUP_ASSIGN:
5084 return btrfs_ioctl_qgroup_assign(file, argp);
5085 case BTRFS_IOC_QGROUP_CREATE:
5086 return btrfs_ioctl_qgroup_create(file, argp);
5087 case BTRFS_IOC_QGROUP_LIMIT:
5088 return btrfs_ioctl_qgroup_limit(file, argp);
5089 case BTRFS_IOC_QUOTA_RESCAN:
5090 return btrfs_ioctl_quota_rescan(file, argp);
5091 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5092 return btrfs_ioctl_quota_rescan_status(fs_info, argp);
5093 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5094 return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
5095 case BTRFS_IOC_DEV_REPLACE:
5096 return btrfs_ioctl_dev_replace(fs_info, argp);
5097 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5098 return btrfs_ioctl_get_supported_features(argp);
5099 case BTRFS_IOC_GET_FEATURES:
5100 return btrfs_ioctl_get_features(fs_info, argp);
5101 case BTRFS_IOC_SET_FEATURES:
5102 return btrfs_ioctl_set_features(file, argp);
5103 case BTRFS_IOC_GET_SUBVOL_INFO:
5104 return btrfs_ioctl_get_subvol_info(file, argp);
5105 case BTRFS_IOC_GET_SUBVOL_ROOTREF:
5106 return btrfs_ioctl_get_subvol_rootref(file, argp);
5107 case BTRFS_IOC_INO_LOOKUP_USER:
5108 return btrfs_ioctl_ino_lookup_user(file, argp);
5109 case FS_IOC_ENABLE_VERITY:
5110 return fsverity_ioctl_enable(file, (const void __user *)argp);
5111 case FS_IOC_MEASURE_VERITY:
5112 return fsverity_ioctl_measure(file, argp);
5118 #ifdef CONFIG_COMPAT
5119 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5122 * These all access 32-bit values anyway so no further
5123 * handling is necessary.
5126 case FS_IOC32_GETVERSION:
5127 cmd = FS_IOC_GETVERSION;
5131 return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));