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 * - not BTRFS_EXCLOP_NONE - this is intentionally incompatible and the caller
391 * must check the condition first that would allow none -> @type
393 bool btrfs_exclop_start_try_lock(struct btrfs_fs_info *fs_info,
394 enum btrfs_exclusive_operation type)
396 spin_lock(&fs_info->super_lock);
397 if (fs_info->exclusive_operation == type)
400 spin_unlock(&fs_info->super_lock);
404 void btrfs_exclop_start_unlock(struct btrfs_fs_info *fs_info)
406 spin_unlock(&fs_info->super_lock);
409 void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
411 spin_lock(&fs_info->super_lock);
412 WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
413 spin_unlock(&fs_info->super_lock);
414 sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
417 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
419 struct inode *inode = file_inode(file);
421 return put_user(inode->i_generation, arg);
424 static noinline int btrfs_ioctl_fitrim(struct btrfs_fs_info *fs_info,
427 struct btrfs_device *device;
428 struct request_queue *q;
429 struct fstrim_range range;
430 u64 minlen = ULLONG_MAX;
434 if (!capable(CAP_SYS_ADMIN))
438 * btrfs_trim_block_group() depends on space cache, which is not
439 * available in zoned filesystem. So, disallow fitrim on a zoned
440 * filesystem for now.
442 if (btrfs_is_zoned(fs_info))
446 * If the fs is mounted with nologreplay, which requires it to be
447 * mounted in RO mode as well, we can not allow discard on free space
448 * inside block groups, because log trees refer to extents that are not
449 * pinned in a block group's free space cache (pinning the extents is
450 * precisely the first phase of replaying a log tree).
452 if (btrfs_test_opt(fs_info, NOLOGREPLAY))
456 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
460 q = bdev_get_queue(device->bdev);
461 if (blk_queue_discard(q)) {
463 minlen = min_t(u64, q->limits.discard_granularity,
471 if (copy_from_user(&range, arg, sizeof(range)))
475 * NOTE: Don't truncate the range using super->total_bytes. Bytenr of
476 * block group is in the logical address space, which can be any
477 * sectorsize aligned bytenr in the range [0, U64_MAX].
479 if (range.len < fs_info->sb->s_blocksize)
482 range.minlen = max(range.minlen, minlen);
483 ret = btrfs_trim_fs(fs_info, &range);
487 if (copy_to_user(arg, &range, sizeof(range)))
493 int __pure btrfs_is_empty_uuid(u8 *uuid)
497 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
504 static noinline int create_subvol(struct user_namespace *mnt_userns,
505 struct inode *dir, struct dentry *dentry,
506 const char *name, int namelen,
507 struct btrfs_qgroup_inherit *inherit)
509 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
510 struct btrfs_trans_handle *trans;
511 struct btrfs_key key;
512 struct btrfs_root_item *root_item;
513 struct btrfs_inode_item *inode_item;
514 struct extent_buffer *leaf;
515 struct btrfs_root *root = BTRFS_I(dir)->root;
516 struct btrfs_root *new_root;
517 struct btrfs_block_rsv block_rsv;
518 struct timespec64 cur_time = current_time(dir);
526 root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
530 ret = btrfs_get_free_objectid(fs_info->tree_root, &objectid);
534 ret = get_anon_bdev(&anon_dev);
539 * Don't create subvolume whose level is not zero. Or qgroup will be
540 * screwed up since it assumes subvolume qgroup's level to be 0.
542 if (btrfs_qgroup_level(objectid)) {
547 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
549 * The same as the snapshot creation, please see the comment
550 * of create_snapshot().
552 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
556 trans = btrfs_start_transaction(root, 0);
558 ret = PTR_ERR(trans);
559 btrfs_subvolume_release_metadata(root, &block_rsv);
562 trans->block_rsv = &block_rsv;
563 trans->bytes_reserved = block_rsv.size;
565 ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
569 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
570 BTRFS_NESTING_NORMAL);
576 btrfs_mark_buffer_dirty(leaf);
578 inode_item = &root_item->inode;
579 btrfs_set_stack_inode_generation(inode_item, 1);
580 btrfs_set_stack_inode_size(inode_item, 3);
581 btrfs_set_stack_inode_nlink(inode_item, 1);
582 btrfs_set_stack_inode_nbytes(inode_item,
584 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
586 btrfs_set_root_flags(root_item, 0);
587 btrfs_set_root_limit(root_item, 0);
588 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
590 btrfs_set_root_bytenr(root_item, leaf->start);
591 btrfs_set_root_generation(root_item, trans->transid);
592 btrfs_set_root_level(root_item, 0);
593 btrfs_set_root_refs(root_item, 1);
594 btrfs_set_root_used(root_item, leaf->len);
595 btrfs_set_root_last_snapshot(root_item, 0);
597 btrfs_set_root_generation_v2(root_item,
598 btrfs_root_generation(root_item));
599 generate_random_guid(root_item->uuid);
600 btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
601 btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
602 root_item->ctime = root_item->otime;
603 btrfs_set_root_ctransid(root_item, trans->transid);
604 btrfs_set_root_otransid(root_item, trans->transid);
606 btrfs_tree_unlock(leaf);
608 btrfs_set_root_dirid(root_item, BTRFS_FIRST_FREE_OBJECTID);
610 key.objectid = objectid;
612 key.type = BTRFS_ROOT_ITEM_KEY;
613 ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
617 * Since we don't abort the transaction in this case, free the
618 * tree block so that we don't leak space and leave the
619 * filesystem in an inconsistent state (an extent item in the
620 * extent tree without backreferences). Also no need to have
621 * the tree block locked since it is not in any tree at this
622 * point, so no other task can find it and use it.
624 btrfs_free_tree_block(trans, root, leaf, 0, 1);
625 free_extent_buffer(leaf);
629 free_extent_buffer(leaf);
632 key.offset = (u64)-1;
633 new_root = btrfs_get_new_fs_root(fs_info, objectid, anon_dev);
634 if (IS_ERR(new_root)) {
635 free_anon_bdev(anon_dev);
636 ret = PTR_ERR(new_root);
637 btrfs_abort_transaction(trans, ret);
640 /* Freeing will be done in btrfs_put_root() of new_root */
643 ret = btrfs_record_root_in_trans(trans, new_root);
645 btrfs_put_root(new_root);
646 btrfs_abort_transaction(trans, ret);
650 ret = btrfs_create_subvol_root(trans, new_root, root, mnt_userns);
651 btrfs_put_root(new_root);
653 /* We potentially lose an unused inode item here */
654 btrfs_abort_transaction(trans, ret);
659 * insert the directory item
661 ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
663 btrfs_abort_transaction(trans, ret);
667 ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
668 BTRFS_FT_DIR, index);
670 btrfs_abort_transaction(trans, ret);
674 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
675 ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
677 btrfs_abort_transaction(trans, ret);
681 ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
682 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
684 btrfs_abort_transaction(trans, ret);
688 ret = btrfs_uuid_tree_add(trans, root_item->uuid,
689 BTRFS_UUID_KEY_SUBVOL, objectid);
691 btrfs_abort_transaction(trans, ret);
695 trans->block_rsv = NULL;
696 trans->bytes_reserved = 0;
697 btrfs_subvolume_release_metadata(root, &block_rsv);
699 err = btrfs_commit_transaction(trans);
704 inode = btrfs_lookup_dentry(dir, dentry);
706 return PTR_ERR(inode);
707 d_instantiate(dentry, inode);
713 free_anon_bdev(anon_dev);
718 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
719 struct dentry *dentry, bool readonly,
720 struct btrfs_qgroup_inherit *inherit)
722 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
724 struct btrfs_pending_snapshot *pending_snapshot;
725 struct btrfs_trans_handle *trans;
728 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
731 if (atomic_read(&root->nr_swapfiles)) {
733 "cannot snapshot subvolume with active swapfile");
737 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
738 if (!pending_snapshot)
741 ret = get_anon_bdev(&pending_snapshot->anon_dev);
744 pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
746 pending_snapshot->path = btrfs_alloc_path();
747 if (!pending_snapshot->root_item || !pending_snapshot->path) {
752 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
753 BTRFS_BLOCK_RSV_TEMP);
755 * 1 - parent dir inode
758 * 2 - root ref/backref
759 * 1 - root of snapshot
762 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
763 &pending_snapshot->block_rsv, 8,
768 pending_snapshot->dentry = dentry;
769 pending_snapshot->root = root;
770 pending_snapshot->readonly = readonly;
771 pending_snapshot->dir = dir;
772 pending_snapshot->inherit = inherit;
774 trans = btrfs_start_transaction(root, 0);
776 ret = PTR_ERR(trans);
780 spin_lock(&fs_info->trans_lock);
781 list_add(&pending_snapshot->list,
782 &trans->transaction->pending_snapshots);
783 spin_unlock(&fs_info->trans_lock);
785 ret = btrfs_commit_transaction(trans);
789 ret = pending_snapshot->error;
793 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
797 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
799 ret = PTR_ERR(inode);
803 d_instantiate(dentry, inode);
805 pending_snapshot->anon_dev = 0;
807 /* Prevent double freeing of anon_dev */
808 if (ret && pending_snapshot->snap)
809 pending_snapshot->snap->anon_dev = 0;
810 btrfs_put_root(pending_snapshot->snap);
811 btrfs_subvolume_release_metadata(root, &pending_snapshot->block_rsv);
813 if (pending_snapshot->anon_dev)
814 free_anon_bdev(pending_snapshot->anon_dev);
815 kfree(pending_snapshot->root_item);
816 btrfs_free_path(pending_snapshot->path);
817 kfree(pending_snapshot);
822 /* copy of may_delete in fs/namei.c()
823 * Check whether we can remove a link victim from directory dir, check
824 * whether the type of victim is right.
825 * 1. We can't do it if dir is read-only (done in permission())
826 * 2. We should have write and exec permissions on dir
827 * 3. We can't remove anything from append-only dir
828 * 4. We can't do anything with immutable dir (done in permission())
829 * 5. If the sticky bit on dir is set we should either
830 * a. be owner of dir, or
831 * b. be owner of victim, or
832 * c. have CAP_FOWNER capability
833 * 6. If the victim is append-only or immutable we can't do anything with
834 * links pointing to it.
835 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
836 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
837 * 9. We can't remove a root or mountpoint.
838 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
839 * nfs_async_unlink().
842 static int btrfs_may_delete(struct user_namespace *mnt_userns,
843 struct inode *dir, struct dentry *victim, int isdir)
847 if (d_really_is_negative(victim))
850 BUG_ON(d_inode(victim->d_parent) != dir);
851 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
853 error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
858 if (check_sticky(mnt_userns, dir, d_inode(victim)) ||
859 IS_APPEND(d_inode(victim)) || IS_IMMUTABLE(d_inode(victim)) ||
860 IS_SWAPFILE(d_inode(victim)))
863 if (!d_is_dir(victim))
867 } else if (d_is_dir(victim))
871 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
876 /* copy of may_create in fs/namei.c() */
877 static inline int btrfs_may_create(struct user_namespace *mnt_userns,
878 struct inode *dir, struct dentry *child)
880 if (d_really_is_positive(child))
884 if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
886 return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
890 * Create a new subvolume below @parent. This is largely modeled after
891 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
892 * inside this filesystem so it's quite a bit simpler.
894 static noinline int btrfs_mksubvol(const struct path *parent,
895 struct user_namespace *mnt_userns,
896 const char *name, int namelen,
897 struct btrfs_root *snap_src,
899 struct btrfs_qgroup_inherit *inherit)
901 struct inode *dir = d_inode(parent->dentry);
902 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
903 struct dentry *dentry;
906 error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
910 dentry = lookup_one(mnt_userns, name, parent->dentry, namelen);
911 error = PTR_ERR(dentry);
915 error = btrfs_may_create(mnt_userns, dir, dentry);
920 * even if this name doesn't exist, we may get hash collisions.
921 * check for them now when we can safely fail
923 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
929 down_read(&fs_info->subvol_sem);
931 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
935 error = create_snapshot(snap_src, dir, dentry, readonly, inherit);
937 error = create_subvol(mnt_userns, dir, dentry, name, namelen, inherit);
940 fsnotify_mkdir(dir, dentry);
942 up_read(&fs_info->subvol_sem);
946 btrfs_inode_unlock(dir, 0);
950 static noinline int btrfs_mksnapshot(const struct path *parent,
951 struct user_namespace *mnt_userns,
952 const char *name, int namelen,
953 struct btrfs_root *root,
955 struct btrfs_qgroup_inherit *inherit)
958 bool snapshot_force_cow = false;
961 * Force new buffered writes to reserve space even when NOCOW is
962 * possible. This is to avoid later writeback (running dealloc) to
963 * fallback to COW mode and unexpectedly fail with ENOSPC.
965 btrfs_drew_read_lock(&root->snapshot_lock);
967 ret = btrfs_start_delalloc_snapshot(root, false);
972 * All previous writes have started writeback in NOCOW mode, so now
973 * we force future writes to fallback to COW mode during snapshot
976 atomic_inc(&root->snapshot_force_cow);
977 snapshot_force_cow = true;
979 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
981 ret = btrfs_mksubvol(parent, mnt_userns, name, namelen,
982 root, readonly, inherit);
984 if (snapshot_force_cow)
985 atomic_dec(&root->snapshot_force_cow);
986 btrfs_drew_read_unlock(&root->snapshot_lock);
990 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start,
993 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
994 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
995 struct extent_map *em;
996 const u32 sectorsize = BTRFS_I(inode)->root->fs_info->sectorsize;
999 * hopefully we have this extent in the tree already, try without
1000 * the full extent lock
1002 read_lock(&em_tree->lock);
1003 em = lookup_extent_mapping(em_tree, start, sectorsize);
1004 read_unlock(&em_tree->lock);
1007 struct extent_state *cached = NULL;
1008 u64 end = start + sectorsize - 1;
1010 /* get the big lock and read metadata off disk */
1012 lock_extent_bits(io_tree, start, end, &cached);
1013 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, sectorsize);
1015 unlock_extent_cached(io_tree, start, end, &cached);
1024 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em,
1027 struct extent_map *next;
1030 /* this is the last extent */
1031 if (em->start + em->len >= i_size_read(inode))
1034 next = defrag_lookup_extent(inode, em->start + em->len, locked);
1035 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1037 else if ((em->block_start + em->block_len == next->block_start) &&
1038 (em->block_len > SZ_128K && next->block_len > SZ_128K))
1041 free_extent_map(next);
1046 * Prepare one page to be defragged.
1050 * - Returned page is locked and has been set up properly.
1051 * - No ordered extent exists in the page.
1052 * - The page is uptodate.
1054 * NOTE: Caller should also wait for page writeback after the cluster is
1055 * prepared, here we don't do writeback wait for each page.
1057 static struct page *defrag_prepare_one_page(struct btrfs_inode *inode,
1060 struct address_space *mapping = inode->vfs_inode.i_mapping;
1061 gfp_t mask = btrfs_alloc_write_mask(mapping);
1062 u64 page_start = (u64)index << PAGE_SHIFT;
1063 u64 page_end = page_start + PAGE_SIZE - 1;
1064 struct extent_state *cached_state = NULL;
1069 page = find_or_create_page(mapping, index, mask);
1071 return ERR_PTR(-ENOMEM);
1074 * Since we can defragment files opened read-only, we can encounter
1075 * transparent huge pages here (see CONFIG_READ_ONLY_THP_FOR_FS). We
1076 * can't do I/O using huge pages yet, so return an error for now.
1077 * Filesystem transparent huge pages are typically only used for
1078 * executables that explicitly enable them, so this isn't very
1081 if (PageCompound(page)) {
1084 return ERR_PTR(-ETXTBSY);
1087 ret = set_page_extent_mapped(page);
1091 return ERR_PTR(ret);
1094 /* Wait for any existing ordered extent in the range */
1096 struct btrfs_ordered_extent *ordered;
1098 lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
1099 ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
1100 unlock_extent_cached(&inode->io_tree, page_start, page_end,
1106 btrfs_start_ordered_extent(ordered, 1);
1107 btrfs_put_ordered_extent(ordered);
1110 * We unlocked the page above, so we need check if it was
1113 if (page->mapping != mapping || !PagePrivate(page)) {
1121 * Now the page range has no ordered extent any more. Read the page to
1124 if (!PageUptodate(page)) {
1125 btrfs_readpage(NULL, page);
1127 if (page->mapping != mapping || !PagePrivate(page)) {
1132 if (!PageUptodate(page)) {
1135 return ERR_PTR(-EIO);
1141 struct defrag_target_range {
1142 struct list_head list;
1148 * Collect all valid target extents.
1150 * @start: file offset to lookup
1151 * @len: length to lookup
1152 * @extent_thresh: file extent size threshold, any extent size >= this value
1154 * @newer_than: only defrag extents newer than this value
1155 * @do_compress: whether the defrag is doing compression
1156 * if true, @extent_thresh will be ignored and all regular
1157 * file extents meeting @newer_than will be targets.
1158 * @locked: if the range has already held extent lock
1159 * @target_list: list of targets file extents
1161 static int defrag_collect_targets(struct btrfs_inode *inode,
1162 u64 start, u64 len, u32 extent_thresh,
1163 u64 newer_than, bool do_compress,
1164 bool locked, struct list_head *target_list)
1169 while (cur < start + len) {
1170 struct extent_map *em;
1171 struct defrag_target_range *new;
1172 bool next_mergeable = true;
1175 em = defrag_lookup_extent(&inode->vfs_inode, cur, locked);
1179 /* Skip hole/inline/preallocated extents */
1180 if (em->block_start >= EXTENT_MAP_LAST_BYTE ||
1181 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1184 /* Skip older extent */
1185 if (em->generation < newer_than)
1189 * For do_compress case, we want to compress all valid file
1190 * extents, thus no @extent_thresh or mergeable check.
1195 /* Skip too large extent */
1196 if (em->len >= extent_thresh)
1199 next_mergeable = defrag_check_next_extent(&inode->vfs_inode, em,
1201 if (!next_mergeable) {
1202 struct defrag_target_range *last;
1204 /* Empty target list, no way to merge with last entry */
1205 if (list_empty(target_list))
1207 last = list_entry(target_list->prev,
1208 struct defrag_target_range, list);
1209 /* Not mergeable with last entry */
1210 if (last->start + last->len != cur)
1213 /* Mergeable, fall through to add it to @target_list. */
1217 range_len = min(extent_map_end(em), start + len) - cur;
1219 * This one is a good target, check if it can be merged into
1220 * last range of the target list.
1222 if (!list_empty(target_list)) {
1223 struct defrag_target_range *last;
1225 last = list_entry(target_list->prev,
1226 struct defrag_target_range, list);
1227 ASSERT(last->start + last->len <= cur);
1228 if (last->start + last->len == cur) {
1229 /* Mergeable, enlarge the last entry */
1230 last->len += range_len;
1233 /* Fall through to allocate a new entry */
1236 /* Allocate new defrag_target_range */
1237 new = kmalloc(sizeof(*new), GFP_NOFS);
1239 free_extent_map(em);
1244 new->len = range_len;
1245 list_add_tail(&new->list, target_list);
1248 cur = extent_map_end(em);
1249 free_extent_map(em);
1252 struct defrag_target_range *entry;
1253 struct defrag_target_range *tmp;
1255 list_for_each_entry_safe(entry, tmp, target_list, list) {
1256 list_del_init(&entry->list);
1263 #define CLUSTER_SIZE (SZ_256K)
1266 * Defrag one contiguous target range.
1268 * @inode: target inode
1269 * @target: target range to defrag
1270 * @pages: locked pages covering the defrag range
1271 * @nr_pages: number of locked pages
1273 * Caller should ensure:
1275 * - Pages are prepared
1276 * Pages should be locked, no ordered extent in the pages range,
1279 * - Extent bits are locked
1281 static int defrag_one_locked_target(struct btrfs_inode *inode,
1282 struct defrag_target_range *target,
1283 struct page **pages, int nr_pages,
1284 struct extent_state **cached_state)
1286 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1287 struct extent_changeset *data_reserved = NULL;
1288 const u64 start = target->start;
1289 const u64 len = target->len;
1290 unsigned long last_index = (start + len - 1) >> PAGE_SHIFT;
1291 unsigned long start_index = start >> PAGE_SHIFT;
1292 unsigned long first_index = page_index(pages[0]);
1296 ASSERT(last_index - first_index + 1 <= nr_pages);
1298 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, start, len);
1301 clear_extent_bit(&inode->io_tree, start, start + len - 1,
1302 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
1303 EXTENT_DEFRAG, 0, 0, cached_state);
1304 set_extent_defrag(&inode->io_tree, start, start + len - 1, cached_state);
1306 /* Update the page status */
1307 for (i = start_index - first_index; i <= last_index - first_index; i++) {
1308 ClearPageChecked(pages[i]);
1309 btrfs_page_clamp_set_dirty(fs_info, pages[i], start, len);
1311 btrfs_delalloc_release_extents(inode, len);
1312 extent_changeset_free(data_reserved);
1317 static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
1318 u32 extent_thresh, u64 newer_than, bool do_compress)
1320 struct extent_state *cached_state = NULL;
1321 struct defrag_target_range *entry;
1322 struct defrag_target_range *tmp;
1323 LIST_HEAD(target_list);
1324 struct page **pages;
1325 const u32 sectorsize = inode->root->fs_info->sectorsize;
1326 u64 last_index = (start + len - 1) >> PAGE_SHIFT;
1327 u64 start_index = start >> PAGE_SHIFT;
1328 unsigned int nr_pages = last_index - start_index + 1;
1332 ASSERT(nr_pages <= CLUSTER_SIZE / PAGE_SIZE);
1333 ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(len, sectorsize));
1335 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
1339 /* Prepare all pages */
1340 for (i = 0; i < nr_pages; i++) {
1341 pages[i] = defrag_prepare_one_page(inode, start_index + i);
1342 if (IS_ERR(pages[i])) {
1343 ret = PTR_ERR(pages[i]);
1348 for (i = 0; i < nr_pages; i++)
1349 wait_on_page_writeback(pages[i]);
1351 /* Lock the pages range */
1352 lock_extent_bits(&inode->io_tree, start_index << PAGE_SHIFT,
1353 (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1356 * Now we have a consistent view about the extent map, re-check
1357 * which range really needs to be defragged.
1359 * And this time we have extent locked already, pass @locked = true
1360 * so that we won't relock the extent range and cause deadlock.
1362 ret = defrag_collect_targets(inode, start, len, extent_thresh,
1363 newer_than, do_compress, true,
1368 list_for_each_entry(entry, &target_list, list) {
1369 ret = defrag_one_locked_target(inode, entry, pages, nr_pages,
1375 list_for_each_entry_safe(entry, tmp, &target_list, list) {
1376 list_del_init(&entry->list);
1380 unlock_extent_cached(&inode->io_tree, start_index << PAGE_SHIFT,
1381 (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1384 for (i = 0; i < nr_pages; i++) {
1386 unlock_page(pages[i]);
1394 static int defrag_one_cluster(struct btrfs_inode *inode,
1395 struct file_ra_state *ra,
1396 u64 start, u32 len, u32 extent_thresh,
1397 u64 newer_than, bool do_compress,
1398 unsigned long *sectors_defragged,
1399 unsigned long max_sectors)
1401 const u32 sectorsize = inode->root->fs_info->sectorsize;
1402 struct defrag_target_range *entry;
1403 struct defrag_target_range *tmp;
1404 LIST_HEAD(target_list);
1407 BUILD_BUG_ON(!IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
1408 ret = defrag_collect_targets(inode, start, len, extent_thresh,
1409 newer_than, do_compress, false,
1414 list_for_each_entry(entry, &target_list, list) {
1415 u32 range_len = entry->len;
1417 /* Reached the limit */
1418 if (max_sectors && max_sectors == *sectors_defragged)
1422 range_len = min_t(u32, range_len,
1423 (max_sectors - *sectors_defragged) * sectorsize);
1426 page_cache_sync_readahead(inode->vfs_inode.i_mapping,
1427 ra, NULL, entry->start >> PAGE_SHIFT,
1428 ((entry->start + range_len - 1) >> PAGE_SHIFT) -
1429 (entry->start >> PAGE_SHIFT) + 1);
1431 * Here we may not defrag any range if holes are punched before
1432 * we locked the pages.
1433 * But that's fine, it only affects the @sectors_defragged
1436 ret = defrag_one_range(inode, entry->start, range_len,
1437 extent_thresh, newer_than, do_compress);
1440 *sectors_defragged += range_len;
1443 list_for_each_entry_safe(entry, tmp, &target_list, list) {
1444 list_del_init(&entry->list);
1451 * Entry point to file defragmentation.
1453 * @inode: inode to be defragged
1454 * @ra: readahead state (can be NUL)
1455 * @range: defrag options including range and flags
1456 * @newer_than: minimum transid to defrag
1457 * @max_to_defrag: max number of sectors to be defragged, if 0, the whole inode
1458 * will be defragged.
1460 int btrfs_defrag_file(struct inode *inode, struct file_ra_state *ra,
1461 struct btrfs_ioctl_defrag_range_args *range,
1462 u64 newer_than, unsigned long max_to_defrag)
1464 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1465 unsigned long sectors_defragged = 0;
1466 u64 isize = i_size_read(inode);
1469 bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1470 bool ra_allocated = false;
1471 int compress_type = BTRFS_COMPRESS_ZLIB;
1473 u32 extent_thresh = range->extent_thresh;
1478 if (range->start >= isize)
1482 if (range->compress_type >= BTRFS_NR_COMPRESS_TYPES)
1484 if (range->compress_type)
1485 compress_type = range->compress_type;
1488 if (extent_thresh == 0)
1489 extent_thresh = SZ_256K;
1491 if (range->start + range->len > range->start) {
1492 /* Got a specific range */
1493 last_byte = min(isize, range->start + range->len) - 1;
1495 /* Defrag until file end */
1496 last_byte = isize - 1;
1500 * If we were not given a ra, allocate a readahead context. As
1501 * readahead is just an optimization, defrag will work without it so
1502 * we don't error out.
1505 ra_allocated = true;
1506 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1508 file_ra_state_init(ra, inode->i_mapping);
1511 /* Align the range */
1512 cur = round_down(range->start, fs_info->sectorsize);
1513 last_byte = round_up(last_byte, fs_info->sectorsize) - 1;
1515 while (cur < last_byte) {
1518 /* The cluster size 256K should always be page aligned */
1519 BUILD_BUG_ON(!IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
1521 /* We want the cluster end at page boundary when possible */
1522 cluster_end = (((cur >> PAGE_SHIFT) +
1523 (SZ_256K >> PAGE_SHIFT)) << PAGE_SHIFT) - 1;
1524 cluster_end = min(cluster_end, last_byte);
1526 btrfs_inode_lock(inode, 0);
1527 if (IS_SWAPFILE(inode)) {
1529 btrfs_inode_unlock(inode, 0);
1532 if (!(inode->i_sb->s_flags & SB_ACTIVE)) {
1533 btrfs_inode_unlock(inode, 0);
1537 BTRFS_I(inode)->defrag_compress = compress_type;
1538 ret = defrag_one_cluster(BTRFS_I(inode), ra, cur,
1539 cluster_end + 1 - cur, extent_thresh,
1540 newer_than, do_compress,
1541 §ors_defragged, max_to_defrag);
1542 btrfs_inode_unlock(inode, 0);
1545 cur = cluster_end + 1;
1550 if (sectors_defragged) {
1552 * We have defragged some sectors, for compression case they
1553 * need to be written back immediately.
1555 if (range->flags & BTRFS_DEFRAG_RANGE_START_IO) {
1556 filemap_flush(inode->i_mapping);
1557 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1558 &BTRFS_I(inode)->runtime_flags))
1559 filemap_flush(inode->i_mapping);
1561 if (range->compress_type == BTRFS_COMPRESS_LZO)
1562 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1563 else if (range->compress_type == BTRFS_COMPRESS_ZSTD)
1564 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1565 ret = sectors_defragged;
1568 btrfs_inode_lock(inode, 0);
1569 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1570 btrfs_inode_unlock(inode, 0);
1576 * Try to start exclusive operation @type or cancel it if it's running.
1579 * 0 - normal mode, newly claimed op started
1580 * >0 - normal mode, something else is running,
1581 * return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS to user space
1582 * ECANCELED - cancel mode, successful cancel
1583 * ENOTCONN - cancel mode, operation not running anymore
1585 static int exclop_start_or_cancel_reloc(struct btrfs_fs_info *fs_info,
1586 enum btrfs_exclusive_operation type, bool cancel)
1589 /* Start normal op */
1590 if (!btrfs_exclop_start(fs_info, type))
1591 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1592 /* Exclusive operation is now claimed */
1596 /* Cancel running op */
1597 if (btrfs_exclop_start_try_lock(fs_info, type)) {
1599 * This blocks any exclop finish from setting it to NONE, so we
1600 * request cancellation. Either it runs and we will wait for it,
1601 * or it has finished and no waiting will happen.
1603 atomic_inc(&fs_info->reloc_cancel_req);
1604 btrfs_exclop_start_unlock(fs_info);
1606 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
1607 wait_on_bit(&fs_info->flags, BTRFS_FS_RELOC_RUNNING,
1608 TASK_INTERRUPTIBLE);
1613 /* Something else is running or none */
1617 static noinline int btrfs_ioctl_resize(struct file *file,
1620 BTRFS_DEV_LOOKUP_ARGS(args);
1621 struct inode *inode = file_inode(file);
1622 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1626 struct btrfs_root *root = BTRFS_I(inode)->root;
1627 struct btrfs_ioctl_vol_args *vol_args;
1628 struct btrfs_trans_handle *trans;
1629 struct btrfs_device *device = NULL;
1632 char *devstr = NULL;
1637 if (!capable(CAP_SYS_ADMIN))
1640 ret = mnt_want_write_file(file);
1645 * Read the arguments before checking exclusivity to be able to
1646 * distinguish regular resize and cancel
1648 vol_args = memdup_user(arg, sizeof(*vol_args));
1649 if (IS_ERR(vol_args)) {
1650 ret = PTR_ERR(vol_args);
1653 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1654 sizestr = vol_args->name;
1655 cancel = (strcmp("cancel", sizestr) == 0);
1656 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_RESIZE, cancel);
1659 /* Exclusive operation is now claimed */
1661 devstr = strchr(sizestr, ':');
1663 sizestr = devstr + 1;
1665 devstr = vol_args->name;
1666 ret = kstrtoull(devstr, 10, &devid);
1673 btrfs_info(fs_info, "resizing devid %llu", devid);
1677 device = btrfs_find_device(fs_info->fs_devices, &args);
1679 btrfs_info(fs_info, "resizer unable to find device %llu",
1685 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1687 "resizer unable to apply on readonly device %llu",
1693 if (!strcmp(sizestr, "max"))
1694 new_size = bdev_nr_bytes(device->bdev);
1696 if (sizestr[0] == '-') {
1699 } else if (sizestr[0] == '+') {
1703 new_size = memparse(sizestr, &retptr);
1704 if (*retptr != '\0' || new_size == 0) {
1710 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1715 old_size = btrfs_device_get_total_bytes(device);
1718 if (new_size > old_size) {
1722 new_size = old_size - new_size;
1723 } else if (mod > 0) {
1724 if (new_size > ULLONG_MAX - old_size) {
1728 new_size = old_size + new_size;
1731 if (new_size < SZ_256M) {
1735 if (new_size > bdev_nr_bytes(device->bdev)) {
1740 new_size = round_down(new_size, fs_info->sectorsize);
1742 if (new_size > old_size) {
1743 trans = btrfs_start_transaction(root, 0);
1744 if (IS_ERR(trans)) {
1745 ret = PTR_ERR(trans);
1748 ret = btrfs_grow_device(trans, device, new_size);
1749 btrfs_commit_transaction(trans);
1750 } else if (new_size < old_size) {
1751 ret = btrfs_shrink_device(device, new_size);
1752 } /* equal, nothing need to do */
1754 if (ret == 0 && new_size != old_size)
1755 btrfs_info_in_rcu(fs_info,
1756 "resize device %s (devid %llu) from %llu to %llu",
1757 rcu_str_deref(device->name), device->devid,
1758 old_size, new_size);
1760 btrfs_exclop_finish(fs_info);
1764 mnt_drop_write_file(file);
1768 static noinline int __btrfs_ioctl_snap_create(struct file *file,
1769 struct user_namespace *mnt_userns,
1770 const char *name, unsigned long fd, int subvol,
1772 struct btrfs_qgroup_inherit *inherit)
1777 if (!S_ISDIR(file_inode(file)->i_mode))
1780 ret = mnt_want_write_file(file);
1784 namelen = strlen(name);
1785 if (strchr(name, '/')) {
1787 goto out_drop_write;
1790 if (name[0] == '.' &&
1791 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1793 goto out_drop_write;
1797 ret = btrfs_mksubvol(&file->f_path, mnt_userns, name,
1798 namelen, NULL, readonly, inherit);
1800 struct fd src = fdget(fd);
1801 struct inode *src_inode;
1804 goto out_drop_write;
1807 src_inode = file_inode(src.file);
1808 if (src_inode->i_sb != file_inode(file)->i_sb) {
1809 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1810 "Snapshot src from another FS");
1812 } else if (!inode_owner_or_capable(mnt_userns, src_inode)) {
1814 * Subvolume creation is not restricted, but snapshots
1815 * are limited to own subvolumes only
1819 ret = btrfs_mksnapshot(&file->f_path, mnt_userns,
1821 BTRFS_I(src_inode)->root,
1827 mnt_drop_write_file(file);
1832 static noinline int btrfs_ioctl_snap_create(struct file *file,
1833 void __user *arg, int subvol)
1835 struct btrfs_ioctl_vol_args *vol_args;
1838 if (!S_ISDIR(file_inode(file)->i_mode))
1841 vol_args = memdup_user(arg, sizeof(*vol_args));
1842 if (IS_ERR(vol_args))
1843 return PTR_ERR(vol_args);
1844 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1846 ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
1847 vol_args->name, vol_args->fd, subvol,
1854 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1855 void __user *arg, int subvol)
1857 struct btrfs_ioctl_vol_args_v2 *vol_args;
1859 bool readonly = false;
1860 struct btrfs_qgroup_inherit *inherit = NULL;
1862 if (!S_ISDIR(file_inode(file)->i_mode))
1865 vol_args = memdup_user(arg, sizeof(*vol_args));
1866 if (IS_ERR(vol_args))
1867 return PTR_ERR(vol_args);
1868 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1870 if (vol_args->flags & ~BTRFS_SUBVOL_CREATE_ARGS_MASK) {
1875 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1877 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1880 if (vol_args->size < sizeof(*inherit) ||
1881 vol_args->size > PAGE_SIZE) {
1885 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1886 if (IS_ERR(inherit)) {
1887 ret = PTR_ERR(inherit);
1891 if (inherit->num_qgroups > PAGE_SIZE ||
1892 inherit->num_ref_copies > PAGE_SIZE ||
1893 inherit->num_excl_copies > PAGE_SIZE) {
1898 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
1899 2 * inherit->num_excl_copies;
1900 if (vol_args->size != struct_size(inherit, qgroups, nums)) {
1906 ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
1907 vol_args->name, vol_args->fd, subvol,
1918 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1921 struct inode *inode = file_inode(file);
1922 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1923 struct btrfs_root *root = BTRFS_I(inode)->root;
1927 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1930 down_read(&fs_info->subvol_sem);
1931 if (btrfs_root_readonly(root))
1932 flags |= BTRFS_SUBVOL_RDONLY;
1933 up_read(&fs_info->subvol_sem);
1935 if (copy_to_user(arg, &flags, sizeof(flags)))
1941 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1944 struct inode *inode = file_inode(file);
1945 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1946 struct btrfs_root *root = BTRFS_I(inode)->root;
1947 struct btrfs_trans_handle *trans;
1952 if (!inode_owner_or_capable(file_mnt_user_ns(file), inode))
1955 ret = mnt_want_write_file(file);
1959 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1961 goto out_drop_write;
1964 if (copy_from_user(&flags, arg, sizeof(flags))) {
1966 goto out_drop_write;
1969 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1971 goto out_drop_write;
1974 down_write(&fs_info->subvol_sem);
1977 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1980 root_flags = btrfs_root_flags(&root->root_item);
1981 if (flags & BTRFS_SUBVOL_RDONLY) {
1982 btrfs_set_root_flags(&root->root_item,
1983 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1986 * Block RO -> RW transition if this subvolume is involved in
1989 spin_lock(&root->root_item_lock);
1990 if (root->send_in_progress == 0) {
1991 btrfs_set_root_flags(&root->root_item,
1992 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1993 spin_unlock(&root->root_item_lock);
1995 spin_unlock(&root->root_item_lock);
1997 "Attempt to set subvolume %llu read-write during send",
1998 root->root_key.objectid);
2004 trans = btrfs_start_transaction(root, 1);
2005 if (IS_ERR(trans)) {
2006 ret = PTR_ERR(trans);
2010 ret = btrfs_update_root(trans, fs_info->tree_root,
2011 &root->root_key, &root->root_item);
2013 btrfs_end_transaction(trans);
2017 ret = btrfs_commit_transaction(trans);
2021 btrfs_set_root_flags(&root->root_item, root_flags);
2023 up_write(&fs_info->subvol_sem);
2025 mnt_drop_write_file(file);
2030 static noinline int key_in_sk(struct btrfs_key *key,
2031 struct btrfs_ioctl_search_key *sk)
2033 struct btrfs_key test;
2036 test.objectid = sk->min_objectid;
2037 test.type = sk->min_type;
2038 test.offset = sk->min_offset;
2040 ret = btrfs_comp_cpu_keys(key, &test);
2044 test.objectid = sk->max_objectid;
2045 test.type = sk->max_type;
2046 test.offset = sk->max_offset;
2048 ret = btrfs_comp_cpu_keys(key, &test);
2054 static noinline int copy_to_sk(struct btrfs_path *path,
2055 struct btrfs_key *key,
2056 struct btrfs_ioctl_search_key *sk,
2059 unsigned long *sk_offset,
2063 struct extent_buffer *leaf;
2064 struct btrfs_ioctl_search_header sh;
2065 struct btrfs_key test;
2066 unsigned long item_off;
2067 unsigned long item_len;
2073 leaf = path->nodes[0];
2074 slot = path->slots[0];
2075 nritems = btrfs_header_nritems(leaf);
2077 if (btrfs_header_generation(leaf) > sk->max_transid) {
2081 found_transid = btrfs_header_generation(leaf);
2083 for (i = slot; i < nritems; i++) {
2084 item_off = btrfs_item_ptr_offset(leaf, i);
2085 item_len = btrfs_item_size_nr(leaf, i);
2087 btrfs_item_key_to_cpu(leaf, key, i);
2088 if (!key_in_sk(key, sk))
2091 if (sizeof(sh) + item_len > *buf_size) {
2098 * return one empty item back for v1, which does not
2102 *buf_size = sizeof(sh) + item_len;
2107 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2112 sh.objectid = key->objectid;
2113 sh.offset = key->offset;
2114 sh.type = key->type;
2116 sh.transid = found_transid;
2119 * Copy search result header. If we fault then loop again so we
2120 * can fault in the pages and -EFAULT there if there's a
2121 * problem. Otherwise we'll fault and then copy the buffer in
2122 * properly this next time through
2124 if (copy_to_user_nofault(ubuf + *sk_offset, &sh, sizeof(sh))) {
2129 *sk_offset += sizeof(sh);
2132 char __user *up = ubuf + *sk_offset;
2134 * Copy the item, same behavior as above, but reset the
2135 * * sk_offset so we copy the full thing again.
2137 if (read_extent_buffer_to_user_nofault(leaf, up,
2138 item_off, item_len)) {
2140 *sk_offset -= sizeof(sh);
2144 *sk_offset += item_len;
2148 if (ret) /* -EOVERFLOW from above */
2151 if (*num_found >= sk->nr_items) {
2158 test.objectid = sk->max_objectid;
2159 test.type = sk->max_type;
2160 test.offset = sk->max_offset;
2161 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2163 else if (key->offset < (u64)-1)
2165 else if (key->type < (u8)-1) {
2168 } else if (key->objectid < (u64)-1) {
2176 * 0: all items from this leaf copied, continue with next
2177 * 1: * more items can be copied, but unused buffer is too small
2178 * * all items were found
2179 * Either way, it will stops the loop which iterates to the next
2181 * -EOVERFLOW: item was to large for buffer
2182 * -EFAULT: could not copy extent buffer back to userspace
2187 static noinline int search_ioctl(struct inode *inode,
2188 struct btrfs_ioctl_search_key *sk,
2192 struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2193 struct btrfs_root *root;
2194 struct btrfs_key key;
2195 struct btrfs_path *path;
2198 unsigned long sk_offset = 0;
2200 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2201 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2205 path = btrfs_alloc_path();
2209 if (sk->tree_id == 0) {
2210 /* search the root of the inode that was passed */
2211 root = btrfs_grab_root(BTRFS_I(inode)->root);
2213 root = btrfs_get_fs_root(info, sk->tree_id, true);
2215 btrfs_free_path(path);
2216 return PTR_ERR(root);
2220 key.objectid = sk->min_objectid;
2221 key.type = sk->min_type;
2222 key.offset = sk->min_offset;
2226 if (fault_in_writeable(ubuf + sk_offset, *buf_size - sk_offset))
2229 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2235 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2236 &sk_offset, &num_found);
2237 btrfs_release_path(path);
2245 sk->nr_items = num_found;
2246 btrfs_put_root(root);
2247 btrfs_free_path(path);
2251 static noinline int btrfs_ioctl_tree_search(struct file *file,
2254 struct btrfs_ioctl_search_args __user *uargs;
2255 struct btrfs_ioctl_search_key sk;
2256 struct inode *inode;
2260 if (!capable(CAP_SYS_ADMIN))
2263 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2265 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2268 buf_size = sizeof(uargs->buf);
2270 inode = file_inode(file);
2271 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2274 * In the origin implementation an overflow is handled by returning a
2275 * search header with a len of zero, so reset ret.
2277 if (ret == -EOVERFLOW)
2280 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2285 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2288 struct btrfs_ioctl_search_args_v2 __user *uarg;
2289 struct btrfs_ioctl_search_args_v2 args;
2290 struct inode *inode;
2293 const size_t buf_limit = SZ_16M;
2295 if (!capable(CAP_SYS_ADMIN))
2298 /* copy search header and buffer size */
2299 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2300 if (copy_from_user(&args, uarg, sizeof(args)))
2303 buf_size = args.buf_size;
2305 /* limit result size to 16MB */
2306 if (buf_size > buf_limit)
2307 buf_size = buf_limit;
2309 inode = file_inode(file);
2310 ret = search_ioctl(inode, &args.key, &buf_size,
2311 (char __user *)(&uarg->buf[0]));
2312 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2314 else if (ret == -EOVERFLOW &&
2315 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2322 * Search INODE_REFs to identify path name of 'dirid' directory
2323 * in a 'tree_id' tree. and sets path name to 'name'.
2325 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2326 u64 tree_id, u64 dirid, char *name)
2328 struct btrfs_root *root;
2329 struct btrfs_key key;
2335 struct btrfs_inode_ref *iref;
2336 struct extent_buffer *l;
2337 struct btrfs_path *path;
2339 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2344 path = btrfs_alloc_path();
2348 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2350 root = btrfs_get_fs_root(info, tree_id, true);
2352 ret = PTR_ERR(root);
2357 key.objectid = dirid;
2358 key.type = BTRFS_INODE_REF_KEY;
2359 key.offset = (u64)-1;
2362 ret = btrfs_search_backwards(root, &key, path);
2371 slot = path->slots[0];
2373 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2374 len = btrfs_inode_ref_name_len(l, iref);
2376 total_len += len + 1;
2378 ret = -ENAMETOOLONG;
2383 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2385 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2388 btrfs_release_path(path);
2389 key.objectid = key.offset;
2390 key.offset = (u64)-1;
2391 dirid = key.objectid;
2393 memmove(name, ptr, total_len);
2394 name[total_len] = '\0';
2397 btrfs_put_root(root);
2398 btrfs_free_path(path);
2402 static int btrfs_search_path_in_tree_user(struct user_namespace *mnt_userns,
2403 struct inode *inode,
2404 struct btrfs_ioctl_ino_lookup_user_args *args)
2406 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2407 struct super_block *sb = inode->i_sb;
2408 struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2409 u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2410 u64 dirid = args->dirid;
2411 unsigned long item_off;
2412 unsigned long item_len;
2413 struct btrfs_inode_ref *iref;
2414 struct btrfs_root_ref *rref;
2415 struct btrfs_root *root = NULL;
2416 struct btrfs_path *path;
2417 struct btrfs_key key, key2;
2418 struct extent_buffer *leaf;
2419 struct inode *temp_inode;
2426 path = btrfs_alloc_path();
2431 * If the bottom subvolume does not exist directly under upper_limit,
2432 * construct the path in from the bottom up.
2434 if (dirid != upper_limit.objectid) {
2435 ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2437 root = btrfs_get_fs_root(fs_info, treeid, true);
2439 ret = PTR_ERR(root);
2443 key.objectid = dirid;
2444 key.type = BTRFS_INODE_REF_KEY;
2445 key.offset = (u64)-1;
2447 ret = btrfs_search_backwards(root, &key, path);
2455 leaf = path->nodes[0];
2456 slot = path->slots[0];
2458 iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2459 len = btrfs_inode_ref_name_len(leaf, iref);
2461 total_len += len + 1;
2462 if (ptr < args->path) {
2463 ret = -ENAMETOOLONG;
2468 read_extent_buffer(leaf, ptr,
2469 (unsigned long)(iref + 1), len);
2471 /* Check the read+exec permission of this directory */
2472 ret = btrfs_previous_item(root, path, dirid,
2473 BTRFS_INODE_ITEM_KEY);
2476 } else if (ret > 0) {
2481 leaf = path->nodes[0];
2482 slot = path->slots[0];
2483 btrfs_item_key_to_cpu(leaf, &key2, slot);
2484 if (key2.objectid != dirid) {
2489 temp_inode = btrfs_iget(sb, key2.objectid, root);
2490 if (IS_ERR(temp_inode)) {
2491 ret = PTR_ERR(temp_inode);
2494 ret = inode_permission(mnt_userns, temp_inode,
2495 MAY_READ | MAY_EXEC);
2502 if (key.offset == upper_limit.objectid)
2504 if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2509 btrfs_release_path(path);
2510 key.objectid = key.offset;
2511 key.offset = (u64)-1;
2512 dirid = key.objectid;
2515 memmove(args->path, ptr, total_len);
2516 args->path[total_len] = '\0';
2517 btrfs_put_root(root);
2519 btrfs_release_path(path);
2522 /* Get the bottom subvolume's name from ROOT_REF */
2523 key.objectid = treeid;
2524 key.type = BTRFS_ROOT_REF_KEY;
2525 key.offset = args->treeid;
2526 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2529 } else if (ret > 0) {
2534 leaf = path->nodes[0];
2535 slot = path->slots[0];
2536 btrfs_item_key_to_cpu(leaf, &key, slot);
2538 item_off = btrfs_item_ptr_offset(leaf, slot);
2539 item_len = btrfs_item_size_nr(leaf, slot);
2540 /* Check if dirid in ROOT_REF corresponds to passed dirid */
2541 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2542 if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2547 /* Copy subvolume's name */
2548 item_off += sizeof(struct btrfs_root_ref);
2549 item_len -= sizeof(struct btrfs_root_ref);
2550 read_extent_buffer(leaf, args->name, item_off, item_len);
2551 args->name[item_len] = 0;
2554 btrfs_put_root(root);
2556 btrfs_free_path(path);
2560 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2563 struct btrfs_ioctl_ino_lookup_args *args;
2564 struct inode *inode;
2567 args = memdup_user(argp, sizeof(*args));
2569 return PTR_ERR(args);
2571 inode = file_inode(file);
2574 * Unprivileged query to obtain the containing subvolume root id. The
2575 * path is reset so it's consistent with btrfs_search_path_in_tree.
2577 if (args->treeid == 0)
2578 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2580 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2585 if (!capable(CAP_SYS_ADMIN)) {
2590 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2591 args->treeid, args->objectid,
2595 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2603 * Version of ino_lookup ioctl (unprivileged)
2605 * The main differences from ino_lookup ioctl are:
2607 * 1. Read + Exec permission will be checked using inode_permission() during
2608 * path construction. -EACCES will be returned in case of failure.
2609 * 2. Path construction will be stopped at the inode number which corresponds
2610 * to the fd with which this ioctl is called. If constructed path does not
2611 * exist under fd's inode, -EACCES will be returned.
2612 * 3. The name of bottom subvolume is also searched and filled.
2614 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2616 struct btrfs_ioctl_ino_lookup_user_args *args;
2617 struct inode *inode;
2620 args = memdup_user(argp, sizeof(*args));
2622 return PTR_ERR(args);
2624 inode = file_inode(file);
2626 if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2627 BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2629 * The subvolume does not exist under fd with which this is
2636 ret = btrfs_search_path_in_tree_user(file_mnt_user_ns(file), inode, args);
2638 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2645 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2646 static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2648 struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2649 struct btrfs_fs_info *fs_info;
2650 struct btrfs_root *root;
2651 struct btrfs_path *path;
2652 struct btrfs_key key;
2653 struct btrfs_root_item *root_item;
2654 struct btrfs_root_ref *rref;
2655 struct extent_buffer *leaf;
2656 unsigned long item_off;
2657 unsigned long item_len;
2658 struct inode *inode;
2662 path = btrfs_alloc_path();
2666 subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2668 btrfs_free_path(path);
2672 inode = file_inode(file);
2673 fs_info = BTRFS_I(inode)->root->fs_info;
2675 /* Get root_item of inode's subvolume */
2676 key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2677 root = btrfs_get_fs_root(fs_info, key.objectid, true);
2679 ret = PTR_ERR(root);
2682 root_item = &root->root_item;
2684 subvol_info->treeid = key.objectid;
2686 subvol_info->generation = btrfs_root_generation(root_item);
2687 subvol_info->flags = btrfs_root_flags(root_item);
2689 memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2690 memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2692 memcpy(subvol_info->received_uuid, root_item->received_uuid,
2695 subvol_info->ctransid = btrfs_root_ctransid(root_item);
2696 subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2697 subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2699 subvol_info->otransid = btrfs_root_otransid(root_item);
2700 subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2701 subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2703 subvol_info->stransid = btrfs_root_stransid(root_item);
2704 subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2705 subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2707 subvol_info->rtransid = btrfs_root_rtransid(root_item);
2708 subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2709 subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2711 if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2712 /* Search root tree for ROOT_BACKREF of this subvolume */
2713 key.type = BTRFS_ROOT_BACKREF_KEY;
2715 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2718 } else if (path->slots[0] >=
2719 btrfs_header_nritems(path->nodes[0])) {
2720 ret = btrfs_next_leaf(fs_info->tree_root, path);
2723 } else if (ret > 0) {
2729 leaf = path->nodes[0];
2730 slot = path->slots[0];
2731 btrfs_item_key_to_cpu(leaf, &key, slot);
2732 if (key.objectid == subvol_info->treeid &&
2733 key.type == BTRFS_ROOT_BACKREF_KEY) {
2734 subvol_info->parent_id = key.offset;
2736 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2737 subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2739 item_off = btrfs_item_ptr_offset(leaf, slot)
2740 + sizeof(struct btrfs_root_ref);
2741 item_len = btrfs_item_size_nr(leaf, slot)
2742 - sizeof(struct btrfs_root_ref);
2743 read_extent_buffer(leaf, subvol_info->name,
2744 item_off, item_len);
2751 if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2755 btrfs_put_root(root);
2757 btrfs_free_path(path);
2763 * Return ROOT_REF information of the subvolume containing this inode
2764 * except the subvolume name.
2766 static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
2768 struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
2769 struct btrfs_root_ref *rref;
2770 struct btrfs_root *root;
2771 struct btrfs_path *path;
2772 struct btrfs_key key;
2773 struct extent_buffer *leaf;
2774 struct inode *inode;
2780 path = btrfs_alloc_path();
2784 rootrefs = memdup_user(argp, sizeof(*rootrefs));
2785 if (IS_ERR(rootrefs)) {
2786 btrfs_free_path(path);
2787 return PTR_ERR(rootrefs);
2790 inode = file_inode(file);
2791 root = BTRFS_I(inode)->root->fs_info->tree_root;
2792 objectid = BTRFS_I(inode)->root->root_key.objectid;
2794 key.objectid = objectid;
2795 key.type = BTRFS_ROOT_REF_KEY;
2796 key.offset = rootrefs->min_treeid;
2799 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2802 } else if (path->slots[0] >=
2803 btrfs_header_nritems(path->nodes[0])) {
2804 ret = btrfs_next_leaf(root, path);
2807 } else if (ret > 0) {
2813 leaf = path->nodes[0];
2814 slot = path->slots[0];
2816 btrfs_item_key_to_cpu(leaf, &key, slot);
2817 if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
2822 if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
2827 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2828 rootrefs->rootref[found].treeid = key.offset;
2829 rootrefs->rootref[found].dirid =
2830 btrfs_root_ref_dirid(leaf, rref);
2833 ret = btrfs_next_item(root, path);
2836 } else if (ret > 0) {
2843 if (!ret || ret == -EOVERFLOW) {
2844 rootrefs->num_items = found;
2845 /* update min_treeid for next search */
2847 rootrefs->min_treeid =
2848 rootrefs->rootref[found - 1].treeid + 1;
2849 if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
2854 btrfs_free_path(path);
2859 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2863 struct dentry *parent = file->f_path.dentry;
2864 struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2865 struct dentry *dentry;
2866 struct inode *dir = d_inode(parent);
2867 struct inode *inode;
2868 struct btrfs_root *root = BTRFS_I(dir)->root;
2869 struct btrfs_root *dest = NULL;
2870 struct btrfs_ioctl_vol_args *vol_args = NULL;
2871 struct btrfs_ioctl_vol_args_v2 *vol_args2 = NULL;
2872 struct user_namespace *mnt_userns = file_mnt_user_ns(file);
2873 char *subvol_name, *subvol_name_ptr = NULL;
2876 bool destroy_parent = false;
2879 vol_args2 = memdup_user(arg, sizeof(*vol_args2));
2880 if (IS_ERR(vol_args2))
2881 return PTR_ERR(vol_args2);
2883 if (vol_args2->flags & ~BTRFS_SUBVOL_DELETE_ARGS_MASK) {
2889 * If SPEC_BY_ID is not set, we are looking for the subvolume by
2890 * name, same as v1 currently does.
2892 if (!(vol_args2->flags & BTRFS_SUBVOL_SPEC_BY_ID)) {
2893 vol_args2->name[BTRFS_SUBVOL_NAME_MAX] = 0;
2894 subvol_name = vol_args2->name;
2896 err = mnt_want_write_file(file);
2900 struct inode *old_dir;
2902 if (vol_args2->subvolid < BTRFS_FIRST_FREE_OBJECTID) {
2907 err = mnt_want_write_file(file);
2911 dentry = btrfs_get_dentry(fs_info->sb,
2912 BTRFS_FIRST_FREE_OBJECTID,
2913 vol_args2->subvolid, 0, 0);
2914 if (IS_ERR(dentry)) {
2915 err = PTR_ERR(dentry);
2916 goto out_drop_write;
2920 * Change the default parent since the subvolume being
2921 * deleted can be outside of the current mount point.
2923 parent = btrfs_get_parent(dentry);
2926 * At this point dentry->d_name can point to '/' if the
2927 * subvolume we want to destroy is outsite of the
2928 * current mount point, so we need to release the
2929 * current dentry and execute the lookup to return a new
2930 * one with ->d_name pointing to the
2931 * <mount point>/subvol_name.
2934 if (IS_ERR(parent)) {
2935 err = PTR_ERR(parent);
2936 goto out_drop_write;
2939 dir = d_inode(parent);
2942 * If v2 was used with SPEC_BY_ID, a new parent was
2943 * allocated since the subvolume can be outside of the
2944 * current mount point. Later on we need to release this
2945 * new parent dentry.
2947 destroy_parent = true;
2950 * On idmapped mounts, deletion via subvolid is
2951 * restricted to subvolumes that are immediate
2952 * ancestors of the inode referenced by the file
2953 * descriptor in the ioctl. Otherwise the idmapping
2954 * could potentially be abused to delete subvolumes
2955 * anywhere in the filesystem the user wouldn't be able
2956 * to delete without an idmapped mount.
2958 if (old_dir != dir && mnt_userns != &init_user_ns) {
2963 subvol_name_ptr = btrfs_get_subvol_name_from_objectid(
2964 fs_info, vol_args2->subvolid);
2965 if (IS_ERR(subvol_name_ptr)) {
2966 err = PTR_ERR(subvol_name_ptr);
2969 /* subvol_name_ptr is already nul terminated */
2970 subvol_name = (char *)kbasename(subvol_name_ptr);
2973 vol_args = memdup_user(arg, sizeof(*vol_args));
2974 if (IS_ERR(vol_args))
2975 return PTR_ERR(vol_args);
2977 vol_args->name[BTRFS_PATH_NAME_MAX] = 0;
2978 subvol_name = vol_args->name;
2980 err = mnt_want_write_file(file);
2985 subvol_namelen = strlen(subvol_name);
2987 if (strchr(subvol_name, '/') ||
2988 strncmp(subvol_name, "..", subvol_namelen) == 0) {
2990 goto free_subvol_name;
2993 if (!S_ISDIR(dir->i_mode)) {
2995 goto free_subvol_name;
2998 err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
3000 goto free_subvol_name;
3001 dentry = lookup_one(mnt_userns, subvol_name, parent, subvol_namelen);
3002 if (IS_ERR(dentry)) {
3003 err = PTR_ERR(dentry);
3004 goto out_unlock_dir;
3007 if (d_really_is_negative(dentry)) {
3012 inode = d_inode(dentry);
3013 dest = BTRFS_I(inode)->root;
3014 if (!capable(CAP_SYS_ADMIN)) {
3016 * Regular user. Only allow this with a special mount
3017 * option, when the user has write+exec access to the
3018 * subvol root, and when rmdir(2) would have been
3021 * Note that this is _not_ check that the subvol is
3022 * empty or doesn't contain data that we wouldn't
3023 * otherwise be able to delete.
3025 * Users who want to delete empty subvols should try
3029 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
3033 * Do not allow deletion if the parent dir is the same
3034 * as the dir to be deleted. That means the ioctl
3035 * must be called on the dentry referencing the root
3036 * of the subvol, not a random directory contained
3043 err = inode_permission(mnt_userns, inode, MAY_WRITE | MAY_EXEC);
3048 /* check if subvolume may be deleted by a user */
3049 err = btrfs_may_delete(mnt_userns, dir, dentry, 1);
3053 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
3058 btrfs_inode_lock(inode, 0);
3059 err = btrfs_delete_subvolume(dir, dentry);
3060 btrfs_inode_unlock(inode, 0);
3062 fsnotify_rmdir(dir, dentry);
3069 btrfs_inode_unlock(dir, 0);
3071 kfree(subvol_name_ptr);
3076 mnt_drop_write_file(file);
3083 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
3085 struct inode *inode = file_inode(file);
3086 struct btrfs_root *root = BTRFS_I(inode)->root;
3087 struct btrfs_ioctl_defrag_range_args range = {0};
3090 ret = mnt_want_write_file(file);
3094 if (btrfs_root_readonly(root)) {
3099 switch (inode->i_mode & S_IFMT) {
3101 if (!capable(CAP_SYS_ADMIN)) {
3105 ret = btrfs_defrag_root(root);
3109 * Note that this does not check the file descriptor for write
3110 * access. This prevents defragmenting executables that are
3111 * running and allows defrag on files open in read-only mode.
3113 if (!capable(CAP_SYS_ADMIN) &&
3114 inode_permission(&init_user_ns, inode, MAY_WRITE)) {
3120 if (copy_from_user(&range, argp, sizeof(range))) {
3124 /* compression requires us to start the IO */
3125 if ((range.flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3126 range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
3127 range.extent_thresh = (u32)-1;
3130 /* the rest are all set to zero by kzalloc */
3131 range.len = (u64)-1;
3133 ret = btrfs_defrag_file(file_inode(file), &file->f_ra,
3134 &range, BTRFS_OLDEST_GENERATION, 0);
3142 mnt_drop_write_file(file);
3146 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3148 struct btrfs_ioctl_vol_args *vol_args;
3151 if (!capable(CAP_SYS_ADMIN))
3154 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_ADD))
3155 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3157 vol_args = memdup_user(arg, sizeof(*vol_args));
3158 if (IS_ERR(vol_args)) {
3159 ret = PTR_ERR(vol_args);
3163 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3164 ret = btrfs_init_new_device(fs_info, vol_args->name);
3167 btrfs_info(fs_info, "disk added %s", vol_args->name);
3171 btrfs_exclop_finish(fs_info);
3175 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3177 BTRFS_DEV_LOOKUP_ARGS(args);
3178 struct inode *inode = file_inode(file);
3179 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3180 struct btrfs_ioctl_vol_args_v2 *vol_args;
3181 struct block_device *bdev = NULL;
3184 bool cancel = false;
3186 if (!capable(CAP_SYS_ADMIN))
3189 vol_args = memdup_user(arg, sizeof(*vol_args));
3190 if (IS_ERR(vol_args)) {
3191 ret = PTR_ERR(vol_args);
3195 if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
3200 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3201 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3202 args.devid = vol_args->devid;
3203 } else if (!strcmp("cancel", vol_args->name)) {
3206 ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3211 ret = mnt_want_write_file(file);
3215 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3220 /* Exclusive operation is now claimed */
3221 ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3223 btrfs_exclop_finish(fs_info);
3226 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3227 btrfs_info(fs_info, "device deleted: id %llu",
3230 btrfs_info(fs_info, "device deleted: %s",
3234 mnt_drop_write_file(file);
3236 blkdev_put(bdev, mode);
3238 btrfs_put_dev_args_from_path(&args);
3243 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3245 BTRFS_DEV_LOOKUP_ARGS(args);
3246 struct inode *inode = file_inode(file);
3247 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3248 struct btrfs_ioctl_vol_args *vol_args;
3249 struct block_device *bdev = NULL;
3254 if (!capable(CAP_SYS_ADMIN))
3257 vol_args = memdup_user(arg, sizeof(*vol_args));
3258 if (IS_ERR(vol_args))
3259 return PTR_ERR(vol_args);
3261 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3262 if (!strcmp("cancel", vol_args->name)) {
3265 ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3270 ret = mnt_want_write_file(file);
3274 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3277 ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3279 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3280 btrfs_exclop_finish(fs_info);
3283 mnt_drop_write_file(file);
3285 blkdev_put(bdev, mode);
3287 btrfs_put_dev_args_from_path(&args);
3292 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3295 struct btrfs_ioctl_fs_info_args *fi_args;
3296 struct btrfs_device *device;
3297 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3301 fi_args = memdup_user(arg, sizeof(*fi_args));
3302 if (IS_ERR(fi_args))
3303 return PTR_ERR(fi_args);
3305 flags_in = fi_args->flags;
3306 memset(fi_args, 0, sizeof(*fi_args));
3309 fi_args->num_devices = fs_devices->num_devices;
3311 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3312 if (device->devid > fi_args->max_id)
3313 fi_args->max_id = device->devid;
3317 memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3318 fi_args->nodesize = fs_info->nodesize;
3319 fi_args->sectorsize = fs_info->sectorsize;
3320 fi_args->clone_alignment = fs_info->sectorsize;
3322 if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3323 fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3324 fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3325 fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3328 if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
3329 fi_args->generation = fs_info->generation;
3330 fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
3333 if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
3334 memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
3335 sizeof(fi_args->metadata_uuid));
3336 fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
3339 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3346 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3349 BTRFS_DEV_LOOKUP_ARGS(args);
3350 struct btrfs_ioctl_dev_info_args *di_args;
3351 struct btrfs_device *dev;
3354 di_args = memdup_user(arg, sizeof(*di_args));
3355 if (IS_ERR(di_args))
3356 return PTR_ERR(di_args);
3358 args.devid = di_args->devid;
3359 if (!btrfs_is_empty_uuid(di_args->uuid))
3360 args.uuid = di_args->uuid;
3363 dev = btrfs_find_device(fs_info->fs_devices, &args);
3369 di_args->devid = dev->devid;
3370 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3371 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3372 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3374 strncpy(di_args->path, rcu_str_deref(dev->name),
3375 sizeof(di_args->path) - 1);
3376 di_args->path[sizeof(di_args->path) - 1] = 0;
3378 di_args->path[0] = '\0';
3383 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3390 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3392 struct inode *inode = file_inode(file);
3393 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3394 struct btrfs_root *root = BTRFS_I(inode)->root;
3395 struct btrfs_root *new_root;
3396 struct btrfs_dir_item *di;
3397 struct btrfs_trans_handle *trans;
3398 struct btrfs_path *path = NULL;
3399 struct btrfs_disk_key disk_key;
3404 if (!capable(CAP_SYS_ADMIN))
3407 ret = mnt_want_write_file(file);
3411 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3417 objectid = BTRFS_FS_TREE_OBJECTID;
3419 new_root = btrfs_get_fs_root(fs_info, objectid, true);
3420 if (IS_ERR(new_root)) {
3421 ret = PTR_ERR(new_root);
3424 if (!is_fstree(new_root->root_key.objectid)) {
3429 path = btrfs_alloc_path();
3435 trans = btrfs_start_transaction(root, 1);
3436 if (IS_ERR(trans)) {
3437 ret = PTR_ERR(trans);
3441 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3442 di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
3443 dir_id, "default", 7, 1);
3444 if (IS_ERR_OR_NULL(di)) {
3445 btrfs_release_path(path);
3446 btrfs_end_transaction(trans);
3448 "Umm, you don't have the default diritem, this isn't going to work");
3453 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3454 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3455 btrfs_mark_buffer_dirty(path->nodes[0]);
3456 btrfs_release_path(path);
3458 btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
3459 btrfs_end_transaction(trans);
3461 btrfs_put_root(new_root);
3462 btrfs_free_path(path);
3464 mnt_drop_write_file(file);
3468 static void get_block_group_info(struct list_head *groups_list,
3469 struct btrfs_ioctl_space_info *space)
3471 struct btrfs_block_group *block_group;
3473 space->total_bytes = 0;
3474 space->used_bytes = 0;
3476 list_for_each_entry(block_group, groups_list, list) {
3477 space->flags = block_group->flags;
3478 space->total_bytes += block_group->length;
3479 space->used_bytes += block_group->used;
3483 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
3486 struct btrfs_ioctl_space_args space_args;
3487 struct btrfs_ioctl_space_info space;
3488 struct btrfs_ioctl_space_info *dest;
3489 struct btrfs_ioctl_space_info *dest_orig;
3490 struct btrfs_ioctl_space_info __user *user_dest;
3491 struct btrfs_space_info *info;
3492 static const u64 types[] = {
3493 BTRFS_BLOCK_GROUP_DATA,
3494 BTRFS_BLOCK_GROUP_SYSTEM,
3495 BTRFS_BLOCK_GROUP_METADATA,
3496 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3504 if (copy_from_user(&space_args,
3505 (struct btrfs_ioctl_space_args __user *)arg,
3506 sizeof(space_args)))
3509 for (i = 0; i < num_types; i++) {
3510 struct btrfs_space_info *tmp;
3513 list_for_each_entry(tmp, &fs_info->space_info, list) {
3514 if (tmp->flags == types[i]) {
3523 down_read(&info->groups_sem);
3524 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3525 if (!list_empty(&info->block_groups[c]))
3528 up_read(&info->groups_sem);
3532 * Global block reserve, exported as a space_info
3536 /* space_slots == 0 means they are asking for a count */
3537 if (space_args.space_slots == 0) {
3538 space_args.total_spaces = slot_count;
3542 slot_count = min_t(u64, space_args.space_slots, slot_count);
3544 alloc_size = sizeof(*dest) * slot_count;
3546 /* we generally have at most 6 or so space infos, one for each raid
3547 * level. So, a whole page should be more than enough for everyone
3549 if (alloc_size > PAGE_SIZE)
3552 space_args.total_spaces = 0;
3553 dest = kmalloc(alloc_size, GFP_KERNEL);
3558 /* now we have a buffer to copy into */
3559 for (i = 0; i < num_types; i++) {
3560 struct btrfs_space_info *tmp;
3566 list_for_each_entry(tmp, &fs_info->space_info, list) {
3567 if (tmp->flags == types[i]) {
3575 down_read(&info->groups_sem);
3576 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3577 if (!list_empty(&info->block_groups[c])) {
3578 get_block_group_info(&info->block_groups[c],
3580 memcpy(dest, &space, sizeof(space));
3582 space_args.total_spaces++;
3588 up_read(&info->groups_sem);
3592 * Add global block reserve
3595 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3597 spin_lock(&block_rsv->lock);
3598 space.total_bytes = block_rsv->size;
3599 space.used_bytes = block_rsv->size - block_rsv->reserved;
3600 spin_unlock(&block_rsv->lock);
3601 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
3602 memcpy(dest, &space, sizeof(space));
3603 space_args.total_spaces++;
3606 user_dest = (struct btrfs_ioctl_space_info __user *)
3607 (arg + sizeof(struct btrfs_ioctl_space_args));
3609 if (copy_to_user(user_dest, dest_orig, alloc_size))
3614 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3620 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3623 struct btrfs_trans_handle *trans;
3627 trans = btrfs_attach_transaction_barrier(root);
3628 if (IS_ERR(trans)) {
3629 if (PTR_ERR(trans) != -ENOENT)
3630 return PTR_ERR(trans);
3632 /* No running transaction, don't bother */
3633 transid = root->fs_info->last_trans_committed;
3636 transid = trans->transid;
3637 ret = btrfs_commit_transaction_async(trans);
3639 btrfs_end_transaction(trans);
3644 if (copy_to_user(argp, &transid, sizeof(transid)))
3649 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
3655 if (copy_from_user(&transid, argp, sizeof(transid)))
3658 transid = 0; /* current trans */
3660 return btrfs_wait_for_commit(fs_info, transid);
3663 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3665 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
3666 struct btrfs_ioctl_scrub_args *sa;
3669 if (!capable(CAP_SYS_ADMIN))
3672 sa = memdup_user(arg, sizeof(*sa));
3676 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3677 ret = mnt_want_write_file(file);
3682 ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
3683 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3687 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
3688 * error. This is important as it allows user space to know how much
3689 * progress scrub has done. For example, if scrub is canceled we get
3690 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
3691 * space. Later user space can inspect the progress from the structure
3692 * btrfs_ioctl_scrub_args and resume scrub from where it left off
3693 * previously (btrfs-progs does this).
3694 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
3695 * then return -EFAULT to signal the structure was not copied or it may
3696 * be corrupt and unreliable due to a partial copy.
3698 if (copy_to_user(arg, sa, sizeof(*sa)))
3701 if (!(sa->flags & BTRFS_SCRUB_READONLY))
3702 mnt_drop_write_file(file);
3708 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
3710 if (!capable(CAP_SYS_ADMIN))
3713 return btrfs_scrub_cancel(fs_info);
3716 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
3719 struct btrfs_ioctl_scrub_args *sa;
3722 if (!capable(CAP_SYS_ADMIN))
3725 sa = memdup_user(arg, sizeof(*sa));
3729 ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
3731 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3738 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
3741 struct btrfs_ioctl_get_dev_stats *sa;
3744 sa = memdup_user(arg, sizeof(*sa));
3748 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3753 ret = btrfs_get_dev_stats(fs_info, sa);
3755 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3762 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
3765 struct btrfs_ioctl_dev_replace_args *p;
3768 if (!capable(CAP_SYS_ADMIN))
3771 p = memdup_user(arg, sizeof(*p));
3776 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3777 if (sb_rdonly(fs_info->sb)) {
3781 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
3782 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3784 ret = btrfs_dev_replace_by_ioctl(fs_info, p);
3785 btrfs_exclop_finish(fs_info);
3788 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3789 btrfs_dev_replace_status(fs_info, p);
3792 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3793 p->result = btrfs_dev_replace_cancel(fs_info);
3801 if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
3808 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3814 struct btrfs_ioctl_ino_path_args *ipa = NULL;
3815 struct inode_fs_paths *ipath = NULL;
3816 struct btrfs_path *path;
3818 if (!capable(CAP_DAC_READ_SEARCH))
3821 path = btrfs_alloc_path();
3827 ipa = memdup_user(arg, sizeof(*ipa));
3834 size = min_t(u32, ipa->size, 4096);
3835 ipath = init_ipath(size, root, path);
3836 if (IS_ERR(ipath)) {
3837 ret = PTR_ERR(ipath);
3842 ret = paths_from_inode(ipa->inum, ipath);
3846 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3847 rel_ptr = ipath->fspath->val[i] -
3848 (u64)(unsigned long)ipath->fspath->val;
3849 ipath->fspath->val[i] = rel_ptr;
3852 ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
3853 ipath->fspath, size);
3860 btrfs_free_path(path);
3867 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3869 struct btrfs_data_container *inodes = ctx;
3870 const size_t c = 3 * sizeof(u64);
3872 if (inodes->bytes_left >= c) {
3873 inodes->bytes_left -= c;
3874 inodes->val[inodes->elem_cnt] = inum;
3875 inodes->val[inodes->elem_cnt + 1] = offset;
3876 inodes->val[inodes->elem_cnt + 2] = root;
3877 inodes->elem_cnt += 3;
3879 inodes->bytes_missing += c - inodes->bytes_left;
3880 inodes->bytes_left = 0;
3881 inodes->elem_missed += 3;
3887 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
3888 void __user *arg, int version)
3892 struct btrfs_ioctl_logical_ino_args *loi;
3893 struct btrfs_data_container *inodes = NULL;
3894 struct btrfs_path *path = NULL;
3897 if (!capable(CAP_SYS_ADMIN))
3900 loi = memdup_user(arg, sizeof(*loi));
3902 return PTR_ERR(loi);
3905 ignore_offset = false;
3906 size = min_t(u32, loi->size, SZ_64K);
3908 /* All reserved bits must be 0 for now */
3909 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
3913 /* Only accept flags we have defined so far */
3914 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
3918 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
3919 size = min_t(u32, loi->size, SZ_16M);
3922 path = btrfs_alloc_path();
3928 inodes = init_data_container(size);
3929 if (IS_ERR(inodes)) {
3930 ret = PTR_ERR(inodes);
3935 ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
3936 build_ino_list, inodes, ignore_offset);
3942 ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
3948 btrfs_free_path(path);
3956 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
3957 struct btrfs_ioctl_balance_args *bargs)
3959 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3961 bargs->flags = bctl->flags;
3963 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
3964 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3965 if (atomic_read(&fs_info->balance_pause_req))
3966 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3967 if (atomic_read(&fs_info->balance_cancel_req))
3968 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3970 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3971 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3972 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3974 spin_lock(&fs_info->balance_lock);
3975 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3976 spin_unlock(&fs_info->balance_lock);
3979 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3981 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3982 struct btrfs_fs_info *fs_info = root->fs_info;
3983 struct btrfs_ioctl_balance_args *bargs;
3984 struct btrfs_balance_control *bctl;
3985 bool need_unlock; /* for mut. excl. ops lock */
3990 "IOC_BALANCE ioctl (v1) is deprecated and will be removed in kernel 5.18");
3992 if (!capable(CAP_SYS_ADMIN))
3995 ret = mnt_want_write_file(file);
4000 if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
4001 mutex_lock(&fs_info->balance_mutex);
4007 * mut. excl. ops lock is locked. Three possibilities:
4008 * (1) some other op is running
4009 * (2) balance is running
4010 * (3) balance is paused -- special case (think resume)
4012 mutex_lock(&fs_info->balance_mutex);
4013 if (fs_info->balance_ctl) {
4014 /* this is either (2) or (3) */
4015 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4016 mutex_unlock(&fs_info->balance_mutex);
4018 * Lock released to allow other waiters to continue,
4019 * we'll reexamine the status again.
4021 mutex_lock(&fs_info->balance_mutex);
4023 if (fs_info->balance_ctl &&
4024 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4026 need_unlock = false;
4030 mutex_unlock(&fs_info->balance_mutex);
4034 mutex_unlock(&fs_info->balance_mutex);
4040 mutex_unlock(&fs_info->balance_mutex);
4041 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4048 bargs = memdup_user(arg, sizeof(*bargs));
4049 if (IS_ERR(bargs)) {
4050 ret = PTR_ERR(bargs);
4054 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4055 if (!fs_info->balance_ctl) {
4060 bctl = fs_info->balance_ctl;
4061 spin_lock(&fs_info->balance_lock);
4062 bctl->flags |= BTRFS_BALANCE_RESUME;
4063 spin_unlock(&fs_info->balance_lock);
4071 if (fs_info->balance_ctl) {
4076 bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4083 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4084 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4085 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4087 bctl->flags = bargs->flags;
4089 /* balance everything - no filters */
4090 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4093 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4100 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4101 * bctl is freed in reset_balance_state, or, if restriper was paused
4102 * all the way until unmount, in free_fs_info. The flag should be
4103 * cleared after reset_balance_state.
4105 need_unlock = false;
4107 ret = btrfs_balance(fs_info, bctl, bargs);
4110 if ((ret == 0 || ret == -ECANCELED) && arg) {
4111 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4120 mutex_unlock(&fs_info->balance_mutex);
4122 btrfs_exclop_finish(fs_info);
4124 mnt_drop_write_file(file);
4128 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4130 if (!capable(CAP_SYS_ADMIN))
4134 case BTRFS_BALANCE_CTL_PAUSE:
4135 return btrfs_pause_balance(fs_info);
4136 case BTRFS_BALANCE_CTL_CANCEL:
4137 return btrfs_cancel_balance(fs_info);
4143 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4146 struct btrfs_ioctl_balance_args *bargs;
4149 if (!capable(CAP_SYS_ADMIN))
4152 mutex_lock(&fs_info->balance_mutex);
4153 if (!fs_info->balance_ctl) {
4158 bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4164 btrfs_update_ioctl_balance_args(fs_info, bargs);
4166 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4171 mutex_unlock(&fs_info->balance_mutex);
4175 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4177 struct inode *inode = file_inode(file);
4178 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4179 struct btrfs_ioctl_quota_ctl_args *sa;
4182 if (!capable(CAP_SYS_ADMIN))
4185 ret = mnt_want_write_file(file);
4189 sa = memdup_user(arg, sizeof(*sa));
4195 down_write(&fs_info->subvol_sem);
4198 case BTRFS_QUOTA_CTL_ENABLE:
4199 ret = btrfs_quota_enable(fs_info);
4201 case BTRFS_QUOTA_CTL_DISABLE:
4202 ret = btrfs_quota_disable(fs_info);
4210 up_write(&fs_info->subvol_sem);
4212 mnt_drop_write_file(file);
4216 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4218 struct inode *inode = file_inode(file);
4219 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4220 struct btrfs_root *root = BTRFS_I(inode)->root;
4221 struct btrfs_ioctl_qgroup_assign_args *sa;
4222 struct btrfs_trans_handle *trans;
4226 if (!capable(CAP_SYS_ADMIN))
4229 ret = mnt_want_write_file(file);
4233 sa = memdup_user(arg, sizeof(*sa));
4239 trans = btrfs_join_transaction(root);
4240 if (IS_ERR(trans)) {
4241 ret = PTR_ERR(trans);
4246 ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
4248 ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
4251 /* update qgroup status and info */
4252 err = btrfs_run_qgroups(trans);
4254 btrfs_handle_fs_error(fs_info, err,
4255 "failed to update qgroup status and info");
4256 err = btrfs_end_transaction(trans);
4263 mnt_drop_write_file(file);
4267 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4269 struct inode *inode = file_inode(file);
4270 struct btrfs_root *root = BTRFS_I(inode)->root;
4271 struct btrfs_ioctl_qgroup_create_args *sa;
4272 struct btrfs_trans_handle *trans;
4276 if (!capable(CAP_SYS_ADMIN))
4279 ret = mnt_want_write_file(file);
4283 sa = memdup_user(arg, sizeof(*sa));
4289 if (!sa->qgroupid) {
4294 trans = btrfs_join_transaction(root);
4295 if (IS_ERR(trans)) {
4296 ret = PTR_ERR(trans);
4301 ret = btrfs_create_qgroup(trans, sa->qgroupid);
4303 ret = btrfs_remove_qgroup(trans, sa->qgroupid);
4306 err = btrfs_end_transaction(trans);
4313 mnt_drop_write_file(file);
4317 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4319 struct inode *inode = file_inode(file);
4320 struct btrfs_root *root = BTRFS_I(inode)->root;
4321 struct btrfs_ioctl_qgroup_limit_args *sa;
4322 struct btrfs_trans_handle *trans;
4327 if (!capable(CAP_SYS_ADMIN))
4330 ret = mnt_want_write_file(file);
4334 sa = memdup_user(arg, sizeof(*sa));
4340 trans = btrfs_join_transaction(root);
4341 if (IS_ERR(trans)) {
4342 ret = PTR_ERR(trans);
4346 qgroupid = sa->qgroupid;
4348 /* take the current subvol as qgroup */
4349 qgroupid = root->root_key.objectid;
4352 ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
4354 err = btrfs_end_transaction(trans);
4361 mnt_drop_write_file(file);
4365 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4367 struct inode *inode = file_inode(file);
4368 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4369 struct btrfs_ioctl_quota_rescan_args *qsa;
4372 if (!capable(CAP_SYS_ADMIN))
4375 ret = mnt_want_write_file(file);
4379 qsa = memdup_user(arg, sizeof(*qsa));
4390 ret = btrfs_qgroup_rescan(fs_info);
4395 mnt_drop_write_file(file);
4399 static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4402 struct btrfs_ioctl_quota_rescan_args qsa = {0};
4404 if (!capable(CAP_SYS_ADMIN))
4407 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4409 qsa.progress = fs_info->qgroup_rescan_progress.objectid;
4412 if (copy_to_user(arg, &qsa, sizeof(qsa)))
4418 static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4421 if (!capable(CAP_SYS_ADMIN))
4424 return btrfs_qgroup_wait_for_completion(fs_info, true);
4427 static long _btrfs_ioctl_set_received_subvol(struct file *file,
4428 struct user_namespace *mnt_userns,
4429 struct btrfs_ioctl_received_subvol_args *sa)
4431 struct inode *inode = file_inode(file);
4432 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4433 struct btrfs_root *root = BTRFS_I(inode)->root;
4434 struct btrfs_root_item *root_item = &root->root_item;
4435 struct btrfs_trans_handle *trans;
4436 struct timespec64 ct = current_time(inode);
4438 int received_uuid_changed;
4440 if (!inode_owner_or_capable(mnt_userns, inode))
4443 ret = mnt_want_write_file(file);
4447 down_write(&fs_info->subvol_sem);
4449 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
4454 if (btrfs_root_readonly(root)) {
4461 * 2 - uuid items (received uuid + subvol uuid)
4463 trans = btrfs_start_transaction(root, 3);
4464 if (IS_ERR(trans)) {
4465 ret = PTR_ERR(trans);
4470 sa->rtransid = trans->transid;
4471 sa->rtime.sec = ct.tv_sec;
4472 sa->rtime.nsec = ct.tv_nsec;
4474 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4476 if (received_uuid_changed &&
4477 !btrfs_is_empty_uuid(root_item->received_uuid)) {
4478 ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
4479 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4480 root->root_key.objectid);
4481 if (ret && ret != -ENOENT) {
4482 btrfs_abort_transaction(trans, ret);
4483 btrfs_end_transaction(trans);
4487 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4488 btrfs_set_root_stransid(root_item, sa->stransid);
4489 btrfs_set_root_rtransid(root_item, sa->rtransid);
4490 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4491 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4492 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4493 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4495 ret = btrfs_update_root(trans, fs_info->tree_root,
4496 &root->root_key, &root->root_item);
4498 btrfs_end_transaction(trans);
4501 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4502 ret = btrfs_uuid_tree_add(trans, sa->uuid,
4503 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4504 root->root_key.objectid);
4505 if (ret < 0 && ret != -EEXIST) {
4506 btrfs_abort_transaction(trans, ret);
4507 btrfs_end_transaction(trans);
4511 ret = btrfs_commit_transaction(trans);
4513 up_write(&fs_info->subvol_sem);
4514 mnt_drop_write_file(file);
4519 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4522 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4523 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4526 args32 = memdup_user(arg, sizeof(*args32));
4528 return PTR_ERR(args32);
4530 args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
4536 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4537 args64->stransid = args32->stransid;
4538 args64->rtransid = args32->rtransid;
4539 args64->stime.sec = args32->stime.sec;
4540 args64->stime.nsec = args32->stime.nsec;
4541 args64->rtime.sec = args32->rtime.sec;
4542 args64->rtime.nsec = args32->rtime.nsec;
4543 args64->flags = args32->flags;
4545 ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), args64);
4549 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4550 args32->stransid = args64->stransid;
4551 args32->rtransid = args64->rtransid;
4552 args32->stime.sec = args64->stime.sec;
4553 args32->stime.nsec = args64->stime.nsec;
4554 args32->rtime.sec = args64->rtime.sec;
4555 args32->rtime.nsec = args64->rtime.nsec;
4556 args32->flags = args64->flags;
4558 ret = copy_to_user(arg, args32, sizeof(*args32));
4569 static long btrfs_ioctl_set_received_subvol(struct file *file,
4572 struct btrfs_ioctl_received_subvol_args *sa = NULL;
4575 sa = memdup_user(arg, sizeof(*sa));
4579 ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), sa);
4584 ret = copy_to_user(arg, sa, sizeof(*sa));
4593 static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4598 char label[BTRFS_LABEL_SIZE];
4600 spin_lock(&fs_info->super_lock);
4601 memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4602 spin_unlock(&fs_info->super_lock);
4604 len = strnlen(label, BTRFS_LABEL_SIZE);
4606 if (len == BTRFS_LABEL_SIZE) {
4608 "label is too long, return the first %zu bytes",
4612 ret = copy_to_user(arg, label, len);
4614 return ret ? -EFAULT : 0;
4617 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4619 struct inode *inode = file_inode(file);
4620 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4621 struct btrfs_root *root = BTRFS_I(inode)->root;
4622 struct btrfs_super_block *super_block = fs_info->super_copy;
4623 struct btrfs_trans_handle *trans;
4624 char label[BTRFS_LABEL_SIZE];
4627 if (!capable(CAP_SYS_ADMIN))
4630 if (copy_from_user(label, arg, sizeof(label)))
4633 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4635 "unable to set label with more than %d bytes",
4636 BTRFS_LABEL_SIZE - 1);
4640 ret = mnt_want_write_file(file);
4644 trans = btrfs_start_transaction(root, 0);
4645 if (IS_ERR(trans)) {
4646 ret = PTR_ERR(trans);
4650 spin_lock(&fs_info->super_lock);
4651 strcpy(super_block->label, label);
4652 spin_unlock(&fs_info->super_lock);
4653 ret = btrfs_commit_transaction(trans);
4656 mnt_drop_write_file(file);
4660 #define INIT_FEATURE_FLAGS(suffix) \
4661 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
4662 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
4663 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
4665 int btrfs_ioctl_get_supported_features(void __user *arg)
4667 static const struct btrfs_ioctl_feature_flags features[3] = {
4668 INIT_FEATURE_FLAGS(SUPP),
4669 INIT_FEATURE_FLAGS(SAFE_SET),
4670 INIT_FEATURE_FLAGS(SAFE_CLEAR)
4673 if (copy_to_user(arg, &features, sizeof(features)))
4679 static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
4682 struct btrfs_super_block *super_block = fs_info->super_copy;
4683 struct btrfs_ioctl_feature_flags features;
4685 features.compat_flags = btrfs_super_compat_flags(super_block);
4686 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
4687 features.incompat_flags = btrfs_super_incompat_flags(super_block);
4689 if (copy_to_user(arg, &features, sizeof(features)))
4695 static int check_feature_bits(struct btrfs_fs_info *fs_info,
4696 enum btrfs_feature_set set,
4697 u64 change_mask, u64 flags, u64 supported_flags,
4698 u64 safe_set, u64 safe_clear)
4700 const char *type = btrfs_feature_set_name(set);
4702 u64 disallowed, unsupported;
4703 u64 set_mask = flags & change_mask;
4704 u64 clear_mask = ~flags & change_mask;
4706 unsupported = set_mask & ~supported_flags;
4708 names = btrfs_printable_features(set, unsupported);
4711 "this kernel does not support the %s feature bit%s",
4712 names, strchr(names, ',') ? "s" : "");
4716 "this kernel does not support %s bits 0x%llx",
4721 disallowed = set_mask & ~safe_set;
4723 names = btrfs_printable_features(set, disallowed);
4726 "can't set the %s feature bit%s while mounted",
4727 names, strchr(names, ',') ? "s" : "");
4731 "can't set %s bits 0x%llx while mounted",
4736 disallowed = clear_mask & ~safe_clear;
4738 names = btrfs_printable_features(set, disallowed);
4741 "can't clear the %s feature bit%s while mounted",
4742 names, strchr(names, ',') ? "s" : "");
4746 "can't clear %s bits 0x%llx while mounted",
4754 #define check_feature(fs_info, change_mask, flags, mask_base) \
4755 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \
4756 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
4757 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
4758 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
4760 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
4762 struct inode *inode = file_inode(file);
4763 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4764 struct btrfs_root *root = BTRFS_I(inode)->root;
4765 struct btrfs_super_block *super_block = fs_info->super_copy;
4766 struct btrfs_ioctl_feature_flags flags[2];
4767 struct btrfs_trans_handle *trans;
4771 if (!capable(CAP_SYS_ADMIN))
4774 if (copy_from_user(flags, arg, sizeof(flags)))
4778 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
4779 !flags[0].incompat_flags)
4782 ret = check_feature(fs_info, flags[0].compat_flags,
4783 flags[1].compat_flags, COMPAT);
4787 ret = check_feature(fs_info, flags[0].compat_ro_flags,
4788 flags[1].compat_ro_flags, COMPAT_RO);
4792 ret = check_feature(fs_info, flags[0].incompat_flags,
4793 flags[1].incompat_flags, INCOMPAT);
4797 ret = mnt_want_write_file(file);
4801 trans = btrfs_start_transaction(root, 0);
4802 if (IS_ERR(trans)) {
4803 ret = PTR_ERR(trans);
4804 goto out_drop_write;
4807 spin_lock(&fs_info->super_lock);
4808 newflags = btrfs_super_compat_flags(super_block);
4809 newflags |= flags[0].compat_flags & flags[1].compat_flags;
4810 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
4811 btrfs_set_super_compat_flags(super_block, newflags);
4813 newflags = btrfs_super_compat_ro_flags(super_block);
4814 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
4815 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
4816 btrfs_set_super_compat_ro_flags(super_block, newflags);
4818 newflags = btrfs_super_incompat_flags(super_block);
4819 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
4820 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
4821 btrfs_set_super_incompat_flags(super_block, newflags);
4822 spin_unlock(&fs_info->super_lock);
4824 ret = btrfs_commit_transaction(trans);
4826 mnt_drop_write_file(file);
4831 static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
4833 struct btrfs_ioctl_send_args *arg;
4837 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
4838 struct btrfs_ioctl_send_args_32 args32;
4840 ret = copy_from_user(&args32, argp, sizeof(args32));
4843 arg = kzalloc(sizeof(*arg), GFP_KERNEL);
4846 arg->send_fd = args32.send_fd;
4847 arg->clone_sources_count = args32.clone_sources_count;
4848 arg->clone_sources = compat_ptr(args32.clone_sources);
4849 arg->parent_root = args32.parent_root;
4850 arg->flags = args32.flags;
4851 memcpy(arg->reserved, args32.reserved,
4852 sizeof(args32.reserved));
4857 arg = memdup_user(argp, sizeof(*arg));
4859 return PTR_ERR(arg);
4861 ret = btrfs_ioctl_send(file, arg);
4866 long btrfs_ioctl(struct file *file, unsigned int
4867 cmd, unsigned long arg)
4869 struct inode *inode = file_inode(file);
4870 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4871 struct btrfs_root *root = BTRFS_I(inode)->root;
4872 void __user *argp = (void __user *)arg;
4875 case FS_IOC_GETVERSION:
4876 return btrfs_ioctl_getversion(file, argp);
4877 case FS_IOC_GETFSLABEL:
4878 return btrfs_ioctl_get_fslabel(fs_info, argp);
4879 case FS_IOC_SETFSLABEL:
4880 return btrfs_ioctl_set_fslabel(file, argp);
4882 return btrfs_ioctl_fitrim(fs_info, argp);
4883 case BTRFS_IOC_SNAP_CREATE:
4884 return btrfs_ioctl_snap_create(file, argp, 0);
4885 case BTRFS_IOC_SNAP_CREATE_V2:
4886 return btrfs_ioctl_snap_create_v2(file, argp, 0);
4887 case BTRFS_IOC_SUBVOL_CREATE:
4888 return btrfs_ioctl_snap_create(file, argp, 1);
4889 case BTRFS_IOC_SUBVOL_CREATE_V2:
4890 return btrfs_ioctl_snap_create_v2(file, argp, 1);
4891 case BTRFS_IOC_SNAP_DESTROY:
4892 return btrfs_ioctl_snap_destroy(file, argp, false);
4893 case BTRFS_IOC_SNAP_DESTROY_V2:
4894 return btrfs_ioctl_snap_destroy(file, argp, true);
4895 case BTRFS_IOC_SUBVOL_GETFLAGS:
4896 return btrfs_ioctl_subvol_getflags(file, argp);
4897 case BTRFS_IOC_SUBVOL_SETFLAGS:
4898 return btrfs_ioctl_subvol_setflags(file, argp);
4899 case BTRFS_IOC_DEFAULT_SUBVOL:
4900 return btrfs_ioctl_default_subvol(file, argp);
4901 case BTRFS_IOC_DEFRAG:
4902 return btrfs_ioctl_defrag(file, NULL);
4903 case BTRFS_IOC_DEFRAG_RANGE:
4904 return btrfs_ioctl_defrag(file, argp);
4905 case BTRFS_IOC_RESIZE:
4906 return btrfs_ioctl_resize(file, argp);
4907 case BTRFS_IOC_ADD_DEV:
4908 return btrfs_ioctl_add_dev(fs_info, argp);
4909 case BTRFS_IOC_RM_DEV:
4910 return btrfs_ioctl_rm_dev(file, argp);
4911 case BTRFS_IOC_RM_DEV_V2:
4912 return btrfs_ioctl_rm_dev_v2(file, argp);
4913 case BTRFS_IOC_FS_INFO:
4914 return btrfs_ioctl_fs_info(fs_info, argp);
4915 case BTRFS_IOC_DEV_INFO:
4916 return btrfs_ioctl_dev_info(fs_info, argp);
4917 case BTRFS_IOC_BALANCE:
4918 return btrfs_ioctl_balance(file, NULL);
4919 case BTRFS_IOC_TREE_SEARCH:
4920 return btrfs_ioctl_tree_search(file, argp);
4921 case BTRFS_IOC_TREE_SEARCH_V2:
4922 return btrfs_ioctl_tree_search_v2(file, argp);
4923 case BTRFS_IOC_INO_LOOKUP:
4924 return btrfs_ioctl_ino_lookup(file, argp);
4925 case BTRFS_IOC_INO_PATHS:
4926 return btrfs_ioctl_ino_to_path(root, argp);
4927 case BTRFS_IOC_LOGICAL_INO:
4928 return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
4929 case BTRFS_IOC_LOGICAL_INO_V2:
4930 return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
4931 case BTRFS_IOC_SPACE_INFO:
4932 return btrfs_ioctl_space_info(fs_info, argp);
4933 case BTRFS_IOC_SYNC: {
4936 ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
4939 ret = btrfs_sync_fs(inode->i_sb, 1);
4941 * The transaction thread may want to do more work,
4942 * namely it pokes the cleaner kthread that will start
4943 * processing uncleaned subvols.
4945 wake_up_process(fs_info->transaction_kthread);
4948 case BTRFS_IOC_START_SYNC:
4949 return btrfs_ioctl_start_sync(root, argp);
4950 case BTRFS_IOC_WAIT_SYNC:
4951 return btrfs_ioctl_wait_sync(fs_info, argp);
4952 case BTRFS_IOC_SCRUB:
4953 return btrfs_ioctl_scrub(file, argp);
4954 case BTRFS_IOC_SCRUB_CANCEL:
4955 return btrfs_ioctl_scrub_cancel(fs_info);
4956 case BTRFS_IOC_SCRUB_PROGRESS:
4957 return btrfs_ioctl_scrub_progress(fs_info, argp);
4958 case BTRFS_IOC_BALANCE_V2:
4959 return btrfs_ioctl_balance(file, argp);
4960 case BTRFS_IOC_BALANCE_CTL:
4961 return btrfs_ioctl_balance_ctl(fs_info, arg);
4962 case BTRFS_IOC_BALANCE_PROGRESS:
4963 return btrfs_ioctl_balance_progress(fs_info, argp);
4964 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
4965 return btrfs_ioctl_set_received_subvol(file, argp);
4967 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
4968 return btrfs_ioctl_set_received_subvol_32(file, argp);
4970 case BTRFS_IOC_SEND:
4971 return _btrfs_ioctl_send(file, argp, false);
4972 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
4973 case BTRFS_IOC_SEND_32:
4974 return _btrfs_ioctl_send(file, argp, true);
4976 case BTRFS_IOC_GET_DEV_STATS:
4977 return btrfs_ioctl_get_dev_stats(fs_info, argp);
4978 case BTRFS_IOC_QUOTA_CTL:
4979 return btrfs_ioctl_quota_ctl(file, argp);
4980 case BTRFS_IOC_QGROUP_ASSIGN:
4981 return btrfs_ioctl_qgroup_assign(file, argp);
4982 case BTRFS_IOC_QGROUP_CREATE:
4983 return btrfs_ioctl_qgroup_create(file, argp);
4984 case BTRFS_IOC_QGROUP_LIMIT:
4985 return btrfs_ioctl_qgroup_limit(file, argp);
4986 case BTRFS_IOC_QUOTA_RESCAN:
4987 return btrfs_ioctl_quota_rescan(file, argp);
4988 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
4989 return btrfs_ioctl_quota_rescan_status(fs_info, argp);
4990 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
4991 return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
4992 case BTRFS_IOC_DEV_REPLACE:
4993 return btrfs_ioctl_dev_replace(fs_info, argp);
4994 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
4995 return btrfs_ioctl_get_supported_features(argp);
4996 case BTRFS_IOC_GET_FEATURES:
4997 return btrfs_ioctl_get_features(fs_info, argp);
4998 case BTRFS_IOC_SET_FEATURES:
4999 return btrfs_ioctl_set_features(file, argp);
5000 case BTRFS_IOC_GET_SUBVOL_INFO:
5001 return btrfs_ioctl_get_subvol_info(file, argp);
5002 case BTRFS_IOC_GET_SUBVOL_ROOTREF:
5003 return btrfs_ioctl_get_subvol_rootref(file, argp);
5004 case BTRFS_IOC_INO_LOOKUP_USER:
5005 return btrfs_ioctl_ino_lookup_user(file, argp);
5006 case FS_IOC_ENABLE_VERITY:
5007 return fsverity_ioctl_enable(file, (const void __user *)argp);
5008 case FS_IOC_MEASURE_VERITY:
5009 return fsverity_ioctl_measure(file, argp);
5015 #ifdef CONFIG_COMPAT
5016 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5019 * These all access 32-bit values anyway so no further
5020 * handling is necessary.
5023 case FS_IOC32_GETVERSION:
5024 cmd = FS_IOC_GETVERSION;
5028 return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));