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>
33 #include "transaction.h"
34 #include "btrfs_inode.h"
35 #include "print-tree.h"
39 #include "rcu-string.h"
41 #include "dev-replace.h"
46 #include "compression.h"
47 #include "space-info.h"
48 #include "delalloc-space.h"
49 #include "block-group.h"
52 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
53 * structures are incorrect, as the timespec structure from userspace
54 * is 4 bytes too small. We define these alternatives here to teach
55 * the kernel about the 32-bit struct packing.
57 struct btrfs_ioctl_timespec_32 {
60 } __attribute__ ((__packed__));
62 struct btrfs_ioctl_received_subvol_args_32 {
63 char uuid[BTRFS_UUID_SIZE]; /* in */
64 __u64 stransid; /* in */
65 __u64 rtransid; /* out */
66 struct btrfs_ioctl_timespec_32 stime; /* in */
67 struct btrfs_ioctl_timespec_32 rtime; /* out */
69 __u64 reserved[16]; /* in */
70 } __attribute__ ((__packed__));
72 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
73 struct btrfs_ioctl_received_subvol_args_32)
76 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
77 struct btrfs_ioctl_send_args_32 {
78 __s64 send_fd; /* in */
79 __u64 clone_sources_count; /* in */
80 compat_uptr_t clone_sources; /* in */
81 __u64 parent_root; /* in */
83 __u64 reserved[4]; /* in */
84 } __attribute__ ((__packed__));
86 #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
87 struct btrfs_ioctl_send_args_32)
90 /* Mask out flags that are inappropriate for the given type of inode. */
91 static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
94 if (S_ISDIR(inode->i_mode))
96 else if (S_ISREG(inode->i_mode))
97 return flags & ~FS_DIRSYNC_FL;
99 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
103 * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
106 static unsigned int btrfs_inode_flags_to_fsflags(struct btrfs_inode *binode)
108 unsigned int iflags = 0;
109 u32 flags = binode->flags;
111 if (flags & BTRFS_INODE_SYNC)
112 iflags |= FS_SYNC_FL;
113 if (flags & BTRFS_INODE_IMMUTABLE)
114 iflags |= FS_IMMUTABLE_FL;
115 if (flags & BTRFS_INODE_APPEND)
116 iflags |= FS_APPEND_FL;
117 if (flags & BTRFS_INODE_NODUMP)
118 iflags |= FS_NODUMP_FL;
119 if (flags & BTRFS_INODE_NOATIME)
120 iflags |= FS_NOATIME_FL;
121 if (flags & BTRFS_INODE_DIRSYNC)
122 iflags |= FS_DIRSYNC_FL;
123 if (flags & BTRFS_INODE_NODATACOW)
124 iflags |= FS_NOCOW_FL;
126 if (flags & BTRFS_INODE_NOCOMPRESS)
127 iflags |= FS_NOCOMP_FL;
128 else if (flags & BTRFS_INODE_COMPRESS)
129 iflags |= FS_COMPR_FL;
135 * Update inode->i_flags based on the btrfs internal flags.
137 void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
139 struct btrfs_inode *binode = BTRFS_I(inode);
140 unsigned int new_fl = 0;
142 if (binode->flags & BTRFS_INODE_SYNC)
144 if (binode->flags & BTRFS_INODE_IMMUTABLE)
145 new_fl |= S_IMMUTABLE;
146 if (binode->flags & BTRFS_INODE_APPEND)
148 if (binode->flags & BTRFS_INODE_NOATIME)
150 if (binode->flags & BTRFS_INODE_DIRSYNC)
153 set_mask_bits(&inode->i_flags,
154 S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
159 * Check if @flags are a supported and valid set of FS_*_FL flags and that
160 * the old and new flags are not conflicting
162 static int check_fsflags(unsigned int old_flags, unsigned int flags)
164 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
165 FS_NOATIME_FL | FS_NODUMP_FL | \
166 FS_SYNC_FL | FS_DIRSYNC_FL | \
167 FS_NOCOMP_FL | FS_COMPR_FL |
171 /* COMPR and NOCOMP on new/old are valid */
172 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
175 if ((flags & FS_COMPR_FL) && (flags & FS_NOCOW_FL))
178 /* NOCOW and compression options are mutually exclusive */
179 if ((old_flags & FS_NOCOW_FL) && (flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
181 if ((flags & FS_NOCOW_FL) && (old_flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
187 static int check_fsflags_compatible(struct btrfs_fs_info *fs_info,
190 if (btrfs_is_zoned(fs_info) && (flags & FS_NOCOW_FL))
197 * Set flags/xflags from the internal inode flags. The remaining items of
198 * fsxattr are zeroed.
200 int btrfs_fileattr_get(struct dentry *dentry, struct fileattr *fa)
202 struct btrfs_inode *binode = BTRFS_I(d_inode(dentry));
204 fileattr_fill_flags(fa, btrfs_inode_flags_to_fsflags(binode));
208 int btrfs_fileattr_set(struct user_namespace *mnt_userns,
209 struct dentry *dentry, struct fileattr *fa)
211 struct inode *inode = d_inode(dentry);
212 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
213 struct btrfs_inode *binode = BTRFS_I(inode);
214 struct btrfs_root *root = binode->root;
215 struct btrfs_trans_handle *trans;
216 unsigned int fsflags, old_fsflags;
218 const char *comp = NULL;
221 if (btrfs_root_readonly(root))
224 if (fileattr_has_fsx(fa))
227 fsflags = btrfs_mask_fsflags_for_type(inode, fa->flags);
228 old_fsflags = btrfs_inode_flags_to_fsflags(binode);
229 ret = check_fsflags(old_fsflags, fsflags);
233 ret = check_fsflags_compatible(fs_info, fsflags);
237 binode_flags = binode->flags;
238 if (fsflags & FS_SYNC_FL)
239 binode_flags |= BTRFS_INODE_SYNC;
241 binode_flags &= ~BTRFS_INODE_SYNC;
242 if (fsflags & FS_IMMUTABLE_FL)
243 binode_flags |= BTRFS_INODE_IMMUTABLE;
245 binode_flags &= ~BTRFS_INODE_IMMUTABLE;
246 if (fsflags & FS_APPEND_FL)
247 binode_flags |= BTRFS_INODE_APPEND;
249 binode_flags &= ~BTRFS_INODE_APPEND;
250 if (fsflags & FS_NODUMP_FL)
251 binode_flags |= BTRFS_INODE_NODUMP;
253 binode_flags &= ~BTRFS_INODE_NODUMP;
254 if (fsflags & FS_NOATIME_FL)
255 binode_flags |= BTRFS_INODE_NOATIME;
257 binode_flags &= ~BTRFS_INODE_NOATIME;
259 /* If coming from FS_IOC_FSSETXATTR then skip unconverted flags */
260 if (!fa->flags_valid) {
261 /* 1 item for the inode */
262 trans = btrfs_start_transaction(root, 1);
264 return PTR_ERR(trans);
268 if (fsflags & FS_DIRSYNC_FL)
269 binode_flags |= BTRFS_INODE_DIRSYNC;
271 binode_flags &= ~BTRFS_INODE_DIRSYNC;
272 if (fsflags & FS_NOCOW_FL) {
273 if (S_ISREG(inode->i_mode)) {
275 * It's safe to turn csums off here, no extents exist.
276 * Otherwise we want the flag to reflect the real COW
277 * status of the file and will not set it.
279 if (inode->i_size == 0)
280 binode_flags |= BTRFS_INODE_NODATACOW |
281 BTRFS_INODE_NODATASUM;
283 binode_flags |= BTRFS_INODE_NODATACOW;
287 * Revert back under same assumptions as above
289 if (S_ISREG(inode->i_mode)) {
290 if (inode->i_size == 0)
291 binode_flags &= ~(BTRFS_INODE_NODATACOW |
292 BTRFS_INODE_NODATASUM);
294 binode_flags &= ~BTRFS_INODE_NODATACOW;
299 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
300 * flag may be changed automatically if compression code won't make
303 if (fsflags & FS_NOCOMP_FL) {
304 binode_flags &= ~BTRFS_INODE_COMPRESS;
305 binode_flags |= BTRFS_INODE_NOCOMPRESS;
306 } else if (fsflags & FS_COMPR_FL) {
308 if (IS_SWAPFILE(inode))
311 binode_flags |= BTRFS_INODE_COMPRESS;
312 binode_flags &= ~BTRFS_INODE_NOCOMPRESS;
314 comp = btrfs_compress_type2str(fs_info->compress_type);
315 if (!comp || comp[0] == 0)
316 comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
318 binode_flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
325 trans = btrfs_start_transaction(root, 3);
327 return PTR_ERR(trans);
330 ret = btrfs_set_prop(trans, inode, "btrfs.compression", comp,
333 btrfs_abort_transaction(trans, ret);
337 ret = btrfs_set_prop(trans, inode, "btrfs.compression", NULL,
339 if (ret && ret != -ENODATA) {
340 btrfs_abort_transaction(trans, ret);
346 binode->flags = binode_flags;
347 btrfs_sync_inode_flags_to_i_flags(inode);
348 inode_inc_iversion(inode);
349 inode->i_ctime = current_time(inode);
350 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
353 btrfs_end_transaction(trans);
358 * Start exclusive operation @type, return true on success
360 bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
361 enum btrfs_exclusive_operation type)
365 spin_lock(&fs_info->super_lock);
366 if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
367 fs_info->exclusive_operation = type;
370 spin_unlock(&fs_info->super_lock);
376 * Conditionally allow to enter the exclusive operation in case it's compatible
377 * with the running one. This must be paired with btrfs_exclop_start_unlock and
378 * btrfs_exclop_finish.
381 * - the same type is already running
382 * - not BTRFS_EXCLOP_NONE - this is intentionally incompatible and the caller
383 * must check the condition first that would allow none -> @type
385 bool btrfs_exclop_start_try_lock(struct btrfs_fs_info *fs_info,
386 enum btrfs_exclusive_operation type)
388 spin_lock(&fs_info->super_lock);
389 if (fs_info->exclusive_operation == type)
392 spin_unlock(&fs_info->super_lock);
396 void btrfs_exclop_start_unlock(struct btrfs_fs_info *fs_info)
398 spin_unlock(&fs_info->super_lock);
401 void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
403 spin_lock(&fs_info->super_lock);
404 WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
405 spin_unlock(&fs_info->super_lock);
406 sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
409 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
411 struct inode *inode = file_inode(file);
413 return put_user(inode->i_generation, arg);
416 static noinline int btrfs_ioctl_fitrim(struct btrfs_fs_info *fs_info,
419 struct btrfs_device *device;
420 struct request_queue *q;
421 struct fstrim_range range;
422 u64 minlen = ULLONG_MAX;
426 if (!capable(CAP_SYS_ADMIN))
430 * btrfs_trim_block_group() depends on space cache, which is not
431 * available in zoned filesystem. So, disallow fitrim on a zoned
432 * filesystem for now.
434 if (btrfs_is_zoned(fs_info))
438 * If the fs is mounted with nologreplay, which requires it to be
439 * mounted in RO mode as well, we can not allow discard on free space
440 * inside block groups, because log trees refer to extents that are not
441 * pinned in a block group's free space cache (pinning the extents is
442 * precisely the first phase of replaying a log tree).
444 if (btrfs_test_opt(fs_info, NOLOGREPLAY))
448 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
452 q = bdev_get_queue(device->bdev);
453 if (blk_queue_discard(q)) {
455 minlen = min_t(u64, q->limits.discard_granularity,
463 if (copy_from_user(&range, arg, sizeof(range)))
467 * NOTE: Don't truncate the range using super->total_bytes. Bytenr of
468 * block group is in the logical address space, which can be any
469 * sectorsize aligned bytenr in the range [0, U64_MAX].
471 if (range.len < fs_info->sb->s_blocksize)
474 range.minlen = max(range.minlen, minlen);
475 ret = btrfs_trim_fs(fs_info, &range);
479 if (copy_to_user(arg, &range, sizeof(range)))
485 int __pure btrfs_is_empty_uuid(u8 *uuid)
489 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
496 static noinline int create_subvol(struct inode *dir,
497 struct dentry *dentry,
498 const char *name, int namelen,
499 struct btrfs_qgroup_inherit *inherit)
501 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
502 struct btrfs_trans_handle *trans;
503 struct btrfs_key key;
504 struct btrfs_root_item *root_item;
505 struct btrfs_inode_item *inode_item;
506 struct extent_buffer *leaf;
507 struct btrfs_root *root = BTRFS_I(dir)->root;
508 struct btrfs_root *new_root;
509 struct btrfs_block_rsv block_rsv;
510 struct timespec64 cur_time = current_time(dir);
518 root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
522 ret = btrfs_get_free_objectid(fs_info->tree_root, &objectid);
526 ret = get_anon_bdev(&anon_dev);
531 * Don't create subvolume whose level is not zero. Or qgroup will be
532 * screwed up since it assumes subvolume qgroup's level to be 0.
534 if (btrfs_qgroup_level(objectid)) {
539 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
541 * The same as the snapshot creation, please see the comment
542 * of create_snapshot().
544 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
548 trans = btrfs_start_transaction(root, 0);
550 ret = PTR_ERR(trans);
551 btrfs_subvolume_release_metadata(root, &block_rsv);
554 trans->block_rsv = &block_rsv;
555 trans->bytes_reserved = block_rsv.size;
557 ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
561 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
562 BTRFS_NESTING_NORMAL);
568 btrfs_mark_buffer_dirty(leaf);
570 inode_item = &root_item->inode;
571 btrfs_set_stack_inode_generation(inode_item, 1);
572 btrfs_set_stack_inode_size(inode_item, 3);
573 btrfs_set_stack_inode_nlink(inode_item, 1);
574 btrfs_set_stack_inode_nbytes(inode_item,
576 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
578 btrfs_set_root_flags(root_item, 0);
579 btrfs_set_root_limit(root_item, 0);
580 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
582 btrfs_set_root_bytenr(root_item, leaf->start);
583 btrfs_set_root_generation(root_item, trans->transid);
584 btrfs_set_root_level(root_item, 0);
585 btrfs_set_root_refs(root_item, 1);
586 btrfs_set_root_used(root_item, leaf->len);
587 btrfs_set_root_last_snapshot(root_item, 0);
589 btrfs_set_root_generation_v2(root_item,
590 btrfs_root_generation(root_item));
591 generate_random_guid(root_item->uuid);
592 btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
593 btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
594 root_item->ctime = root_item->otime;
595 btrfs_set_root_ctransid(root_item, trans->transid);
596 btrfs_set_root_otransid(root_item, trans->transid);
598 btrfs_tree_unlock(leaf);
600 btrfs_set_root_dirid(root_item, BTRFS_FIRST_FREE_OBJECTID);
602 key.objectid = objectid;
604 key.type = BTRFS_ROOT_ITEM_KEY;
605 ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
609 * Since we don't abort the transaction in this case, free the
610 * tree block so that we don't leak space and leave the
611 * filesystem in an inconsistent state (an extent item in the
612 * extent tree without backreferences). Also no need to have
613 * the tree block locked since it is not in any tree at this
614 * point, so no other task can find it and use it.
616 btrfs_free_tree_block(trans, root, leaf, 0, 1);
617 free_extent_buffer(leaf);
621 free_extent_buffer(leaf);
624 key.offset = (u64)-1;
625 new_root = btrfs_get_new_fs_root(fs_info, objectid, anon_dev);
626 if (IS_ERR(new_root)) {
627 free_anon_bdev(anon_dev);
628 ret = PTR_ERR(new_root);
629 btrfs_abort_transaction(trans, ret);
632 /* Freeing will be done in btrfs_put_root() of new_root */
635 ret = btrfs_record_root_in_trans(trans, new_root);
637 btrfs_put_root(new_root);
638 btrfs_abort_transaction(trans, ret);
642 ret = btrfs_create_subvol_root(trans, new_root, root);
643 btrfs_put_root(new_root);
645 /* We potentially lose an unused inode item here */
646 btrfs_abort_transaction(trans, ret);
651 * insert the directory item
653 ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
655 btrfs_abort_transaction(trans, ret);
659 ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
660 BTRFS_FT_DIR, index);
662 btrfs_abort_transaction(trans, ret);
666 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
667 ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
669 btrfs_abort_transaction(trans, ret);
673 ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
674 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
676 btrfs_abort_transaction(trans, ret);
680 ret = btrfs_uuid_tree_add(trans, root_item->uuid,
681 BTRFS_UUID_KEY_SUBVOL, objectid);
683 btrfs_abort_transaction(trans, ret);
687 trans->block_rsv = NULL;
688 trans->bytes_reserved = 0;
689 btrfs_subvolume_release_metadata(root, &block_rsv);
691 err = btrfs_commit_transaction(trans);
696 inode = btrfs_lookup_dentry(dir, dentry);
698 return PTR_ERR(inode);
699 d_instantiate(dentry, inode);
705 free_anon_bdev(anon_dev);
710 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
711 struct dentry *dentry, bool readonly,
712 struct btrfs_qgroup_inherit *inherit)
714 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
716 struct btrfs_pending_snapshot *pending_snapshot;
717 struct btrfs_trans_handle *trans;
720 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
723 if (atomic_read(&root->nr_swapfiles)) {
725 "cannot snapshot subvolume with active swapfile");
729 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
730 if (!pending_snapshot)
733 ret = get_anon_bdev(&pending_snapshot->anon_dev);
736 pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
738 pending_snapshot->path = btrfs_alloc_path();
739 if (!pending_snapshot->root_item || !pending_snapshot->path) {
744 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
745 BTRFS_BLOCK_RSV_TEMP);
747 * 1 - parent dir inode
750 * 2 - root ref/backref
751 * 1 - root of snapshot
754 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
755 &pending_snapshot->block_rsv, 8,
760 pending_snapshot->dentry = dentry;
761 pending_snapshot->root = root;
762 pending_snapshot->readonly = readonly;
763 pending_snapshot->dir = dir;
764 pending_snapshot->inherit = inherit;
766 trans = btrfs_start_transaction(root, 0);
768 ret = PTR_ERR(trans);
772 spin_lock(&fs_info->trans_lock);
773 list_add(&pending_snapshot->list,
774 &trans->transaction->pending_snapshots);
775 spin_unlock(&fs_info->trans_lock);
777 ret = btrfs_commit_transaction(trans);
781 ret = pending_snapshot->error;
785 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
789 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
791 ret = PTR_ERR(inode);
795 d_instantiate(dentry, inode);
797 pending_snapshot->anon_dev = 0;
799 /* Prevent double freeing of anon_dev */
800 if (ret && pending_snapshot->snap)
801 pending_snapshot->snap->anon_dev = 0;
802 btrfs_put_root(pending_snapshot->snap);
803 btrfs_subvolume_release_metadata(root, &pending_snapshot->block_rsv);
805 if (pending_snapshot->anon_dev)
806 free_anon_bdev(pending_snapshot->anon_dev);
807 kfree(pending_snapshot->root_item);
808 btrfs_free_path(pending_snapshot->path);
809 kfree(pending_snapshot);
814 /* copy of may_delete in fs/namei.c()
815 * Check whether we can remove a link victim from directory dir, check
816 * whether the type of victim is right.
817 * 1. We can't do it if dir is read-only (done in permission())
818 * 2. We should have write and exec permissions on dir
819 * 3. We can't remove anything from append-only dir
820 * 4. We can't do anything with immutable dir (done in permission())
821 * 5. If the sticky bit on dir is set we should either
822 * a. be owner of dir, or
823 * b. be owner of victim, or
824 * c. have CAP_FOWNER capability
825 * 6. If the victim is append-only or immutable we can't do anything with
826 * links pointing to it.
827 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
828 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
829 * 9. We can't remove a root or mountpoint.
830 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
831 * nfs_async_unlink().
834 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
838 if (d_really_is_negative(victim))
841 BUG_ON(d_inode(victim->d_parent) != dir);
842 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
844 error = inode_permission(&init_user_ns, dir, MAY_WRITE | MAY_EXEC);
849 if (check_sticky(&init_user_ns, dir, d_inode(victim)) ||
850 IS_APPEND(d_inode(victim)) || IS_IMMUTABLE(d_inode(victim)) ||
851 IS_SWAPFILE(d_inode(victim)))
854 if (!d_is_dir(victim))
858 } else if (d_is_dir(victim))
862 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
867 /* copy of may_create in fs/namei.c() */
868 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
870 if (d_really_is_positive(child))
874 return inode_permission(&init_user_ns, dir, MAY_WRITE | MAY_EXEC);
878 * Create a new subvolume below @parent. This is largely modeled after
879 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
880 * inside this filesystem so it's quite a bit simpler.
882 static noinline int btrfs_mksubvol(const struct path *parent,
883 const char *name, int namelen,
884 struct btrfs_root *snap_src,
886 struct btrfs_qgroup_inherit *inherit)
888 struct inode *dir = d_inode(parent->dentry);
889 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
890 struct dentry *dentry;
893 error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
897 dentry = lookup_one_len(name, parent->dentry, namelen);
898 error = PTR_ERR(dentry);
902 error = btrfs_may_create(dir, dentry);
907 * even if this name doesn't exist, we may get hash collisions.
908 * check for them now when we can safely fail
910 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
916 down_read(&fs_info->subvol_sem);
918 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
922 error = create_snapshot(snap_src, dir, dentry, readonly, inherit);
924 error = create_subvol(dir, dentry, name, namelen, inherit);
927 fsnotify_mkdir(dir, dentry);
929 up_read(&fs_info->subvol_sem);
933 btrfs_inode_unlock(dir, 0);
937 static noinline int btrfs_mksnapshot(const struct path *parent,
938 const char *name, int namelen,
939 struct btrfs_root *root,
941 struct btrfs_qgroup_inherit *inherit)
944 bool snapshot_force_cow = false;
947 * Force new buffered writes to reserve space even when NOCOW is
948 * possible. This is to avoid later writeback (running dealloc) to
949 * fallback to COW mode and unexpectedly fail with ENOSPC.
951 btrfs_drew_read_lock(&root->snapshot_lock);
953 ret = btrfs_start_delalloc_snapshot(root, false);
958 * All previous writes have started writeback in NOCOW mode, so now
959 * we force future writes to fallback to COW mode during snapshot
962 atomic_inc(&root->snapshot_force_cow);
963 snapshot_force_cow = true;
965 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
967 ret = btrfs_mksubvol(parent, name, namelen,
968 root, readonly, inherit);
970 if (snapshot_force_cow)
971 atomic_dec(&root->snapshot_force_cow);
972 btrfs_drew_read_unlock(&root->snapshot_lock);
977 * When we're defragging a range, we don't want to kick it off again
978 * if it is really just waiting for delalloc to send it down.
979 * If we find a nice big extent or delalloc range for the bytes in the
980 * file you want to defrag, we return 0 to let you know to skip this
983 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
985 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
986 struct extent_map *em = NULL;
987 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
990 read_lock(&em_tree->lock);
991 em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
992 read_unlock(&em_tree->lock);
995 end = extent_map_end(em);
997 if (end - offset > thresh)
1000 /* if we already have a nice delalloc here, just stop */
1002 end = count_range_bits(io_tree, &offset, offset + thresh,
1003 thresh, EXTENT_DELALLOC, 1);
1010 * helper function to walk through a file and find extents
1011 * newer than a specific transid, and smaller than thresh.
1013 * This is used by the defragging code to find new and small
1016 static int find_new_extents(struct btrfs_root *root,
1017 struct inode *inode, u64 newer_than,
1018 u64 *off, u32 thresh)
1020 struct btrfs_path *path;
1021 struct btrfs_key min_key;
1022 struct extent_buffer *leaf;
1023 struct btrfs_file_extent_item *extent;
1026 u64 ino = btrfs_ino(BTRFS_I(inode));
1028 path = btrfs_alloc_path();
1032 min_key.objectid = ino;
1033 min_key.type = BTRFS_EXTENT_DATA_KEY;
1034 min_key.offset = *off;
1037 ret = btrfs_search_forward(root, &min_key, path, newer_than);
1041 if (min_key.objectid != ino)
1043 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
1046 leaf = path->nodes[0];
1047 extent = btrfs_item_ptr(leaf, path->slots[0],
1048 struct btrfs_file_extent_item);
1050 type = btrfs_file_extent_type(leaf, extent);
1051 if (type == BTRFS_FILE_EXTENT_REG &&
1052 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
1053 check_defrag_in_cache(inode, min_key.offset, thresh)) {
1054 *off = min_key.offset;
1055 btrfs_free_path(path);
1060 if (path->slots[0] < btrfs_header_nritems(leaf)) {
1061 btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1065 if (min_key.offset == (u64)-1)
1069 btrfs_release_path(path);
1072 btrfs_free_path(path);
1076 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
1078 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1079 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1080 struct extent_map *em;
1081 u64 len = PAGE_SIZE;
1084 * hopefully we have this extent in the tree already, try without
1085 * the full extent lock
1087 read_lock(&em_tree->lock);
1088 em = lookup_extent_mapping(em_tree, start, len);
1089 read_unlock(&em_tree->lock);
1092 struct extent_state *cached = NULL;
1093 u64 end = start + len - 1;
1095 /* get the big lock and read metadata off disk */
1096 lock_extent_bits(io_tree, start, end, &cached);
1097 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
1098 unlock_extent_cached(io_tree, start, end, &cached);
1107 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1109 struct extent_map *next;
1112 /* this is the last extent */
1113 if (em->start + em->len >= i_size_read(inode))
1116 next = defrag_lookup_extent(inode, em->start + em->len);
1117 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1119 else if ((em->block_start + em->block_len == next->block_start) &&
1120 (em->block_len > SZ_128K && next->block_len > SZ_128K))
1123 free_extent_map(next);
1127 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1128 u64 *last_len, u64 *skip, u64 *defrag_end,
1131 struct extent_map *em;
1133 bool next_mergeable = true;
1134 bool prev_mergeable = true;
1137 * make sure that once we start defragging an extent, we keep on
1140 if (start < *defrag_end)
1145 em = defrag_lookup_extent(inode, start);
1149 /* this will cover holes, and inline extents */
1150 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1156 prev_mergeable = false;
1158 next_mergeable = defrag_check_next_extent(inode, em);
1160 * we hit a real extent, if it is big or the next extent is not a
1161 * real extent, don't bother defragging it
1163 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1164 (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1168 * last_len ends up being a counter of how many bytes we've defragged.
1169 * every time we choose not to defrag an extent, we reset *last_len
1170 * so that the next tiny extent will force a defrag.
1172 * The end result of this is that tiny extents before a single big
1173 * extent will force at least part of that big extent to be defragged.
1176 *defrag_end = extent_map_end(em);
1179 *skip = extent_map_end(em);
1183 free_extent_map(em);
1188 * it doesn't do much good to defrag one or two pages
1189 * at a time. This pulls in a nice chunk of pages
1190 * to COW and defrag.
1192 * It also makes sure the delalloc code has enough
1193 * dirty data to avoid making new small extents as part
1196 * It's a good idea to start RA on this range
1197 * before calling this.
1199 static int cluster_pages_for_defrag(struct inode *inode,
1200 struct page **pages,
1201 unsigned long start_index,
1202 unsigned long num_pages)
1204 unsigned long file_end;
1205 u64 isize = i_size_read(inode);
1209 u64 start = (u64)start_index << PAGE_SHIFT;
1214 struct btrfs_ordered_extent *ordered;
1215 struct extent_state *cached_state = NULL;
1216 struct extent_io_tree *tree;
1217 struct extent_changeset *data_reserved = NULL;
1218 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1220 file_end = (isize - 1) >> PAGE_SHIFT;
1221 if (!isize || start_index > file_end)
1224 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1226 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
1227 start, page_cnt << PAGE_SHIFT);
1231 tree = &BTRFS_I(inode)->io_tree;
1233 /* step one, lock all the pages */
1234 for (i = 0; i < page_cnt; i++) {
1237 page = find_or_create_page(inode->i_mapping,
1238 start_index + i, mask);
1242 ret = set_page_extent_mapped(page);
1249 page_start = page_offset(page);
1250 page_end = page_start + PAGE_SIZE - 1;
1252 lock_extent_bits(tree, page_start, page_end,
1254 ordered = btrfs_lookup_ordered_extent(BTRFS_I(inode),
1256 unlock_extent_cached(tree, page_start, page_end,
1262 btrfs_start_ordered_extent(ordered, 1);
1263 btrfs_put_ordered_extent(ordered);
1266 * we unlocked the page above, so we need check if
1267 * it was released or not.
1269 if (page->mapping != inode->i_mapping) {
1276 if (!PageUptodate(page)) {
1277 btrfs_readpage(NULL, page);
1279 if (!PageUptodate(page)) {
1287 if (page->mapping != inode->i_mapping) {
1299 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1303 * so now we have a nice long stream of locked
1304 * and up to date pages, lets wait on them
1306 for (i = 0; i < i_done; i++)
1307 wait_on_page_writeback(pages[i]);
1309 page_start = page_offset(pages[0]);
1310 page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
1312 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1313 page_start, page_end - 1, &cached_state);
1316 * When defragmenting we skip ranges that have holes or inline extents,
1317 * (check should_defrag_range()), to avoid unnecessary IO and wasting
1318 * space. At btrfs_defrag_file(), we check if a range should be defragged
1319 * before locking the inode and then, if it should, we trigger a sync
1320 * page cache readahead - we lock the inode only after that to avoid
1321 * blocking for too long other tasks that possibly want to operate on
1322 * other file ranges. But before we were able to get the inode lock,
1323 * some other task may have punched a hole in the range, or we may have
1324 * now an inline extent, in which case we should not defrag. So check
1325 * for that here, where we have the inode and the range locked, and bail
1326 * out if that happened.
1328 search_start = page_start;
1329 while (search_start < page_end) {
1330 struct extent_map *em;
1332 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, search_start,
1333 page_end - search_start);
1336 goto out_unlock_range;
1338 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1339 free_extent_map(em);
1340 /* Ok, 0 means we did not defrag anything */
1342 goto out_unlock_range;
1344 search_start = extent_map_end(em);
1345 free_extent_map(em);
1348 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1349 page_end - 1, EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
1350 EXTENT_DEFRAG, 0, 0, &cached_state);
1352 if (i_done != page_cnt) {
1353 spin_lock(&BTRFS_I(inode)->lock);
1354 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1355 spin_unlock(&BTRFS_I(inode)->lock);
1356 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved,
1357 start, (page_cnt - i_done) << PAGE_SHIFT, true);
1361 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1364 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1365 page_start, page_end - 1, &cached_state);
1367 for (i = 0; i < i_done; i++) {
1368 clear_page_dirty_for_io(pages[i]);
1369 ClearPageChecked(pages[i]);
1370 set_page_dirty(pages[i]);
1371 unlock_page(pages[i]);
1374 btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT);
1375 extent_changeset_free(data_reserved);
1379 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1380 page_start, page_end - 1, &cached_state);
1382 for (i = 0; i < i_done; i++) {
1383 unlock_page(pages[i]);
1386 btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved,
1387 start, page_cnt << PAGE_SHIFT, true);
1388 btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT);
1389 extent_changeset_free(data_reserved);
1394 int btrfs_defrag_file(struct inode *inode, struct file *file,
1395 struct btrfs_ioctl_defrag_range_args *range,
1396 u64 newer_than, unsigned long max_to_defrag)
1398 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1399 struct btrfs_root *root = BTRFS_I(inode)->root;
1400 struct file_ra_state *ra = NULL;
1401 unsigned long last_index;
1402 u64 isize = i_size_read(inode);
1406 u64 newer_off = range->start;
1408 unsigned long ra_index = 0;
1410 int defrag_count = 0;
1411 int compress_type = BTRFS_COMPRESS_ZLIB;
1412 u32 extent_thresh = range->extent_thresh;
1413 unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1414 unsigned long cluster = max_cluster;
1415 u64 new_align = ~((u64)SZ_128K - 1);
1416 struct page **pages = NULL;
1417 bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1422 if (range->start >= isize)
1426 if (range->compress_type >= BTRFS_NR_COMPRESS_TYPES)
1428 if (range->compress_type)
1429 compress_type = range->compress_type;
1432 if (extent_thresh == 0)
1433 extent_thresh = SZ_256K;
1436 * If we were not given a file, allocate a readahead context. As
1437 * readahead is just an optimization, defrag will work without it so
1438 * we don't error out.
1441 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1443 file_ra_state_init(ra, inode->i_mapping);
1448 pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
1454 /* find the last page to defrag */
1455 if (range->start + range->len > range->start) {
1456 last_index = min_t(u64, isize - 1,
1457 range->start + range->len - 1) >> PAGE_SHIFT;
1459 last_index = (isize - 1) >> PAGE_SHIFT;
1463 ret = find_new_extents(root, inode, newer_than,
1464 &newer_off, SZ_64K);
1466 range->start = newer_off;
1468 * we always align our defrag to help keep
1469 * the extents in the file evenly spaced
1471 i = (newer_off & new_align) >> PAGE_SHIFT;
1475 i = range->start >> PAGE_SHIFT;
1478 max_to_defrag = last_index - i + 1;
1481 * make writeback starts from i, so the defrag range can be
1482 * written sequentially.
1484 if (i < inode->i_mapping->writeback_index)
1485 inode->i_mapping->writeback_index = i;
1487 while (i <= last_index && defrag_count < max_to_defrag &&
1488 (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
1490 * make sure we stop running if someone unmounts
1493 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1496 if (btrfs_defrag_cancelled(fs_info)) {
1497 btrfs_debug(fs_info, "defrag_file cancelled");
1502 if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
1503 extent_thresh, &last_len, &skip,
1504 &defrag_end, do_compress)){
1507 * the should_defrag function tells us how much to skip
1508 * bump our counter by the suggested amount
1510 next = DIV_ROUND_UP(skip, PAGE_SIZE);
1511 i = max(i + 1, next);
1516 cluster = (PAGE_ALIGN(defrag_end) >>
1518 cluster = min(cluster, max_cluster);
1520 cluster = max_cluster;
1523 if (i + cluster > ra_index) {
1524 ra_index = max(i, ra_index);
1526 page_cache_sync_readahead(inode->i_mapping, ra,
1527 file, ra_index, cluster);
1528 ra_index += cluster;
1531 btrfs_inode_lock(inode, 0);
1532 if (IS_SWAPFILE(inode)) {
1536 BTRFS_I(inode)->defrag_compress = compress_type;
1537 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1540 btrfs_inode_unlock(inode, 0);
1544 defrag_count += ret;
1545 balance_dirty_pages_ratelimited(inode->i_mapping);
1546 btrfs_inode_unlock(inode, 0);
1549 if (newer_off == (u64)-1)
1555 newer_off = max(newer_off + 1,
1556 (u64)i << PAGE_SHIFT);
1558 ret = find_new_extents(root, inode, newer_than,
1559 &newer_off, SZ_64K);
1561 range->start = newer_off;
1562 i = (newer_off & new_align) >> PAGE_SHIFT;
1569 last_len += ret << PAGE_SHIFT;
1579 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1580 filemap_flush(inode->i_mapping);
1581 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1582 &BTRFS_I(inode)->runtime_flags))
1583 filemap_flush(inode->i_mapping);
1586 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1587 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1588 } else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
1589 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1594 btrfs_inode_lock(inode, 0);
1595 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1596 btrfs_inode_unlock(inode, 0);
1605 * Try to start exclusive operation @type or cancel it if it's running.
1608 * 0 - normal mode, newly claimed op started
1609 * >0 - normal mode, something else is running,
1610 * return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS to user space
1611 * ECANCELED - cancel mode, successful cancel
1612 * ENOTCONN - cancel mode, operation not running anymore
1614 static int exclop_start_or_cancel_reloc(struct btrfs_fs_info *fs_info,
1615 enum btrfs_exclusive_operation type, bool cancel)
1618 /* Start normal op */
1619 if (!btrfs_exclop_start(fs_info, type))
1620 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1621 /* Exclusive operation is now claimed */
1625 /* Cancel running op */
1626 if (btrfs_exclop_start_try_lock(fs_info, type)) {
1628 * This blocks any exclop finish from setting it to NONE, so we
1629 * request cancellation. Either it runs and we will wait for it,
1630 * or it has finished and no waiting will happen.
1632 atomic_inc(&fs_info->reloc_cancel_req);
1633 btrfs_exclop_start_unlock(fs_info);
1635 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
1636 wait_on_bit(&fs_info->flags, BTRFS_FS_RELOC_RUNNING,
1637 TASK_INTERRUPTIBLE);
1642 /* Something else is running or none */
1646 static noinline int btrfs_ioctl_resize(struct file *file,
1649 struct inode *inode = file_inode(file);
1650 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1654 struct btrfs_root *root = BTRFS_I(inode)->root;
1655 struct btrfs_ioctl_vol_args *vol_args;
1656 struct btrfs_trans_handle *trans;
1657 struct btrfs_device *device = NULL;
1660 char *devstr = NULL;
1665 if (!capable(CAP_SYS_ADMIN))
1668 ret = mnt_want_write_file(file);
1673 * Read the arguments before checking exclusivity to be able to
1674 * distinguish regular resize and cancel
1676 vol_args = memdup_user(arg, sizeof(*vol_args));
1677 if (IS_ERR(vol_args)) {
1678 ret = PTR_ERR(vol_args);
1681 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1682 sizestr = vol_args->name;
1683 cancel = (strcmp("cancel", sizestr) == 0);
1684 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_RESIZE, cancel);
1687 /* Exclusive operation is now claimed */
1689 devstr = strchr(sizestr, ':');
1691 sizestr = devstr + 1;
1693 devstr = vol_args->name;
1694 ret = kstrtoull(devstr, 10, &devid);
1701 btrfs_info(fs_info, "resizing devid %llu", devid);
1704 device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);
1706 btrfs_info(fs_info, "resizer unable to find device %llu",
1712 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1714 "resizer unable to apply on readonly device %llu",
1720 if (!strcmp(sizestr, "max"))
1721 new_size = device->bdev->bd_inode->i_size;
1723 if (sizestr[0] == '-') {
1726 } else if (sizestr[0] == '+') {
1730 new_size = memparse(sizestr, &retptr);
1731 if (*retptr != '\0' || new_size == 0) {
1737 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1742 old_size = btrfs_device_get_total_bytes(device);
1745 if (new_size > old_size) {
1749 new_size = old_size - new_size;
1750 } else if (mod > 0) {
1751 if (new_size > ULLONG_MAX - old_size) {
1755 new_size = old_size + new_size;
1758 if (new_size < SZ_256M) {
1762 if (new_size > device->bdev->bd_inode->i_size) {
1767 new_size = round_down(new_size, fs_info->sectorsize);
1769 if (new_size > old_size) {
1770 trans = btrfs_start_transaction(root, 0);
1771 if (IS_ERR(trans)) {
1772 ret = PTR_ERR(trans);
1775 ret = btrfs_grow_device(trans, device, new_size);
1776 btrfs_commit_transaction(trans);
1777 } else if (new_size < old_size) {
1778 ret = btrfs_shrink_device(device, new_size);
1779 } /* equal, nothing need to do */
1781 if (ret == 0 && new_size != old_size)
1782 btrfs_info_in_rcu(fs_info,
1783 "resize device %s (devid %llu) from %llu to %llu",
1784 rcu_str_deref(device->name), device->devid,
1785 old_size, new_size);
1787 btrfs_exclop_finish(fs_info);
1791 mnt_drop_write_file(file);
1795 static noinline int __btrfs_ioctl_snap_create(struct file *file,
1796 const char *name, unsigned long fd, int subvol,
1798 struct btrfs_qgroup_inherit *inherit)
1803 if (!S_ISDIR(file_inode(file)->i_mode))
1806 ret = mnt_want_write_file(file);
1810 namelen = strlen(name);
1811 if (strchr(name, '/')) {
1813 goto out_drop_write;
1816 if (name[0] == '.' &&
1817 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1819 goto out_drop_write;
1823 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1824 NULL, readonly, inherit);
1826 struct fd src = fdget(fd);
1827 struct inode *src_inode;
1830 goto out_drop_write;
1833 src_inode = file_inode(src.file);
1834 if (src_inode->i_sb != file_inode(file)->i_sb) {
1835 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1836 "Snapshot src from another FS");
1838 } else if (!inode_owner_or_capable(&init_user_ns, src_inode)) {
1840 * Subvolume creation is not restricted, but snapshots
1841 * are limited to own subvolumes only
1845 ret = btrfs_mksnapshot(&file->f_path, name, namelen,
1846 BTRFS_I(src_inode)->root,
1852 mnt_drop_write_file(file);
1857 static noinline int btrfs_ioctl_snap_create(struct file *file,
1858 void __user *arg, int subvol)
1860 struct btrfs_ioctl_vol_args *vol_args;
1863 if (!S_ISDIR(file_inode(file)->i_mode))
1866 vol_args = memdup_user(arg, sizeof(*vol_args));
1867 if (IS_ERR(vol_args))
1868 return PTR_ERR(vol_args);
1869 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1871 ret = __btrfs_ioctl_snap_create(file, vol_args->name, vol_args->fd,
1872 subvol, false, NULL);
1878 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1879 void __user *arg, int subvol)
1881 struct btrfs_ioctl_vol_args_v2 *vol_args;
1883 bool readonly = false;
1884 struct btrfs_qgroup_inherit *inherit = NULL;
1886 if (!S_ISDIR(file_inode(file)->i_mode))
1889 vol_args = memdup_user(arg, sizeof(*vol_args));
1890 if (IS_ERR(vol_args))
1891 return PTR_ERR(vol_args);
1892 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1894 if (vol_args->flags & ~BTRFS_SUBVOL_CREATE_ARGS_MASK) {
1899 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1901 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1904 if (vol_args->size < sizeof(*inherit) ||
1905 vol_args->size > PAGE_SIZE) {
1909 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1910 if (IS_ERR(inherit)) {
1911 ret = PTR_ERR(inherit);
1915 if (inherit->num_qgroups > PAGE_SIZE ||
1916 inherit->num_ref_copies > PAGE_SIZE ||
1917 inherit->num_excl_copies > PAGE_SIZE) {
1922 nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
1923 2 * inherit->num_excl_copies;
1924 if (vol_args->size != struct_size(inherit, qgroups, nums)) {
1930 ret = __btrfs_ioctl_snap_create(file, vol_args->name, vol_args->fd,
1931 subvol, readonly, inherit);
1941 static noinline int btrfs_ioctl_subvol_getflags(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;
1950 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1953 down_read(&fs_info->subvol_sem);
1954 if (btrfs_root_readonly(root))
1955 flags |= BTRFS_SUBVOL_RDONLY;
1956 up_read(&fs_info->subvol_sem);
1958 if (copy_to_user(arg, &flags, sizeof(flags)))
1964 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1967 struct inode *inode = file_inode(file);
1968 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1969 struct btrfs_root *root = BTRFS_I(inode)->root;
1970 struct btrfs_trans_handle *trans;
1975 if (!inode_owner_or_capable(&init_user_ns, inode))
1978 ret = mnt_want_write_file(file);
1982 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1984 goto out_drop_write;
1987 if (copy_from_user(&flags, arg, sizeof(flags))) {
1989 goto out_drop_write;
1992 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1994 goto out_drop_write;
1997 down_write(&fs_info->subvol_sem);
2000 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
2003 root_flags = btrfs_root_flags(&root->root_item);
2004 if (flags & BTRFS_SUBVOL_RDONLY) {
2005 btrfs_set_root_flags(&root->root_item,
2006 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
2009 * Block RO -> RW transition if this subvolume is involved in
2012 spin_lock(&root->root_item_lock);
2013 if (root->send_in_progress == 0) {
2014 btrfs_set_root_flags(&root->root_item,
2015 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
2016 spin_unlock(&root->root_item_lock);
2018 spin_unlock(&root->root_item_lock);
2020 "Attempt to set subvolume %llu read-write during send",
2021 root->root_key.objectid);
2027 trans = btrfs_start_transaction(root, 1);
2028 if (IS_ERR(trans)) {
2029 ret = PTR_ERR(trans);
2033 ret = btrfs_update_root(trans, fs_info->tree_root,
2034 &root->root_key, &root->root_item);
2036 btrfs_end_transaction(trans);
2040 ret = btrfs_commit_transaction(trans);
2044 btrfs_set_root_flags(&root->root_item, root_flags);
2046 up_write(&fs_info->subvol_sem);
2048 mnt_drop_write_file(file);
2053 static noinline int key_in_sk(struct btrfs_key *key,
2054 struct btrfs_ioctl_search_key *sk)
2056 struct btrfs_key test;
2059 test.objectid = sk->min_objectid;
2060 test.type = sk->min_type;
2061 test.offset = sk->min_offset;
2063 ret = btrfs_comp_cpu_keys(key, &test);
2067 test.objectid = sk->max_objectid;
2068 test.type = sk->max_type;
2069 test.offset = sk->max_offset;
2071 ret = btrfs_comp_cpu_keys(key, &test);
2077 static noinline int copy_to_sk(struct btrfs_path *path,
2078 struct btrfs_key *key,
2079 struct btrfs_ioctl_search_key *sk,
2082 unsigned long *sk_offset,
2086 struct extent_buffer *leaf;
2087 struct btrfs_ioctl_search_header sh;
2088 struct btrfs_key test;
2089 unsigned long item_off;
2090 unsigned long item_len;
2096 leaf = path->nodes[0];
2097 slot = path->slots[0];
2098 nritems = btrfs_header_nritems(leaf);
2100 if (btrfs_header_generation(leaf) > sk->max_transid) {
2104 found_transid = btrfs_header_generation(leaf);
2106 for (i = slot; i < nritems; i++) {
2107 item_off = btrfs_item_ptr_offset(leaf, i);
2108 item_len = btrfs_item_size_nr(leaf, i);
2110 btrfs_item_key_to_cpu(leaf, key, i);
2111 if (!key_in_sk(key, sk))
2114 if (sizeof(sh) + item_len > *buf_size) {
2121 * return one empty item back for v1, which does not
2125 *buf_size = sizeof(sh) + item_len;
2130 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2135 sh.objectid = key->objectid;
2136 sh.offset = key->offset;
2137 sh.type = key->type;
2139 sh.transid = found_transid;
2142 * Copy search result header. If we fault then loop again so we
2143 * can fault in the pages and -EFAULT there if there's a
2144 * problem. Otherwise we'll fault and then copy the buffer in
2145 * properly this next time through
2147 if (copy_to_user_nofault(ubuf + *sk_offset, &sh, sizeof(sh))) {
2152 *sk_offset += sizeof(sh);
2155 char __user *up = ubuf + *sk_offset;
2157 * Copy the item, same behavior as above, but reset the
2158 * * sk_offset so we copy the full thing again.
2160 if (read_extent_buffer_to_user_nofault(leaf, up,
2161 item_off, item_len)) {
2163 *sk_offset -= sizeof(sh);
2167 *sk_offset += item_len;
2171 if (ret) /* -EOVERFLOW from above */
2174 if (*num_found >= sk->nr_items) {
2181 test.objectid = sk->max_objectid;
2182 test.type = sk->max_type;
2183 test.offset = sk->max_offset;
2184 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2186 else if (key->offset < (u64)-1)
2188 else if (key->type < (u8)-1) {
2191 } else if (key->objectid < (u64)-1) {
2199 * 0: all items from this leaf copied, continue with next
2200 * 1: * more items can be copied, but unused buffer is too small
2201 * * all items were found
2202 * Either way, it will stops the loop which iterates to the next
2204 * -EOVERFLOW: item was to large for buffer
2205 * -EFAULT: could not copy extent buffer back to userspace
2210 static noinline int search_ioctl(struct inode *inode,
2211 struct btrfs_ioctl_search_key *sk,
2215 struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2216 struct btrfs_root *root;
2217 struct btrfs_key key;
2218 struct btrfs_path *path;
2221 unsigned long sk_offset = 0;
2223 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2224 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2228 path = btrfs_alloc_path();
2232 if (sk->tree_id == 0) {
2233 /* search the root of the inode that was passed */
2234 root = btrfs_grab_root(BTRFS_I(inode)->root);
2236 root = btrfs_get_fs_root(info, sk->tree_id, true);
2238 btrfs_free_path(path);
2239 return PTR_ERR(root);
2243 key.objectid = sk->min_objectid;
2244 key.type = sk->min_type;
2245 key.offset = sk->min_offset;
2248 ret = fault_in_pages_writeable(ubuf + sk_offset,
2249 *buf_size - sk_offset);
2253 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2259 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2260 &sk_offset, &num_found);
2261 btrfs_release_path(path);
2269 sk->nr_items = num_found;
2270 btrfs_put_root(root);
2271 btrfs_free_path(path);
2275 static noinline int btrfs_ioctl_tree_search(struct file *file,
2278 struct btrfs_ioctl_search_args __user *uargs;
2279 struct btrfs_ioctl_search_key sk;
2280 struct inode *inode;
2284 if (!capable(CAP_SYS_ADMIN))
2287 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2289 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2292 buf_size = sizeof(uargs->buf);
2294 inode = file_inode(file);
2295 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2298 * In the origin implementation an overflow is handled by returning a
2299 * search header with a len of zero, so reset ret.
2301 if (ret == -EOVERFLOW)
2304 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2309 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2312 struct btrfs_ioctl_search_args_v2 __user *uarg;
2313 struct btrfs_ioctl_search_args_v2 args;
2314 struct inode *inode;
2317 const size_t buf_limit = SZ_16M;
2319 if (!capable(CAP_SYS_ADMIN))
2322 /* copy search header and buffer size */
2323 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2324 if (copy_from_user(&args, uarg, sizeof(args)))
2327 buf_size = args.buf_size;
2329 /* limit result size to 16MB */
2330 if (buf_size > buf_limit)
2331 buf_size = buf_limit;
2333 inode = file_inode(file);
2334 ret = search_ioctl(inode, &args.key, &buf_size,
2335 (char __user *)(&uarg->buf[0]));
2336 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2338 else if (ret == -EOVERFLOW &&
2339 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2346 * Search INODE_REFs to identify path name of 'dirid' directory
2347 * in a 'tree_id' tree. and sets path name to 'name'.
2349 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2350 u64 tree_id, u64 dirid, char *name)
2352 struct btrfs_root *root;
2353 struct btrfs_key key;
2359 struct btrfs_inode_ref *iref;
2360 struct extent_buffer *l;
2361 struct btrfs_path *path;
2363 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2368 path = btrfs_alloc_path();
2372 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2374 root = btrfs_get_fs_root(info, tree_id, true);
2376 ret = PTR_ERR(root);
2381 key.objectid = dirid;
2382 key.type = BTRFS_INODE_REF_KEY;
2383 key.offset = (u64)-1;
2386 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2390 ret = btrfs_previous_item(root, path, dirid,
2391 BTRFS_INODE_REF_KEY);
2401 slot = path->slots[0];
2402 btrfs_item_key_to_cpu(l, &key, slot);
2404 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2405 len = btrfs_inode_ref_name_len(l, iref);
2407 total_len += len + 1;
2409 ret = -ENAMETOOLONG;
2414 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2416 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2419 btrfs_release_path(path);
2420 key.objectid = key.offset;
2421 key.offset = (u64)-1;
2422 dirid = key.objectid;
2424 memmove(name, ptr, total_len);
2425 name[total_len] = '\0';
2428 btrfs_put_root(root);
2429 btrfs_free_path(path);
2433 static int btrfs_search_path_in_tree_user(struct inode *inode,
2434 struct btrfs_ioctl_ino_lookup_user_args *args)
2436 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2437 struct super_block *sb = inode->i_sb;
2438 struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2439 u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2440 u64 dirid = args->dirid;
2441 unsigned long item_off;
2442 unsigned long item_len;
2443 struct btrfs_inode_ref *iref;
2444 struct btrfs_root_ref *rref;
2445 struct btrfs_root *root = NULL;
2446 struct btrfs_path *path;
2447 struct btrfs_key key, key2;
2448 struct extent_buffer *leaf;
2449 struct inode *temp_inode;
2456 path = btrfs_alloc_path();
2461 * If the bottom subvolume does not exist directly under upper_limit,
2462 * construct the path in from the bottom up.
2464 if (dirid != upper_limit.objectid) {
2465 ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2467 root = btrfs_get_fs_root(fs_info, treeid, true);
2469 ret = PTR_ERR(root);
2473 key.objectid = dirid;
2474 key.type = BTRFS_INODE_REF_KEY;
2475 key.offset = (u64)-1;
2477 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2480 } else if (ret > 0) {
2481 ret = btrfs_previous_item(root, path, dirid,
2482 BTRFS_INODE_REF_KEY);
2485 } else if (ret > 0) {
2491 leaf = path->nodes[0];
2492 slot = path->slots[0];
2493 btrfs_item_key_to_cpu(leaf, &key, slot);
2495 iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2496 len = btrfs_inode_ref_name_len(leaf, iref);
2498 total_len += len + 1;
2499 if (ptr < args->path) {
2500 ret = -ENAMETOOLONG;
2505 read_extent_buffer(leaf, ptr,
2506 (unsigned long)(iref + 1), len);
2508 /* Check the read+exec permission of this directory */
2509 ret = btrfs_previous_item(root, path, dirid,
2510 BTRFS_INODE_ITEM_KEY);
2513 } else if (ret > 0) {
2518 leaf = path->nodes[0];
2519 slot = path->slots[0];
2520 btrfs_item_key_to_cpu(leaf, &key2, slot);
2521 if (key2.objectid != dirid) {
2526 temp_inode = btrfs_iget(sb, key2.objectid, root);
2527 if (IS_ERR(temp_inode)) {
2528 ret = PTR_ERR(temp_inode);
2531 ret = inode_permission(&init_user_ns, temp_inode,
2532 MAY_READ | MAY_EXEC);
2539 if (key.offset == upper_limit.objectid)
2541 if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2546 btrfs_release_path(path);
2547 key.objectid = key.offset;
2548 key.offset = (u64)-1;
2549 dirid = key.objectid;
2552 memmove(args->path, ptr, total_len);
2553 args->path[total_len] = '\0';
2554 btrfs_put_root(root);
2556 btrfs_release_path(path);
2559 /* Get the bottom subvolume's name from ROOT_REF */
2560 key.objectid = treeid;
2561 key.type = BTRFS_ROOT_REF_KEY;
2562 key.offset = args->treeid;
2563 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2566 } else if (ret > 0) {
2571 leaf = path->nodes[0];
2572 slot = path->slots[0];
2573 btrfs_item_key_to_cpu(leaf, &key, slot);
2575 item_off = btrfs_item_ptr_offset(leaf, slot);
2576 item_len = btrfs_item_size_nr(leaf, slot);
2577 /* Check if dirid in ROOT_REF corresponds to passed dirid */
2578 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2579 if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2584 /* Copy subvolume's name */
2585 item_off += sizeof(struct btrfs_root_ref);
2586 item_len -= sizeof(struct btrfs_root_ref);
2587 read_extent_buffer(leaf, args->name, item_off, item_len);
2588 args->name[item_len] = 0;
2591 btrfs_put_root(root);
2593 btrfs_free_path(path);
2597 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2600 struct btrfs_ioctl_ino_lookup_args *args;
2601 struct inode *inode;
2604 args = memdup_user(argp, sizeof(*args));
2606 return PTR_ERR(args);
2608 inode = file_inode(file);
2611 * Unprivileged query to obtain the containing subvolume root id. The
2612 * path is reset so it's consistent with btrfs_search_path_in_tree.
2614 if (args->treeid == 0)
2615 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2617 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2622 if (!capable(CAP_SYS_ADMIN)) {
2627 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2628 args->treeid, args->objectid,
2632 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2640 * Version of ino_lookup ioctl (unprivileged)
2642 * The main differences from ino_lookup ioctl are:
2644 * 1. Read + Exec permission will be checked using inode_permission() during
2645 * path construction. -EACCES will be returned in case of failure.
2646 * 2. Path construction will be stopped at the inode number which corresponds
2647 * to the fd with which this ioctl is called. If constructed path does not
2648 * exist under fd's inode, -EACCES will be returned.
2649 * 3. The name of bottom subvolume is also searched and filled.
2651 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2653 struct btrfs_ioctl_ino_lookup_user_args *args;
2654 struct inode *inode;
2657 args = memdup_user(argp, sizeof(*args));
2659 return PTR_ERR(args);
2661 inode = file_inode(file);
2663 if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2664 BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2666 * The subvolume does not exist under fd with which this is
2673 ret = btrfs_search_path_in_tree_user(inode, args);
2675 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2682 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2683 static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2685 struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2686 struct btrfs_fs_info *fs_info;
2687 struct btrfs_root *root;
2688 struct btrfs_path *path;
2689 struct btrfs_key key;
2690 struct btrfs_root_item *root_item;
2691 struct btrfs_root_ref *rref;
2692 struct extent_buffer *leaf;
2693 unsigned long item_off;
2694 unsigned long item_len;
2695 struct inode *inode;
2699 path = btrfs_alloc_path();
2703 subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2705 btrfs_free_path(path);
2709 inode = file_inode(file);
2710 fs_info = BTRFS_I(inode)->root->fs_info;
2712 /* Get root_item of inode's subvolume */
2713 key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2714 root = btrfs_get_fs_root(fs_info, key.objectid, true);
2716 ret = PTR_ERR(root);
2719 root_item = &root->root_item;
2721 subvol_info->treeid = key.objectid;
2723 subvol_info->generation = btrfs_root_generation(root_item);
2724 subvol_info->flags = btrfs_root_flags(root_item);
2726 memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2727 memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2729 memcpy(subvol_info->received_uuid, root_item->received_uuid,
2732 subvol_info->ctransid = btrfs_root_ctransid(root_item);
2733 subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2734 subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2736 subvol_info->otransid = btrfs_root_otransid(root_item);
2737 subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2738 subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2740 subvol_info->stransid = btrfs_root_stransid(root_item);
2741 subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2742 subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2744 subvol_info->rtransid = btrfs_root_rtransid(root_item);
2745 subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2746 subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2748 if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2749 /* Search root tree for ROOT_BACKREF of this subvolume */
2750 key.type = BTRFS_ROOT_BACKREF_KEY;
2752 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2755 } else if (path->slots[0] >=
2756 btrfs_header_nritems(path->nodes[0])) {
2757 ret = btrfs_next_leaf(fs_info->tree_root, path);
2760 } else if (ret > 0) {
2766 leaf = path->nodes[0];
2767 slot = path->slots[0];
2768 btrfs_item_key_to_cpu(leaf, &key, slot);
2769 if (key.objectid == subvol_info->treeid &&
2770 key.type == BTRFS_ROOT_BACKREF_KEY) {
2771 subvol_info->parent_id = key.offset;
2773 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2774 subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2776 item_off = btrfs_item_ptr_offset(leaf, slot)
2777 + sizeof(struct btrfs_root_ref);
2778 item_len = btrfs_item_size_nr(leaf, slot)
2779 - sizeof(struct btrfs_root_ref);
2780 read_extent_buffer(leaf, subvol_info->name,
2781 item_off, item_len);
2788 if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2792 btrfs_put_root(root);
2794 btrfs_free_path(path);
2800 * Return ROOT_REF information of the subvolume containing this inode
2801 * except the subvolume name.
2803 static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
2805 struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
2806 struct btrfs_root_ref *rref;
2807 struct btrfs_root *root;
2808 struct btrfs_path *path;
2809 struct btrfs_key key;
2810 struct extent_buffer *leaf;
2811 struct inode *inode;
2817 path = btrfs_alloc_path();
2821 rootrefs = memdup_user(argp, sizeof(*rootrefs));
2822 if (IS_ERR(rootrefs)) {
2823 btrfs_free_path(path);
2824 return PTR_ERR(rootrefs);
2827 inode = file_inode(file);
2828 root = BTRFS_I(inode)->root->fs_info->tree_root;
2829 objectid = BTRFS_I(inode)->root->root_key.objectid;
2831 key.objectid = objectid;
2832 key.type = BTRFS_ROOT_REF_KEY;
2833 key.offset = rootrefs->min_treeid;
2836 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2839 } else if (path->slots[0] >=
2840 btrfs_header_nritems(path->nodes[0])) {
2841 ret = btrfs_next_leaf(root, path);
2844 } else if (ret > 0) {
2850 leaf = path->nodes[0];
2851 slot = path->slots[0];
2853 btrfs_item_key_to_cpu(leaf, &key, slot);
2854 if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
2859 if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
2864 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2865 rootrefs->rootref[found].treeid = key.offset;
2866 rootrefs->rootref[found].dirid =
2867 btrfs_root_ref_dirid(leaf, rref);
2870 ret = btrfs_next_item(root, path);
2873 } else if (ret > 0) {
2880 if (!ret || ret == -EOVERFLOW) {
2881 rootrefs->num_items = found;
2882 /* update min_treeid for next search */
2884 rootrefs->min_treeid =
2885 rootrefs->rootref[found - 1].treeid + 1;
2886 if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
2891 btrfs_free_path(path);
2896 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2900 struct dentry *parent = file->f_path.dentry;
2901 struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2902 struct dentry *dentry;
2903 struct inode *dir = d_inode(parent);
2904 struct inode *inode;
2905 struct btrfs_root *root = BTRFS_I(dir)->root;
2906 struct btrfs_root *dest = NULL;
2907 struct btrfs_ioctl_vol_args *vol_args = NULL;
2908 struct btrfs_ioctl_vol_args_v2 *vol_args2 = NULL;
2909 char *subvol_name, *subvol_name_ptr = NULL;
2912 bool destroy_parent = false;
2915 vol_args2 = memdup_user(arg, sizeof(*vol_args2));
2916 if (IS_ERR(vol_args2))
2917 return PTR_ERR(vol_args2);
2919 if (vol_args2->flags & ~BTRFS_SUBVOL_DELETE_ARGS_MASK) {
2925 * If SPEC_BY_ID is not set, we are looking for the subvolume by
2926 * name, same as v1 currently does.
2928 if (!(vol_args2->flags & BTRFS_SUBVOL_SPEC_BY_ID)) {
2929 vol_args2->name[BTRFS_SUBVOL_NAME_MAX] = 0;
2930 subvol_name = vol_args2->name;
2932 err = mnt_want_write_file(file);
2936 if (vol_args2->subvolid < BTRFS_FIRST_FREE_OBJECTID) {
2941 err = mnt_want_write_file(file);
2945 dentry = btrfs_get_dentry(fs_info->sb,
2946 BTRFS_FIRST_FREE_OBJECTID,
2947 vol_args2->subvolid, 0, 0);
2948 if (IS_ERR(dentry)) {
2949 err = PTR_ERR(dentry);
2950 goto out_drop_write;
2954 * Change the default parent since the subvolume being
2955 * deleted can be outside of the current mount point.
2957 parent = btrfs_get_parent(dentry);
2960 * At this point dentry->d_name can point to '/' if the
2961 * subvolume we want to destroy is outsite of the
2962 * current mount point, so we need to release the
2963 * current dentry and execute the lookup to return a new
2964 * one with ->d_name pointing to the
2965 * <mount point>/subvol_name.
2968 if (IS_ERR(parent)) {
2969 err = PTR_ERR(parent);
2970 goto out_drop_write;
2972 dir = d_inode(parent);
2975 * If v2 was used with SPEC_BY_ID, a new parent was
2976 * allocated since the subvolume can be outside of the
2977 * current mount point. Later on we need to release this
2978 * new parent dentry.
2980 destroy_parent = true;
2982 subvol_name_ptr = btrfs_get_subvol_name_from_objectid(
2983 fs_info, vol_args2->subvolid);
2984 if (IS_ERR(subvol_name_ptr)) {
2985 err = PTR_ERR(subvol_name_ptr);
2988 /* subvol_name_ptr is already nul terminated */
2989 subvol_name = (char *)kbasename(subvol_name_ptr);
2992 vol_args = memdup_user(arg, sizeof(*vol_args));
2993 if (IS_ERR(vol_args))
2994 return PTR_ERR(vol_args);
2996 vol_args->name[BTRFS_PATH_NAME_MAX] = 0;
2997 subvol_name = vol_args->name;
2999 err = mnt_want_write_file(file);
3004 subvol_namelen = strlen(subvol_name);
3006 if (strchr(subvol_name, '/') ||
3007 strncmp(subvol_name, "..", subvol_namelen) == 0) {
3009 goto free_subvol_name;
3012 if (!S_ISDIR(dir->i_mode)) {
3014 goto free_subvol_name;
3017 err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
3019 goto free_subvol_name;
3020 dentry = lookup_one_len(subvol_name, parent, subvol_namelen);
3021 if (IS_ERR(dentry)) {
3022 err = PTR_ERR(dentry);
3023 goto out_unlock_dir;
3026 if (d_really_is_negative(dentry)) {
3031 inode = d_inode(dentry);
3032 dest = BTRFS_I(inode)->root;
3033 if (!capable(CAP_SYS_ADMIN)) {
3035 * Regular user. Only allow this with a special mount
3036 * option, when the user has write+exec access to the
3037 * subvol root, and when rmdir(2) would have been
3040 * Note that this is _not_ check that the subvol is
3041 * empty or doesn't contain data that we wouldn't
3042 * otherwise be able to delete.
3044 * Users who want to delete empty subvols should try
3048 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
3052 * Do not allow deletion if the parent dir is the same
3053 * as the dir to be deleted. That means the ioctl
3054 * must be called on the dentry referencing the root
3055 * of the subvol, not a random directory contained
3062 err = inode_permission(&init_user_ns, inode,
3063 MAY_WRITE | MAY_EXEC);
3068 /* check if subvolume may be deleted by a user */
3069 err = btrfs_may_delete(dir, dentry, 1);
3073 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
3078 btrfs_inode_lock(inode, 0);
3079 err = btrfs_delete_subvolume(dir, dentry);
3080 btrfs_inode_unlock(inode, 0);
3082 fsnotify_rmdir(dir, dentry);
3089 btrfs_inode_unlock(dir, 0);
3091 kfree(subvol_name_ptr);
3096 mnt_drop_write_file(file);
3103 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
3105 struct inode *inode = file_inode(file);
3106 struct btrfs_root *root = BTRFS_I(inode)->root;
3107 struct btrfs_ioctl_defrag_range_args *range;
3110 ret = mnt_want_write_file(file);
3114 if (btrfs_root_readonly(root)) {
3119 /* Subpage defrag will be supported in later commits */
3120 if (root->fs_info->sectorsize < PAGE_SIZE) {
3125 switch (inode->i_mode & S_IFMT) {
3127 if (!capable(CAP_SYS_ADMIN)) {
3131 ret = btrfs_defrag_root(root);
3135 * Note that this does not check the file descriptor for write
3136 * access. This prevents defragmenting executables that are
3137 * running and allows defrag on files open in read-only mode.
3139 if (!capable(CAP_SYS_ADMIN) &&
3140 inode_permission(&init_user_ns, inode, MAY_WRITE)) {
3145 range = kzalloc(sizeof(*range), GFP_KERNEL);
3152 if (copy_from_user(range, argp,
3158 /* compression requires us to start the IO */
3159 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3160 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
3161 range->extent_thresh = (u32)-1;
3164 /* the rest are all set to zero by kzalloc */
3165 range->len = (u64)-1;
3167 ret = btrfs_defrag_file(file_inode(file), file,
3168 range, BTRFS_OLDEST_GENERATION, 0);
3177 mnt_drop_write_file(file);
3181 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3183 struct btrfs_ioctl_vol_args *vol_args;
3186 if (!capable(CAP_SYS_ADMIN))
3189 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_ADD))
3190 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3192 vol_args = memdup_user(arg, sizeof(*vol_args));
3193 if (IS_ERR(vol_args)) {
3194 ret = PTR_ERR(vol_args);
3198 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3199 ret = btrfs_init_new_device(fs_info, vol_args->name);
3202 btrfs_info(fs_info, "disk added %s", vol_args->name);
3206 btrfs_exclop_finish(fs_info);
3210 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3212 struct inode *inode = file_inode(file);
3213 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3214 struct btrfs_ioctl_vol_args_v2 *vol_args;
3216 bool cancel = false;
3218 if (!capable(CAP_SYS_ADMIN))
3221 ret = mnt_want_write_file(file);
3225 vol_args = memdup_user(arg, sizeof(*vol_args));
3226 if (IS_ERR(vol_args)) {
3227 ret = PTR_ERR(vol_args);
3231 if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
3235 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3236 if (!(vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) &&
3237 strcmp("cancel", vol_args->name) == 0)
3240 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3244 /* Exclusive operation is now claimed */
3246 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3247 ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
3249 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3251 btrfs_exclop_finish(fs_info);
3254 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3255 btrfs_info(fs_info, "device deleted: id %llu",
3258 btrfs_info(fs_info, "device deleted: %s",
3264 mnt_drop_write_file(file);
3268 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3270 struct inode *inode = file_inode(file);
3271 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3272 struct btrfs_ioctl_vol_args *vol_args;
3276 if (!capable(CAP_SYS_ADMIN))
3279 ret = mnt_want_write_file(file);
3283 vol_args = memdup_user(arg, sizeof(*vol_args));
3284 if (IS_ERR(vol_args)) {
3285 ret = PTR_ERR(vol_args);
3286 goto out_drop_write;
3288 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3289 cancel = (strcmp("cancel", vol_args->name) == 0);
3291 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3294 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3296 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3297 btrfs_exclop_finish(fs_info);
3302 mnt_drop_write_file(file);
3307 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3310 struct btrfs_ioctl_fs_info_args *fi_args;
3311 struct btrfs_device *device;
3312 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3316 fi_args = memdup_user(arg, sizeof(*fi_args));
3317 if (IS_ERR(fi_args))
3318 return PTR_ERR(fi_args);
3320 flags_in = fi_args->flags;
3321 memset(fi_args, 0, sizeof(*fi_args));
3324 fi_args->num_devices = fs_devices->num_devices;
3326 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3327 if (device->devid > fi_args->max_id)
3328 fi_args->max_id = device->devid;
3332 memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3333 fi_args->nodesize = fs_info->nodesize;
3334 fi_args->sectorsize = fs_info->sectorsize;
3335 fi_args->clone_alignment = fs_info->sectorsize;
3337 if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3338 fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3339 fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3340 fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3343 if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
3344 fi_args->generation = fs_info->generation;
3345 fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
3348 if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
3349 memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
3350 sizeof(fi_args->metadata_uuid));
3351 fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
3354 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3361 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3364 struct btrfs_ioctl_dev_info_args *di_args;
3365 struct btrfs_device *dev;
3367 char *s_uuid = NULL;
3369 di_args = memdup_user(arg, sizeof(*di_args));
3370 if (IS_ERR(di_args))
3371 return PTR_ERR(di_args);
3373 if (!btrfs_is_empty_uuid(di_args->uuid))
3374 s_uuid = di_args->uuid;
3377 dev = btrfs_find_device(fs_info->fs_devices, di_args->devid, s_uuid,
3385 di_args->devid = dev->devid;
3386 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3387 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3388 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3390 strncpy(di_args->path, rcu_str_deref(dev->name),
3391 sizeof(di_args->path) - 1);
3392 di_args->path[sizeof(di_args->path) - 1] = 0;
3394 di_args->path[0] = '\0';
3399 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3406 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3408 struct inode *inode = file_inode(file);
3409 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3410 struct btrfs_root *root = BTRFS_I(inode)->root;
3411 struct btrfs_root *new_root;
3412 struct btrfs_dir_item *di;
3413 struct btrfs_trans_handle *trans;
3414 struct btrfs_path *path = NULL;
3415 struct btrfs_disk_key disk_key;
3420 if (!capable(CAP_SYS_ADMIN))
3423 ret = mnt_want_write_file(file);
3427 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3433 objectid = BTRFS_FS_TREE_OBJECTID;
3435 new_root = btrfs_get_fs_root(fs_info, objectid, true);
3436 if (IS_ERR(new_root)) {
3437 ret = PTR_ERR(new_root);
3440 if (!is_fstree(new_root->root_key.objectid)) {
3445 path = btrfs_alloc_path();
3451 trans = btrfs_start_transaction(root, 1);
3452 if (IS_ERR(trans)) {
3453 ret = PTR_ERR(trans);
3457 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3458 di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
3459 dir_id, "default", 7, 1);
3460 if (IS_ERR_OR_NULL(di)) {
3461 btrfs_release_path(path);
3462 btrfs_end_transaction(trans);
3464 "Umm, you don't have the default diritem, this isn't going to work");
3469 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3470 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3471 btrfs_mark_buffer_dirty(path->nodes[0]);
3472 btrfs_release_path(path);
3474 btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
3475 btrfs_end_transaction(trans);
3477 btrfs_put_root(new_root);
3478 btrfs_free_path(path);
3480 mnt_drop_write_file(file);
3484 static void get_block_group_info(struct list_head *groups_list,
3485 struct btrfs_ioctl_space_info *space)
3487 struct btrfs_block_group *block_group;
3489 space->total_bytes = 0;
3490 space->used_bytes = 0;
3492 list_for_each_entry(block_group, groups_list, list) {
3493 space->flags = block_group->flags;
3494 space->total_bytes += block_group->length;
3495 space->used_bytes += block_group->used;
3499 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
3502 struct btrfs_ioctl_space_args space_args;
3503 struct btrfs_ioctl_space_info space;
3504 struct btrfs_ioctl_space_info *dest;
3505 struct btrfs_ioctl_space_info *dest_orig;
3506 struct btrfs_ioctl_space_info __user *user_dest;
3507 struct btrfs_space_info *info;
3508 static const u64 types[] = {
3509 BTRFS_BLOCK_GROUP_DATA,
3510 BTRFS_BLOCK_GROUP_SYSTEM,
3511 BTRFS_BLOCK_GROUP_METADATA,
3512 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3520 if (copy_from_user(&space_args,
3521 (struct btrfs_ioctl_space_args __user *)arg,
3522 sizeof(space_args)))
3525 for (i = 0; i < num_types; i++) {
3526 struct btrfs_space_info *tmp;
3529 list_for_each_entry(tmp, &fs_info->space_info, list) {
3530 if (tmp->flags == types[i]) {
3539 down_read(&info->groups_sem);
3540 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3541 if (!list_empty(&info->block_groups[c]))
3544 up_read(&info->groups_sem);
3548 * Global block reserve, exported as a space_info
3552 /* space_slots == 0 means they are asking for a count */
3553 if (space_args.space_slots == 0) {
3554 space_args.total_spaces = slot_count;
3558 slot_count = min_t(u64, space_args.space_slots, slot_count);
3560 alloc_size = sizeof(*dest) * slot_count;
3562 /* we generally have at most 6 or so space infos, one for each raid
3563 * level. So, a whole page should be more than enough for everyone
3565 if (alloc_size > PAGE_SIZE)
3568 space_args.total_spaces = 0;
3569 dest = kmalloc(alloc_size, GFP_KERNEL);
3574 /* now we have a buffer to copy into */
3575 for (i = 0; i < num_types; i++) {
3576 struct btrfs_space_info *tmp;
3582 list_for_each_entry(tmp, &fs_info->space_info, list) {
3583 if (tmp->flags == types[i]) {
3591 down_read(&info->groups_sem);
3592 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3593 if (!list_empty(&info->block_groups[c])) {
3594 get_block_group_info(&info->block_groups[c],
3596 memcpy(dest, &space, sizeof(space));
3598 space_args.total_spaces++;
3604 up_read(&info->groups_sem);
3608 * Add global block reserve
3611 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3613 spin_lock(&block_rsv->lock);
3614 space.total_bytes = block_rsv->size;
3615 space.used_bytes = block_rsv->size - block_rsv->reserved;
3616 spin_unlock(&block_rsv->lock);
3617 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
3618 memcpy(dest, &space, sizeof(space));
3619 space_args.total_spaces++;
3622 user_dest = (struct btrfs_ioctl_space_info __user *)
3623 (arg + sizeof(struct btrfs_ioctl_space_args));
3625 if (copy_to_user(user_dest, dest_orig, alloc_size))
3630 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3636 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3639 struct btrfs_trans_handle *trans;
3643 trans = btrfs_attach_transaction_barrier(root);
3644 if (IS_ERR(trans)) {
3645 if (PTR_ERR(trans) != -ENOENT)
3646 return PTR_ERR(trans);
3648 /* No running transaction, don't bother */
3649 transid = root->fs_info->last_trans_committed;
3652 transid = trans->transid;
3653 ret = btrfs_commit_transaction_async(trans);
3655 btrfs_end_transaction(trans);
3660 if (copy_to_user(argp, &transid, sizeof(transid)))
3665 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
3671 if (copy_from_user(&transid, argp, sizeof(transid)))
3674 transid = 0; /* current trans */
3676 return btrfs_wait_for_commit(fs_info, transid);
3679 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3681 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
3682 struct btrfs_ioctl_scrub_args *sa;
3685 if (!capable(CAP_SYS_ADMIN))
3688 sa = memdup_user(arg, sizeof(*sa));
3692 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3693 ret = mnt_want_write_file(file);
3698 ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
3699 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3703 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
3704 * error. This is important as it allows user space to know how much
3705 * progress scrub has done. For example, if scrub is canceled we get
3706 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
3707 * space. Later user space can inspect the progress from the structure
3708 * btrfs_ioctl_scrub_args and resume scrub from where it left off
3709 * previously (btrfs-progs does this).
3710 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
3711 * then return -EFAULT to signal the structure was not copied or it may
3712 * be corrupt and unreliable due to a partial copy.
3714 if (copy_to_user(arg, sa, sizeof(*sa)))
3717 if (!(sa->flags & BTRFS_SCRUB_READONLY))
3718 mnt_drop_write_file(file);
3724 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
3726 if (!capable(CAP_SYS_ADMIN))
3729 return btrfs_scrub_cancel(fs_info);
3732 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
3735 struct btrfs_ioctl_scrub_args *sa;
3738 if (!capable(CAP_SYS_ADMIN))
3741 sa = memdup_user(arg, sizeof(*sa));
3745 ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
3747 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3754 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
3757 struct btrfs_ioctl_get_dev_stats *sa;
3760 sa = memdup_user(arg, sizeof(*sa));
3764 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3769 ret = btrfs_get_dev_stats(fs_info, sa);
3771 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3778 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
3781 struct btrfs_ioctl_dev_replace_args *p;
3784 if (!capable(CAP_SYS_ADMIN))
3787 p = memdup_user(arg, sizeof(*p));
3792 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3793 if (sb_rdonly(fs_info->sb)) {
3797 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
3798 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3800 ret = btrfs_dev_replace_by_ioctl(fs_info, p);
3801 btrfs_exclop_finish(fs_info);
3804 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3805 btrfs_dev_replace_status(fs_info, p);
3808 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3809 p->result = btrfs_dev_replace_cancel(fs_info);
3817 if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
3824 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3830 struct btrfs_ioctl_ino_path_args *ipa = NULL;
3831 struct inode_fs_paths *ipath = NULL;
3832 struct btrfs_path *path;
3834 if (!capable(CAP_DAC_READ_SEARCH))
3837 path = btrfs_alloc_path();
3843 ipa = memdup_user(arg, sizeof(*ipa));
3850 size = min_t(u32, ipa->size, 4096);
3851 ipath = init_ipath(size, root, path);
3852 if (IS_ERR(ipath)) {
3853 ret = PTR_ERR(ipath);
3858 ret = paths_from_inode(ipa->inum, ipath);
3862 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3863 rel_ptr = ipath->fspath->val[i] -
3864 (u64)(unsigned long)ipath->fspath->val;
3865 ipath->fspath->val[i] = rel_ptr;
3868 ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
3869 ipath->fspath, size);
3876 btrfs_free_path(path);
3883 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3885 struct btrfs_data_container *inodes = ctx;
3886 const size_t c = 3 * sizeof(u64);
3888 if (inodes->bytes_left >= c) {
3889 inodes->bytes_left -= c;
3890 inodes->val[inodes->elem_cnt] = inum;
3891 inodes->val[inodes->elem_cnt + 1] = offset;
3892 inodes->val[inodes->elem_cnt + 2] = root;
3893 inodes->elem_cnt += 3;
3895 inodes->bytes_missing += c - inodes->bytes_left;
3896 inodes->bytes_left = 0;
3897 inodes->elem_missed += 3;
3903 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
3904 void __user *arg, int version)
3908 struct btrfs_ioctl_logical_ino_args *loi;
3909 struct btrfs_data_container *inodes = NULL;
3910 struct btrfs_path *path = NULL;
3913 if (!capable(CAP_SYS_ADMIN))
3916 loi = memdup_user(arg, sizeof(*loi));
3918 return PTR_ERR(loi);
3921 ignore_offset = false;
3922 size = min_t(u32, loi->size, SZ_64K);
3924 /* All reserved bits must be 0 for now */
3925 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
3929 /* Only accept flags we have defined so far */
3930 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
3934 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
3935 size = min_t(u32, loi->size, SZ_16M);
3938 path = btrfs_alloc_path();
3944 inodes = init_data_container(size);
3945 if (IS_ERR(inodes)) {
3946 ret = PTR_ERR(inodes);
3951 ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
3952 build_ino_list, inodes, ignore_offset);
3958 ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
3964 btrfs_free_path(path);
3972 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
3973 struct btrfs_ioctl_balance_args *bargs)
3975 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3977 bargs->flags = bctl->flags;
3979 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
3980 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3981 if (atomic_read(&fs_info->balance_pause_req))
3982 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3983 if (atomic_read(&fs_info->balance_cancel_req))
3984 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3986 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3987 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3988 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3990 spin_lock(&fs_info->balance_lock);
3991 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3992 spin_unlock(&fs_info->balance_lock);
3995 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3997 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3998 struct btrfs_fs_info *fs_info = root->fs_info;
3999 struct btrfs_ioctl_balance_args *bargs;
4000 struct btrfs_balance_control *bctl;
4001 bool need_unlock; /* for mut. excl. ops lock */
4004 if (!capable(CAP_SYS_ADMIN))
4007 ret = mnt_want_write_file(file);
4012 if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
4013 mutex_lock(&fs_info->balance_mutex);
4019 * mut. excl. ops lock is locked. Three possibilities:
4020 * (1) some other op is running
4021 * (2) balance is running
4022 * (3) balance is paused -- special case (think resume)
4024 mutex_lock(&fs_info->balance_mutex);
4025 if (fs_info->balance_ctl) {
4026 /* this is either (2) or (3) */
4027 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4028 mutex_unlock(&fs_info->balance_mutex);
4030 * Lock released to allow other waiters to continue,
4031 * we'll reexamine the status again.
4033 mutex_lock(&fs_info->balance_mutex);
4035 if (fs_info->balance_ctl &&
4036 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4038 need_unlock = false;
4042 mutex_unlock(&fs_info->balance_mutex);
4046 mutex_unlock(&fs_info->balance_mutex);
4052 mutex_unlock(&fs_info->balance_mutex);
4053 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4060 bargs = memdup_user(arg, sizeof(*bargs));
4061 if (IS_ERR(bargs)) {
4062 ret = PTR_ERR(bargs);
4066 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4067 if (!fs_info->balance_ctl) {
4072 bctl = fs_info->balance_ctl;
4073 spin_lock(&fs_info->balance_lock);
4074 bctl->flags |= BTRFS_BALANCE_RESUME;
4075 spin_unlock(&fs_info->balance_lock);
4083 if (fs_info->balance_ctl) {
4088 bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4095 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4096 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4097 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4099 bctl->flags = bargs->flags;
4101 /* balance everything - no filters */
4102 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4105 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4112 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4113 * bctl is freed in reset_balance_state, or, if restriper was paused
4114 * all the way until unmount, in free_fs_info. The flag should be
4115 * cleared after reset_balance_state.
4117 need_unlock = false;
4119 ret = btrfs_balance(fs_info, bctl, bargs);
4122 if ((ret == 0 || ret == -ECANCELED) && arg) {
4123 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4132 mutex_unlock(&fs_info->balance_mutex);
4134 btrfs_exclop_finish(fs_info);
4136 mnt_drop_write_file(file);
4140 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4142 if (!capable(CAP_SYS_ADMIN))
4146 case BTRFS_BALANCE_CTL_PAUSE:
4147 return btrfs_pause_balance(fs_info);
4148 case BTRFS_BALANCE_CTL_CANCEL:
4149 return btrfs_cancel_balance(fs_info);
4155 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4158 struct btrfs_ioctl_balance_args *bargs;
4161 if (!capable(CAP_SYS_ADMIN))
4164 mutex_lock(&fs_info->balance_mutex);
4165 if (!fs_info->balance_ctl) {
4170 bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4176 btrfs_update_ioctl_balance_args(fs_info, bargs);
4178 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4183 mutex_unlock(&fs_info->balance_mutex);
4187 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4189 struct inode *inode = file_inode(file);
4190 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4191 struct btrfs_ioctl_quota_ctl_args *sa;
4194 if (!capable(CAP_SYS_ADMIN))
4197 ret = mnt_want_write_file(file);
4201 sa = memdup_user(arg, sizeof(*sa));
4207 down_write(&fs_info->subvol_sem);
4210 case BTRFS_QUOTA_CTL_ENABLE:
4211 ret = btrfs_quota_enable(fs_info);
4213 case BTRFS_QUOTA_CTL_DISABLE:
4214 ret = btrfs_quota_disable(fs_info);
4222 up_write(&fs_info->subvol_sem);
4224 mnt_drop_write_file(file);
4228 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4230 struct inode *inode = file_inode(file);
4231 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4232 struct btrfs_root *root = BTRFS_I(inode)->root;
4233 struct btrfs_ioctl_qgroup_assign_args *sa;
4234 struct btrfs_trans_handle *trans;
4238 if (!capable(CAP_SYS_ADMIN))
4241 ret = mnt_want_write_file(file);
4245 sa = memdup_user(arg, sizeof(*sa));
4251 trans = btrfs_join_transaction(root);
4252 if (IS_ERR(trans)) {
4253 ret = PTR_ERR(trans);
4258 ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
4260 ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
4263 /* update qgroup status and info */
4264 err = btrfs_run_qgroups(trans);
4266 btrfs_handle_fs_error(fs_info, err,
4267 "failed to update qgroup status and info");
4268 err = btrfs_end_transaction(trans);
4275 mnt_drop_write_file(file);
4279 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4281 struct inode *inode = file_inode(file);
4282 struct btrfs_root *root = BTRFS_I(inode)->root;
4283 struct btrfs_ioctl_qgroup_create_args *sa;
4284 struct btrfs_trans_handle *trans;
4288 if (!capable(CAP_SYS_ADMIN))
4291 ret = mnt_want_write_file(file);
4295 sa = memdup_user(arg, sizeof(*sa));
4301 if (!sa->qgroupid) {
4306 trans = btrfs_join_transaction(root);
4307 if (IS_ERR(trans)) {
4308 ret = PTR_ERR(trans);
4313 ret = btrfs_create_qgroup(trans, sa->qgroupid);
4315 ret = btrfs_remove_qgroup(trans, sa->qgroupid);
4318 err = btrfs_end_transaction(trans);
4325 mnt_drop_write_file(file);
4329 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4331 struct inode *inode = file_inode(file);
4332 struct btrfs_root *root = BTRFS_I(inode)->root;
4333 struct btrfs_ioctl_qgroup_limit_args *sa;
4334 struct btrfs_trans_handle *trans;
4339 if (!capable(CAP_SYS_ADMIN))
4342 ret = mnt_want_write_file(file);
4346 sa = memdup_user(arg, sizeof(*sa));
4352 trans = btrfs_join_transaction(root);
4353 if (IS_ERR(trans)) {
4354 ret = PTR_ERR(trans);
4358 qgroupid = sa->qgroupid;
4360 /* take the current subvol as qgroup */
4361 qgroupid = root->root_key.objectid;
4364 ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
4366 err = btrfs_end_transaction(trans);
4373 mnt_drop_write_file(file);
4377 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4379 struct inode *inode = file_inode(file);
4380 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4381 struct btrfs_ioctl_quota_rescan_args *qsa;
4384 if (!capable(CAP_SYS_ADMIN))
4387 ret = mnt_want_write_file(file);
4391 qsa = memdup_user(arg, sizeof(*qsa));
4402 ret = btrfs_qgroup_rescan(fs_info);
4407 mnt_drop_write_file(file);
4411 static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4414 struct btrfs_ioctl_quota_rescan_args *qsa;
4417 if (!capable(CAP_SYS_ADMIN))
4420 qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
4424 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4426 qsa->progress = fs_info->qgroup_rescan_progress.objectid;
4429 if (copy_to_user(arg, qsa, sizeof(*qsa)))
4436 static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4439 if (!capable(CAP_SYS_ADMIN))
4442 return btrfs_qgroup_wait_for_completion(fs_info, true);
4445 static long _btrfs_ioctl_set_received_subvol(struct file *file,
4446 struct btrfs_ioctl_received_subvol_args *sa)
4448 struct inode *inode = file_inode(file);
4449 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4450 struct btrfs_root *root = BTRFS_I(inode)->root;
4451 struct btrfs_root_item *root_item = &root->root_item;
4452 struct btrfs_trans_handle *trans;
4453 struct timespec64 ct = current_time(inode);
4455 int received_uuid_changed;
4457 if (!inode_owner_or_capable(&init_user_ns, inode))
4460 ret = mnt_want_write_file(file);
4464 down_write(&fs_info->subvol_sem);
4466 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
4471 if (btrfs_root_readonly(root)) {
4478 * 2 - uuid items (received uuid + subvol uuid)
4480 trans = btrfs_start_transaction(root, 3);
4481 if (IS_ERR(trans)) {
4482 ret = PTR_ERR(trans);
4487 sa->rtransid = trans->transid;
4488 sa->rtime.sec = ct.tv_sec;
4489 sa->rtime.nsec = ct.tv_nsec;
4491 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4493 if (received_uuid_changed &&
4494 !btrfs_is_empty_uuid(root_item->received_uuid)) {
4495 ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
4496 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4497 root->root_key.objectid);
4498 if (ret && ret != -ENOENT) {
4499 btrfs_abort_transaction(trans, ret);
4500 btrfs_end_transaction(trans);
4504 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4505 btrfs_set_root_stransid(root_item, sa->stransid);
4506 btrfs_set_root_rtransid(root_item, sa->rtransid);
4507 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4508 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4509 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4510 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4512 ret = btrfs_update_root(trans, fs_info->tree_root,
4513 &root->root_key, &root->root_item);
4515 btrfs_end_transaction(trans);
4518 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4519 ret = btrfs_uuid_tree_add(trans, sa->uuid,
4520 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4521 root->root_key.objectid);
4522 if (ret < 0 && ret != -EEXIST) {
4523 btrfs_abort_transaction(trans, ret);
4524 btrfs_end_transaction(trans);
4528 ret = btrfs_commit_transaction(trans);
4530 up_write(&fs_info->subvol_sem);
4531 mnt_drop_write_file(file);
4536 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4539 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4540 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4543 args32 = memdup_user(arg, sizeof(*args32));
4545 return PTR_ERR(args32);
4547 args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
4553 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4554 args64->stransid = args32->stransid;
4555 args64->rtransid = args32->rtransid;
4556 args64->stime.sec = args32->stime.sec;
4557 args64->stime.nsec = args32->stime.nsec;
4558 args64->rtime.sec = args32->rtime.sec;
4559 args64->rtime.nsec = args32->rtime.nsec;
4560 args64->flags = args32->flags;
4562 ret = _btrfs_ioctl_set_received_subvol(file, args64);
4566 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4567 args32->stransid = args64->stransid;
4568 args32->rtransid = args64->rtransid;
4569 args32->stime.sec = args64->stime.sec;
4570 args32->stime.nsec = args64->stime.nsec;
4571 args32->rtime.sec = args64->rtime.sec;
4572 args32->rtime.nsec = args64->rtime.nsec;
4573 args32->flags = args64->flags;
4575 ret = copy_to_user(arg, args32, sizeof(*args32));
4586 static long btrfs_ioctl_set_received_subvol(struct file *file,
4589 struct btrfs_ioctl_received_subvol_args *sa = NULL;
4592 sa = memdup_user(arg, sizeof(*sa));
4596 ret = _btrfs_ioctl_set_received_subvol(file, sa);
4601 ret = copy_to_user(arg, sa, sizeof(*sa));
4610 static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4615 char label[BTRFS_LABEL_SIZE];
4617 spin_lock(&fs_info->super_lock);
4618 memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4619 spin_unlock(&fs_info->super_lock);
4621 len = strnlen(label, BTRFS_LABEL_SIZE);
4623 if (len == BTRFS_LABEL_SIZE) {
4625 "label is too long, return the first %zu bytes",
4629 ret = copy_to_user(arg, label, len);
4631 return ret ? -EFAULT : 0;
4634 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4636 struct inode *inode = file_inode(file);
4637 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4638 struct btrfs_root *root = BTRFS_I(inode)->root;
4639 struct btrfs_super_block *super_block = fs_info->super_copy;
4640 struct btrfs_trans_handle *trans;
4641 char label[BTRFS_LABEL_SIZE];
4644 if (!capable(CAP_SYS_ADMIN))
4647 if (copy_from_user(label, arg, sizeof(label)))
4650 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4652 "unable to set label with more than %d bytes",
4653 BTRFS_LABEL_SIZE - 1);
4657 ret = mnt_want_write_file(file);
4661 trans = btrfs_start_transaction(root, 0);
4662 if (IS_ERR(trans)) {
4663 ret = PTR_ERR(trans);
4667 spin_lock(&fs_info->super_lock);
4668 strcpy(super_block->label, label);
4669 spin_unlock(&fs_info->super_lock);
4670 ret = btrfs_commit_transaction(trans);
4673 mnt_drop_write_file(file);
4677 #define INIT_FEATURE_FLAGS(suffix) \
4678 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
4679 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
4680 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
4682 int btrfs_ioctl_get_supported_features(void __user *arg)
4684 static const struct btrfs_ioctl_feature_flags features[3] = {
4685 INIT_FEATURE_FLAGS(SUPP),
4686 INIT_FEATURE_FLAGS(SAFE_SET),
4687 INIT_FEATURE_FLAGS(SAFE_CLEAR)
4690 if (copy_to_user(arg, &features, sizeof(features)))
4696 static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
4699 struct btrfs_super_block *super_block = fs_info->super_copy;
4700 struct btrfs_ioctl_feature_flags features;
4702 features.compat_flags = btrfs_super_compat_flags(super_block);
4703 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
4704 features.incompat_flags = btrfs_super_incompat_flags(super_block);
4706 if (copy_to_user(arg, &features, sizeof(features)))
4712 static int check_feature_bits(struct btrfs_fs_info *fs_info,
4713 enum btrfs_feature_set set,
4714 u64 change_mask, u64 flags, u64 supported_flags,
4715 u64 safe_set, u64 safe_clear)
4717 const char *type = btrfs_feature_set_name(set);
4719 u64 disallowed, unsupported;
4720 u64 set_mask = flags & change_mask;
4721 u64 clear_mask = ~flags & change_mask;
4723 unsupported = set_mask & ~supported_flags;
4725 names = btrfs_printable_features(set, unsupported);
4728 "this kernel does not support the %s feature bit%s",
4729 names, strchr(names, ',') ? "s" : "");
4733 "this kernel does not support %s bits 0x%llx",
4738 disallowed = set_mask & ~safe_set;
4740 names = btrfs_printable_features(set, disallowed);
4743 "can't set the %s feature bit%s while mounted",
4744 names, strchr(names, ',') ? "s" : "");
4748 "can't set %s bits 0x%llx while mounted",
4753 disallowed = clear_mask & ~safe_clear;
4755 names = btrfs_printable_features(set, disallowed);
4758 "can't clear the %s feature bit%s while mounted",
4759 names, strchr(names, ',') ? "s" : "");
4763 "can't clear %s bits 0x%llx while mounted",
4771 #define check_feature(fs_info, change_mask, flags, mask_base) \
4772 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \
4773 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
4774 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
4775 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
4777 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
4779 struct inode *inode = file_inode(file);
4780 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4781 struct btrfs_root *root = BTRFS_I(inode)->root;
4782 struct btrfs_super_block *super_block = fs_info->super_copy;
4783 struct btrfs_ioctl_feature_flags flags[2];
4784 struct btrfs_trans_handle *trans;
4788 if (!capable(CAP_SYS_ADMIN))
4791 if (copy_from_user(flags, arg, sizeof(flags)))
4795 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
4796 !flags[0].incompat_flags)
4799 ret = check_feature(fs_info, flags[0].compat_flags,
4800 flags[1].compat_flags, COMPAT);
4804 ret = check_feature(fs_info, flags[0].compat_ro_flags,
4805 flags[1].compat_ro_flags, COMPAT_RO);
4809 ret = check_feature(fs_info, flags[0].incompat_flags,
4810 flags[1].incompat_flags, INCOMPAT);
4814 ret = mnt_want_write_file(file);
4818 trans = btrfs_start_transaction(root, 0);
4819 if (IS_ERR(trans)) {
4820 ret = PTR_ERR(trans);
4821 goto out_drop_write;
4824 spin_lock(&fs_info->super_lock);
4825 newflags = btrfs_super_compat_flags(super_block);
4826 newflags |= flags[0].compat_flags & flags[1].compat_flags;
4827 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
4828 btrfs_set_super_compat_flags(super_block, newflags);
4830 newflags = btrfs_super_compat_ro_flags(super_block);
4831 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
4832 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
4833 btrfs_set_super_compat_ro_flags(super_block, newflags);
4835 newflags = btrfs_super_incompat_flags(super_block);
4836 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
4837 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
4838 btrfs_set_super_incompat_flags(super_block, newflags);
4839 spin_unlock(&fs_info->super_lock);
4841 ret = btrfs_commit_transaction(trans);
4843 mnt_drop_write_file(file);
4848 static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
4850 struct btrfs_ioctl_send_args *arg;
4854 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
4855 struct btrfs_ioctl_send_args_32 args32;
4857 ret = copy_from_user(&args32, argp, sizeof(args32));
4860 arg = kzalloc(sizeof(*arg), GFP_KERNEL);
4863 arg->send_fd = args32.send_fd;
4864 arg->clone_sources_count = args32.clone_sources_count;
4865 arg->clone_sources = compat_ptr(args32.clone_sources);
4866 arg->parent_root = args32.parent_root;
4867 arg->flags = args32.flags;
4868 memcpy(arg->reserved, args32.reserved,
4869 sizeof(args32.reserved));
4874 arg = memdup_user(argp, sizeof(*arg));
4876 return PTR_ERR(arg);
4878 ret = btrfs_ioctl_send(file, arg);
4883 long btrfs_ioctl(struct file *file, unsigned int
4884 cmd, unsigned long arg)
4886 struct inode *inode = file_inode(file);
4887 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4888 struct btrfs_root *root = BTRFS_I(inode)->root;
4889 void __user *argp = (void __user *)arg;
4892 case FS_IOC_GETVERSION:
4893 return btrfs_ioctl_getversion(file, argp);
4894 case FS_IOC_GETFSLABEL:
4895 return btrfs_ioctl_get_fslabel(fs_info, argp);
4896 case FS_IOC_SETFSLABEL:
4897 return btrfs_ioctl_set_fslabel(file, argp);
4899 return btrfs_ioctl_fitrim(fs_info, argp);
4900 case BTRFS_IOC_SNAP_CREATE:
4901 return btrfs_ioctl_snap_create(file, argp, 0);
4902 case BTRFS_IOC_SNAP_CREATE_V2:
4903 return btrfs_ioctl_snap_create_v2(file, argp, 0);
4904 case BTRFS_IOC_SUBVOL_CREATE:
4905 return btrfs_ioctl_snap_create(file, argp, 1);
4906 case BTRFS_IOC_SUBVOL_CREATE_V2:
4907 return btrfs_ioctl_snap_create_v2(file, argp, 1);
4908 case BTRFS_IOC_SNAP_DESTROY:
4909 return btrfs_ioctl_snap_destroy(file, argp, false);
4910 case BTRFS_IOC_SNAP_DESTROY_V2:
4911 return btrfs_ioctl_snap_destroy(file, argp, true);
4912 case BTRFS_IOC_SUBVOL_GETFLAGS:
4913 return btrfs_ioctl_subvol_getflags(file, argp);
4914 case BTRFS_IOC_SUBVOL_SETFLAGS:
4915 return btrfs_ioctl_subvol_setflags(file, argp);
4916 case BTRFS_IOC_DEFAULT_SUBVOL:
4917 return btrfs_ioctl_default_subvol(file, argp);
4918 case BTRFS_IOC_DEFRAG:
4919 return btrfs_ioctl_defrag(file, NULL);
4920 case BTRFS_IOC_DEFRAG_RANGE:
4921 return btrfs_ioctl_defrag(file, argp);
4922 case BTRFS_IOC_RESIZE:
4923 return btrfs_ioctl_resize(file, argp);
4924 case BTRFS_IOC_ADD_DEV:
4925 return btrfs_ioctl_add_dev(fs_info, argp);
4926 case BTRFS_IOC_RM_DEV:
4927 return btrfs_ioctl_rm_dev(file, argp);
4928 case BTRFS_IOC_RM_DEV_V2:
4929 return btrfs_ioctl_rm_dev_v2(file, argp);
4930 case BTRFS_IOC_FS_INFO:
4931 return btrfs_ioctl_fs_info(fs_info, argp);
4932 case BTRFS_IOC_DEV_INFO:
4933 return btrfs_ioctl_dev_info(fs_info, argp);
4934 case BTRFS_IOC_BALANCE:
4935 return btrfs_ioctl_balance(file, NULL);
4936 case BTRFS_IOC_TREE_SEARCH:
4937 return btrfs_ioctl_tree_search(file, argp);
4938 case BTRFS_IOC_TREE_SEARCH_V2:
4939 return btrfs_ioctl_tree_search_v2(file, argp);
4940 case BTRFS_IOC_INO_LOOKUP:
4941 return btrfs_ioctl_ino_lookup(file, argp);
4942 case BTRFS_IOC_INO_PATHS:
4943 return btrfs_ioctl_ino_to_path(root, argp);
4944 case BTRFS_IOC_LOGICAL_INO:
4945 return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
4946 case BTRFS_IOC_LOGICAL_INO_V2:
4947 return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
4948 case BTRFS_IOC_SPACE_INFO:
4949 return btrfs_ioctl_space_info(fs_info, argp);
4950 case BTRFS_IOC_SYNC: {
4953 ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
4956 ret = btrfs_sync_fs(inode->i_sb, 1);
4958 * The transaction thread may want to do more work,
4959 * namely it pokes the cleaner kthread that will start
4960 * processing uncleaned subvols.
4962 wake_up_process(fs_info->transaction_kthread);
4965 case BTRFS_IOC_START_SYNC:
4966 return btrfs_ioctl_start_sync(root, argp);
4967 case BTRFS_IOC_WAIT_SYNC:
4968 return btrfs_ioctl_wait_sync(fs_info, argp);
4969 case BTRFS_IOC_SCRUB:
4970 return btrfs_ioctl_scrub(file, argp);
4971 case BTRFS_IOC_SCRUB_CANCEL:
4972 return btrfs_ioctl_scrub_cancel(fs_info);
4973 case BTRFS_IOC_SCRUB_PROGRESS:
4974 return btrfs_ioctl_scrub_progress(fs_info, argp);
4975 case BTRFS_IOC_BALANCE_V2:
4976 return btrfs_ioctl_balance(file, argp);
4977 case BTRFS_IOC_BALANCE_CTL:
4978 return btrfs_ioctl_balance_ctl(fs_info, arg);
4979 case BTRFS_IOC_BALANCE_PROGRESS:
4980 return btrfs_ioctl_balance_progress(fs_info, argp);
4981 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
4982 return btrfs_ioctl_set_received_subvol(file, argp);
4984 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
4985 return btrfs_ioctl_set_received_subvol_32(file, argp);
4987 case BTRFS_IOC_SEND:
4988 return _btrfs_ioctl_send(file, argp, false);
4989 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
4990 case BTRFS_IOC_SEND_32:
4991 return _btrfs_ioctl_send(file, argp, true);
4993 case BTRFS_IOC_GET_DEV_STATS:
4994 return btrfs_ioctl_get_dev_stats(fs_info, argp);
4995 case BTRFS_IOC_QUOTA_CTL:
4996 return btrfs_ioctl_quota_ctl(file, argp);
4997 case BTRFS_IOC_QGROUP_ASSIGN:
4998 return btrfs_ioctl_qgroup_assign(file, argp);
4999 case BTRFS_IOC_QGROUP_CREATE:
5000 return btrfs_ioctl_qgroup_create(file, argp);
5001 case BTRFS_IOC_QGROUP_LIMIT:
5002 return btrfs_ioctl_qgroup_limit(file, argp);
5003 case BTRFS_IOC_QUOTA_RESCAN:
5004 return btrfs_ioctl_quota_rescan(file, argp);
5005 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5006 return btrfs_ioctl_quota_rescan_status(fs_info, argp);
5007 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5008 return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
5009 case BTRFS_IOC_DEV_REPLACE:
5010 return btrfs_ioctl_dev_replace(fs_info, argp);
5011 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5012 return btrfs_ioctl_get_supported_features(argp);
5013 case BTRFS_IOC_GET_FEATURES:
5014 return btrfs_ioctl_get_features(fs_info, argp);
5015 case BTRFS_IOC_SET_FEATURES:
5016 return btrfs_ioctl_set_features(file, argp);
5017 case BTRFS_IOC_GET_SUBVOL_INFO:
5018 return btrfs_ioctl_get_subvol_info(file, argp);
5019 case BTRFS_IOC_GET_SUBVOL_ROOTREF:
5020 return btrfs_ioctl_get_subvol_rootref(file, argp);
5021 case BTRFS_IOC_INO_LOOKUP_USER:
5022 return btrfs_ioctl_ino_lookup_user(file, argp);
5028 #ifdef CONFIG_COMPAT
5029 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5032 * These all access 32-bit values anyway so no further
5033 * handling is necessary.
5036 case FS_IOC32_GETVERSION:
5037 cmd = FS_IOC_GETVERSION;
5041 return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));