xref: /openbmc/linux/fs/btrfs/ioctl.c (revision 1a15eb72)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
2f46b5a66SChristoph Hellwig /*
3f46b5a66SChristoph Hellwig  * Copyright (C) 2007 Oracle.  All rights reserved.
4f46b5a66SChristoph Hellwig  */
5f46b5a66SChristoph Hellwig 
6f46b5a66SChristoph Hellwig #include <linux/kernel.h>
7f46b5a66SChristoph Hellwig #include <linux/bio.h>
8f46b5a66SChristoph Hellwig #include <linux/file.h>
9f46b5a66SChristoph Hellwig #include <linux/fs.h>
10cb8e7090SChristoph Hellwig #include <linux/fsnotify.h>
11f46b5a66SChristoph Hellwig #include <linux/pagemap.h>
12f46b5a66SChristoph Hellwig #include <linux/highmem.h>
13f46b5a66SChristoph Hellwig #include <linux/time.h>
14f46b5a66SChristoph Hellwig #include <linux/string.h>
15f46b5a66SChristoph Hellwig #include <linux/backing-dev.h>
16cb8e7090SChristoph Hellwig #include <linux/mount.h>
17cb8e7090SChristoph Hellwig #include <linux/namei.h>
18f46b5a66SChristoph Hellwig #include <linux/writeback.h>
19f46b5a66SChristoph Hellwig #include <linux/compat.h>
20cb8e7090SChristoph Hellwig #include <linux/security.h>
21f46b5a66SChristoph Hellwig #include <linux/xattr.h>
22f54de068SDavid Sterba #include <linux/mm.h>
235a0e3ad6STejun Heo #include <linux/slab.h>
24f7039b1dSLi Dongyang #include <linux/blkdev.h>
258ea05e3aSAlexander Block #include <linux/uuid.h>
2655e301fdSFilipe Brandenburger #include <linux/btrfs.h>
27416161dbSMark Fasheh #include <linux/uaccess.h>
28ae5e165dSJeff Layton #include <linux/iversion.h>
2997fc2977SMiklos Szeredi #include <linux/fileattr.h>
3014605409SBoris Burkov #include <linux/fsverity.h>
31f46b5a66SChristoph Hellwig #include "ctree.h"
32f46b5a66SChristoph Hellwig #include "disk-io.h"
33949964c9SMarcos Paulo de Souza #include "export.h"
34f46b5a66SChristoph Hellwig #include "transaction.h"
35f46b5a66SChristoph Hellwig #include "btrfs_inode.h"
36f46b5a66SChristoph Hellwig #include "print-tree.h"
37f46b5a66SChristoph Hellwig #include "volumes.h"
38925baeddSChris Mason #include "locking.h"
39d7728c96SJan Schmidt #include "backref.h"
40606686eeSJosef Bacik #include "rcu-string.h"
4131db9f7cSAlexander Block #include "send.h"
423f6bcfbdSStefan Behrens #include "dev-replace.h"
4363541927SFilipe David Borba Manana #include "props.h"
443b02a68aSJeff Mahoney #include "sysfs.h"
45fcebe456SJosef Bacik #include "qgroup.h"
461ec9a1aeSFilipe Manana #include "tree-log.h"
47ebb8765bSAnand Jain #include "compression.h"
488719aaaeSJosef Bacik #include "space-info.h"
4986736342SJosef Bacik #include "delalloc-space.h"
50aac0023cSJosef Bacik #include "block-group.h"
5122b398eeSQu Wenruo #include "subpage.h"
52f46b5a66SChristoph Hellwig 
53abccd00fSHugo Mills #ifdef CONFIG_64BIT
54abccd00fSHugo Mills /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
55abccd00fSHugo Mills  * structures are incorrect, as the timespec structure from userspace
56abccd00fSHugo Mills  * is 4 bytes too small. We define these alternatives here to teach
57abccd00fSHugo Mills  * the kernel about the 32-bit struct packing.
58abccd00fSHugo Mills  */
59abccd00fSHugo Mills struct btrfs_ioctl_timespec_32 {
60abccd00fSHugo Mills 	__u64 sec;
61abccd00fSHugo Mills 	__u32 nsec;
62abccd00fSHugo Mills } __attribute__ ((__packed__));
63abccd00fSHugo Mills 
64abccd00fSHugo Mills struct btrfs_ioctl_received_subvol_args_32 {
65abccd00fSHugo Mills 	char	uuid[BTRFS_UUID_SIZE];	/* in */
66abccd00fSHugo Mills 	__u64	stransid;		/* in */
67abccd00fSHugo Mills 	__u64	rtransid;		/* out */
68abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 stime; /* in */
69abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 rtime; /* out */
70abccd00fSHugo Mills 	__u64	flags;			/* in */
71abccd00fSHugo Mills 	__u64	reserved[16];		/* in */
72abccd00fSHugo Mills } __attribute__ ((__packed__));
73abccd00fSHugo Mills 
74abccd00fSHugo Mills #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
75abccd00fSHugo Mills 				struct btrfs_ioctl_received_subvol_args_32)
76abccd00fSHugo Mills #endif
77abccd00fSHugo Mills 
782351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
792351f431SJosef Bacik struct btrfs_ioctl_send_args_32 {
802351f431SJosef Bacik 	__s64 send_fd;			/* in */
812351f431SJosef Bacik 	__u64 clone_sources_count;	/* in */
822351f431SJosef Bacik 	compat_uptr_t clone_sources;	/* in */
832351f431SJosef Bacik 	__u64 parent_root;		/* in */
842351f431SJosef Bacik 	__u64 flags;			/* in */
852351f431SJosef Bacik 	__u64 reserved[4];		/* in */
862351f431SJosef Bacik } __attribute__ ((__packed__));
872351f431SJosef Bacik 
882351f431SJosef Bacik #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
892351f431SJosef Bacik 			       struct btrfs_ioctl_send_args_32)
902351f431SJosef Bacik #endif
91abccd00fSHugo Mills 
926cbff00fSChristoph Hellwig /* Mask out flags that are inappropriate for the given type of inode. */
931905a0f7SDavid Sterba static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
941905a0f7SDavid Sterba 		unsigned int flags)
956cbff00fSChristoph Hellwig {
961905a0f7SDavid Sterba 	if (S_ISDIR(inode->i_mode))
976cbff00fSChristoph Hellwig 		return flags;
981905a0f7SDavid Sterba 	else if (S_ISREG(inode->i_mode))
996cbff00fSChristoph Hellwig 		return flags & ~FS_DIRSYNC_FL;
1006cbff00fSChristoph Hellwig 	else
1016cbff00fSChristoph Hellwig 		return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
1026cbff00fSChristoph Hellwig }
103f46b5a66SChristoph Hellwig 
1046cbff00fSChristoph Hellwig /*
105a157d4fdSDavid Sterba  * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
106a157d4fdSDavid Sterba  * ioctl.
1076cbff00fSChristoph Hellwig  */
10877eea05eSBoris Burkov static unsigned int btrfs_inode_flags_to_fsflags(struct btrfs_inode *binode)
1096cbff00fSChristoph Hellwig {
1106cbff00fSChristoph Hellwig 	unsigned int iflags = 0;
11177eea05eSBoris Burkov 	u32 flags = binode->flags;
11214605409SBoris Burkov 	u32 ro_flags = binode->ro_flags;
1136cbff00fSChristoph Hellwig 
1146cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_SYNC)
1156cbff00fSChristoph Hellwig 		iflags |= FS_SYNC_FL;
1166cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_IMMUTABLE)
1176cbff00fSChristoph Hellwig 		iflags |= FS_IMMUTABLE_FL;
1186cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_APPEND)
1196cbff00fSChristoph Hellwig 		iflags |= FS_APPEND_FL;
1206cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NODUMP)
1216cbff00fSChristoph Hellwig 		iflags |= FS_NODUMP_FL;
1226cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NOATIME)
1236cbff00fSChristoph Hellwig 		iflags |= FS_NOATIME_FL;
1246cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_DIRSYNC)
1256cbff00fSChristoph Hellwig 		iflags |= FS_DIRSYNC_FL;
126d0092bddSLi Zefan 	if (flags & BTRFS_INODE_NODATACOW)
127d0092bddSLi Zefan 		iflags |= FS_NOCOW_FL;
12814605409SBoris Burkov 	if (ro_flags & BTRFS_INODE_RO_VERITY)
12914605409SBoris Burkov 		iflags |= FS_VERITY_FL;
130d0092bddSLi Zefan 
13113f48dc9SSatoru Takeuchi 	if (flags & BTRFS_INODE_NOCOMPRESS)
132d0092bddSLi Zefan 		iflags |= FS_NOCOMP_FL;
13313f48dc9SSatoru Takeuchi 	else if (flags & BTRFS_INODE_COMPRESS)
13413f48dc9SSatoru Takeuchi 		iflags |= FS_COMPR_FL;
1356cbff00fSChristoph Hellwig 
1366cbff00fSChristoph Hellwig 	return iflags;
1376cbff00fSChristoph Hellwig }
1386cbff00fSChristoph Hellwig 
1396cbff00fSChristoph Hellwig /*
1406cbff00fSChristoph Hellwig  * Update inode->i_flags based on the btrfs internal flags.
1416cbff00fSChristoph Hellwig  */
1427b6a221eSDavid Sterba void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
1436cbff00fSChristoph Hellwig {
1445c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
1453cc79392SFilipe Manana 	unsigned int new_fl = 0;
1466cbff00fSChristoph Hellwig 
1475c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_SYNC)
1483cc79392SFilipe Manana 		new_fl |= S_SYNC;
1495c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_IMMUTABLE)
1503cc79392SFilipe Manana 		new_fl |= S_IMMUTABLE;
1515c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_APPEND)
1523cc79392SFilipe Manana 		new_fl |= S_APPEND;
1535c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_NOATIME)
1543cc79392SFilipe Manana 		new_fl |= S_NOATIME;
1555c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_DIRSYNC)
1563cc79392SFilipe Manana 		new_fl |= S_DIRSYNC;
15714605409SBoris Burkov 	if (binode->ro_flags & BTRFS_INODE_RO_VERITY)
15814605409SBoris Burkov 		new_fl |= S_VERITY;
1593cc79392SFilipe Manana 
1603cc79392SFilipe Manana 	set_mask_bits(&inode->i_flags,
16114605409SBoris Burkov 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC |
16214605409SBoris Burkov 		      S_VERITY, new_fl);
1636cbff00fSChristoph Hellwig }
1646cbff00fSChristoph Hellwig 
165f37c563bSDavid Sterba /*
166f37c563bSDavid Sterba  * Check if @flags are a supported and valid set of FS_*_FL flags and that
167f37c563bSDavid Sterba  * the old and new flags are not conflicting
168f37c563bSDavid Sterba  */
169f37c563bSDavid Sterba static int check_fsflags(unsigned int old_flags, unsigned int flags)
17075e7cb7fSLiu Bo {
17175e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
17275e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
17375e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
174e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
175e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
17675e7cb7fSLiu Bo 		return -EOPNOTSUPP;
17775e7cb7fSLiu Bo 
178f37c563bSDavid Sterba 	/* COMPR and NOCOMP on new/old are valid */
17975e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
18075e7cb7fSLiu Bo 		return -EINVAL;
18175e7cb7fSLiu Bo 
182f37c563bSDavid Sterba 	if ((flags & FS_COMPR_FL) && (flags & FS_NOCOW_FL))
183f37c563bSDavid Sterba 		return -EINVAL;
184f37c563bSDavid Sterba 
185f37c563bSDavid Sterba 	/* NOCOW and compression options are mutually exclusive */
186f37c563bSDavid Sterba 	if ((old_flags & FS_NOCOW_FL) && (flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
187f37c563bSDavid Sterba 		return -EINVAL;
188f37c563bSDavid Sterba 	if ((flags & FS_NOCOW_FL) && (old_flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
189f37c563bSDavid Sterba 		return -EINVAL;
190f37c563bSDavid Sterba 
19175e7cb7fSLiu Bo 	return 0;
19275e7cb7fSLiu Bo }
19375e7cb7fSLiu Bo 
194d206e9c9SNaohiro Aota static int check_fsflags_compatible(struct btrfs_fs_info *fs_info,
195d206e9c9SNaohiro Aota 				    unsigned int flags)
196d206e9c9SNaohiro Aota {
197d206e9c9SNaohiro Aota 	if (btrfs_is_zoned(fs_info) && (flags & FS_NOCOW_FL))
198d206e9c9SNaohiro Aota 		return -EPERM;
199d206e9c9SNaohiro Aota 
200d206e9c9SNaohiro Aota 	return 0;
201d206e9c9SNaohiro Aota }
202d206e9c9SNaohiro Aota 
20397fc2977SMiklos Szeredi /*
20497fc2977SMiklos Szeredi  * Set flags/xflags from the internal inode flags. The remaining items of
20597fc2977SMiklos Szeredi  * fsxattr are zeroed.
20697fc2977SMiklos Szeredi  */
20797fc2977SMiklos Szeredi int btrfs_fileattr_get(struct dentry *dentry, struct fileattr *fa)
2086cbff00fSChristoph Hellwig {
20997fc2977SMiklos Szeredi 	struct btrfs_inode *binode = BTRFS_I(d_inode(dentry));
21097fc2977SMiklos Szeredi 
21177eea05eSBoris Burkov 	fileattr_fill_flags(fa, btrfs_inode_flags_to_fsflags(binode));
21297fc2977SMiklos Szeredi 	return 0;
21397fc2977SMiklos Szeredi }
21497fc2977SMiklos Szeredi 
21597fc2977SMiklos Szeredi int btrfs_fileattr_set(struct user_namespace *mnt_userns,
21697fc2977SMiklos Szeredi 		       struct dentry *dentry, struct fileattr *fa)
21797fc2977SMiklos Szeredi {
21897fc2977SMiklos Szeredi 	struct inode *inode = d_inode(dentry);
2190b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2205c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
2215c57b8b6SDavid Sterba 	struct btrfs_root *root = binode->root;
2226cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
2235aca2842SDarrick J. Wong 	unsigned int fsflags, old_fsflags;
2246cbff00fSChristoph Hellwig 	int ret;
225ff9fef55SAnand Jain 	const char *comp = NULL;
226f37c563bSDavid Sterba 	u32 binode_flags;
2276cbff00fSChristoph Hellwig 
228b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
229b83cc969SLi Zefan 		return -EROFS;
230b83cc969SLi Zefan 
23197fc2977SMiklos Szeredi 	if (fileattr_has_fsx(fa))
23297fc2977SMiklos Szeredi 		return -EOPNOTSUPP;
2336cbff00fSChristoph Hellwig 
23497fc2977SMiklos Szeredi 	fsflags = btrfs_mask_fsflags_for_type(inode, fa->flags);
23577eea05eSBoris Burkov 	old_fsflags = btrfs_inode_flags_to_fsflags(binode);
23697fc2977SMiklos Szeredi 	ret = check_fsflags(old_fsflags, fsflags);
237e7848683SJan Kara 	if (ret)
238e7848683SJan Kara 		return ret;
239e7848683SJan Kara 
240d206e9c9SNaohiro Aota 	ret = check_fsflags_compatible(fs_info, fsflags);
241d206e9c9SNaohiro Aota 	if (ret)
24297fc2977SMiklos Szeredi 		return ret;
243d206e9c9SNaohiro Aota 
244f37c563bSDavid Sterba 	binode_flags = binode->flags;
2455c57b8b6SDavid Sterba 	if (fsflags & FS_SYNC_FL)
246d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_SYNC;
2476cbff00fSChristoph Hellwig 	else
248d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_SYNC;
2495c57b8b6SDavid Sterba 	if (fsflags & FS_IMMUTABLE_FL)
250d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_IMMUTABLE;
2516cbff00fSChristoph Hellwig 	else
252d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_IMMUTABLE;
2535c57b8b6SDavid Sterba 	if (fsflags & FS_APPEND_FL)
254d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_APPEND;
2556cbff00fSChristoph Hellwig 	else
256d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_APPEND;
2575c57b8b6SDavid Sterba 	if (fsflags & FS_NODUMP_FL)
258d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NODUMP;
2596cbff00fSChristoph Hellwig 	else
260d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NODUMP;
2615c57b8b6SDavid Sterba 	if (fsflags & FS_NOATIME_FL)
262d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NOATIME;
2636cbff00fSChristoph Hellwig 	else
264d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NOATIME;
26597fc2977SMiklos Szeredi 
26697fc2977SMiklos Szeredi 	/* If coming from FS_IOC_FSSETXATTR then skip unconverted flags */
26797fc2977SMiklos Szeredi 	if (!fa->flags_valid) {
26897fc2977SMiklos Szeredi 		/* 1 item for the inode */
26997fc2977SMiklos Szeredi 		trans = btrfs_start_transaction(root, 1);
2709b8a233bSRitesh Harjani 		if (IS_ERR(trans))
2719b8a233bSRitesh Harjani 			return PTR_ERR(trans);
27297fc2977SMiklos Szeredi 		goto update_flags;
27397fc2977SMiklos Szeredi 	}
27497fc2977SMiklos Szeredi 
2755c57b8b6SDavid Sterba 	if (fsflags & FS_DIRSYNC_FL)
276d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_DIRSYNC;
2776cbff00fSChristoph Hellwig 	else
278d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_DIRSYNC;
2795c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOW_FL) {
28044e5194bSAnand Jain 		if (S_ISREG(inode->i_mode)) {
2817e97b8daSDavid Sterba 			/*
2827e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2837e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2847e97b8daSDavid Sterba 			 * status of the file and will not set it.
2857e97b8daSDavid Sterba 			 */
2867e97b8daSDavid Sterba 			if (inode->i_size == 0)
287d2b8fcfeSAnand Jain 				binode_flags |= BTRFS_INODE_NODATACOW |
288d2b8fcfeSAnand Jain 						BTRFS_INODE_NODATASUM;
2897e97b8daSDavid Sterba 		} else {
290d2b8fcfeSAnand Jain 			binode_flags |= BTRFS_INODE_NODATACOW;
2917e97b8daSDavid Sterba 		}
2927e97b8daSDavid Sterba 	} else {
2937e97b8daSDavid Sterba 		/*
29401327610SNicholas D Steeves 		 * Revert back under same assumptions as above
2957e97b8daSDavid Sterba 		 */
29644e5194bSAnand Jain 		if (S_ISREG(inode->i_mode)) {
2977e97b8daSDavid Sterba 			if (inode->i_size == 0)
298d2b8fcfeSAnand Jain 				binode_flags &= ~(BTRFS_INODE_NODATACOW |
299d2b8fcfeSAnand Jain 						  BTRFS_INODE_NODATASUM);
3007e97b8daSDavid Sterba 		} else {
301d2b8fcfeSAnand Jain 			binode_flags &= ~BTRFS_INODE_NODATACOW;
3027e97b8daSDavid Sterba 		}
3037e97b8daSDavid Sterba 	}
3046cbff00fSChristoph Hellwig 
30575e7cb7fSLiu Bo 	/*
30675e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
30775e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
30875e7cb7fSLiu Bo 	 * things smaller.
30975e7cb7fSLiu Bo 	 */
3105c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOMP_FL) {
311d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_COMPRESS;
312d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NOCOMPRESS;
3135c57b8b6SDavid Sterba 	} else if (fsflags & FS_COMPR_FL) {
31463541927SFilipe David Borba Manana 
31597fc2977SMiklos Szeredi 		if (IS_SWAPFILE(inode))
31697fc2977SMiklos Szeredi 			return -ETXTBSY;
317eede2bf3SOmar Sandoval 
318d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_COMPRESS;
319d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NOCOMPRESS;
32063541927SFilipe David Borba Manana 
32193370509SDavid Sterba 		comp = btrfs_compress_type2str(fs_info->compress_type);
32293370509SDavid Sterba 		if (!comp || comp[0] == 0)
32393370509SDavid Sterba 			comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
324ebcb904dSLi Zefan 	} else {
325d2b8fcfeSAnand Jain 		binode_flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
32675e7cb7fSLiu Bo 	}
3276cbff00fSChristoph Hellwig 
328ff9fef55SAnand Jain 	/*
329ff9fef55SAnand Jain 	 * 1 for inode item
330ff9fef55SAnand Jain 	 * 2 for properties
331ff9fef55SAnand Jain 	 */
332ff9fef55SAnand Jain 	trans = btrfs_start_transaction(root, 3);
33397fc2977SMiklos Szeredi 	if (IS_ERR(trans))
33497fc2977SMiklos Szeredi 		return PTR_ERR(trans);
3356cbff00fSChristoph Hellwig 
336ff9fef55SAnand Jain 	if (comp) {
337ff9fef55SAnand Jain 		ret = btrfs_set_prop(trans, inode, "btrfs.compression", comp,
338ff9fef55SAnand Jain 				     strlen(comp), 0);
339ff9fef55SAnand Jain 		if (ret) {
340ff9fef55SAnand Jain 			btrfs_abort_transaction(trans, ret);
341ff9fef55SAnand Jain 			goto out_end_trans;
342ff9fef55SAnand Jain 		}
343ff9fef55SAnand Jain 	} else {
344ff9fef55SAnand Jain 		ret = btrfs_set_prop(trans, inode, "btrfs.compression", NULL,
345ff9fef55SAnand Jain 				     0, 0);
346ff9fef55SAnand Jain 		if (ret && ret != -ENODATA) {
347ff9fef55SAnand Jain 			btrfs_abort_transaction(trans, ret);
348ff9fef55SAnand Jain 			goto out_end_trans;
349ff9fef55SAnand Jain 		}
350ff9fef55SAnand Jain 	}
351ff9fef55SAnand Jain 
35297fc2977SMiklos Szeredi update_flags:
353d2b8fcfeSAnand Jain 	binode->flags = binode_flags;
3547b6a221eSDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
3550c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
356c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3579a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3586cbff00fSChristoph Hellwig 
359ff9fef55SAnand Jain  out_end_trans:
3603a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
3612d4e6f6aSliubo 	return ret;
3626cbff00fSChristoph Hellwig }
3636cbff00fSChristoph Hellwig 
3640d7ed32cSDavid Sterba /*
3650d7ed32cSDavid Sterba  * Start exclusive operation @type, return true on success
3660d7ed32cSDavid Sterba  */
367c3e1f96cSGoldwyn Rodrigues bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
368c3e1f96cSGoldwyn Rodrigues 			enum btrfs_exclusive_operation type)
369c3e1f96cSGoldwyn Rodrigues {
3700d7ed32cSDavid Sterba 	bool ret = false;
3710d7ed32cSDavid Sterba 
3720d7ed32cSDavid Sterba 	spin_lock(&fs_info->super_lock);
3730d7ed32cSDavid Sterba 	if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
3740d7ed32cSDavid Sterba 		fs_info->exclusive_operation = type;
3750d7ed32cSDavid Sterba 		ret = true;
3760d7ed32cSDavid Sterba 	}
3770d7ed32cSDavid Sterba 	spin_unlock(&fs_info->super_lock);
3780d7ed32cSDavid Sterba 
3790d7ed32cSDavid Sterba 	return ret;
380c3e1f96cSGoldwyn Rodrigues }
381c3e1f96cSGoldwyn Rodrigues 
382578bda9eSDavid Sterba /*
383578bda9eSDavid Sterba  * Conditionally allow to enter the exclusive operation in case it's compatible
384578bda9eSDavid Sterba  * with the running one.  This must be paired with btrfs_exclop_start_unlock and
385578bda9eSDavid Sterba  * btrfs_exclop_finish.
386578bda9eSDavid Sterba  *
387578bda9eSDavid Sterba  * Compatibility:
388578bda9eSDavid Sterba  * - the same type is already running
389578bda9eSDavid Sterba  * - not BTRFS_EXCLOP_NONE - this is intentionally incompatible and the caller
390578bda9eSDavid Sterba  *   must check the condition first that would allow none -> @type
391578bda9eSDavid Sterba  */
392578bda9eSDavid Sterba bool btrfs_exclop_start_try_lock(struct btrfs_fs_info *fs_info,
393578bda9eSDavid Sterba 				 enum btrfs_exclusive_operation type)
394578bda9eSDavid Sterba {
395578bda9eSDavid Sterba 	spin_lock(&fs_info->super_lock);
396578bda9eSDavid Sterba 	if (fs_info->exclusive_operation == type)
397578bda9eSDavid Sterba 		return true;
398578bda9eSDavid Sterba 
399578bda9eSDavid Sterba 	spin_unlock(&fs_info->super_lock);
400578bda9eSDavid Sterba 	return false;
401578bda9eSDavid Sterba }
402578bda9eSDavid Sterba 
403578bda9eSDavid Sterba void btrfs_exclop_start_unlock(struct btrfs_fs_info *fs_info)
404578bda9eSDavid Sterba {
405578bda9eSDavid Sterba 	spin_unlock(&fs_info->super_lock);
406578bda9eSDavid Sterba }
407578bda9eSDavid Sterba 
408c3e1f96cSGoldwyn Rodrigues void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
409c3e1f96cSGoldwyn Rodrigues {
4100d7ed32cSDavid Sterba 	spin_lock(&fs_info->super_lock);
411c3e1f96cSGoldwyn Rodrigues 	WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
4120d7ed32cSDavid Sterba 	spin_unlock(&fs_info->super_lock);
41366a2823cSGoldwyn Rodrigues 	sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
414c3e1f96cSGoldwyn Rodrigues }
415c3e1f96cSGoldwyn Rodrigues 
4166cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
4176cbff00fSChristoph Hellwig {
418496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4196cbff00fSChristoph Hellwig 
4206cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
4216cbff00fSChristoph Hellwig }
422f46b5a66SChristoph Hellwig 
423b929c1d8SMarcos Paulo de Souza static noinline int btrfs_ioctl_fitrim(struct btrfs_fs_info *fs_info,
424b929c1d8SMarcos Paulo de Souza 					void __user *arg)
425f7039b1dSLi Dongyang {
426f7039b1dSLi Dongyang 	struct btrfs_device *device;
427f7039b1dSLi Dongyang 	struct request_queue *q;
428f7039b1dSLi Dongyang 	struct fstrim_range range;
429f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
430f7039b1dSLi Dongyang 	u64 num_devices = 0;
431f7039b1dSLi Dongyang 	int ret;
432f7039b1dSLi Dongyang 
433f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
434f7039b1dSLi Dongyang 		return -EPERM;
435f7039b1dSLi Dongyang 
436f35f06c3SFilipe Manana 	/*
4371cb3dc3fSNaohiro Aota 	 * btrfs_trim_block_group() depends on space cache, which is not
4381cb3dc3fSNaohiro Aota 	 * available in zoned filesystem. So, disallow fitrim on a zoned
4391cb3dc3fSNaohiro Aota 	 * filesystem for now.
4401cb3dc3fSNaohiro Aota 	 */
4411cb3dc3fSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
4421cb3dc3fSNaohiro Aota 		return -EOPNOTSUPP;
4431cb3dc3fSNaohiro Aota 
4441cb3dc3fSNaohiro Aota 	/*
445f35f06c3SFilipe Manana 	 * If the fs is mounted with nologreplay, which requires it to be
446f35f06c3SFilipe Manana 	 * mounted in RO mode as well, we can not allow discard on free space
447f35f06c3SFilipe Manana 	 * inside block groups, because log trees refer to extents that are not
448f35f06c3SFilipe Manana 	 * pinned in a block group's free space cache (pinning the extents is
449f35f06c3SFilipe Manana 	 * precisely the first phase of replaying a log tree).
450f35f06c3SFilipe Manana 	 */
451f35f06c3SFilipe Manana 	if (btrfs_test_opt(fs_info, NOLOGREPLAY))
452f35f06c3SFilipe Manana 		return -EROFS;
453f35f06c3SFilipe Manana 
4541f78160cSXiao Guangrong 	rcu_read_lock();
4551f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
4561f78160cSXiao Guangrong 				dev_list) {
457f7039b1dSLi Dongyang 		if (!device->bdev)
458f7039b1dSLi Dongyang 			continue;
459f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
460f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
461f7039b1dSLi Dongyang 			num_devices++;
46250d0446eSSeraphime Kirkovski 			minlen = min_t(u64, q->limits.discard_granularity,
463f7039b1dSLi Dongyang 				     minlen);
464f7039b1dSLi Dongyang 		}
465f7039b1dSLi Dongyang 	}
4661f78160cSXiao Guangrong 	rcu_read_unlock();
467f4c697e6SLukas Czerner 
468f7039b1dSLi Dongyang 	if (!num_devices)
469f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
470f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
471f7039b1dSLi Dongyang 		return -EFAULT;
4726ba9fc8eSQu Wenruo 
4736ba9fc8eSQu Wenruo 	/*
4746ba9fc8eSQu Wenruo 	 * NOTE: Don't truncate the range using super->total_bytes.  Bytenr of
4756ba9fc8eSQu Wenruo 	 * block group is in the logical address space, which can be any
4766ba9fc8eSQu Wenruo 	 * sectorsize aligned bytenr in  the range [0, U64_MAX].
4776ba9fc8eSQu Wenruo 	 */
4786ba9fc8eSQu Wenruo 	if (range.len < fs_info->sb->s_blocksize)
479f4c697e6SLukas Czerner 		return -EINVAL;
480f7039b1dSLi Dongyang 
481f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
4822ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
483f7039b1dSLi Dongyang 	if (ret < 0)
484f7039b1dSLi Dongyang 		return ret;
485f7039b1dSLi Dongyang 
486f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
487f7039b1dSLi Dongyang 		return -EFAULT;
488f7039b1dSLi Dongyang 
489f7039b1dSLi Dongyang 	return 0;
490f7039b1dSLi Dongyang }
491f7039b1dSLi Dongyang 
492e1f60a65SDavid Sterba int __pure btrfs_is_empty_uuid(u8 *uuid)
493dd5f9615SStefan Behrens {
49446e0f66aSChris Mason 	int i;
49546e0f66aSChris Mason 
49646e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
49746e0f66aSChris Mason 		if (uuid[i])
49846e0f66aSChris Mason 			return 0;
49946e0f66aSChris Mason 	}
50046e0f66aSChris Mason 	return 1;
501dd5f9615SStefan Behrens }
502dd5f9615SStefan Behrens 
5034d4340c9SChristian Brauner static noinline int create_subvol(struct user_namespace *mnt_userns,
5044d4340c9SChristian Brauner 				  struct inode *dir, struct dentry *dentry,
50552f75f4fSDavid Sterba 				  const char *name, int namelen,
5068696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
507f46b5a66SChristoph Hellwig {
5080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
509f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
510f46b5a66SChristoph Hellwig 	struct btrfs_key key;
51149a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
512f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
513f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
514d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
51576dda93cSYan, Zheng 	struct btrfs_root *new_root;
516d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
51795582b00SDeepa Dinamani 	struct timespec64 cur_time = current_time(dir);
5185662344bSTsutomu Itoh 	struct inode *inode;
519f46b5a66SChristoph Hellwig 	int ret;
520f46b5a66SChristoph Hellwig 	int err;
5212dfb1e43SQu Wenruo 	dev_t anon_dev = 0;
522f46b5a66SChristoph Hellwig 	u64 objectid;
5233de4586cSChris Mason 	u64 index = 0;
524f46b5a66SChristoph Hellwig 
52549a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
52649a3c4d9SDavid Sterba 	if (!root_item)
52749a3c4d9SDavid Sterba 		return -ENOMEM;
52849a3c4d9SDavid Sterba 
529543068a2SNikolay Borisov 	ret = btrfs_get_free_objectid(fs_info->tree_root, &objectid);
5302fbe8c8aSAl Viro 	if (ret)
53149a3c4d9SDavid Sterba 		goto fail_free;
5326a912213SJosef Bacik 
5332dfb1e43SQu Wenruo 	ret = get_anon_bdev(&anon_dev);
5342dfb1e43SQu Wenruo 	if (ret < 0)
5352dfb1e43SQu Wenruo 		goto fail_free;
5362dfb1e43SQu Wenruo 
537e09fe2d2SQu Wenruo 	/*
538e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
53901327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
540e09fe2d2SQu Wenruo 	 */
54149a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
54249a3c4d9SDavid Sterba 		ret = -ENOSPC;
54349a3c4d9SDavid Sterba 		goto fail_free;
54449a3c4d9SDavid Sterba 	}
545e09fe2d2SQu Wenruo 
546d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
5479ed74f2dSJosef Bacik 	/*
548d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
549d5c12070SMiao Xie 	 * of create_snapshot().
5509ed74f2dSJosef Bacik 	 */
551c4c129dbSGu JinXiang 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
552d5c12070SMiao Xie 	if (ret)
55349a3c4d9SDavid Sterba 		goto fail_free;
554f46b5a66SChristoph Hellwig 
555d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
556d5c12070SMiao Xie 	if (IS_ERR(trans)) {
557d5c12070SMiao Xie 		ret = PTR_ERR(trans);
558e85fde51SQu Wenruo 		btrfs_subvolume_release_metadata(root, &block_rsv);
55949a3c4d9SDavid Sterba 		goto fail_free;
560d5c12070SMiao Xie 	}
561d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
562d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
563f46b5a66SChristoph Hellwig 
564a9377422SLu Fengqi 	ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
5656f72c7e2SArne Jansen 	if (ret)
5666f72c7e2SArne Jansen 		goto fail;
5676f72c7e2SArne Jansen 
5689631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
5699631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
5708e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
5718e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
5728e8a1e31SJosef Bacik 		goto fail;
5738e8a1e31SJosef Bacik 	}
574f46b5a66SChristoph Hellwig 
575f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
576f46b5a66SChristoph Hellwig 
57749a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
5783cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
5793cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
5803cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
581da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
5820b246afaSJeff Mahoney 				     fs_info->nodesize);
5833cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
584f46b5a66SChristoph Hellwig 
58549a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
58649a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
5873cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
58808fe4db1SLi Zefan 
58949a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
59049a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
59149a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
59249a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
59349a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
59449a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
595f46b5a66SChristoph Hellwig 
59649a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
59749a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
598807fc790SAndy Shevchenko 	generate_random_guid(root_item->uuid);
59949a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
60049a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
60149a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
60249a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
60349a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
604f46b5a66SChristoph Hellwig 
605925baeddSChris Mason 	btrfs_tree_unlock(leaf);
606f46b5a66SChristoph Hellwig 
60769948022SNikolay Borisov 	btrfs_set_root_dirid(root_item, BTRFS_FIRST_FREE_OBJECTID);
608f46b5a66SChristoph Hellwig 
609f46b5a66SChristoph Hellwig 	key.objectid = objectid;
6105d4f98a2SYan Zheng 	key.offset = 0;
611962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
6120b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
61349a3c4d9SDavid Sterba 				root_item);
61467addf29SFilipe Manana 	if (ret) {
61567addf29SFilipe Manana 		/*
61667addf29SFilipe Manana 		 * Since we don't abort the transaction in this case, free the
61767addf29SFilipe Manana 		 * tree block so that we don't leak space and leave the
61867addf29SFilipe Manana 		 * filesystem in an inconsistent state (an extent item in the
61967addf29SFilipe Manana 		 * extent tree without backreferences). Also no need to have
62067addf29SFilipe Manana 		 * the tree block locked since it is not in any tree at this
62167addf29SFilipe Manana 		 * point, so no other task can find it and use it.
62267addf29SFilipe Manana 		 */
62367addf29SFilipe Manana 		btrfs_free_tree_block(trans, root, leaf, 0, 1);
62467addf29SFilipe Manana 		free_extent_buffer(leaf);
625f46b5a66SChristoph Hellwig 		goto fail;
62667addf29SFilipe Manana 	}
62767addf29SFilipe Manana 
62867addf29SFilipe Manana 	free_extent_buffer(leaf);
62967addf29SFilipe Manana 	leaf = NULL;
630f46b5a66SChristoph Hellwig 
63176dda93cSYan, Zheng 	key.offset = (u64)-1;
6322dfb1e43SQu Wenruo 	new_root = btrfs_get_new_fs_root(fs_info, objectid, anon_dev);
63379787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
6342dfb1e43SQu Wenruo 		free_anon_bdev(anon_dev);
63579787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
63666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
63779787eaaSJeff Mahoney 		goto fail;
63879787eaaSJeff Mahoney 	}
6392dfb1e43SQu Wenruo 	/* Freeing will be done in btrfs_put_root() of new_root */
6402dfb1e43SQu Wenruo 	anon_dev = 0;
64176dda93cSYan, Zheng 
642221581e4SJosef Bacik 	ret = btrfs_record_root_in_trans(trans, new_root);
643221581e4SJosef Bacik 	if (ret) {
644221581e4SJosef Bacik 		btrfs_put_root(new_root);
645221581e4SJosef Bacik 		btrfs_abort_transaction(trans, ret);
646221581e4SJosef Bacik 		goto fail;
647221581e4SJosef Bacik 	}
64876dda93cSYan, Zheng 
6494d4340c9SChristian Brauner 	ret = btrfs_create_subvol_root(trans, new_root, root, mnt_userns);
65000246528SJosef Bacik 	btrfs_put_root(new_root);
651ce598979SMark Fasheh 	if (ret) {
652ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
65366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
654ce598979SMark Fasheh 		goto fail;
655ce598979SMark Fasheh 	}
656ce598979SMark Fasheh 
657f46b5a66SChristoph Hellwig 	/*
658f46b5a66SChristoph Hellwig 	 * insert the directory item
659f46b5a66SChristoph Hellwig 	 */
660877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
66179787eaaSJeff Mahoney 	if (ret) {
66266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
66379787eaaSJeff Mahoney 		goto fail;
66479787eaaSJeff Mahoney 	}
6653de4586cSChris Mason 
666684572dfSLu Fengqi 	ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
6673de4586cSChris Mason 				    BTRFS_FT_DIR, index);
66879787eaaSJeff Mahoney 	if (ret) {
66966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
670f46b5a66SChristoph Hellwig 		goto fail;
67179787eaaSJeff Mahoney 	}
6720660b5afSChris Mason 
6736ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
6749a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
675c7e54b51SJosef Bacik 	if (ret) {
676c7e54b51SJosef Bacik 		btrfs_abort_transaction(trans, ret);
677c7e54b51SJosef Bacik 		goto fail;
678c7e54b51SJosef Bacik 	}
67952c26179SYan Zheng 
6806025c19fSLu Fengqi 	ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
6814a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
682c7e54b51SJosef Bacik 	if (ret) {
683c7e54b51SJosef Bacik 		btrfs_abort_transaction(trans, ret);
684c7e54b51SJosef Bacik 		goto fail;
685c7e54b51SJosef Bacik 	}
6860660b5afSChris Mason 
687cdb345a8SLu Fengqi 	ret = btrfs_uuid_tree_add(trans, root_item->uuid,
6886bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
689dd5f9615SStefan Behrens 	if (ret)
69066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
691dd5f9615SStefan Behrens 
692f46b5a66SChristoph Hellwig fail:
69349a3c4d9SDavid Sterba 	kfree(root_item);
694d5c12070SMiao Xie 	trans->block_rsv = NULL;
695d5c12070SMiao Xie 	trans->bytes_reserved = 0;
696e85fde51SQu Wenruo 	btrfs_subvolume_release_metadata(root, &block_rsv);
697de6e8200SLiu Bo 
6983a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
699f46b5a66SChristoph Hellwig 	if (err && !ret)
700f46b5a66SChristoph Hellwig 		ret = err;
7011a65e24bSChris Mason 
7025662344bSTsutomu Itoh 	if (!ret) {
7035662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
704de6e8200SLiu Bo 		if (IS_ERR(inode))
705de6e8200SLiu Bo 			return PTR_ERR(inode);
7065662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
7075662344bSTsutomu Itoh 	}
708f46b5a66SChristoph Hellwig 	return ret;
70949a3c4d9SDavid Sterba 
71049a3c4d9SDavid Sterba fail_free:
7112dfb1e43SQu Wenruo 	if (anon_dev)
7122dfb1e43SQu Wenruo 		free_anon_bdev(anon_dev);
71349a3c4d9SDavid Sterba 	kfree(root_item);
71449a3c4d9SDavid Sterba 	return ret;
715f46b5a66SChristoph Hellwig }
716f46b5a66SChristoph Hellwig 
717e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
7189babda9fSNikolay Borisov 			   struct dentry *dentry, bool readonly,
719e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
720f46b5a66SChristoph Hellwig {
7210b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
7222e4bfab9SYan, Zheng 	struct inode *inode;
723f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
724f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
7252e4bfab9SYan, Zheng 	int ret;
726f46b5a66SChristoph Hellwig 
72792a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
728f46b5a66SChristoph Hellwig 		return -EINVAL;
729f46b5a66SChristoph Hellwig 
730eede2bf3SOmar Sandoval 	if (atomic_read(&root->nr_swapfiles)) {
731eede2bf3SOmar Sandoval 		btrfs_warn(fs_info,
732eede2bf3SOmar Sandoval 			   "cannot snapshot subvolume with active swapfile");
733eede2bf3SOmar Sandoval 		return -ETXTBSY;
734eede2bf3SOmar Sandoval 	}
735eede2bf3SOmar Sandoval 
73623269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
737a1ee7362SDavid Sterba 	if (!pending_snapshot)
738a1ee7362SDavid Sterba 		return -ENOMEM;
739a1ee7362SDavid Sterba 
7402dfb1e43SQu Wenruo 	ret = get_anon_bdev(&pending_snapshot->anon_dev);
7412dfb1e43SQu Wenruo 	if (ret < 0)
7422dfb1e43SQu Wenruo 		goto free_pending;
743b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
74423269bf5SDavid Sterba 			GFP_KERNEL);
7458546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
7468546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
747b0c0ea63SDavid Sterba 		ret = -ENOMEM;
748b0c0ea63SDavid Sterba 		goto free_pending;
749b0c0ea63SDavid Sterba 	}
750b0c0ea63SDavid Sterba 
75166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
75266d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
753d5c12070SMiao Xie 	/*
754d5c12070SMiao Xie 	 * 1 - parent dir inode
755d5c12070SMiao Xie 	 * 2 - dir entries
756d5c12070SMiao Xie 	 * 1 - root item
757d5c12070SMiao Xie 	 * 2 - root ref/backref
758d5c12070SMiao Xie 	 * 1 - root of snapshot
759dd5f9615SStefan Behrens 	 * 1 - UUID item
760d5c12070SMiao Xie 	 */
761d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
762dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
763ee3441b4SJeff Mahoney 					false);
764d5c12070SMiao Xie 	if (ret)
765c11fbb6eSRobbie Ko 		goto free_pending;
766d5c12070SMiao Xie 
767a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
768a22285a6SYan, Zheng 	pending_snapshot->root = root;
769b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
770e9662f70SMiao Xie 	pending_snapshot->dir = dir;
7718696c533SMiao Xie 	pending_snapshot->inherit = inherit;
772a22285a6SYan, Zheng 
773d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
774a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
775a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
776a22285a6SYan, Zheng 		goto fail;
777a22285a6SYan, Zheng 	}
778a22285a6SYan, Zheng 
7790b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
780a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
781a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
7820b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
7839babda9fSNikolay Borisov 
7843a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
785aec8030aSMiao Xie 	if (ret)
786c37b2b62SJosef Bacik 		goto fail;
787a22285a6SYan, Zheng 
788a22285a6SYan, Zheng 	ret = pending_snapshot->error;
789f46b5a66SChristoph Hellwig 	if (ret)
7902e4bfab9SYan, Zheng 		goto fail;
791f46b5a66SChristoph Hellwig 
792d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
793d3797308SChris Mason 	if (ret)
794d3797308SChris Mason 		goto fail;
795d3797308SChris Mason 
7962b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
7972e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
7982e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
7992e4bfab9SYan, Zheng 		goto fail;
8002e4bfab9SYan, Zheng 	}
8015662344bSTsutomu Itoh 
8022e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
8032e4bfab9SYan, Zheng 	ret = 0;
8042dfb1e43SQu Wenruo 	pending_snapshot->anon_dev = 0;
8052e4bfab9SYan, Zheng fail:
8062dfb1e43SQu Wenruo 	/* Prevent double freeing of anon_dev */
8072dfb1e43SQu Wenruo 	if (ret && pending_snapshot->snap)
8082dfb1e43SQu Wenruo 		pending_snapshot->snap->anon_dev = 0;
80900246528SJosef Bacik 	btrfs_put_root(pending_snapshot->snap);
810e85fde51SQu Wenruo 	btrfs_subvolume_release_metadata(root, &pending_snapshot->block_rsv);
811b0c0ea63SDavid Sterba free_pending:
8122dfb1e43SQu Wenruo 	if (pending_snapshot->anon_dev)
8132dfb1e43SQu Wenruo 		free_anon_bdev(pending_snapshot->anon_dev);
814b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
8158546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
816a1ee7362SDavid Sterba 	kfree(pending_snapshot);
817a1ee7362SDavid Sterba 
818f46b5a66SChristoph Hellwig 	return ret;
819f46b5a66SChristoph Hellwig }
820f46b5a66SChristoph Hellwig 
8214260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
8224260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
8234260f7c7SSage Weil  *  whether the type of victim is right.
8244260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
8254260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
8264260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
8274260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
8284260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
8294260f7c7SSage Weil  *	a. be owner of dir, or
8304260f7c7SSage Weil  *	b. be owner of victim, or
8314260f7c7SSage Weil  *	c. have CAP_FOWNER capability
83201327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
8334260f7c7SSage Weil  *     links pointing to it.
8344260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
8354260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
8364260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
8374260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
8384260f7c7SSage Weil  *     nfs_async_unlink().
8394260f7c7SSage Weil  */
8404260f7c7SSage Weil 
841c4ed533bSChristian Brauner static int btrfs_may_delete(struct user_namespace *mnt_userns,
842c4ed533bSChristian Brauner 			    struct inode *dir, struct dentry *victim, int isdir)
8434260f7c7SSage Weil {
8444260f7c7SSage Weil 	int error;
8454260f7c7SSage Weil 
8462b0143b5SDavid Howells 	if (d_really_is_negative(victim))
8474260f7c7SSage Weil 		return -ENOENT;
8484260f7c7SSage Weil 
8492b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
8504fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
8514260f7c7SSage Weil 
852c4ed533bSChristian Brauner 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
8534260f7c7SSage Weil 	if (error)
8544260f7c7SSage Weil 		return error;
8554260f7c7SSage Weil 	if (IS_APPEND(dir))
8564260f7c7SSage Weil 		return -EPERM;
857c4ed533bSChristian Brauner 	if (check_sticky(mnt_userns, dir, d_inode(victim)) ||
858ba73d987SChristian Brauner 	    IS_APPEND(d_inode(victim)) || IS_IMMUTABLE(d_inode(victim)) ||
859ba73d987SChristian Brauner 	    IS_SWAPFILE(d_inode(victim)))
8604260f7c7SSage Weil 		return -EPERM;
8614260f7c7SSage Weil 	if (isdir) {
862e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
8634260f7c7SSage Weil 			return -ENOTDIR;
8644260f7c7SSage Weil 		if (IS_ROOT(victim))
8654260f7c7SSage Weil 			return -EBUSY;
866e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
8674260f7c7SSage Weil 		return -EISDIR;
8684260f7c7SSage Weil 	if (IS_DEADDIR(dir))
8694260f7c7SSage Weil 		return -ENOENT;
8704260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
8714260f7c7SSage Weil 		return -EBUSY;
8724260f7c7SSage Weil 	return 0;
8734260f7c7SSage Weil }
8744260f7c7SSage Weil 
875cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
8764d4340c9SChristian Brauner static inline int btrfs_may_create(struct user_namespace *mnt_userns,
8774d4340c9SChristian Brauner 				   struct inode *dir, struct dentry *child)
878cb8e7090SChristoph Hellwig {
8792b0143b5SDavid Howells 	if (d_really_is_positive(child))
880cb8e7090SChristoph Hellwig 		return -EEXIST;
881cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
882cb8e7090SChristoph Hellwig 		return -ENOENT;
8834d4340c9SChristian Brauner 	if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
8845474bf40SChristian Brauner 		return -EOVERFLOW;
8854d4340c9SChristian Brauner 	return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
886cb8e7090SChristoph Hellwig }
887cb8e7090SChristoph Hellwig 
888cb8e7090SChristoph Hellwig /*
889cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
890cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
891cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
892cb8e7090SChristoph Hellwig  */
89392872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
8944d4340c9SChristian Brauner 				   struct user_namespace *mnt_userns,
89552f75f4fSDavid Sterba 				   const char *name, int namelen,
89672fd032eSSage Weil 				   struct btrfs_root *snap_src,
8979babda9fSNikolay Borisov 				   bool readonly,
8988696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
899cb8e7090SChristoph Hellwig {
9002b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
9010b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
902cb8e7090SChristoph Hellwig 	struct dentry *dentry;
903cb8e7090SChristoph Hellwig 	int error;
904cb8e7090SChristoph Hellwig 
90500235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
90600235411SAl Viro 	if (error == -EINTR)
90700235411SAl Viro 		return error;
908cb8e7090SChristoph Hellwig 
9094d4340c9SChristian Brauner 	dentry = lookup_one(mnt_userns, name, parent->dentry, namelen);
910cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
911cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
912cb8e7090SChristoph Hellwig 		goto out_unlock;
913cb8e7090SChristoph Hellwig 
9144d4340c9SChristian Brauner 	error = btrfs_may_create(mnt_userns, dir, dentry);
915cb8e7090SChristoph Hellwig 	if (error)
916a874a63eSLiu Bo 		goto out_dput;
917cb8e7090SChristoph Hellwig 
9189c52057cSChris Mason 	/*
9199c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
9209c52057cSChris Mason 	 * check for them now when we can safely fail
9219c52057cSChris Mason 	 */
9229c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
9239c52057cSChris Mason 					       dir->i_ino, name,
9249c52057cSChris Mason 					       namelen);
9259c52057cSChris Mason 	if (error)
9269c52057cSChris Mason 		goto out_dput;
9279c52057cSChris Mason 
9280b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
92976dda93cSYan, Zheng 
93076dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
93176dda93cSYan, Zheng 		goto out_up_read;
93276dda93cSYan, Zheng 
9339babda9fSNikolay Borisov 	if (snap_src)
9349babda9fSNikolay Borisov 		error = create_snapshot(snap_src, dir, dentry, readonly, inherit);
9359babda9fSNikolay Borisov 	else
9364d4340c9SChristian Brauner 		error = create_subvol(mnt_userns, dir, dentry, name, namelen, inherit);
9379babda9fSNikolay Borisov 
93876dda93cSYan, Zheng 	if (!error)
93976dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
94076dda93cSYan, Zheng out_up_read:
9410b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
942cb8e7090SChristoph Hellwig out_dput:
943cb8e7090SChristoph Hellwig 	dput(dentry);
944cb8e7090SChristoph Hellwig out_unlock:
94564708539SJosef Bacik 	btrfs_inode_unlock(dir, 0);
946cb8e7090SChristoph Hellwig 	return error;
947cb8e7090SChristoph Hellwig }
948cb8e7090SChristoph Hellwig 
949c11fbb6eSRobbie Ko static noinline int btrfs_mksnapshot(const struct path *parent,
9504d4340c9SChristian Brauner 				   struct user_namespace *mnt_userns,
951c11fbb6eSRobbie Ko 				   const char *name, int namelen,
952c11fbb6eSRobbie Ko 				   struct btrfs_root *root,
953c11fbb6eSRobbie Ko 				   bool readonly,
954c11fbb6eSRobbie Ko 				   struct btrfs_qgroup_inherit *inherit)
955c11fbb6eSRobbie Ko {
956c11fbb6eSRobbie Ko 	int ret;
957c11fbb6eSRobbie Ko 	bool snapshot_force_cow = false;
958c11fbb6eSRobbie Ko 
959c11fbb6eSRobbie Ko 	/*
960c11fbb6eSRobbie Ko 	 * Force new buffered writes to reserve space even when NOCOW is
961c11fbb6eSRobbie Ko 	 * possible. This is to avoid later writeback (running dealloc) to
962c11fbb6eSRobbie Ko 	 * fallback to COW mode and unexpectedly fail with ENOSPC.
963c11fbb6eSRobbie Ko 	 */
964c11fbb6eSRobbie Ko 	btrfs_drew_read_lock(&root->snapshot_lock);
965c11fbb6eSRobbie Ko 
966f9baa501SFilipe Manana 	ret = btrfs_start_delalloc_snapshot(root, false);
967c11fbb6eSRobbie Ko 	if (ret)
968c11fbb6eSRobbie Ko 		goto out;
969c11fbb6eSRobbie Ko 
970c11fbb6eSRobbie Ko 	/*
971c11fbb6eSRobbie Ko 	 * All previous writes have started writeback in NOCOW mode, so now
972c11fbb6eSRobbie Ko 	 * we force future writes to fallback to COW mode during snapshot
973c11fbb6eSRobbie Ko 	 * creation.
974c11fbb6eSRobbie Ko 	 */
975c11fbb6eSRobbie Ko 	atomic_inc(&root->snapshot_force_cow);
976c11fbb6eSRobbie Ko 	snapshot_force_cow = true;
977c11fbb6eSRobbie Ko 
978c11fbb6eSRobbie Ko 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
979c11fbb6eSRobbie Ko 
9804d4340c9SChristian Brauner 	ret = btrfs_mksubvol(parent, mnt_userns, name, namelen,
981c11fbb6eSRobbie Ko 			     root, readonly, inherit);
982c11fbb6eSRobbie Ko out:
983c11fbb6eSRobbie Ko 	if (snapshot_force_cow)
984c11fbb6eSRobbie Ko 		atomic_dec(&root->snapshot_force_cow);
985c11fbb6eSRobbie Ko 	btrfs_drew_read_unlock(&root->snapshot_lock);
986c11fbb6eSRobbie Ko 	return ret;
987c11fbb6eSRobbie Ko }
988c11fbb6eSRobbie Ko 
989e9eec721SQu Wenruo static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start,
990e9eec721SQu Wenruo 					       bool locked)
99117ce6ef8SLiu Bo {
99217ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
993940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9946c282eb4SLi Zefan 	struct extent_map *em;
99576068caeSQu Wenruo 	const u32 sectorsize = BTRFS_I(inode)->root->fs_info->sectorsize;
996940100a4SChris Mason 
997940100a4SChris Mason 	/*
998940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
999940100a4SChris Mason 	 * the full extent lock
1000940100a4SChris Mason 	 */
1001940100a4SChris Mason 	read_lock(&em_tree->lock);
100276068caeSQu Wenruo 	em = lookup_extent_mapping(em_tree, start, sectorsize);
1003940100a4SChris Mason 	read_unlock(&em_tree->lock);
1004940100a4SChris Mason 
1005940100a4SChris Mason 	if (!em) {
1006308d9800SFilipe Manana 		struct extent_state *cached = NULL;
100776068caeSQu Wenruo 		u64 end = start + sectorsize - 1;
1008308d9800SFilipe Manana 
1009940100a4SChris Mason 		/* get the big lock and read metadata off disk */
1010e9eec721SQu Wenruo 		if (!locked)
1011ff13db41SDavid Sterba 			lock_extent_bits(io_tree, start, end, &cached);
101276068caeSQu Wenruo 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, sectorsize);
1013e9eec721SQu Wenruo 		if (!locked)
1014e43bbe5eSDavid Sterba 			unlock_extent_cached(io_tree, start, end, &cached);
1015940100a4SChris Mason 
10166cf8bfbfSDan Carpenter 		if (IS_ERR(em))
10176c282eb4SLi Zefan 			return NULL;
1018940100a4SChris Mason 	}
1019940100a4SChris Mason 
10206c282eb4SLi Zefan 	return em;
10216c282eb4SLi Zefan }
10226c282eb4SLi Zefan 
1023e9eec721SQu Wenruo static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em,
1024e9eec721SQu Wenruo 				     bool locked)
10256c282eb4SLi Zefan {
10266c282eb4SLi Zefan 	struct extent_map *next;
10276c282eb4SLi Zefan 	bool ret = true;
10286c282eb4SLi Zefan 
10296c282eb4SLi Zefan 	/* this is the last extent */
10306c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
10316c282eb4SLi Zefan 		return false;
10326c282eb4SLi Zefan 
1033e9eec721SQu Wenruo 	next = defrag_lookup_extent(inode, em->start + em->len, locked);
1034e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1035e9512d72SChris Mason 		ret = false;
1036e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1037ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
10386c282eb4SLi Zefan 		ret = false;
10396c282eb4SLi Zefan 
10406c282eb4SLi Zefan 	free_extent_map(next);
10416c282eb4SLi Zefan 	return ret;
10426c282eb4SLi Zefan }
10436c282eb4SLi Zefan 
10444cb5300bSChris Mason /*
10455767b50cSQu Wenruo  * Prepare one page to be defragged.
10465767b50cSQu Wenruo  *
10475767b50cSQu Wenruo  * This will ensure:
10485767b50cSQu Wenruo  *
10495767b50cSQu Wenruo  * - Returned page is locked and has been set up properly.
10505767b50cSQu Wenruo  * - No ordered extent exists in the page.
10515767b50cSQu Wenruo  * - The page is uptodate.
10525767b50cSQu Wenruo  *
10535767b50cSQu Wenruo  * NOTE: Caller should also wait for page writeback after the cluster is
10545767b50cSQu Wenruo  * prepared, here we don't do writeback wait for each page.
10555767b50cSQu Wenruo  */
10565767b50cSQu Wenruo static struct page *defrag_prepare_one_page(struct btrfs_inode *inode,
10575767b50cSQu Wenruo 					    pgoff_t index)
10585767b50cSQu Wenruo {
10595767b50cSQu Wenruo 	struct address_space *mapping = inode->vfs_inode.i_mapping;
10605767b50cSQu Wenruo 	gfp_t mask = btrfs_alloc_write_mask(mapping);
10615767b50cSQu Wenruo 	u64 page_start = (u64)index << PAGE_SHIFT;
10625767b50cSQu Wenruo 	u64 page_end = page_start + PAGE_SIZE - 1;
10635767b50cSQu Wenruo 	struct extent_state *cached_state = NULL;
10645767b50cSQu Wenruo 	struct page *page;
10655767b50cSQu Wenruo 	int ret;
10665767b50cSQu Wenruo 
10675767b50cSQu Wenruo again:
10685767b50cSQu Wenruo 	page = find_or_create_page(mapping, index, mask);
10695767b50cSQu Wenruo 	if (!page)
10705767b50cSQu Wenruo 		return ERR_PTR(-ENOMEM);
10715767b50cSQu Wenruo 
10725767b50cSQu Wenruo 	ret = set_page_extent_mapped(page);
10735767b50cSQu Wenruo 	if (ret < 0) {
10745767b50cSQu Wenruo 		unlock_page(page);
10755767b50cSQu Wenruo 		put_page(page);
10765767b50cSQu Wenruo 		return ERR_PTR(ret);
10775767b50cSQu Wenruo 	}
10785767b50cSQu Wenruo 
10795767b50cSQu Wenruo 	/* Wait for any existing ordered extent in the range */
10805767b50cSQu Wenruo 	while (1) {
10815767b50cSQu Wenruo 		struct btrfs_ordered_extent *ordered;
10825767b50cSQu Wenruo 
10835767b50cSQu Wenruo 		lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
10845767b50cSQu Wenruo 		ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
10855767b50cSQu Wenruo 		unlock_extent_cached(&inode->io_tree, page_start, page_end,
10865767b50cSQu Wenruo 				     &cached_state);
10875767b50cSQu Wenruo 		if (!ordered)
10885767b50cSQu Wenruo 			break;
10895767b50cSQu Wenruo 
10905767b50cSQu Wenruo 		unlock_page(page);
10915767b50cSQu Wenruo 		btrfs_start_ordered_extent(ordered, 1);
10925767b50cSQu Wenruo 		btrfs_put_ordered_extent(ordered);
10935767b50cSQu Wenruo 		lock_page(page);
10945767b50cSQu Wenruo 		/*
10955767b50cSQu Wenruo 		 * We unlocked the page above, so we need check if it was
10965767b50cSQu Wenruo 		 * released or not.
10975767b50cSQu Wenruo 		 */
10985767b50cSQu Wenruo 		if (page->mapping != mapping || !PagePrivate(page)) {
10995767b50cSQu Wenruo 			unlock_page(page);
11005767b50cSQu Wenruo 			put_page(page);
11015767b50cSQu Wenruo 			goto again;
11025767b50cSQu Wenruo 		}
11035767b50cSQu Wenruo 	}
11045767b50cSQu Wenruo 
11055767b50cSQu Wenruo 	/*
11065767b50cSQu Wenruo 	 * Now the page range has no ordered extent any more.  Read the page to
11075767b50cSQu Wenruo 	 * make it uptodate.
11085767b50cSQu Wenruo 	 */
11095767b50cSQu Wenruo 	if (!PageUptodate(page)) {
11105767b50cSQu Wenruo 		btrfs_readpage(NULL, page);
11115767b50cSQu Wenruo 		lock_page(page);
11125767b50cSQu Wenruo 		if (page->mapping != mapping || !PagePrivate(page)) {
11135767b50cSQu Wenruo 			unlock_page(page);
11145767b50cSQu Wenruo 			put_page(page);
11155767b50cSQu Wenruo 			goto again;
11165767b50cSQu Wenruo 		}
11175767b50cSQu Wenruo 		if (!PageUptodate(page)) {
11185767b50cSQu Wenruo 			unlock_page(page);
11195767b50cSQu Wenruo 			put_page(page);
11205767b50cSQu Wenruo 			return ERR_PTR(-EIO);
11215767b50cSQu Wenruo 		}
11225767b50cSQu Wenruo 	}
11235767b50cSQu Wenruo 	return page;
11245767b50cSQu Wenruo }
11255767b50cSQu Wenruo 
1126eb793cf8SQu Wenruo struct defrag_target_range {
1127eb793cf8SQu Wenruo 	struct list_head list;
1128eb793cf8SQu Wenruo 	u64 start;
1129eb793cf8SQu Wenruo 	u64 len;
1130eb793cf8SQu Wenruo };
1131eb793cf8SQu Wenruo 
1132eb793cf8SQu Wenruo /*
1133eb793cf8SQu Wenruo  * Collect all valid target extents.
1134eb793cf8SQu Wenruo  *
1135eb793cf8SQu Wenruo  * @start:	   file offset to lookup
1136eb793cf8SQu Wenruo  * @len:	   length to lookup
1137eb793cf8SQu Wenruo  * @extent_thresh: file extent size threshold, any extent size >= this value
1138eb793cf8SQu Wenruo  *		   will be ignored
1139eb793cf8SQu Wenruo  * @newer_than:    only defrag extents newer than this value
1140eb793cf8SQu Wenruo  * @do_compress:   whether the defrag is doing compression
1141eb793cf8SQu Wenruo  *		   if true, @extent_thresh will be ignored and all regular
1142eb793cf8SQu Wenruo  *		   file extents meeting @newer_than will be targets.
1143e9eec721SQu Wenruo  * @locked:	   if the range has already held extent lock
1144eb793cf8SQu Wenruo  * @target_list:   list of targets file extents
1145eb793cf8SQu Wenruo  */
1146eb793cf8SQu Wenruo static int defrag_collect_targets(struct btrfs_inode *inode,
1147eb793cf8SQu Wenruo 				  u64 start, u64 len, u32 extent_thresh,
1148eb793cf8SQu Wenruo 				  u64 newer_than, bool do_compress,
1149e9eec721SQu Wenruo 				  bool locked, struct list_head *target_list)
1150eb793cf8SQu Wenruo {
1151eb793cf8SQu Wenruo 	u64 cur = start;
1152eb793cf8SQu Wenruo 	int ret = 0;
1153eb793cf8SQu Wenruo 
1154eb793cf8SQu Wenruo 	while (cur < start + len) {
1155eb793cf8SQu Wenruo 		struct extent_map *em;
1156eb793cf8SQu Wenruo 		struct defrag_target_range *new;
1157eb793cf8SQu Wenruo 		bool next_mergeable = true;
1158eb793cf8SQu Wenruo 		u64 range_len;
1159eb793cf8SQu Wenruo 
1160e9eec721SQu Wenruo 		em = defrag_lookup_extent(&inode->vfs_inode, cur, locked);
1161eb793cf8SQu Wenruo 		if (!em)
1162eb793cf8SQu Wenruo 			break;
1163eb793cf8SQu Wenruo 
1164eb793cf8SQu Wenruo 		/* Skip hole/inline/preallocated extents */
1165eb793cf8SQu Wenruo 		if (em->block_start >= EXTENT_MAP_LAST_BYTE ||
1166eb793cf8SQu Wenruo 		    test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1167eb793cf8SQu Wenruo 			goto next;
1168eb793cf8SQu Wenruo 
1169eb793cf8SQu Wenruo 		/* Skip older extent */
1170eb793cf8SQu Wenruo 		if (em->generation < newer_than)
1171eb793cf8SQu Wenruo 			goto next;
1172eb793cf8SQu Wenruo 
1173eb793cf8SQu Wenruo 		/*
1174eb793cf8SQu Wenruo 		 * For do_compress case, we want to compress all valid file
1175eb793cf8SQu Wenruo 		 * extents, thus no @extent_thresh or mergeable check.
1176eb793cf8SQu Wenruo 		 */
1177eb793cf8SQu Wenruo 		if (do_compress)
1178eb793cf8SQu Wenruo 			goto add;
1179eb793cf8SQu Wenruo 
1180eb793cf8SQu Wenruo 		/* Skip too large extent */
1181eb793cf8SQu Wenruo 		if (em->len >= extent_thresh)
1182eb793cf8SQu Wenruo 			goto next;
1183eb793cf8SQu Wenruo 
1184e9eec721SQu Wenruo 		next_mergeable = defrag_check_next_extent(&inode->vfs_inode, em,
1185e9eec721SQu Wenruo 							  locked);
1186eb793cf8SQu Wenruo 		if (!next_mergeable) {
1187eb793cf8SQu Wenruo 			struct defrag_target_range *last;
1188eb793cf8SQu Wenruo 
1189eb793cf8SQu Wenruo 			/* Empty target list, no way to merge with last entry */
1190eb793cf8SQu Wenruo 			if (list_empty(target_list))
1191eb793cf8SQu Wenruo 				goto next;
1192eb793cf8SQu Wenruo 			last = list_entry(target_list->prev,
1193eb793cf8SQu Wenruo 					  struct defrag_target_range, list);
1194eb793cf8SQu Wenruo 			/* Not mergeable with last entry */
1195eb793cf8SQu Wenruo 			if (last->start + last->len != cur)
1196eb793cf8SQu Wenruo 				goto next;
1197eb793cf8SQu Wenruo 
1198eb793cf8SQu Wenruo 			/* Mergeable, fall through to add it to @target_list. */
1199eb793cf8SQu Wenruo 		}
1200eb793cf8SQu Wenruo 
1201eb793cf8SQu Wenruo add:
1202eb793cf8SQu Wenruo 		range_len = min(extent_map_end(em), start + len) - cur;
1203eb793cf8SQu Wenruo 		/*
1204eb793cf8SQu Wenruo 		 * This one is a good target, check if it can be merged into
1205eb793cf8SQu Wenruo 		 * last range of the target list.
1206eb793cf8SQu Wenruo 		 */
1207eb793cf8SQu Wenruo 		if (!list_empty(target_list)) {
1208eb793cf8SQu Wenruo 			struct defrag_target_range *last;
1209eb793cf8SQu Wenruo 
1210eb793cf8SQu Wenruo 			last = list_entry(target_list->prev,
1211eb793cf8SQu Wenruo 					  struct defrag_target_range, list);
1212eb793cf8SQu Wenruo 			ASSERT(last->start + last->len <= cur);
1213eb793cf8SQu Wenruo 			if (last->start + last->len == cur) {
1214eb793cf8SQu Wenruo 				/* Mergeable, enlarge the last entry */
1215eb793cf8SQu Wenruo 				last->len += range_len;
1216eb793cf8SQu Wenruo 				goto next;
1217eb793cf8SQu Wenruo 			}
1218eb793cf8SQu Wenruo 			/* Fall through to allocate a new entry */
1219eb793cf8SQu Wenruo 		}
1220eb793cf8SQu Wenruo 
1221eb793cf8SQu Wenruo 		/* Allocate new defrag_target_range */
1222eb793cf8SQu Wenruo 		new = kmalloc(sizeof(*new), GFP_NOFS);
1223eb793cf8SQu Wenruo 		if (!new) {
1224eb793cf8SQu Wenruo 			free_extent_map(em);
1225eb793cf8SQu Wenruo 			ret = -ENOMEM;
1226eb793cf8SQu Wenruo 			break;
1227eb793cf8SQu Wenruo 		}
1228eb793cf8SQu Wenruo 		new->start = cur;
1229eb793cf8SQu Wenruo 		new->len = range_len;
1230eb793cf8SQu Wenruo 		list_add_tail(&new->list, target_list);
1231eb793cf8SQu Wenruo 
1232eb793cf8SQu Wenruo next:
1233eb793cf8SQu Wenruo 		cur = extent_map_end(em);
1234eb793cf8SQu Wenruo 		free_extent_map(em);
1235eb793cf8SQu Wenruo 	}
1236eb793cf8SQu Wenruo 	if (ret < 0) {
1237eb793cf8SQu Wenruo 		struct defrag_target_range *entry;
1238eb793cf8SQu Wenruo 		struct defrag_target_range *tmp;
1239eb793cf8SQu Wenruo 
1240eb793cf8SQu Wenruo 		list_for_each_entry_safe(entry, tmp, target_list, list) {
1241eb793cf8SQu Wenruo 			list_del_init(&entry->list);
1242eb793cf8SQu Wenruo 			kfree(entry);
1243eb793cf8SQu Wenruo 		}
1244eb793cf8SQu Wenruo 	}
1245eb793cf8SQu Wenruo 	return ret;
1246eb793cf8SQu Wenruo }
1247eb793cf8SQu Wenruo 
124822b398eeSQu Wenruo #define CLUSTER_SIZE	(SZ_256K)
124922b398eeSQu Wenruo 
125022b398eeSQu Wenruo /*
125122b398eeSQu Wenruo  * Defrag one contiguous target range.
125222b398eeSQu Wenruo  *
125322b398eeSQu Wenruo  * @inode:	target inode
125422b398eeSQu Wenruo  * @target:	target range to defrag
125522b398eeSQu Wenruo  * @pages:	locked pages covering the defrag range
125622b398eeSQu Wenruo  * @nr_pages:	number of locked pages
125722b398eeSQu Wenruo  *
125822b398eeSQu Wenruo  * Caller should ensure:
125922b398eeSQu Wenruo  *
126022b398eeSQu Wenruo  * - Pages are prepared
126122b398eeSQu Wenruo  *   Pages should be locked, no ordered extent in the pages range,
126222b398eeSQu Wenruo  *   no writeback.
126322b398eeSQu Wenruo  *
126422b398eeSQu Wenruo  * - Extent bits are locked
126522b398eeSQu Wenruo  */
126622b398eeSQu Wenruo static int defrag_one_locked_target(struct btrfs_inode *inode,
126722b398eeSQu Wenruo 				    struct defrag_target_range *target,
126822b398eeSQu Wenruo 				    struct page **pages, int nr_pages,
126922b398eeSQu Wenruo 				    struct extent_state **cached_state)
127022b398eeSQu Wenruo {
127122b398eeSQu Wenruo 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
127222b398eeSQu Wenruo 	struct extent_changeset *data_reserved = NULL;
127322b398eeSQu Wenruo 	const u64 start = target->start;
127422b398eeSQu Wenruo 	const u64 len = target->len;
127522b398eeSQu Wenruo 	unsigned long last_index = (start + len - 1) >> PAGE_SHIFT;
127622b398eeSQu Wenruo 	unsigned long start_index = start >> PAGE_SHIFT;
127722b398eeSQu Wenruo 	unsigned long first_index = page_index(pages[0]);
127822b398eeSQu Wenruo 	int ret = 0;
127922b398eeSQu Wenruo 	int i;
128022b398eeSQu Wenruo 
128122b398eeSQu Wenruo 	ASSERT(last_index - first_index + 1 <= nr_pages);
128222b398eeSQu Wenruo 
128322b398eeSQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved, start, len);
128422b398eeSQu Wenruo 	if (ret < 0)
128522b398eeSQu Wenruo 		return ret;
128622b398eeSQu Wenruo 	clear_extent_bit(&inode->io_tree, start, start + len - 1,
128722b398eeSQu Wenruo 			 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
128822b398eeSQu Wenruo 			 EXTENT_DEFRAG, 0, 0, cached_state);
128922b398eeSQu Wenruo 	set_extent_defrag(&inode->io_tree, start, start + len - 1, cached_state);
129022b398eeSQu Wenruo 
129122b398eeSQu Wenruo 	/* Update the page status */
129222b398eeSQu Wenruo 	for (i = start_index - first_index; i <= last_index - first_index; i++) {
129322b398eeSQu Wenruo 		ClearPageChecked(pages[i]);
129422b398eeSQu Wenruo 		btrfs_page_clamp_set_dirty(fs_info, pages[i], start, len);
129522b398eeSQu Wenruo 	}
129622b398eeSQu Wenruo 	btrfs_delalloc_release_extents(inode, len);
129722b398eeSQu Wenruo 	extent_changeset_free(data_reserved);
129822b398eeSQu Wenruo 
129922b398eeSQu Wenruo 	return ret;
130022b398eeSQu Wenruo }
130122b398eeSQu Wenruo 
1302e9eec721SQu Wenruo static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
1303e9eec721SQu Wenruo 			    u32 extent_thresh, u64 newer_than, bool do_compress)
1304e9eec721SQu Wenruo {
1305e9eec721SQu Wenruo 	struct extent_state *cached_state = NULL;
1306e9eec721SQu Wenruo 	struct defrag_target_range *entry;
1307e9eec721SQu Wenruo 	struct defrag_target_range *tmp;
1308e9eec721SQu Wenruo 	LIST_HEAD(target_list);
1309e9eec721SQu Wenruo 	struct page **pages;
1310e9eec721SQu Wenruo 	const u32 sectorsize = inode->root->fs_info->sectorsize;
1311e9eec721SQu Wenruo 	u64 last_index = (start + len - 1) >> PAGE_SHIFT;
1312e9eec721SQu Wenruo 	u64 start_index = start >> PAGE_SHIFT;
1313e9eec721SQu Wenruo 	unsigned int nr_pages = last_index - start_index + 1;
1314e9eec721SQu Wenruo 	int ret = 0;
1315e9eec721SQu Wenruo 	int i;
1316e9eec721SQu Wenruo 
1317e9eec721SQu Wenruo 	ASSERT(nr_pages <= CLUSTER_SIZE / PAGE_SIZE);
1318e9eec721SQu Wenruo 	ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(len, sectorsize));
1319e9eec721SQu Wenruo 
1320e9eec721SQu Wenruo 	pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
1321e9eec721SQu Wenruo 	if (!pages)
1322e9eec721SQu Wenruo 		return -ENOMEM;
1323e9eec721SQu Wenruo 
1324e9eec721SQu Wenruo 	/* Prepare all pages */
1325e9eec721SQu Wenruo 	for (i = 0; i < nr_pages; i++) {
1326e9eec721SQu Wenruo 		pages[i] = defrag_prepare_one_page(inode, start_index + i);
1327e9eec721SQu Wenruo 		if (IS_ERR(pages[i])) {
1328e9eec721SQu Wenruo 			ret = PTR_ERR(pages[i]);
1329e9eec721SQu Wenruo 			pages[i] = NULL;
1330e9eec721SQu Wenruo 			goto free_pages;
1331e9eec721SQu Wenruo 		}
1332e9eec721SQu Wenruo 	}
1333e9eec721SQu Wenruo 	for (i = 0; i < nr_pages; i++)
1334e9eec721SQu Wenruo 		wait_on_page_writeback(pages[i]);
1335e9eec721SQu Wenruo 
1336e9eec721SQu Wenruo 	/* Lock the pages range */
1337e9eec721SQu Wenruo 	lock_extent_bits(&inode->io_tree, start_index << PAGE_SHIFT,
1338e9eec721SQu Wenruo 			 (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1339e9eec721SQu Wenruo 			 &cached_state);
1340e9eec721SQu Wenruo 	/*
1341e9eec721SQu Wenruo 	 * Now we have a consistent view about the extent map, re-check
1342e9eec721SQu Wenruo 	 * which range really needs to be defragged.
1343e9eec721SQu Wenruo 	 *
1344e9eec721SQu Wenruo 	 * And this time we have extent locked already, pass @locked = true
1345e9eec721SQu Wenruo 	 * so that we won't relock the extent range and cause deadlock.
1346e9eec721SQu Wenruo 	 */
1347e9eec721SQu Wenruo 	ret = defrag_collect_targets(inode, start, len, extent_thresh,
1348e9eec721SQu Wenruo 				     newer_than, do_compress, true,
1349e9eec721SQu Wenruo 				     &target_list);
1350e9eec721SQu Wenruo 	if (ret < 0)
1351e9eec721SQu Wenruo 		goto unlock_extent;
1352e9eec721SQu Wenruo 
1353e9eec721SQu Wenruo 	list_for_each_entry(entry, &target_list, list) {
1354e9eec721SQu Wenruo 		ret = defrag_one_locked_target(inode, entry, pages, nr_pages,
1355e9eec721SQu Wenruo 					       &cached_state);
1356e9eec721SQu Wenruo 		if (ret < 0)
1357e9eec721SQu Wenruo 			break;
1358e9eec721SQu Wenruo 	}
1359e9eec721SQu Wenruo 
1360e9eec721SQu Wenruo 	list_for_each_entry_safe(entry, tmp, &target_list, list) {
1361e9eec721SQu Wenruo 		list_del_init(&entry->list);
1362e9eec721SQu Wenruo 		kfree(entry);
1363e9eec721SQu Wenruo 	}
1364e9eec721SQu Wenruo unlock_extent:
1365e9eec721SQu Wenruo 	unlock_extent_cached(&inode->io_tree, start_index << PAGE_SHIFT,
1366e9eec721SQu Wenruo 			     (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1367e9eec721SQu Wenruo 			     &cached_state);
1368e9eec721SQu Wenruo free_pages:
1369e9eec721SQu Wenruo 	for (i = 0; i < nr_pages; i++) {
1370e9eec721SQu Wenruo 		if (pages[i]) {
1371e9eec721SQu Wenruo 			unlock_page(pages[i]);
1372e9eec721SQu Wenruo 			put_page(pages[i]);
1373e9eec721SQu Wenruo 		}
1374e9eec721SQu Wenruo 	}
1375e9eec721SQu Wenruo 	kfree(pages);
1376e9eec721SQu Wenruo 	return ret;
1377e9eec721SQu Wenruo }
1378e9eec721SQu Wenruo 
1379b18c3ab2SQu Wenruo static int defrag_one_cluster(struct btrfs_inode *inode,
1380b18c3ab2SQu Wenruo 			      struct file_ra_state *ra,
1381b18c3ab2SQu Wenruo 			      u64 start, u32 len, u32 extent_thresh,
1382b18c3ab2SQu Wenruo 			      u64 newer_than, bool do_compress,
1383b18c3ab2SQu Wenruo 			      unsigned long *sectors_defragged,
1384b18c3ab2SQu Wenruo 			      unsigned long max_sectors)
1385b18c3ab2SQu Wenruo {
1386b18c3ab2SQu Wenruo 	const u32 sectorsize = inode->root->fs_info->sectorsize;
1387b18c3ab2SQu Wenruo 	struct defrag_target_range *entry;
1388b18c3ab2SQu Wenruo 	struct defrag_target_range *tmp;
1389b18c3ab2SQu Wenruo 	LIST_HEAD(target_list);
1390b18c3ab2SQu Wenruo 	int ret;
1391b18c3ab2SQu Wenruo 
1392b18c3ab2SQu Wenruo 	BUILD_BUG_ON(!IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
1393b18c3ab2SQu Wenruo 	ret = defrag_collect_targets(inode, start, len, extent_thresh,
1394b18c3ab2SQu Wenruo 				     newer_than, do_compress, false,
1395b18c3ab2SQu Wenruo 				     &target_list);
1396b18c3ab2SQu Wenruo 	if (ret < 0)
1397b18c3ab2SQu Wenruo 		goto out;
1398b18c3ab2SQu Wenruo 
1399b18c3ab2SQu Wenruo 	list_for_each_entry(entry, &target_list, list) {
1400b18c3ab2SQu Wenruo 		u32 range_len = entry->len;
1401b18c3ab2SQu Wenruo 
1402b18c3ab2SQu Wenruo 		/* Reached the limit */
1403b18c3ab2SQu Wenruo 		if (max_sectors && max_sectors == *sectors_defragged)
1404b18c3ab2SQu Wenruo 			break;
1405b18c3ab2SQu Wenruo 
1406b18c3ab2SQu Wenruo 		if (max_sectors)
1407b18c3ab2SQu Wenruo 			range_len = min_t(u32, range_len,
1408b18c3ab2SQu Wenruo 				(max_sectors - *sectors_defragged) * sectorsize);
1409b18c3ab2SQu Wenruo 
1410b18c3ab2SQu Wenruo 		if (ra)
1411b18c3ab2SQu Wenruo 			page_cache_sync_readahead(inode->vfs_inode.i_mapping,
1412b18c3ab2SQu Wenruo 				ra, NULL, entry->start >> PAGE_SHIFT,
1413b18c3ab2SQu Wenruo 				((entry->start + range_len - 1) >> PAGE_SHIFT) -
1414b18c3ab2SQu Wenruo 				(entry->start >> PAGE_SHIFT) + 1);
1415b18c3ab2SQu Wenruo 		/*
1416b18c3ab2SQu Wenruo 		 * Here we may not defrag any range if holes are punched before
1417b18c3ab2SQu Wenruo 		 * we locked the pages.
1418b18c3ab2SQu Wenruo 		 * But that's fine, it only affects the @sectors_defragged
1419b18c3ab2SQu Wenruo 		 * accounting.
1420b18c3ab2SQu Wenruo 		 */
1421b18c3ab2SQu Wenruo 		ret = defrag_one_range(inode, entry->start, range_len,
1422b18c3ab2SQu Wenruo 				       extent_thresh, newer_than, do_compress);
1423b18c3ab2SQu Wenruo 		if (ret < 0)
1424b18c3ab2SQu Wenruo 			break;
1425b18c3ab2SQu Wenruo 		*sectors_defragged += range_len;
1426b18c3ab2SQu Wenruo 	}
1427b18c3ab2SQu Wenruo out:
1428b18c3ab2SQu Wenruo 	list_for_each_entry_safe(entry, tmp, &target_list, list) {
1429b18c3ab2SQu Wenruo 		list_del_init(&entry->list);
1430b18c3ab2SQu Wenruo 		kfree(entry);
1431b18c3ab2SQu Wenruo 	}
1432b18c3ab2SQu Wenruo 	return ret;
1433b18c3ab2SQu Wenruo }
1434b18c3ab2SQu Wenruo 
14351ccc2e8aSQu Wenruo /*
14361ccc2e8aSQu Wenruo  * Entry point to file defragmentation.
14371ccc2e8aSQu Wenruo  *
14381ccc2e8aSQu Wenruo  * @inode:	   inode to be defragged
14391ccc2e8aSQu Wenruo  * @ra:		   readahead state (can be NUL)
14401ccc2e8aSQu Wenruo  * @range:	   defrag options including range and flags
14411ccc2e8aSQu Wenruo  * @newer_than:	   minimum transid to defrag
14421ccc2e8aSQu Wenruo  * @max_to_defrag: max number of sectors to be defragged, if 0, the whole inode
14431ccc2e8aSQu Wenruo  *		   will be defragged.
14441ccc2e8aSQu Wenruo  */
14451ccc2e8aSQu Wenruo int btrfs_defrag_file(struct inode *inode, struct file_ra_state *ra,
14464cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
14474cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
14484cb5300bSChris Mason {
14490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
14507b508037SQu Wenruo 	unsigned long sectors_defragged = 0;
1451151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
14527b508037SQu Wenruo 	u64 cur;
14537b508037SQu Wenruo 	u64 last_byte;
14541e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
14551ccc2e8aSQu Wenruo 	bool ra_allocated = false;
14567b508037SQu Wenruo 	int compress_type = BTRFS_COMPRESS_ZLIB;
14577b508037SQu Wenruo 	int ret = 0;
14587b508037SQu Wenruo 	u32 extent_thresh = range->extent_thresh;
14594cb5300bSChris Mason 
14600abd5b17SLiu Bo 	if (isize == 0)
14610abd5b17SLiu Bo 		return 0;
14620abd5b17SLiu Bo 
14630abd5b17SLiu Bo 	if (range->start >= isize)
14640abd5b17SLiu Bo 		return -EINVAL;
14651a419d85SLi Zefan 
14661e2ef46dSDavid Sterba 	if (do_compress) {
1467ce96b7ffSChengguang Xu 		if (range->compress_type >= BTRFS_NR_COMPRESS_TYPES)
14681a419d85SLi Zefan 			return -EINVAL;
14691a419d85SLi Zefan 		if (range->compress_type)
14701a419d85SLi Zefan 			compress_type = range->compress_type;
14711a419d85SLi Zefan 	}
1472f46b5a66SChristoph Hellwig 
14730abd5b17SLiu Bo 	if (extent_thresh == 0)
1474ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1475f46b5a66SChristoph Hellwig 
14767b508037SQu Wenruo 	if (range->start + range->len > range->start) {
14777b508037SQu Wenruo 		/* Got a specific range */
14787b508037SQu Wenruo 		last_byte = min(isize, range->start + range->len) - 1;
14797b508037SQu Wenruo 	} else {
14807b508037SQu Wenruo 		/* Defrag until file end */
14817b508037SQu Wenruo 		last_byte = isize - 1;
14827b508037SQu Wenruo 	}
14837b508037SQu Wenruo 
14844cb5300bSChris Mason 	/*
14851ccc2e8aSQu Wenruo 	 * If we were not given a ra, allocate a readahead context. As
14860a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
14870a52d108SDavid Sterba 	 * we don't error out.
14884cb5300bSChris Mason 	 */
14891ccc2e8aSQu Wenruo 	if (!ra) {
14901ccc2e8aSQu Wenruo 		ra_allocated = true;
149163e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
14920a52d108SDavid Sterba 		if (ra)
14934cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
14944cb5300bSChris Mason 	}
14954cb5300bSChris Mason 
14967b508037SQu Wenruo 	/* Align the range */
14977b508037SQu Wenruo 	cur = round_down(range->start, fs_info->sectorsize);
14987b508037SQu Wenruo 	last_byte = round_up(last_byte, fs_info->sectorsize) - 1;
14994cb5300bSChris Mason 
15007b508037SQu Wenruo 	while (cur < last_byte) {
15017b508037SQu Wenruo 		u64 cluster_end;
15021e701a32SChris Mason 
15037b508037SQu Wenruo 		/* The cluster size 256K should always be page aligned */
15047b508037SQu Wenruo 		BUILD_BUG_ON(!IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
15054cb5300bSChris Mason 
15067b508037SQu Wenruo 		/* We want the cluster end at page boundary when possible */
15077b508037SQu Wenruo 		cluster_end = (((cur >> PAGE_SHIFT) +
15087b508037SQu Wenruo 			       (SZ_256K >> PAGE_SHIFT)) << PAGE_SHIFT) - 1;
15097b508037SQu Wenruo 		cluster_end = min(cluster_end, last_byte);
15104cb5300bSChris Mason 
151164708539SJosef Bacik 		btrfs_inode_lock(inode, 0);
1512eede2bf3SOmar Sandoval 		if (IS_SWAPFILE(inode)) {
1513eede2bf3SOmar Sandoval 			ret = -ETXTBSY;
15147b508037SQu Wenruo 			btrfs_inode_unlock(inode, 0);
15157b508037SQu Wenruo 			break;
15167b508037SQu Wenruo 		}
15177b508037SQu Wenruo 		if (!(inode->i_sb->s_flags & SB_ACTIVE)) {
15187b508037SQu Wenruo 			btrfs_inode_unlock(inode, 0);
15197b508037SQu Wenruo 			break;
15207b508037SQu Wenruo 		}
15211e2ef46dSDavid Sterba 		if (do_compress)
1522eec63c65SDavid Sterba 			BTRFS_I(inode)->defrag_compress = compress_type;
15237b508037SQu Wenruo 		ret = defrag_one_cluster(BTRFS_I(inode), ra, cur,
15247b508037SQu Wenruo 				cluster_end + 1 - cur, extent_thresh,
15257b508037SQu Wenruo 				newer_than, do_compress,
15267b508037SQu Wenruo 				&sectors_defragged, max_to_defrag);
152764708539SJosef Bacik 		btrfs_inode_unlock(inode, 0);
15287b508037SQu Wenruo 		if (ret < 0)
15294cb5300bSChris Mason 			break;
15307b508037SQu Wenruo 		cur = cluster_end + 1;
15314cb5300bSChris Mason 	}
1532f46b5a66SChristoph Hellwig 
15337b508037SQu Wenruo 	if (ra_allocated)
15347b508037SQu Wenruo 		kfree(ra);
15357b508037SQu Wenruo 	if (sectors_defragged) {
15367b508037SQu Wenruo 		/*
15377b508037SQu Wenruo 		 * We have defragged some sectors, for compression case they
15387b508037SQu Wenruo 		 * need to be written back immediately.
15397b508037SQu Wenruo 		 */
15407b508037SQu Wenruo 		if (range->flags & BTRFS_DEFRAG_RANGE_START_IO) {
15411e701a32SChris Mason 			filemap_flush(inode->i_mapping);
1542dec8ef90SFilipe Manana 			if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1543dec8ef90SFilipe Manana 				     &BTRFS_I(inode)->runtime_flags))
1544dec8ef90SFilipe Manana 				filemap_flush(inode->i_mapping);
1545dec8ef90SFilipe Manana 		}
15467b508037SQu Wenruo 		if (range->compress_type == BTRFS_COMPRESS_LZO)
15470b246afaSJeff Mahoney 			btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
15487b508037SQu Wenruo 		else if (range->compress_type == BTRFS_COMPRESS_ZSTD)
15495c1aab1dSNick Terrell 			btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
15507b508037SQu Wenruo 		ret = sectors_defragged;
15511a419d85SLi Zefan 	}
15521e2ef46dSDavid Sterba 	if (do_compress) {
155364708539SJosef Bacik 		btrfs_inode_lock(inode, 0);
1554eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
155564708539SJosef Bacik 		btrfs_inode_unlock(inode, 0);
1556633085c7SFilipe David Borba Manana 	}
1557940100a4SChris Mason 	return ret;
1558f46b5a66SChristoph Hellwig }
1559f46b5a66SChristoph Hellwig 
156017aaa434SDavid Sterba /*
156117aaa434SDavid Sterba  * Try to start exclusive operation @type or cancel it if it's running.
156217aaa434SDavid Sterba  *
156317aaa434SDavid Sterba  * Return:
156417aaa434SDavid Sterba  *   0        - normal mode, newly claimed op started
156517aaa434SDavid Sterba  *  >0        - normal mode, something else is running,
156617aaa434SDavid Sterba  *              return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS to user space
156717aaa434SDavid Sterba  * ECANCELED  - cancel mode, successful cancel
156817aaa434SDavid Sterba  * ENOTCONN   - cancel mode, operation not running anymore
156917aaa434SDavid Sterba  */
157017aaa434SDavid Sterba static int exclop_start_or_cancel_reloc(struct btrfs_fs_info *fs_info,
157117aaa434SDavid Sterba 			enum btrfs_exclusive_operation type, bool cancel)
157217aaa434SDavid Sterba {
157317aaa434SDavid Sterba 	if (!cancel) {
157417aaa434SDavid Sterba 		/* Start normal op */
157517aaa434SDavid Sterba 		if (!btrfs_exclop_start(fs_info, type))
157617aaa434SDavid Sterba 			return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
157717aaa434SDavid Sterba 		/* Exclusive operation is now claimed */
157817aaa434SDavid Sterba 		return 0;
157917aaa434SDavid Sterba 	}
158017aaa434SDavid Sterba 
158117aaa434SDavid Sterba 	/* Cancel running op */
158217aaa434SDavid Sterba 	if (btrfs_exclop_start_try_lock(fs_info, type)) {
158317aaa434SDavid Sterba 		/*
158417aaa434SDavid Sterba 		 * This blocks any exclop finish from setting it to NONE, so we
158517aaa434SDavid Sterba 		 * request cancellation. Either it runs and we will wait for it,
158617aaa434SDavid Sterba 		 * or it has finished and no waiting will happen.
158717aaa434SDavid Sterba 		 */
158817aaa434SDavid Sterba 		atomic_inc(&fs_info->reloc_cancel_req);
158917aaa434SDavid Sterba 		btrfs_exclop_start_unlock(fs_info);
159017aaa434SDavid Sterba 
159117aaa434SDavid Sterba 		if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
159217aaa434SDavid Sterba 			wait_on_bit(&fs_info->flags, BTRFS_FS_RELOC_RUNNING,
159317aaa434SDavid Sterba 				    TASK_INTERRUPTIBLE);
159417aaa434SDavid Sterba 
159517aaa434SDavid Sterba 		return -ECANCELED;
159617aaa434SDavid Sterba 	}
159717aaa434SDavid Sterba 
159817aaa434SDavid Sterba 	/* Something else is running or none */
159917aaa434SDavid Sterba 	return -ENOTCONN;
160017aaa434SDavid Sterba }
160117aaa434SDavid Sterba 
1602198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
160376dda93cSYan, Zheng 					void __user *arg)
1604f46b5a66SChristoph Hellwig {
1605562d7b15SJosef Bacik 	BTRFS_DEV_LOOKUP_ARGS(args);
16060b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
16070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1608f46b5a66SChristoph Hellwig 	u64 new_size;
1609f46b5a66SChristoph Hellwig 	u64 old_size;
1610f46b5a66SChristoph Hellwig 	u64 devid = 1;
16110b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1612f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1613f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1614f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1615f46b5a66SChristoph Hellwig 	char *sizestr;
16169a40f122SGui Hecheng 	char *retptr;
1617f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1618f46b5a66SChristoph Hellwig 	int ret = 0;
1619f46b5a66SChristoph Hellwig 	int mod = 0;
1620bb059a37SDavid Sterba 	bool cancel;
1621f46b5a66SChristoph Hellwig 
1622e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1623e441d54dSChris Mason 		return -EPERM;
1624e441d54dSChris Mason 
1625198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1626198605a8SMiao Xie 	if (ret)
1627198605a8SMiao Xie 		return ret;
1628198605a8SMiao Xie 
1629bb059a37SDavid Sterba 	/*
1630bb059a37SDavid Sterba 	 * Read the arguments before checking exclusivity to be able to
1631bb059a37SDavid Sterba 	 * distinguish regular resize and cancel
1632bb059a37SDavid Sterba 	 */
1633dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1634c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1635c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1636bb059a37SDavid Sterba 		goto out_drop;
1637c9e9f97bSIlya Dryomov 	}
16385516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1639f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1640bb059a37SDavid Sterba 	cancel = (strcmp("cancel", sizestr) == 0);
1641bb059a37SDavid Sterba 	ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_RESIZE, cancel);
1642bb059a37SDavid Sterba 	if (ret)
1643bb059a37SDavid Sterba 		goto out_free;
1644bb059a37SDavid Sterba 	/* Exclusive operation is now claimed */
1645bb059a37SDavid Sterba 
1646f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1647f46b5a66SChristoph Hellwig 	if (devstr) {
1648f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1649f46b5a66SChristoph Hellwig 		*devstr = '\0';
1650f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
165158dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
165258dfae63SZhangZhen 		if (ret)
1653bb059a37SDavid Sterba 			goto out_finish;
1654dfd79829SMiao Xie 		if (!devid) {
1655dfd79829SMiao Xie 			ret = -EINVAL;
1656bb059a37SDavid Sterba 			goto out_finish;
1657dfd79829SMiao Xie 		}
16580b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1659f46b5a66SChristoph Hellwig 	}
1660dba60f3fSMiao Xie 
1661562d7b15SJosef Bacik 	args.devid = devid;
1662562d7b15SJosef Bacik 	device = btrfs_find_device(fs_info->fs_devices, &args);
1663f46b5a66SChristoph Hellwig 	if (!device) {
16640b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1665c1c9ff7cSGeert Uytterhoeven 			   devid);
1666dfd79829SMiao Xie 		ret = -ENODEV;
1667bb059a37SDavid Sterba 		goto out_finish;
1668f46b5a66SChristoph Hellwig 	}
1669dba60f3fSMiao Xie 
1670ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
16710b246afaSJeff Mahoney 		btrfs_info(fs_info,
1672efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1673c1c9ff7cSGeert Uytterhoeven 		       devid);
1674dfd79829SMiao Xie 		ret = -EPERM;
1675bb059a37SDavid Sterba 		goto out_finish;
16764e42ae1bSLiu Bo 	}
16774e42ae1bSLiu Bo 
1678f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1679f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1680f46b5a66SChristoph Hellwig 	else {
1681f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1682f46b5a66SChristoph Hellwig 			mod = -1;
1683f46b5a66SChristoph Hellwig 			sizestr++;
1684f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1685f46b5a66SChristoph Hellwig 			mod = 1;
1686f46b5a66SChristoph Hellwig 			sizestr++;
1687f46b5a66SChristoph Hellwig 		}
16889a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
16899a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1690f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1691bb059a37SDavid Sterba 			goto out_finish;
1692f46b5a66SChristoph Hellwig 		}
1693f46b5a66SChristoph Hellwig 	}
1694f46b5a66SChristoph Hellwig 
1695401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1696dfd79829SMiao Xie 		ret = -EPERM;
1697bb059a37SDavid Sterba 		goto out_finish;
169863a212abSStefan Behrens 	}
169963a212abSStefan Behrens 
17007cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1701f46b5a66SChristoph Hellwig 
1702f46b5a66SChristoph Hellwig 	if (mod < 0) {
1703f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1704f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1705bb059a37SDavid Sterba 			goto out_finish;
1706f46b5a66SChristoph Hellwig 		}
1707f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1708f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1709eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1710902c68a4SGui Hecheng 			ret = -ERANGE;
1711bb059a37SDavid Sterba 			goto out_finish;
1712eb8052e0SWenliang Fan 		}
1713f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1714f46b5a66SChristoph Hellwig 	}
1715f46b5a66SChristoph Hellwig 
1716ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1717f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1718bb059a37SDavid Sterba 		goto out_finish;
1719f46b5a66SChristoph Hellwig 	}
1720f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1721f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1722bb059a37SDavid Sterba 		goto out_finish;
1723f46b5a66SChristoph Hellwig 	}
1724f46b5a66SChristoph Hellwig 
172547f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1726f46b5a66SChristoph Hellwig 
1727f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1728a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
172998d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
173098d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1731bb059a37SDavid Sterba 			goto out_finish;
173298d5dc13STsutomu Itoh 		}
1733f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
17343a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1735ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1736f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
17370253f40eSjeff.liu 	} /* equal, nothing need to do */
1738f46b5a66SChristoph Hellwig 
1739faf8f7b9SMarcos Paulo de Souza 	if (ret == 0 && new_size != old_size)
1740faf8f7b9SMarcos Paulo de Souza 		btrfs_info_in_rcu(fs_info,
1741faf8f7b9SMarcos Paulo de Souza 			"resize device %s (devid %llu) from %llu to %llu",
1742faf8f7b9SMarcos Paulo de Souza 			rcu_str_deref(device->name), device->devid,
1743faf8f7b9SMarcos Paulo de Souza 			old_size, new_size);
1744bb059a37SDavid Sterba out_finish:
1745bb059a37SDavid Sterba 	btrfs_exclop_finish(fs_info);
1746c9e9f97bSIlya Dryomov out_free:
1747f46b5a66SChristoph Hellwig 	kfree(vol_args);
1748bb059a37SDavid Sterba out_drop:
174918f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1750f46b5a66SChristoph Hellwig 	return ret;
1751f46b5a66SChristoph Hellwig }
1752f46b5a66SChristoph Hellwig 
17535d54c67eSNikolay Borisov static noinline int __btrfs_ioctl_snap_create(struct file *file,
17544d4340c9SChristian Brauner 				struct user_namespace *mnt_userns,
175552f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
17565d54c67eSNikolay Borisov 				bool readonly,
17578696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1758f46b5a66SChristoph Hellwig {
1759f46b5a66SChristoph Hellwig 	int namelen;
17603de4586cSChris Mason 	int ret = 0;
1761f46b5a66SChristoph Hellwig 
1762325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1763325c50e3SJeff Mahoney 		return -ENOTDIR;
1764325c50e3SJeff Mahoney 
1765a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1766a874a63eSLiu Bo 	if (ret)
1767a874a63eSLiu Bo 		goto out;
1768a874a63eSLiu Bo 
176972fd032eSSage Weil 	namelen = strlen(name);
177072fd032eSSage Weil 	if (strchr(name, '/')) {
1771f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1772a874a63eSLiu Bo 		goto out_drop_write;
1773f46b5a66SChristoph Hellwig 	}
1774f46b5a66SChristoph Hellwig 
177516780cabSChris Mason 	if (name[0] == '.' &&
177616780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
177716780cabSChris Mason 		ret = -EEXIST;
1778a874a63eSLiu Bo 		goto out_drop_write;
177916780cabSChris Mason 	}
178016780cabSChris Mason 
17813de4586cSChris Mason 	if (subvol) {
17824d4340c9SChristian Brauner 		ret = btrfs_mksubvol(&file->f_path, mnt_userns, name,
17834d4340c9SChristian Brauner 				     namelen, NULL, readonly, inherit);
1784cb8e7090SChristoph Hellwig 	} else {
17852903ff01SAl Viro 		struct fd src = fdget(fd);
17863de4586cSChris Mason 		struct inode *src_inode;
17872903ff01SAl Viro 		if (!src.file) {
17883de4586cSChris Mason 			ret = -EINVAL;
1789a874a63eSLiu Bo 			goto out_drop_write;
17903de4586cSChris Mason 		}
17913de4586cSChris Mason 
1792496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1793496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1794c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1795efe120a0SFrank Holton 				   "Snapshot src from another FS");
179623ad5b17SKusanagi Kouichi 			ret = -EXDEV;
17974d4340c9SChristian Brauner 		} else if (!inode_owner_or_capable(mnt_userns, src_inode)) {
1798d0242061SDavid Sterba 			/*
1799d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1800d0242061SDavid Sterba 			 * are limited to own subvolumes only
1801d0242061SDavid Sterba 			 */
1802d0242061SDavid Sterba 			ret = -EPERM;
1803ecd18815SAl Viro 		} else {
18044d4340c9SChristian Brauner 			ret = btrfs_mksnapshot(&file->f_path, mnt_userns,
18054d4340c9SChristian Brauner 					       name, namelen,
180672fd032eSSage Weil 					       BTRFS_I(src_inode)->root,
18075d54c67eSNikolay Borisov 					       readonly, inherit);
1808ecd18815SAl Viro 		}
18092903ff01SAl Viro 		fdput(src);
1810cb8e7090SChristoph Hellwig 	}
1811a874a63eSLiu Bo out_drop_write:
1812a874a63eSLiu Bo 	mnt_drop_write_file(file);
1813f46b5a66SChristoph Hellwig out:
181472fd032eSSage Weil 	return ret;
181572fd032eSSage Weil }
181672fd032eSSage Weil 
181772fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1818fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
181972fd032eSSage Weil {
1820fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
182172fd032eSSage Weil 	int ret;
182272fd032eSSage Weil 
1823325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1824325c50e3SJeff Mahoney 		return -ENOTDIR;
1825325c50e3SJeff Mahoney 
1826fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1827fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1828fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1829fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1830fa0d2b9bSLi Zefan 
18314d4340c9SChristian Brauner 	ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
18324d4340c9SChristian Brauner 					vol_args->name, vol_args->fd, subvol,
18334d4340c9SChristian Brauner 					false, NULL);
1834fa0d2b9bSLi Zefan 
1835fa0d2b9bSLi Zefan 	kfree(vol_args);
1836fa0d2b9bSLi Zefan 	return ret;
1837fa0d2b9bSLi Zefan }
1838fa0d2b9bSLi Zefan 
1839fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1840fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1841fa0d2b9bSLi Zefan {
1842fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1843fa0d2b9bSLi Zefan 	int ret;
1844b83cc969SLi Zefan 	bool readonly = false;
18456f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
184672fd032eSSage Weil 
1847325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1848325c50e3SJeff Mahoney 		return -ENOTDIR;
1849325c50e3SJeff Mahoney 
1850fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1851fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1852fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1853fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1854fdfb1e4fSLi Zefan 
1855673990dbSDavid Sterba 	if (vol_args->flags & ~BTRFS_SUBVOL_CREATE_ARGS_MASK) {
1856b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1857c47ca32dSDan Carpenter 		goto free_args;
1858fdfb1e4fSLi Zefan 	}
1859fdfb1e4fSLi Zefan 
1860b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1861b83cc969SLi Zefan 		readonly = true;
18626f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
18635011c5a6SDan Carpenter 		u64 nums;
18645011c5a6SDan Carpenter 
18655011c5a6SDan Carpenter 		if (vol_args->size < sizeof(*inherit) ||
18665011c5a6SDan Carpenter 		    vol_args->size > PAGE_SIZE) {
18676f72c7e2SArne Jansen 			ret = -EINVAL;
1868c47ca32dSDan Carpenter 			goto free_args;
18696f72c7e2SArne Jansen 		}
18706f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
18716f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
18726f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1873c47ca32dSDan Carpenter 			goto free_args;
18746f72c7e2SArne Jansen 		}
18755011c5a6SDan Carpenter 
18765011c5a6SDan Carpenter 		if (inherit->num_qgroups > PAGE_SIZE ||
18775011c5a6SDan Carpenter 		    inherit->num_ref_copies > PAGE_SIZE ||
18785011c5a6SDan Carpenter 		    inherit->num_excl_copies > PAGE_SIZE) {
18795011c5a6SDan Carpenter 			ret = -EINVAL;
18805011c5a6SDan Carpenter 			goto free_inherit;
18815011c5a6SDan Carpenter 		}
18825011c5a6SDan Carpenter 
18835011c5a6SDan Carpenter 		nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
18845011c5a6SDan Carpenter 		       2 * inherit->num_excl_copies;
18855011c5a6SDan Carpenter 		if (vol_args->size != struct_size(inherit, qgroups, nums)) {
18865011c5a6SDan Carpenter 			ret = -EINVAL;
18875011c5a6SDan Carpenter 			goto free_inherit;
18885011c5a6SDan Carpenter 		}
18896f72c7e2SArne Jansen 	}
189075eaa0e2SSage Weil 
18914d4340c9SChristian Brauner 	ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
18924d4340c9SChristian Brauner 					vol_args->name, vol_args->fd, subvol,
18934d4340c9SChristian Brauner 					readonly, inherit);
1894c47ca32dSDan Carpenter 	if (ret)
1895c47ca32dSDan Carpenter 		goto free_inherit;
1896c47ca32dSDan Carpenter free_inherit:
18976f72c7e2SArne Jansen 	kfree(inherit);
1898c47ca32dSDan Carpenter free_args:
1899c47ca32dSDan Carpenter 	kfree(vol_args);
1900f46b5a66SChristoph Hellwig 	return ret;
1901f46b5a66SChristoph Hellwig }
1902f46b5a66SChristoph Hellwig 
19030caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
19040caa102dSLi Zefan 						void __user *arg)
19050caa102dSLi Zefan {
1906496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
19070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
19080caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
19090caa102dSLi Zefan 	int ret = 0;
19100caa102dSLi Zefan 	u64 flags = 0;
19110caa102dSLi Zefan 
19124a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
19130caa102dSLi Zefan 		return -EINVAL;
19140caa102dSLi Zefan 
19150b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
19160caa102dSLi Zefan 	if (btrfs_root_readonly(root))
19170caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
19180b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
19190caa102dSLi Zefan 
19200caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
19210caa102dSLi Zefan 		ret = -EFAULT;
19220caa102dSLi Zefan 
19230caa102dSLi Zefan 	return ret;
19240caa102dSLi Zefan }
19250caa102dSLi Zefan 
19260caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
19270caa102dSLi Zefan 					      void __user *arg)
19280caa102dSLi Zefan {
1929496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
19300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
19310caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
19320caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
19330caa102dSLi Zefan 	u64 root_flags;
19340caa102dSLi Zefan 	u64 flags;
19350caa102dSLi Zefan 	int ret = 0;
19360caa102dSLi Zefan 
193739e1674fSChristian Brauner 	if (!inode_owner_or_capable(file_mnt_user_ns(file), inode))
1938bd60ea0fSDavid Sterba 		return -EPERM;
1939bd60ea0fSDavid Sterba 
1940b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1941b9ca0664SLiu Bo 	if (ret)
1942b9ca0664SLiu Bo 		goto out;
19430caa102dSLi Zefan 
19444a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1945b9ca0664SLiu Bo 		ret = -EINVAL;
1946b9ca0664SLiu Bo 		goto out_drop_write;
1947b9ca0664SLiu Bo 	}
19480caa102dSLi Zefan 
1949b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1950b9ca0664SLiu Bo 		ret = -EFAULT;
1951b9ca0664SLiu Bo 		goto out_drop_write;
1952b9ca0664SLiu Bo 	}
19530caa102dSLi Zefan 
1954b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1955b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1956b9ca0664SLiu Bo 		goto out_drop_write;
1957b9ca0664SLiu Bo 	}
19580caa102dSLi Zefan 
19590b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
19600caa102dSLi Zefan 
19610caa102dSLi Zefan 	/* nothing to do */
19620caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1963b9ca0664SLiu Bo 		goto out_drop_sem;
19640caa102dSLi Zefan 
19650caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
19662c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
19670caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
19680caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
19692c686537SDavid Sterba 	} else {
19702c686537SDavid Sterba 		/*
19712c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
19722c686537SDavid Sterba 		 * send
19732c686537SDavid Sterba 		 */
19742c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
19752c686537SDavid Sterba 		if (root->send_in_progress == 0) {
19760caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
19770caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
19782c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19792c686537SDavid Sterba 		} else {
19802c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19810b246afaSJeff Mahoney 			btrfs_warn(fs_info,
19822c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
19832c686537SDavid Sterba 				   root->root_key.objectid);
19842c686537SDavid Sterba 			ret = -EPERM;
19852c686537SDavid Sterba 			goto out_drop_sem;
19862c686537SDavid Sterba 		}
19872c686537SDavid Sterba 	}
19880caa102dSLi Zefan 
19890caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
19900caa102dSLi Zefan 	if (IS_ERR(trans)) {
19910caa102dSLi Zefan 		ret = PTR_ERR(trans);
19920caa102dSLi Zefan 		goto out_reset;
19930caa102dSLi Zefan 	}
19940caa102dSLi Zefan 
19950b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
19960caa102dSLi Zefan 				&root->root_key, &root->root_item);
19979417ebc8SNikolay Borisov 	if (ret < 0) {
19989417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
19999417ebc8SNikolay Borisov 		goto out_reset;
20009417ebc8SNikolay Borisov 	}
20010caa102dSLi Zefan 
20029417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
20039417ebc8SNikolay Borisov 
20040caa102dSLi Zefan out_reset:
20050caa102dSLi Zefan 	if (ret)
20060caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
2007b9ca0664SLiu Bo out_drop_sem:
20080b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
2009b9ca0664SLiu Bo out_drop_write:
2010b9ca0664SLiu Bo 	mnt_drop_write_file(file);
2011b9ca0664SLiu Bo out:
20120caa102dSLi Zefan 	return ret;
20130caa102dSLi Zefan }
20140caa102dSLi Zefan 
2015ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
2016ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
2017ac8e9819SChris Mason {
2018abc6e134SChris Mason 	struct btrfs_key test;
2019abc6e134SChris Mason 	int ret;
2020abc6e134SChris Mason 
2021abc6e134SChris Mason 	test.objectid = sk->min_objectid;
2022abc6e134SChris Mason 	test.type = sk->min_type;
2023abc6e134SChris Mason 	test.offset = sk->min_offset;
2024abc6e134SChris Mason 
2025abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
2026abc6e134SChris Mason 	if (ret < 0)
2027ac8e9819SChris Mason 		return 0;
2028abc6e134SChris Mason 
2029abc6e134SChris Mason 	test.objectid = sk->max_objectid;
2030abc6e134SChris Mason 	test.type = sk->max_type;
2031abc6e134SChris Mason 	test.offset = sk->max_offset;
2032abc6e134SChris Mason 
2033abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
2034abc6e134SChris Mason 	if (ret > 0)
2035ac8e9819SChris Mason 		return 0;
2036ac8e9819SChris Mason 	return 1;
2037ac8e9819SChris Mason }
2038ac8e9819SChris Mason 
2039df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
2040ac8e9819SChris Mason 			       struct btrfs_key *key,
2041ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
20429b6e817dSGerhard Heift 			       size_t *buf_size,
2043ba346b35SGerhard Heift 			       char __user *ubuf,
2044ac8e9819SChris Mason 			       unsigned long *sk_offset,
2045ac8e9819SChris Mason 			       int *num_found)
2046ac8e9819SChris Mason {
2047ac8e9819SChris Mason 	u64 found_transid;
2048ac8e9819SChris Mason 	struct extent_buffer *leaf;
2049ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
2050dd81d459SNaohiro Aota 	struct btrfs_key test;
2051ac8e9819SChris Mason 	unsigned long item_off;
2052ac8e9819SChris Mason 	unsigned long item_len;
2053ac8e9819SChris Mason 	int nritems;
2054ac8e9819SChris Mason 	int i;
2055ac8e9819SChris Mason 	int slot;
2056ac8e9819SChris Mason 	int ret = 0;
2057ac8e9819SChris Mason 
2058ac8e9819SChris Mason 	leaf = path->nodes[0];
2059ac8e9819SChris Mason 	slot = path->slots[0];
2060ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
2061ac8e9819SChris Mason 
2062ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
2063ac8e9819SChris Mason 		i = nritems;
2064ac8e9819SChris Mason 		goto advance_key;
2065ac8e9819SChris Mason 	}
2066ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
2067ac8e9819SChris Mason 
2068ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
2069ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
2070ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
2071ac8e9819SChris Mason 
207203b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
207303b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
207403b71c6cSGabriel de Perthuis 			continue;
207503b71c6cSGabriel de Perthuis 
20769b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
20778f5f6178SGerhard Heift 			if (*num_found) {
2078ac8e9819SChris Mason 				ret = 1;
20798f5f6178SGerhard Heift 				goto out;
20808f5f6178SGerhard Heift 			}
20818f5f6178SGerhard Heift 
20828f5f6178SGerhard Heift 			/*
20838f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
20848f5f6178SGerhard Heift 			 * handle -EOVERFLOW
20858f5f6178SGerhard Heift 			 */
20868f5f6178SGerhard Heift 
20879b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
2088ac8e9819SChris Mason 			item_len = 0;
20898f5f6178SGerhard Heift 			ret = -EOVERFLOW;
20908f5f6178SGerhard Heift 		}
2091ac8e9819SChris Mason 
20929b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2093ac8e9819SChris Mason 			ret = 1;
209425c9bc2eSGerhard Heift 			goto out;
2095ac8e9819SChris Mason 		}
2096ac8e9819SChris Mason 
2097ac8e9819SChris Mason 		sh.objectid = key->objectid;
2098ac8e9819SChris Mason 		sh.offset = key->offset;
2099ac8e9819SChris Mason 		sh.type = key->type;
2100ac8e9819SChris Mason 		sh.len = item_len;
2101ac8e9819SChris Mason 		sh.transid = found_transid;
2102ac8e9819SChris Mason 
2103a48b73ecSJosef Bacik 		/*
2104a48b73ecSJosef Bacik 		 * Copy search result header. If we fault then loop again so we
2105a48b73ecSJosef Bacik 		 * can fault in the pages and -EFAULT there if there's a
2106a48b73ecSJosef Bacik 		 * problem. Otherwise we'll fault and then copy the buffer in
2107a48b73ecSJosef Bacik 		 * properly this next time through
2108a48b73ecSJosef Bacik 		 */
2109a48b73ecSJosef Bacik 		if (copy_to_user_nofault(ubuf + *sk_offset, &sh, sizeof(sh))) {
2110a48b73ecSJosef Bacik 			ret = 0;
2111ba346b35SGerhard Heift 			goto out;
2112ba346b35SGerhard Heift 		}
2113ba346b35SGerhard Heift 
2114ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2115ac8e9819SChris Mason 
2116ac8e9819SChris Mason 		if (item_len) {
2117ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2118a48b73ecSJosef Bacik 			/*
2119a48b73ecSJosef Bacik 			 * Copy the item, same behavior as above, but reset the
2120a48b73ecSJosef Bacik 			 * * sk_offset so we copy the full thing again.
2121a48b73ecSJosef Bacik 			 */
2122a48b73ecSJosef Bacik 			if (read_extent_buffer_to_user_nofault(leaf, up,
2123ba346b35SGerhard Heift 						item_off, item_len)) {
2124a48b73ecSJosef Bacik 				ret = 0;
2125a48b73ecSJosef Bacik 				*sk_offset -= sizeof(sh);
2126ba346b35SGerhard Heift 				goto out;
2127ba346b35SGerhard Heift 			}
2128ba346b35SGerhard Heift 
2129ac8e9819SChris Mason 			*sk_offset += item_len;
2130ac8e9819SChris Mason 		}
2131e2156867SHugo Mills 		(*num_found)++;
2132ac8e9819SChris Mason 
21338f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
21348f5f6178SGerhard Heift 			goto out;
21358f5f6178SGerhard Heift 
213625c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
213725c9bc2eSGerhard Heift 			ret = 1;
213825c9bc2eSGerhard Heift 			goto out;
213925c9bc2eSGerhard Heift 		}
2140ac8e9819SChris Mason 	}
2141ac8e9819SChris Mason advance_key:
2142ac8e9819SChris Mason 	ret = 0;
2143dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2144dd81d459SNaohiro Aota 	test.type = sk->max_type;
2145dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2146dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2147dd81d459SNaohiro Aota 		ret = 1;
2148dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2149abc6e134SChris Mason 		key->offset++;
2150dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2151abc6e134SChris Mason 		key->offset = 0;
2152abc6e134SChris Mason 		key->type++;
2153dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2154abc6e134SChris Mason 		key->offset = 0;
2155abc6e134SChris Mason 		key->type = 0;
2156abc6e134SChris Mason 		key->objectid++;
2157abc6e134SChris Mason 	} else
2158abc6e134SChris Mason 		ret = 1;
215925c9bc2eSGerhard Heift out:
2160ba346b35SGerhard Heift 	/*
2161ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2162ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2163ba346b35SGerhard Heift 	 *     * all items were found
2164ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2165ba346b35SGerhard Heift 	 *     leaf
2166ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2167ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2168ba346b35SGerhard Heift 	 */
2169ac8e9819SChris Mason 	return ret;
2170ac8e9819SChris Mason }
2171ac8e9819SChris Mason 
2172ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
217312544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
21749b6e817dSGerhard Heift 				 size_t *buf_size,
2175ba346b35SGerhard Heift 				 char __user *ubuf)
2176ac8e9819SChris Mason {
21770b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2178ac8e9819SChris Mason 	struct btrfs_root *root;
2179ac8e9819SChris Mason 	struct btrfs_key key;
2180ac8e9819SChris Mason 	struct btrfs_path *path;
2181ac8e9819SChris Mason 	int ret;
2182ac8e9819SChris Mason 	int num_found = 0;
2183ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2184ac8e9819SChris Mason 
21859b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
21869b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
218712544442SGerhard Heift 		return -EOVERFLOW;
21889b6e817dSGerhard Heift 	}
218912544442SGerhard Heift 
2190ac8e9819SChris Mason 	path = btrfs_alloc_path();
2191ac8e9819SChris Mason 	if (!path)
2192ac8e9819SChris Mason 		return -ENOMEM;
2193ac8e9819SChris Mason 
2194ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2195ac8e9819SChris Mason 		/* search the root of the inode that was passed */
219600246528SJosef Bacik 		root = btrfs_grab_root(BTRFS_I(inode)->root);
2197ac8e9819SChris Mason 	} else {
219856e9357aSDavid Sterba 		root = btrfs_get_fs_root(info, sk->tree_id, true);
2199ac8e9819SChris Mason 		if (IS_ERR(root)) {
2200ac8e9819SChris Mason 			btrfs_free_path(path);
2201ad1e3d56SMisono Tomohiro 			return PTR_ERR(root);
2202ac8e9819SChris Mason 		}
2203ac8e9819SChris Mason 	}
2204ac8e9819SChris Mason 
2205ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2206ac8e9819SChris Mason 	key.type = sk->min_type;
2207ac8e9819SChris Mason 	key.offset = sk->min_offset;
2208ac8e9819SChris Mason 
2209ac8e9819SChris Mason 	while (1) {
22101c78544eSFilipe Manana 		ret = fault_in_pages_writeable(ubuf + sk_offset,
22111c78544eSFilipe Manana 					       *buf_size - sk_offset);
2212a48b73ecSJosef Bacik 		if (ret)
2213a48b73ecSJosef Bacik 			break;
2214a48b73ecSJosef Bacik 
22156174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2216ac8e9819SChris Mason 		if (ret != 0) {
2217ac8e9819SChris Mason 			if (ret > 0)
2218ac8e9819SChris Mason 				ret = 0;
2219ac8e9819SChris Mason 			goto err;
2220ac8e9819SChris Mason 		}
2221df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2222ac8e9819SChris Mason 				 &sk_offset, &num_found);
2223b3b4aa74SDavid Sterba 		btrfs_release_path(path);
222425c9bc2eSGerhard Heift 		if (ret)
2225ac8e9819SChris Mason 			break;
2226ac8e9819SChris Mason 
2227ac8e9819SChris Mason 	}
22288f5f6178SGerhard Heift 	if (ret > 0)
2229ac8e9819SChris Mason 		ret = 0;
2230ac8e9819SChris Mason err:
2231ac8e9819SChris Mason 	sk->nr_items = num_found;
223200246528SJosef Bacik 	btrfs_put_root(root);
2233ac8e9819SChris Mason 	btrfs_free_path(path);
2234ac8e9819SChris Mason 	return ret;
2235ac8e9819SChris Mason }
2236ac8e9819SChris Mason 
2237ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2238ac8e9819SChris Mason 					   void __user *argp)
2239ac8e9819SChris Mason {
2240ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2241ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2242ac8e9819SChris Mason 	struct inode *inode;
2243ac8e9819SChris Mason 	int ret;
22449b6e817dSGerhard Heift 	size_t buf_size;
2245ac8e9819SChris Mason 
2246ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2247ac8e9819SChris Mason 		return -EPERM;
2248ac8e9819SChris Mason 
2249ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2250ac8e9819SChris Mason 
2251ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2252ba346b35SGerhard Heift 		return -EFAULT;
2253ba346b35SGerhard Heift 
2254ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2255ac8e9819SChris Mason 
2256496ad9aaSAl Viro 	inode = file_inode(file);
2257ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
22588f5f6178SGerhard Heift 
22598f5f6178SGerhard Heift 	/*
22608f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
22618f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
22628f5f6178SGerhard Heift 	 */
22638f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
22648f5f6178SGerhard Heift 		ret = 0;
22658f5f6178SGerhard Heift 
2266ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2267ac8e9819SChris Mason 		ret = -EFAULT;
2268ac8e9819SChris Mason 	return ret;
2269ac8e9819SChris Mason }
2270ac8e9819SChris Mason 
2271cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2272cc68a8a5SGerhard Heift 					       void __user *argp)
2273cc68a8a5SGerhard Heift {
2274cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2275cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2276cc68a8a5SGerhard Heift 	struct inode *inode;
2277cc68a8a5SGerhard Heift 	int ret;
2278cc68a8a5SGerhard Heift 	size_t buf_size;
2279ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2280cc68a8a5SGerhard Heift 
2281cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2282cc68a8a5SGerhard Heift 		return -EPERM;
2283cc68a8a5SGerhard Heift 
2284cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2285cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2286cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2287cc68a8a5SGerhard Heift 		return -EFAULT;
2288cc68a8a5SGerhard Heift 
2289cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2290cc68a8a5SGerhard Heift 
2291cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2292cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2293cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2294cc68a8a5SGerhard Heift 
2295cc68a8a5SGerhard Heift 	inode = file_inode(file);
2296cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2297718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2298cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2299cc68a8a5SGerhard Heift 		ret = -EFAULT;
2300cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2301cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2302cc68a8a5SGerhard Heift 		ret = -EFAULT;
2303cc68a8a5SGerhard Heift 
230476dda93cSYan, Zheng 	return ret;
230576dda93cSYan, Zheng }
230676dda93cSYan, Zheng 
230798d377a0STARUISI Hiroaki /*
2308ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2309ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
231098d377a0STARUISI Hiroaki  */
231198d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
231298d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
231398d377a0STARUISI Hiroaki {
231498d377a0STARUISI Hiroaki 	struct btrfs_root *root;
231598d377a0STARUISI Hiroaki 	struct btrfs_key key;
2316ac8e9819SChris Mason 	char *ptr;
231798d377a0STARUISI Hiroaki 	int ret = -1;
231898d377a0STARUISI Hiroaki 	int slot;
231998d377a0STARUISI Hiroaki 	int len;
232098d377a0STARUISI Hiroaki 	int total_len = 0;
232198d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
232298d377a0STARUISI Hiroaki 	struct extent_buffer *l;
232398d377a0STARUISI Hiroaki 	struct btrfs_path *path;
232498d377a0STARUISI Hiroaki 
232598d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
232698d377a0STARUISI Hiroaki 		name[0]='\0';
232798d377a0STARUISI Hiroaki 		return 0;
232898d377a0STARUISI Hiroaki 	}
232998d377a0STARUISI Hiroaki 
233098d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
233198d377a0STARUISI Hiroaki 	if (!path)
233298d377a0STARUISI Hiroaki 		return -ENOMEM;
233398d377a0STARUISI Hiroaki 
2334c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
233598d377a0STARUISI Hiroaki 
233656e9357aSDavid Sterba 	root = btrfs_get_fs_root(info, tree_id, true);
233798d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2338ad1e3d56SMisono Tomohiro 		ret = PTR_ERR(root);
233988234012SJosef Bacik 		root = NULL;
234088234012SJosef Bacik 		goto out;
234188234012SJosef Bacik 	}
234298d377a0STARUISI Hiroaki 
234398d377a0STARUISI Hiroaki 	key.objectid = dirid;
234498d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
23458ad6fcabSChris Mason 	key.offset = (u64)-1;
234698d377a0STARUISI Hiroaki 
234798d377a0STARUISI Hiroaki 	while (1) {
23480ff40a91SMarcos Paulo de Souza 		ret = btrfs_search_backwards(root, &key, path);
234918674c6cSFilipe David Borba Manana 		if (ret < 0)
235018674c6cSFilipe David Borba Manana 			goto out;
235118674c6cSFilipe David Borba Manana 		else if (ret > 0) {
2352ac8e9819SChris Mason 			ret = -ENOENT;
235398d377a0STARUISI Hiroaki 			goto out;
2354ac8e9819SChris Mason 		}
235518674c6cSFilipe David Borba Manana 
235618674c6cSFilipe David Borba Manana 		l = path->nodes[0];
235718674c6cSFilipe David Borba Manana 		slot = path->slots[0];
235898d377a0STARUISI Hiroaki 
235998d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
236098d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
236198d377a0STARUISI Hiroaki 		ptr -= len + 1;
236298d377a0STARUISI Hiroaki 		total_len += len + 1;
2363a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2364a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
236598d377a0STARUISI Hiroaki 			goto out;
2366a696cf35SFilipe David Borba Manana 		}
236798d377a0STARUISI Hiroaki 
236898d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
236998d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
237098d377a0STARUISI Hiroaki 
237198d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
237298d377a0STARUISI Hiroaki 			break;
237398d377a0STARUISI Hiroaki 
2374b3b4aa74SDavid Sterba 		btrfs_release_path(path);
237598d377a0STARUISI Hiroaki 		key.objectid = key.offset;
23768ad6fcabSChris Mason 		key.offset = (u64)-1;
237798d377a0STARUISI Hiroaki 		dirid = key.objectid;
237898d377a0STARUISI Hiroaki 	}
237977906a50SLi Zefan 	memmove(name, ptr, total_len);
238098d377a0STARUISI Hiroaki 	name[total_len] = '\0';
238198d377a0STARUISI Hiroaki 	ret = 0;
238298d377a0STARUISI Hiroaki out:
238300246528SJosef Bacik 	btrfs_put_root(root);
238498d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2385ac8e9819SChris Mason 	return ret;
2386ac8e9819SChris Mason }
2387ac8e9819SChris Mason 
23886623d9a0SChristian Brauner static int btrfs_search_path_in_tree_user(struct user_namespace *mnt_userns,
23896623d9a0SChristian Brauner 				struct inode *inode,
239023d0b79dSTomohiro Misono 				struct btrfs_ioctl_ino_lookup_user_args *args)
239123d0b79dSTomohiro Misono {
239223d0b79dSTomohiro Misono 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
239323d0b79dSTomohiro Misono 	struct super_block *sb = inode->i_sb;
239423d0b79dSTomohiro Misono 	struct btrfs_key upper_limit = BTRFS_I(inode)->location;
239523d0b79dSTomohiro Misono 	u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
239623d0b79dSTomohiro Misono 	u64 dirid = args->dirid;
239723d0b79dSTomohiro Misono 	unsigned long item_off;
239823d0b79dSTomohiro Misono 	unsigned long item_len;
239923d0b79dSTomohiro Misono 	struct btrfs_inode_ref *iref;
240023d0b79dSTomohiro Misono 	struct btrfs_root_ref *rref;
2401b8a49ae1SJosef Bacik 	struct btrfs_root *root = NULL;
240223d0b79dSTomohiro Misono 	struct btrfs_path *path;
240323d0b79dSTomohiro Misono 	struct btrfs_key key, key2;
240423d0b79dSTomohiro Misono 	struct extent_buffer *leaf;
240523d0b79dSTomohiro Misono 	struct inode *temp_inode;
240623d0b79dSTomohiro Misono 	char *ptr;
240723d0b79dSTomohiro Misono 	int slot;
240823d0b79dSTomohiro Misono 	int len;
240923d0b79dSTomohiro Misono 	int total_len = 0;
241023d0b79dSTomohiro Misono 	int ret;
241123d0b79dSTomohiro Misono 
241223d0b79dSTomohiro Misono 	path = btrfs_alloc_path();
241323d0b79dSTomohiro Misono 	if (!path)
241423d0b79dSTomohiro Misono 		return -ENOMEM;
241523d0b79dSTomohiro Misono 
241623d0b79dSTomohiro Misono 	/*
241723d0b79dSTomohiro Misono 	 * If the bottom subvolume does not exist directly under upper_limit,
241823d0b79dSTomohiro Misono 	 * construct the path in from the bottom up.
241923d0b79dSTomohiro Misono 	 */
242023d0b79dSTomohiro Misono 	if (dirid != upper_limit.objectid) {
242123d0b79dSTomohiro Misono 		ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
242223d0b79dSTomohiro Misono 
242356e9357aSDavid Sterba 		root = btrfs_get_fs_root(fs_info, treeid, true);
242423d0b79dSTomohiro Misono 		if (IS_ERR(root)) {
242523d0b79dSTomohiro Misono 			ret = PTR_ERR(root);
242623d0b79dSTomohiro Misono 			goto out;
242723d0b79dSTomohiro Misono 		}
242823d0b79dSTomohiro Misono 
242923d0b79dSTomohiro Misono 		key.objectid = dirid;
243023d0b79dSTomohiro Misono 		key.type = BTRFS_INODE_REF_KEY;
243123d0b79dSTomohiro Misono 		key.offset = (u64)-1;
243223d0b79dSTomohiro Misono 		while (1) {
24330ff40a91SMarcos Paulo de Souza 			ret = btrfs_search_backwards(root, &key, path);
24340ff40a91SMarcos Paulo de Souza 			if (ret < 0)
2435b8a49ae1SJosef Bacik 				goto out_put;
24360ff40a91SMarcos Paulo de Souza 			else if (ret > 0) {
243723d0b79dSTomohiro Misono 				ret = -ENOENT;
2438b8a49ae1SJosef Bacik 				goto out_put;
243923d0b79dSTomohiro Misono 			}
244023d0b79dSTomohiro Misono 
244123d0b79dSTomohiro Misono 			leaf = path->nodes[0];
244223d0b79dSTomohiro Misono 			slot = path->slots[0];
244323d0b79dSTomohiro Misono 
244423d0b79dSTomohiro Misono 			iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
244523d0b79dSTomohiro Misono 			len = btrfs_inode_ref_name_len(leaf, iref);
244623d0b79dSTomohiro Misono 			ptr -= len + 1;
244723d0b79dSTomohiro Misono 			total_len += len + 1;
244823d0b79dSTomohiro Misono 			if (ptr < args->path) {
244923d0b79dSTomohiro Misono 				ret = -ENAMETOOLONG;
2450b8a49ae1SJosef Bacik 				goto out_put;
245123d0b79dSTomohiro Misono 			}
245223d0b79dSTomohiro Misono 
245323d0b79dSTomohiro Misono 			*(ptr + len) = '/';
245423d0b79dSTomohiro Misono 			read_extent_buffer(leaf, ptr,
245523d0b79dSTomohiro Misono 					(unsigned long)(iref + 1), len);
245623d0b79dSTomohiro Misono 
245723d0b79dSTomohiro Misono 			/* Check the read+exec permission of this directory */
245823d0b79dSTomohiro Misono 			ret = btrfs_previous_item(root, path, dirid,
245923d0b79dSTomohiro Misono 						  BTRFS_INODE_ITEM_KEY);
246023d0b79dSTomohiro Misono 			if (ret < 0) {
2461b8a49ae1SJosef Bacik 				goto out_put;
246223d0b79dSTomohiro Misono 			} else if (ret > 0) {
246323d0b79dSTomohiro Misono 				ret = -ENOENT;
2464b8a49ae1SJosef Bacik 				goto out_put;
246523d0b79dSTomohiro Misono 			}
246623d0b79dSTomohiro Misono 
246723d0b79dSTomohiro Misono 			leaf = path->nodes[0];
246823d0b79dSTomohiro Misono 			slot = path->slots[0];
246923d0b79dSTomohiro Misono 			btrfs_item_key_to_cpu(leaf, &key2, slot);
247023d0b79dSTomohiro Misono 			if (key2.objectid != dirid) {
247123d0b79dSTomohiro Misono 				ret = -ENOENT;
2472b8a49ae1SJosef Bacik 				goto out_put;
247323d0b79dSTomohiro Misono 			}
247423d0b79dSTomohiro Misono 
24750202e83fSDavid Sterba 			temp_inode = btrfs_iget(sb, key2.objectid, root);
24763ca57bd6SMisono Tomohiro 			if (IS_ERR(temp_inode)) {
24773ca57bd6SMisono Tomohiro 				ret = PTR_ERR(temp_inode);
2478b8a49ae1SJosef Bacik 				goto out_put;
24793ca57bd6SMisono Tomohiro 			}
24806623d9a0SChristian Brauner 			ret = inode_permission(mnt_userns, temp_inode,
248147291baaSChristian Brauner 					       MAY_READ | MAY_EXEC);
248223d0b79dSTomohiro Misono 			iput(temp_inode);
248323d0b79dSTomohiro Misono 			if (ret) {
248423d0b79dSTomohiro Misono 				ret = -EACCES;
2485b8a49ae1SJosef Bacik 				goto out_put;
248623d0b79dSTomohiro Misono 			}
248723d0b79dSTomohiro Misono 
248823d0b79dSTomohiro Misono 			if (key.offset == upper_limit.objectid)
248923d0b79dSTomohiro Misono 				break;
249023d0b79dSTomohiro Misono 			if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
249123d0b79dSTomohiro Misono 				ret = -EACCES;
2492b8a49ae1SJosef Bacik 				goto out_put;
249323d0b79dSTomohiro Misono 			}
249423d0b79dSTomohiro Misono 
249523d0b79dSTomohiro Misono 			btrfs_release_path(path);
249623d0b79dSTomohiro Misono 			key.objectid = key.offset;
249723d0b79dSTomohiro Misono 			key.offset = (u64)-1;
249823d0b79dSTomohiro Misono 			dirid = key.objectid;
249923d0b79dSTomohiro Misono 		}
250023d0b79dSTomohiro Misono 
250123d0b79dSTomohiro Misono 		memmove(args->path, ptr, total_len);
250223d0b79dSTomohiro Misono 		args->path[total_len] = '\0';
250300246528SJosef Bacik 		btrfs_put_root(root);
2504b8a49ae1SJosef Bacik 		root = NULL;
250523d0b79dSTomohiro Misono 		btrfs_release_path(path);
250623d0b79dSTomohiro Misono 	}
250723d0b79dSTomohiro Misono 
250823d0b79dSTomohiro Misono 	/* Get the bottom subvolume's name from ROOT_REF */
250923d0b79dSTomohiro Misono 	key.objectid = treeid;
251023d0b79dSTomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
251123d0b79dSTomohiro Misono 	key.offset = args->treeid;
2512b8a49ae1SJosef Bacik 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
251323d0b79dSTomohiro Misono 	if (ret < 0) {
251423d0b79dSTomohiro Misono 		goto out;
251523d0b79dSTomohiro Misono 	} else if (ret > 0) {
251623d0b79dSTomohiro Misono 		ret = -ENOENT;
251723d0b79dSTomohiro Misono 		goto out;
251823d0b79dSTomohiro Misono 	}
251923d0b79dSTomohiro Misono 
252023d0b79dSTomohiro Misono 	leaf = path->nodes[0];
252123d0b79dSTomohiro Misono 	slot = path->slots[0];
252223d0b79dSTomohiro Misono 	btrfs_item_key_to_cpu(leaf, &key, slot);
252323d0b79dSTomohiro Misono 
252423d0b79dSTomohiro Misono 	item_off = btrfs_item_ptr_offset(leaf, slot);
252523d0b79dSTomohiro Misono 	item_len = btrfs_item_size_nr(leaf, slot);
252623d0b79dSTomohiro Misono 	/* Check if dirid in ROOT_REF corresponds to passed dirid */
252723d0b79dSTomohiro Misono 	rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
252823d0b79dSTomohiro Misono 	if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
252923d0b79dSTomohiro Misono 		ret = -EINVAL;
253023d0b79dSTomohiro Misono 		goto out;
253123d0b79dSTomohiro Misono 	}
253223d0b79dSTomohiro Misono 
253323d0b79dSTomohiro Misono 	/* Copy subvolume's name */
253423d0b79dSTomohiro Misono 	item_off += sizeof(struct btrfs_root_ref);
253523d0b79dSTomohiro Misono 	item_len -= sizeof(struct btrfs_root_ref);
253623d0b79dSTomohiro Misono 	read_extent_buffer(leaf, args->name, item_off, item_len);
253723d0b79dSTomohiro Misono 	args->name[item_len] = 0;
253823d0b79dSTomohiro Misono 
2539b8a49ae1SJosef Bacik out_put:
254000246528SJosef Bacik 	btrfs_put_root(root);
254123d0b79dSTomohiro Misono out:
254223d0b79dSTomohiro Misono 	btrfs_free_path(path);
254323d0b79dSTomohiro Misono 	return ret;
254423d0b79dSTomohiro Misono }
254523d0b79dSTomohiro Misono 
2546ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2547ac8e9819SChris Mason 					   void __user *argp)
2548ac8e9819SChris Mason {
2549ac8e9819SChris Mason 	struct btrfs_ioctl_ino_lookup_args *args;
2550ac8e9819SChris Mason 	struct inode *inode;
255101b810b8SDavid Sterba 	int ret = 0;
2552ac8e9819SChris Mason 
25532354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
25542354d08fSJulia Lawall 	if (IS_ERR(args))
25552354d08fSJulia Lawall 		return PTR_ERR(args);
2556c2b96929SDan Carpenter 
2557496ad9aaSAl Viro 	inode = file_inode(file);
2558ac8e9819SChris Mason 
255901b810b8SDavid Sterba 	/*
256001b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
256101b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
256201b810b8SDavid Sterba 	 */
25631b53ac4dSChris Mason 	if (args->treeid == 0)
25641b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
25651b53ac4dSChris Mason 
256601b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
256701b810b8SDavid Sterba 		args->name[0] = 0;
256801b810b8SDavid Sterba 		goto out;
256901b810b8SDavid Sterba 	}
257001b810b8SDavid Sterba 
257101b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
257201b810b8SDavid Sterba 		ret = -EPERM;
257301b810b8SDavid Sterba 		goto out;
257401b810b8SDavid Sterba 	}
257501b810b8SDavid Sterba 
2576ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2577ac8e9819SChris Mason 					args->treeid, args->objectid,
2578ac8e9819SChris Mason 					args->name);
2579ac8e9819SChris Mason 
258001b810b8SDavid Sterba out:
2581ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2582ac8e9819SChris Mason 		ret = -EFAULT;
2583ac8e9819SChris Mason 
2584ac8e9819SChris Mason 	kfree(args);
258598d377a0STARUISI Hiroaki 	return ret;
258698d377a0STARUISI Hiroaki }
258798d377a0STARUISI Hiroaki 
258823d0b79dSTomohiro Misono /*
258923d0b79dSTomohiro Misono  * Version of ino_lookup ioctl (unprivileged)
259023d0b79dSTomohiro Misono  *
259123d0b79dSTomohiro Misono  * The main differences from ino_lookup ioctl are:
259223d0b79dSTomohiro Misono  *
259323d0b79dSTomohiro Misono  *   1. Read + Exec permission will be checked using inode_permission() during
259423d0b79dSTomohiro Misono  *      path construction. -EACCES will be returned in case of failure.
259523d0b79dSTomohiro Misono  *   2. Path construction will be stopped at the inode number which corresponds
259623d0b79dSTomohiro Misono  *      to the fd with which this ioctl is called. If constructed path does not
259723d0b79dSTomohiro Misono  *      exist under fd's inode, -EACCES will be returned.
259823d0b79dSTomohiro Misono  *   3. The name of bottom subvolume is also searched and filled.
259923d0b79dSTomohiro Misono  */
260023d0b79dSTomohiro Misono static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
260123d0b79dSTomohiro Misono {
260223d0b79dSTomohiro Misono 	struct btrfs_ioctl_ino_lookup_user_args *args;
260323d0b79dSTomohiro Misono 	struct inode *inode;
260423d0b79dSTomohiro Misono 	int ret;
260523d0b79dSTomohiro Misono 
260623d0b79dSTomohiro Misono 	args = memdup_user(argp, sizeof(*args));
260723d0b79dSTomohiro Misono 	if (IS_ERR(args))
260823d0b79dSTomohiro Misono 		return PTR_ERR(args);
260923d0b79dSTomohiro Misono 
261023d0b79dSTomohiro Misono 	inode = file_inode(file);
261123d0b79dSTomohiro Misono 
261223d0b79dSTomohiro Misono 	if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
261323d0b79dSTomohiro Misono 	    BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
261423d0b79dSTomohiro Misono 		/*
261523d0b79dSTomohiro Misono 		 * The subvolume does not exist under fd with which this is
261623d0b79dSTomohiro Misono 		 * called
261723d0b79dSTomohiro Misono 		 */
261823d0b79dSTomohiro Misono 		kfree(args);
261923d0b79dSTomohiro Misono 		return -EACCES;
262023d0b79dSTomohiro Misono 	}
262123d0b79dSTomohiro Misono 
26226623d9a0SChristian Brauner 	ret = btrfs_search_path_in_tree_user(file_mnt_user_ns(file), inode, args);
262323d0b79dSTomohiro Misono 
262423d0b79dSTomohiro Misono 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
262523d0b79dSTomohiro Misono 		ret = -EFAULT;
262623d0b79dSTomohiro Misono 
262723d0b79dSTomohiro Misono 	kfree(args);
262823d0b79dSTomohiro Misono 	return ret;
262923d0b79dSTomohiro Misono }
263023d0b79dSTomohiro Misono 
2631b64ec075STomohiro Misono /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2632b64ec075STomohiro Misono static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2633b64ec075STomohiro Misono {
2634b64ec075STomohiro Misono 	struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2635b64ec075STomohiro Misono 	struct btrfs_fs_info *fs_info;
2636b64ec075STomohiro Misono 	struct btrfs_root *root;
2637b64ec075STomohiro Misono 	struct btrfs_path *path;
2638b64ec075STomohiro Misono 	struct btrfs_key key;
2639b64ec075STomohiro Misono 	struct btrfs_root_item *root_item;
2640b64ec075STomohiro Misono 	struct btrfs_root_ref *rref;
2641b64ec075STomohiro Misono 	struct extent_buffer *leaf;
2642b64ec075STomohiro Misono 	unsigned long item_off;
2643b64ec075STomohiro Misono 	unsigned long item_len;
2644b64ec075STomohiro Misono 	struct inode *inode;
2645b64ec075STomohiro Misono 	int slot;
2646b64ec075STomohiro Misono 	int ret = 0;
2647b64ec075STomohiro Misono 
2648b64ec075STomohiro Misono 	path = btrfs_alloc_path();
2649b64ec075STomohiro Misono 	if (!path)
2650b64ec075STomohiro Misono 		return -ENOMEM;
2651b64ec075STomohiro Misono 
2652b64ec075STomohiro Misono 	subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2653b64ec075STomohiro Misono 	if (!subvol_info) {
2654b64ec075STomohiro Misono 		btrfs_free_path(path);
2655b64ec075STomohiro Misono 		return -ENOMEM;
2656b64ec075STomohiro Misono 	}
2657b64ec075STomohiro Misono 
2658b64ec075STomohiro Misono 	inode = file_inode(file);
2659b64ec075STomohiro Misono 	fs_info = BTRFS_I(inode)->root->fs_info;
2660b64ec075STomohiro Misono 
2661b64ec075STomohiro Misono 	/* Get root_item of inode's subvolume */
2662b64ec075STomohiro Misono 	key.objectid = BTRFS_I(inode)->root->root_key.objectid;
266356e9357aSDavid Sterba 	root = btrfs_get_fs_root(fs_info, key.objectid, true);
2664b64ec075STomohiro Misono 	if (IS_ERR(root)) {
2665b64ec075STomohiro Misono 		ret = PTR_ERR(root);
266604734e84SJosef Bacik 		goto out_free;
266704734e84SJosef Bacik 	}
2668b64ec075STomohiro Misono 	root_item = &root->root_item;
2669b64ec075STomohiro Misono 
2670b64ec075STomohiro Misono 	subvol_info->treeid = key.objectid;
2671b64ec075STomohiro Misono 
2672b64ec075STomohiro Misono 	subvol_info->generation = btrfs_root_generation(root_item);
2673b64ec075STomohiro Misono 	subvol_info->flags = btrfs_root_flags(root_item);
2674b64ec075STomohiro Misono 
2675b64ec075STomohiro Misono 	memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2676b64ec075STomohiro Misono 	memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2677b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2678b64ec075STomohiro Misono 	memcpy(subvol_info->received_uuid, root_item->received_uuid,
2679b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2680b64ec075STomohiro Misono 
2681b64ec075STomohiro Misono 	subvol_info->ctransid = btrfs_root_ctransid(root_item);
2682b64ec075STomohiro Misono 	subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2683b64ec075STomohiro Misono 	subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2684b64ec075STomohiro Misono 
2685b64ec075STomohiro Misono 	subvol_info->otransid = btrfs_root_otransid(root_item);
2686b64ec075STomohiro Misono 	subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2687b64ec075STomohiro Misono 	subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2688b64ec075STomohiro Misono 
2689b64ec075STomohiro Misono 	subvol_info->stransid = btrfs_root_stransid(root_item);
2690b64ec075STomohiro Misono 	subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2691b64ec075STomohiro Misono 	subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2692b64ec075STomohiro Misono 
2693b64ec075STomohiro Misono 	subvol_info->rtransid = btrfs_root_rtransid(root_item);
2694b64ec075STomohiro Misono 	subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2695b64ec075STomohiro Misono 	subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2696b64ec075STomohiro Misono 
2697b64ec075STomohiro Misono 	if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2698b64ec075STomohiro Misono 		/* Search root tree for ROOT_BACKREF of this subvolume */
2699b64ec075STomohiro Misono 		key.type = BTRFS_ROOT_BACKREF_KEY;
2700b64ec075STomohiro Misono 		key.offset = 0;
270104734e84SJosef Bacik 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2702b64ec075STomohiro Misono 		if (ret < 0) {
2703b64ec075STomohiro Misono 			goto out;
2704b64ec075STomohiro Misono 		} else if (path->slots[0] >=
2705b64ec075STomohiro Misono 			   btrfs_header_nritems(path->nodes[0])) {
270604734e84SJosef Bacik 			ret = btrfs_next_leaf(fs_info->tree_root, path);
2707b64ec075STomohiro Misono 			if (ret < 0) {
2708b64ec075STomohiro Misono 				goto out;
2709b64ec075STomohiro Misono 			} else if (ret > 0) {
2710b64ec075STomohiro Misono 				ret = -EUCLEAN;
2711b64ec075STomohiro Misono 				goto out;
2712b64ec075STomohiro Misono 			}
2713b64ec075STomohiro Misono 		}
2714b64ec075STomohiro Misono 
2715b64ec075STomohiro Misono 		leaf = path->nodes[0];
2716b64ec075STomohiro Misono 		slot = path->slots[0];
2717b64ec075STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
2718b64ec075STomohiro Misono 		if (key.objectid == subvol_info->treeid &&
2719b64ec075STomohiro Misono 		    key.type == BTRFS_ROOT_BACKREF_KEY) {
2720b64ec075STomohiro Misono 			subvol_info->parent_id = key.offset;
2721b64ec075STomohiro Misono 
2722b64ec075STomohiro Misono 			rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2723b64ec075STomohiro Misono 			subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2724b64ec075STomohiro Misono 
2725b64ec075STomohiro Misono 			item_off = btrfs_item_ptr_offset(leaf, slot)
2726b64ec075STomohiro Misono 					+ sizeof(struct btrfs_root_ref);
2727b64ec075STomohiro Misono 			item_len = btrfs_item_size_nr(leaf, slot)
2728b64ec075STomohiro Misono 					- sizeof(struct btrfs_root_ref);
2729b64ec075STomohiro Misono 			read_extent_buffer(leaf, subvol_info->name,
2730b64ec075STomohiro Misono 					   item_off, item_len);
2731b64ec075STomohiro Misono 		} else {
2732b64ec075STomohiro Misono 			ret = -ENOENT;
2733b64ec075STomohiro Misono 			goto out;
2734b64ec075STomohiro Misono 		}
2735b64ec075STomohiro Misono 	}
2736b64ec075STomohiro Misono 
2737b64ec075STomohiro Misono 	if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2738b64ec075STomohiro Misono 		ret = -EFAULT;
2739b64ec075STomohiro Misono 
2740b64ec075STomohiro Misono out:
274100246528SJosef Bacik 	btrfs_put_root(root);
274204734e84SJosef Bacik out_free:
2743b64ec075STomohiro Misono 	btrfs_free_path(path);
2744b091f7feSWaiman Long 	kfree(subvol_info);
2745b64ec075STomohiro Misono 	return ret;
2746b64ec075STomohiro Misono }
2747b64ec075STomohiro Misono 
274842e4b520STomohiro Misono /*
274942e4b520STomohiro Misono  * Return ROOT_REF information of the subvolume containing this inode
275042e4b520STomohiro Misono  * except the subvolume name.
275142e4b520STomohiro Misono  */
275242e4b520STomohiro Misono static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
275342e4b520STomohiro Misono {
275442e4b520STomohiro Misono 	struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
275542e4b520STomohiro Misono 	struct btrfs_root_ref *rref;
275642e4b520STomohiro Misono 	struct btrfs_root *root;
275742e4b520STomohiro Misono 	struct btrfs_path *path;
275842e4b520STomohiro Misono 	struct btrfs_key key;
275942e4b520STomohiro Misono 	struct extent_buffer *leaf;
276042e4b520STomohiro Misono 	struct inode *inode;
276142e4b520STomohiro Misono 	u64 objectid;
276242e4b520STomohiro Misono 	int slot;
276342e4b520STomohiro Misono 	int ret;
276442e4b520STomohiro Misono 	u8 found;
276542e4b520STomohiro Misono 
276642e4b520STomohiro Misono 	path = btrfs_alloc_path();
276742e4b520STomohiro Misono 	if (!path)
276842e4b520STomohiro Misono 		return -ENOMEM;
276942e4b520STomohiro Misono 
277042e4b520STomohiro Misono 	rootrefs = memdup_user(argp, sizeof(*rootrefs));
277142e4b520STomohiro Misono 	if (IS_ERR(rootrefs)) {
277242e4b520STomohiro Misono 		btrfs_free_path(path);
277342e4b520STomohiro Misono 		return PTR_ERR(rootrefs);
277442e4b520STomohiro Misono 	}
277542e4b520STomohiro Misono 
277642e4b520STomohiro Misono 	inode = file_inode(file);
277742e4b520STomohiro Misono 	root = BTRFS_I(inode)->root->fs_info->tree_root;
277842e4b520STomohiro Misono 	objectid = BTRFS_I(inode)->root->root_key.objectid;
277942e4b520STomohiro Misono 
278042e4b520STomohiro Misono 	key.objectid = objectid;
278142e4b520STomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
278242e4b520STomohiro Misono 	key.offset = rootrefs->min_treeid;
278342e4b520STomohiro Misono 	found = 0;
278442e4b520STomohiro Misono 
278542e4b520STomohiro Misono 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
278642e4b520STomohiro Misono 	if (ret < 0) {
278742e4b520STomohiro Misono 		goto out;
278842e4b520STomohiro Misono 	} else if (path->slots[0] >=
278942e4b520STomohiro Misono 		   btrfs_header_nritems(path->nodes[0])) {
279042e4b520STomohiro Misono 		ret = btrfs_next_leaf(root, path);
279142e4b520STomohiro Misono 		if (ret < 0) {
279242e4b520STomohiro Misono 			goto out;
279342e4b520STomohiro Misono 		} else if (ret > 0) {
279442e4b520STomohiro Misono 			ret = -EUCLEAN;
279542e4b520STomohiro Misono 			goto out;
279642e4b520STomohiro Misono 		}
279742e4b520STomohiro Misono 	}
279842e4b520STomohiro Misono 	while (1) {
279942e4b520STomohiro Misono 		leaf = path->nodes[0];
280042e4b520STomohiro Misono 		slot = path->slots[0];
280142e4b520STomohiro Misono 
280242e4b520STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
280342e4b520STomohiro Misono 		if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
280442e4b520STomohiro Misono 			ret = 0;
280542e4b520STomohiro Misono 			goto out;
280642e4b520STomohiro Misono 		}
280742e4b520STomohiro Misono 
280842e4b520STomohiro Misono 		if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
280942e4b520STomohiro Misono 			ret = -EOVERFLOW;
281042e4b520STomohiro Misono 			goto out;
281142e4b520STomohiro Misono 		}
281242e4b520STomohiro Misono 
281342e4b520STomohiro Misono 		rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
281442e4b520STomohiro Misono 		rootrefs->rootref[found].treeid = key.offset;
281542e4b520STomohiro Misono 		rootrefs->rootref[found].dirid =
281642e4b520STomohiro Misono 				  btrfs_root_ref_dirid(leaf, rref);
281742e4b520STomohiro Misono 		found++;
281842e4b520STomohiro Misono 
281942e4b520STomohiro Misono 		ret = btrfs_next_item(root, path);
282042e4b520STomohiro Misono 		if (ret < 0) {
282142e4b520STomohiro Misono 			goto out;
282242e4b520STomohiro Misono 		} else if (ret > 0) {
282342e4b520STomohiro Misono 			ret = -EUCLEAN;
282442e4b520STomohiro Misono 			goto out;
282542e4b520STomohiro Misono 		}
282642e4b520STomohiro Misono 	}
282742e4b520STomohiro Misono 
282842e4b520STomohiro Misono out:
282942e4b520STomohiro Misono 	if (!ret || ret == -EOVERFLOW) {
283042e4b520STomohiro Misono 		rootrefs->num_items = found;
283142e4b520STomohiro Misono 		/* update min_treeid for next search */
283242e4b520STomohiro Misono 		if (found)
283342e4b520STomohiro Misono 			rootrefs->min_treeid =
283442e4b520STomohiro Misono 				rootrefs->rootref[found - 1].treeid + 1;
283542e4b520STomohiro Misono 		if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
283642e4b520STomohiro Misono 			ret = -EFAULT;
283742e4b520STomohiro Misono 	}
283842e4b520STomohiro Misono 
283942e4b520STomohiro Misono 	kfree(rootrefs);
284042e4b520STomohiro Misono 	btrfs_free_path(path);
284142e4b520STomohiro Misono 
284242e4b520STomohiro Misono 	return ret;
284342e4b520STomohiro Misono }
284442e4b520STomohiro Misono 
284576dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2846949964c9SMarcos Paulo de Souza 					     void __user *arg,
2847949964c9SMarcos Paulo de Souza 					     bool destroy_v2)
284876dda93cSYan, Zheng {
284954563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
28500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
285176dda93cSYan, Zheng 	struct dentry *dentry;
28522b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
285376dda93cSYan, Zheng 	struct inode *inode;
285476dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
285576dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
2856949964c9SMarcos Paulo de Souza 	struct btrfs_ioctl_vol_args *vol_args = NULL;
2857949964c9SMarcos Paulo de Souza 	struct btrfs_ioctl_vol_args_v2 *vol_args2 = NULL;
2858c4ed533bSChristian Brauner 	struct user_namespace *mnt_userns = file_mnt_user_ns(file);
2859949964c9SMarcos Paulo de Souza 	char *subvol_name, *subvol_name_ptr = NULL;
2860949964c9SMarcos Paulo de Souza 	int subvol_namelen;
286176dda93cSYan, Zheng 	int err = 0;
2862949964c9SMarcos Paulo de Souza 	bool destroy_parent = false;
286376dda93cSYan, Zheng 
2864949964c9SMarcos Paulo de Souza 	if (destroy_v2) {
2865949964c9SMarcos Paulo de Souza 		vol_args2 = memdup_user(arg, sizeof(*vol_args2));
2866949964c9SMarcos Paulo de Souza 		if (IS_ERR(vol_args2))
2867949964c9SMarcos Paulo de Souza 			return PTR_ERR(vol_args2);
2868325c50e3SJeff Mahoney 
2869949964c9SMarcos Paulo de Souza 		if (vol_args2->flags & ~BTRFS_SUBVOL_DELETE_ARGS_MASK) {
2870949964c9SMarcos Paulo de Souza 			err = -EOPNOTSUPP;
2871949964c9SMarcos Paulo de Souza 			goto out;
2872949964c9SMarcos Paulo de Souza 		}
287376dda93cSYan, Zheng 
2874949964c9SMarcos Paulo de Souza 		/*
2875949964c9SMarcos Paulo de Souza 		 * If SPEC_BY_ID is not set, we are looking for the subvolume by
2876949964c9SMarcos Paulo de Souza 		 * name, same as v1 currently does.
2877949964c9SMarcos Paulo de Souza 		 */
2878949964c9SMarcos Paulo de Souza 		if (!(vol_args2->flags & BTRFS_SUBVOL_SPEC_BY_ID)) {
2879949964c9SMarcos Paulo de Souza 			vol_args2->name[BTRFS_SUBVOL_NAME_MAX] = 0;
2880949964c9SMarcos Paulo de Souza 			subvol_name = vol_args2->name;
2881949964c9SMarcos Paulo de Souza 
2882949964c9SMarcos Paulo de Souza 			err = mnt_want_write_file(file);
2883949964c9SMarcos Paulo de Souza 			if (err)
2884949964c9SMarcos Paulo de Souza 				goto out;
2885949964c9SMarcos Paulo de Souza 		} else {
2886aabb34e7SChristian Brauner 			struct inode *old_dir;
2887c4ed533bSChristian Brauner 
2888949964c9SMarcos Paulo de Souza 			if (vol_args2->subvolid < BTRFS_FIRST_FREE_OBJECTID) {
288976dda93cSYan, Zheng 				err = -EINVAL;
289076dda93cSYan, Zheng 				goto out;
289176dda93cSYan, Zheng 			}
289276dda93cSYan, Zheng 
2893a561be71SAl Viro 			err = mnt_want_write_file(file);
289476dda93cSYan, Zheng 			if (err)
289576dda93cSYan, Zheng 				goto out;
289676dda93cSYan, Zheng 
2897949964c9SMarcos Paulo de Souza 			dentry = btrfs_get_dentry(fs_info->sb,
2898949964c9SMarcos Paulo de Souza 					BTRFS_FIRST_FREE_OBJECTID,
2899949964c9SMarcos Paulo de Souza 					vol_args2->subvolid, 0, 0);
2900949964c9SMarcos Paulo de Souza 			if (IS_ERR(dentry)) {
2901949964c9SMarcos Paulo de Souza 				err = PTR_ERR(dentry);
2902949964c9SMarcos Paulo de Souza 				goto out_drop_write;
2903949964c9SMarcos Paulo de Souza 			}
2904949964c9SMarcos Paulo de Souza 
2905949964c9SMarcos Paulo de Souza 			/*
2906949964c9SMarcos Paulo de Souza 			 * Change the default parent since the subvolume being
2907949964c9SMarcos Paulo de Souza 			 * deleted can be outside of the current mount point.
2908949964c9SMarcos Paulo de Souza 			 */
2909949964c9SMarcos Paulo de Souza 			parent = btrfs_get_parent(dentry);
2910949964c9SMarcos Paulo de Souza 
2911949964c9SMarcos Paulo de Souza 			/*
2912949964c9SMarcos Paulo de Souza 			 * At this point dentry->d_name can point to '/' if the
2913949964c9SMarcos Paulo de Souza 			 * subvolume we want to destroy is outsite of the
2914949964c9SMarcos Paulo de Souza 			 * current mount point, so we need to release the
2915949964c9SMarcos Paulo de Souza 			 * current dentry and execute the lookup to return a new
2916949964c9SMarcos Paulo de Souza 			 * one with ->d_name pointing to the
2917949964c9SMarcos Paulo de Souza 			 * <mount point>/subvol_name.
2918949964c9SMarcos Paulo de Souza 			 */
2919949964c9SMarcos Paulo de Souza 			dput(dentry);
2920949964c9SMarcos Paulo de Souza 			if (IS_ERR(parent)) {
2921949964c9SMarcos Paulo de Souza 				err = PTR_ERR(parent);
2922949964c9SMarcos Paulo de Souza 				goto out_drop_write;
2923949964c9SMarcos Paulo de Souza 			}
2924aabb34e7SChristian Brauner 			old_dir = dir;
2925949964c9SMarcos Paulo de Souza 			dir = d_inode(parent);
2926949964c9SMarcos Paulo de Souza 
2927949964c9SMarcos Paulo de Souza 			/*
2928949964c9SMarcos Paulo de Souza 			 * If v2 was used with SPEC_BY_ID, a new parent was
2929949964c9SMarcos Paulo de Souza 			 * allocated since the subvolume can be outside of the
2930949964c9SMarcos Paulo de Souza 			 * current mount point. Later on we need to release this
2931949964c9SMarcos Paulo de Souza 			 * new parent dentry.
2932949964c9SMarcos Paulo de Souza 			 */
2933949964c9SMarcos Paulo de Souza 			destroy_parent = true;
2934949964c9SMarcos Paulo de Souza 
2935aabb34e7SChristian Brauner 			/*
2936aabb34e7SChristian Brauner 			 * On idmapped mounts, deletion via subvolid is
2937aabb34e7SChristian Brauner 			 * restricted to subvolumes that are immediate
2938aabb34e7SChristian Brauner 			 * ancestors of the inode referenced by the file
2939aabb34e7SChristian Brauner 			 * descriptor in the ioctl. Otherwise the idmapping
2940aabb34e7SChristian Brauner 			 * could potentially be abused to delete subvolumes
2941aabb34e7SChristian Brauner 			 * anywhere in the filesystem the user wouldn't be able
2942aabb34e7SChristian Brauner 			 * to delete without an idmapped mount.
2943aabb34e7SChristian Brauner 			 */
2944aabb34e7SChristian Brauner 			if (old_dir != dir && mnt_userns != &init_user_ns) {
2945aabb34e7SChristian Brauner 				err = -EOPNOTSUPP;
2946aabb34e7SChristian Brauner 				goto free_parent;
2947aabb34e7SChristian Brauner 			}
2948aabb34e7SChristian Brauner 
2949949964c9SMarcos Paulo de Souza 			subvol_name_ptr = btrfs_get_subvol_name_from_objectid(
2950949964c9SMarcos Paulo de Souza 						fs_info, vol_args2->subvolid);
2951949964c9SMarcos Paulo de Souza 			if (IS_ERR(subvol_name_ptr)) {
2952949964c9SMarcos Paulo de Souza 				err = PTR_ERR(subvol_name_ptr);
2953949964c9SMarcos Paulo de Souza 				goto free_parent;
2954949964c9SMarcos Paulo de Souza 			}
29551a9fd417SDavid Sterba 			/* subvol_name_ptr is already nul terminated */
2956949964c9SMarcos Paulo de Souza 			subvol_name = (char *)kbasename(subvol_name_ptr);
2957949964c9SMarcos Paulo de Souza 		}
2958949964c9SMarcos Paulo de Souza 	} else {
2959949964c9SMarcos Paulo de Souza 		vol_args = memdup_user(arg, sizeof(*vol_args));
2960949964c9SMarcos Paulo de Souza 		if (IS_ERR(vol_args))
2961949964c9SMarcos Paulo de Souza 			return PTR_ERR(vol_args);
2962949964c9SMarcos Paulo de Souza 
2963949964c9SMarcos Paulo de Souza 		vol_args->name[BTRFS_PATH_NAME_MAX] = 0;
2964949964c9SMarcos Paulo de Souza 		subvol_name = vol_args->name;
2965949964c9SMarcos Paulo de Souza 
2966949964c9SMarcos Paulo de Souza 		err = mnt_want_write_file(file);
2967949964c9SMarcos Paulo de Souza 		if (err)
2968949964c9SMarcos Paulo de Souza 			goto out;
2969949964c9SMarcos Paulo de Souza 	}
2970949964c9SMarcos Paulo de Souza 
2971949964c9SMarcos Paulo de Souza 	subvol_namelen = strlen(subvol_name);
2972949964c9SMarcos Paulo de Souza 
2973949964c9SMarcos Paulo de Souza 	if (strchr(subvol_name, '/') ||
2974949964c9SMarcos Paulo de Souza 	    strncmp(subvol_name, "..", subvol_namelen) == 0) {
2975949964c9SMarcos Paulo de Souza 		err = -EINVAL;
2976949964c9SMarcos Paulo de Souza 		goto free_subvol_name;
2977949964c9SMarcos Paulo de Souza 	}
2978949964c9SMarcos Paulo de Souza 
2979949964c9SMarcos Paulo de Souza 	if (!S_ISDIR(dir->i_mode)) {
2980949964c9SMarcos Paulo de Souza 		err = -ENOTDIR;
2981949964c9SMarcos Paulo de Souza 		goto free_subvol_name;
2982949964c9SMarcos Paulo de Souza 	}
2983521e0546SDavid Sterba 
298400235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
298500235411SAl Viro 	if (err == -EINTR)
2986949964c9SMarcos Paulo de Souza 		goto free_subvol_name;
2987c4ed533bSChristian Brauner 	dentry = lookup_one(mnt_userns, subvol_name, parent, subvol_namelen);
298876dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
298976dda93cSYan, Zheng 		err = PTR_ERR(dentry);
299076dda93cSYan, Zheng 		goto out_unlock_dir;
299176dda93cSYan, Zheng 	}
299276dda93cSYan, Zheng 
29932b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
299476dda93cSYan, Zheng 		err = -ENOENT;
299576dda93cSYan, Zheng 		goto out_dput;
299676dda93cSYan, Zheng 	}
299776dda93cSYan, Zheng 
29982b0143b5SDavid Howells 	inode = d_inode(dentry);
29994260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
30004260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
30014260f7c7SSage Weil 		/*
30024260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
30034260f7c7SSage Weil 		 * option, when the user has write+exec access to the
30044260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
30054260f7c7SSage Weil 		 * allowed.
30064260f7c7SSage Weil 		 *
30074260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
30084260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
30094260f7c7SSage Weil 		 * otherwise be able to delete.
30104260f7c7SSage Weil 		 *
30114260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
30124260f7c7SSage Weil 		 * rmdir(2).
30134260f7c7SSage Weil 		 */
30144260f7c7SSage Weil 		err = -EPERM;
30150b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
30164260f7c7SSage Weil 			goto out_dput;
30174260f7c7SSage Weil 
30184260f7c7SSage Weil 		/*
30194260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
30204260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
30214260f7c7SSage Weil 		 * must be called on the dentry referencing the root
30224260f7c7SSage Weil 		 * of the subvol, not a random directory contained
30234260f7c7SSage Weil 		 * within it.
30244260f7c7SSage Weil 		 */
30254260f7c7SSage Weil 		err = -EINVAL;
30264260f7c7SSage Weil 		if (root == dest)
30274260f7c7SSage Weil 			goto out_dput;
30284260f7c7SSage Weil 
3029c4ed533bSChristian Brauner 		err = inode_permission(mnt_userns, inode, MAY_WRITE | MAY_EXEC);
30304260f7c7SSage Weil 		if (err)
30314260f7c7SSage Weil 			goto out_dput;
30325c39da5bSMiao Xie 	}
30334260f7c7SSage Weil 
30345c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
3035c4ed533bSChristian Brauner 	err = btrfs_may_delete(mnt_userns, dir, dentry, 1);
30364260f7c7SSage Weil 	if (err)
30374260f7c7SSage Weil 		goto out_dput;
30384260f7c7SSage Weil 
30394a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
304076dda93cSYan, Zheng 		err = -EINVAL;
304176dda93cSYan, Zheng 		goto out_dput;
304276dda93cSYan, Zheng 	}
304376dda93cSYan, Zheng 
304464708539SJosef Bacik 	btrfs_inode_lock(inode, 0);
3045f60a2364SMisono Tomohiro 	err = btrfs_delete_subvolume(dir, dentry);
304664708539SJosef Bacik 	btrfs_inode_unlock(inode, 0);
304746008d9dSAmir Goldstein 	if (!err) {
304846008d9dSAmir Goldstein 		fsnotify_rmdir(dir, dentry);
304976dda93cSYan, Zheng 		d_delete(dentry);
305046008d9dSAmir Goldstein 	}
3051fa6ac876SLiu Bo 
305276dda93cSYan, Zheng out_dput:
305376dda93cSYan, Zheng 	dput(dentry);
305476dda93cSYan, Zheng out_unlock_dir:
305564708539SJosef Bacik 	btrfs_inode_unlock(dir, 0);
3056949964c9SMarcos Paulo de Souza free_subvol_name:
3057949964c9SMarcos Paulo de Souza 	kfree(subvol_name_ptr);
3058949964c9SMarcos Paulo de Souza free_parent:
3059949964c9SMarcos Paulo de Souza 	if (destroy_parent)
3060949964c9SMarcos Paulo de Souza 		dput(parent);
306100235411SAl Viro out_drop_write:
30622a79f17eSAl Viro 	mnt_drop_write_file(file);
306376dda93cSYan, Zheng out:
3064949964c9SMarcos Paulo de Souza 	kfree(vol_args2);
306576dda93cSYan, Zheng 	kfree(vol_args);
306676dda93cSYan, Zheng 	return err;
306776dda93cSYan, Zheng }
306876dda93cSYan, Zheng 
30691e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
3070f46b5a66SChristoph Hellwig {
3071496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3072f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
3073c853a578SGoldwyn Rodrigues 	struct btrfs_ioctl_defrag_range_args range = {0};
3074c146afadSYan Zheng 	int ret;
3075c146afadSYan Zheng 
307625122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
307725122d15SIlya Dryomov 	if (ret)
307825122d15SIlya Dryomov 		return ret;
3079b83cc969SLi Zefan 
308025122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
308125122d15SIlya Dryomov 		ret = -EROFS;
308225122d15SIlya Dryomov 		goto out;
30835ac00addSStefan Behrens 	}
3084f46b5a66SChristoph Hellwig 
3085f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
3086f46b5a66SChristoph Hellwig 	case S_IFDIR:
3087e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
3088e441d54dSChris Mason 			ret = -EPERM;
3089e441d54dSChris Mason 			goto out;
3090e441d54dSChris Mason 		}
3091de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
3092f46b5a66SChristoph Hellwig 		break;
3093f46b5a66SChristoph Hellwig 	case S_IFREG:
3094616d374eSAdam Borowski 		/*
3095616d374eSAdam Borowski 		 * Note that this does not check the file descriptor for write
3096616d374eSAdam Borowski 		 * access. This prevents defragmenting executables that are
3097616d374eSAdam Borowski 		 * running and allows defrag on files open in read-only mode.
3098616d374eSAdam Borowski 		 */
3099616d374eSAdam Borowski 		if (!capable(CAP_SYS_ADMIN) &&
310047291baaSChristian Brauner 		    inode_permission(&init_user_ns, inode, MAY_WRITE)) {
3101616d374eSAdam Borowski 			ret = -EPERM;
3102e441d54dSChris Mason 			goto out;
3103e441d54dSChris Mason 		}
31041e701a32SChris Mason 
31051e701a32SChris Mason 		if (argp) {
3106c853a578SGoldwyn Rodrigues 			if (copy_from_user(&range, argp, sizeof(range))) {
31071e701a32SChris Mason 				ret = -EFAULT;
3108683be16eSDan Carpenter 				goto out;
31091e701a32SChris Mason 			}
31101e701a32SChris Mason 			/* compression requires us to start the IO */
3111c853a578SGoldwyn Rodrigues 			if ((range.flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3112c853a578SGoldwyn Rodrigues 				range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
3113c853a578SGoldwyn Rodrigues 				range.extent_thresh = (u32)-1;
31141e701a32SChris Mason 			}
31151e701a32SChris Mason 		} else {
31161e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
3117c853a578SGoldwyn Rodrigues 			range.len = (u64)-1;
31181e701a32SChris Mason 		}
31191ccc2e8aSQu Wenruo 		ret = btrfs_defrag_file(file_inode(file), &file->f_ra,
3120c853a578SGoldwyn Rodrigues 					&range, BTRFS_OLDEST_GENERATION, 0);
31214cb5300bSChris Mason 		if (ret > 0)
31224cb5300bSChris Mason 			ret = 0;
3123f46b5a66SChristoph Hellwig 		break;
31248929ecfaSYan, Zheng 	default:
31258929ecfaSYan, Zheng 		ret = -EINVAL;
3126f46b5a66SChristoph Hellwig 	}
3127e441d54dSChris Mason out:
312825122d15SIlya Dryomov 	mnt_drop_write_file(file);
3129e441d54dSChris Mason 	return ret;
3130f46b5a66SChristoph Hellwig }
3131f46b5a66SChristoph Hellwig 
31322ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3133f46b5a66SChristoph Hellwig {
3134f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
3135f46b5a66SChristoph Hellwig 	int ret;
3136f46b5a66SChristoph Hellwig 
3137e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
3138e441d54dSChris Mason 		return -EPERM;
3139e441d54dSChris Mason 
3140c3e1f96cSGoldwyn Rodrigues 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_ADD))
3141e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3142c9e9f97bSIlya Dryomov 
3143dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
3144c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
3145c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
3146c9e9f97bSIlya Dryomov 		goto out;
3147c9e9f97bSIlya Dryomov 	}
3148f46b5a66SChristoph Hellwig 
31495516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
31502ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
3151f46b5a66SChristoph Hellwig 
315243d20761SAnand Jain 	if (!ret)
31530b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
315443d20761SAnand Jain 
3155f46b5a66SChristoph Hellwig 	kfree(vol_args);
3156c9e9f97bSIlya Dryomov out:
3157c3e1f96cSGoldwyn Rodrigues 	btrfs_exclop_finish(fs_info);
3158f46b5a66SChristoph Hellwig 	return ret;
3159f46b5a66SChristoph Hellwig }
3160f46b5a66SChristoph Hellwig 
31616b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3162f46b5a66SChristoph Hellwig {
3163*1a15eb72SJosef Bacik 	BTRFS_DEV_LOOKUP_ARGS(args);
31640b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
31650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
31666b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
31673fa421deSJosef Bacik 	struct block_device *bdev = NULL;
31683fa421deSJosef Bacik 	fmode_t mode;
3169f46b5a66SChristoph Hellwig 	int ret;
317067ae34b6SDavid Sterba 	bool cancel = false;
3171f46b5a66SChristoph Hellwig 
3172e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
3173e441d54dSChris Mason 		return -EPERM;
3174e441d54dSChris Mason 
3175dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
3176c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
3177c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
3178*1a15eb72SJosef Bacik 		goto out;
3179c9e9f97bSIlya Dryomov 	}
3180f46b5a66SChristoph Hellwig 
3181748449cdSDavid Sterba 	if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
3182fd4e994bSOmar Sandoval 		ret = -EOPNOTSUPP;
3183fd4e994bSOmar Sandoval 		goto out;
3184fd4e994bSOmar Sandoval 	}
3185*1a15eb72SJosef Bacik 
31866b526ed7SAnand Jain 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3187*1a15eb72SJosef Bacik 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3188*1a15eb72SJosef Bacik 		args.devid = vol_args->devid;
3189*1a15eb72SJosef Bacik 	} else if (!strcmp("cancel", vol_args->name)) {
319067ae34b6SDavid Sterba 		cancel = true;
3191*1a15eb72SJosef Bacik 	} else {
3192*1a15eb72SJosef Bacik 		ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3193*1a15eb72SJosef Bacik 		if (ret)
3194*1a15eb72SJosef Bacik 			goto out;
3195*1a15eb72SJosef Bacik 	}
3196*1a15eb72SJosef Bacik 
3197*1a15eb72SJosef Bacik 	ret = mnt_want_write_file(file);
3198*1a15eb72SJosef Bacik 	if (ret)
3199*1a15eb72SJosef Bacik 		goto out;
320067ae34b6SDavid Sterba 
320167ae34b6SDavid Sterba 	ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
320267ae34b6SDavid Sterba 					   cancel);
320367ae34b6SDavid Sterba 	if (ret)
3204*1a15eb72SJosef Bacik 		goto err_drop;
320567ae34b6SDavid Sterba 
3206*1a15eb72SJosef Bacik 	/* Exclusive operation is now claimed */
3207*1a15eb72SJosef Bacik 	ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
320867ae34b6SDavid Sterba 
3209c3e1f96cSGoldwyn Rodrigues 	btrfs_exclop_finish(fs_info);
3210183860f6SAnand Jain 
32116b526ed7SAnand Jain 	if (!ret) {
3212735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
32130b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
32146b526ed7SAnand Jain 					vol_args->devid);
32156b526ed7SAnand Jain 		else
32160b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
32176b526ed7SAnand Jain 					vol_args->name);
32186b526ed7SAnand Jain 	}
3219c47ca32dSDan Carpenter err_drop:
32204ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
32213fa421deSJosef Bacik 	if (bdev)
32223fa421deSJosef Bacik 		blkdev_put(bdev, mode);
3223*1a15eb72SJosef Bacik out:
3224*1a15eb72SJosef Bacik 	btrfs_put_dev_args_from_path(&args);
3225*1a15eb72SJosef Bacik 	kfree(vol_args);
3226f46b5a66SChristoph Hellwig 	return ret;
3227f46b5a66SChristoph Hellwig }
3228f46b5a66SChristoph Hellwig 
3229f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3230f46b5a66SChristoph Hellwig {
3231*1a15eb72SJosef Bacik 	BTRFS_DEV_LOOKUP_ARGS(args);
32320b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
32330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3234f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
32353fa421deSJosef Bacik 	struct block_device *bdev = NULL;
32363fa421deSJosef Bacik 	fmode_t mode;
3237f46b5a66SChristoph Hellwig 	int ret;
323867ae34b6SDavid Sterba 	bool cancel;
3239f46b5a66SChristoph Hellwig 
3240f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
3241f46b5a66SChristoph Hellwig 		return -EPERM;
3242f46b5a66SChristoph Hellwig 
3243*1a15eb72SJosef Bacik 	vol_args = memdup_user(arg, sizeof(*vol_args));
3244*1a15eb72SJosef Bacik 	if (IS_ERR(vol_args))
3245*1a15eb72SJosef Bacik 		return PTR_ERR(vol_args);
3246*1a15eb72SJosef Bacik 
3247*1a15eb72SJosef Bacik 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3248*1a15eb72SJosef Bacik 	if (!strcmp("cancel", vol_args->name)) {
3249*1a15eb72SJosef Bacik 		cancel = true;
3250*1a15eb72SJosef Bacik 	} else {
3251*1a15eb72SJosef Bacik 		ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3252*1a15eb72SJosef Bacik 		if (ret)
3253*1a15eb72SJosef Bacik 			goto out;
3254*1a15eb72SJosef Bacik 	}
3255*1a15eb72SJosef Bacik 
3256f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
3257f46b5a66SChristoph Hellwig 	if (ret)
3258*1a15eb72SJosef Bacik 		goto out;
3259f46b5a66SChristoph Hellwig 
326067ae34b6SDavid Sterba 	ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
326167ae34b6SDavid Sterba 					   cancel);
326267ae34b6SDavid Sterba 	if (ret == 0) {
3263*1a15eb72SJosef Bacik 		ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3264f46b5a66SChristoph Hellwig 		if (!ret)
32650b246afaSJeff Mahoney 			btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3266c3e1f96cSGoldwyn Rodrigues 		btrfs_exclop_finish(fs_info);
326767ae34b6SDavid Sterba 	}
326867ae34b6SDavid Sterba 
3269f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
32703fa421deSJosef Bacik 	if (bdev)
32713fa421deSJosef Bacik 		blkdev_put(bdev, mode);
3272*1a15eb72SJosef Bacik out:
3273*1a15eb72SJosef Bacik 	btrfs_put_dev_args_from_path(&args);
3274*1a15eb72SJosef Bacik 	kfree(vol_args);
3275f46b5a66SChristoph Hellwig 	return ret;
3276f46b5a66SChristoph Hellwig }
3277f46b5a66SChristoph Hellwig 
32782ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
32792ff7e61eSJeff Mahoney 				void __user *arg)
3280475f6387SJan Schmidt {
3281027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
3282475f6387SJan Schmidt 	struct btrfs_device *device;
32830b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3284137c5418SJohannes Thumshirn 	u64 flags_in;
3285027ed2f0SLi Zefan 	int ret = 0;
3286475f6387SJan Schmidt 
3287137c5418SJohannes Thumshirn 	fi_args = memdup_user(arg, sizeof(*fi_args));
3288137c5418SJohannes Thumshirn 	if (IS_ERR(fi_args))
3289137c5418SJohannes Thumshirn 		return PTR_ERR(fi_args);
3290137c5418SJohannes Thumshirn 
3291137c5418SJohannes Thumshirn 	flags_in = fi_args->flags;
3292137c5418SJohannes Thumshirn 	memset(fi_args, 0, sizeof(*fi_args));
3293027ed2f0SLi Zefan 
3294d03262c7SDavid Sterba 	rcu_read_lock();
3295027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
3296475f6387SJan Schmidt 
3297d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3298027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
3299027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
3300475f6387SJan Schmidt 	}
3301d03262c7SDavid Sterba 	rcu_read_unlock();
3302475f6387SJan Schmidt 
3303de37aa51SNikolay Borisov 	memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3304bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
3305bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
3306bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
330780a773fbSDavid Sterba 
3308137c5418SJohannes Thumshirn 	if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3309137c5418SJohannes Thumshirn 		fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3310137c5418SJohannes Thumshirn 		fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3311137c5418SJohannes Thumshirn 		fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3312137c5418SJohannes Thumshirn 	}
3313137c5418SJohannes Thumshirn 
33140fb408a5SJohannes Thumshirn 	if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
33150fb408a5SJohannes Thumshirn 		fi_args->generation = fs_info->generation;
33160fb408a5SJohannes Thumshirn 		fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
33170fb408a5SJohannes Thumshirn 	}
33180fb408a5SJohannes Thumshirn 
331949bac897SJohannes Thumshirn 	if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
332049bac897SJohannes Thumshirn 		memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
332149bac897SJohannes Thumshirn 		       sizeof(fi_args->metadata_uuid));
332249bac897SJohannes Thumshirn 		fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
332349bac897SJohannes Thumshirn 	}
332449bac897SJohannes Thumshirn 
3325027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3326027ed2f0SLi Zefan 		ret = -EFAULT;
3327475f6387SJan Schmidt 
3328027ed2f0SLi Zefan 	kfree(fi_args);
3329027ed2f0SLi Zefan 	return ret;
3330475f6387SJan Schmidt }
3331475f6387SJan Schmidt 
33322ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
33332ff7e61eSJeff Mahoney 				 void __user *arg)
3334475f6387SJan Schmidt {
3335562d7b15SJosef Bacik 	BTRFS_DEV_LOOKUP_ARGS(args);
3336475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
3337475f6387SJan Schmidt 	struct btrfs_device *dev;
3338475f6387SJan Schmidt 	int ret = 0;
3339475f6387SJan Schmidt 
3340475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
3341475f6387SJan Schmidt 	if (IS_ERR(di_args))
3342475f6387SJan Schmidt 		return PTR_ERR(di_args);
3343475f6387SJan Schmidt 
3344562d7b15SJosef Bacik 	args.devid = di_args->devid;
3345dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
3346562d7b15SJosef Bacik 		args.uuid = di_args->uuid;
3347475f6387SJan Schmidt 
3348c5593ca3SDavid Sterba 	rcu_read_lock();
3349562d7b15SJosef Bacik 	dev = btrfs_find_device(fs_info->fs_devices, &args);
3350475f6387SJan Schmidt 	if (!dev) {
3351475f6387SJan Schmidt 		ret = -ENODEV;
3352475f6387SJan Schmidt 		goto out;
3353475f6387SJan Schmidt 	}
3354475f6387SJan Schmidt 
3355475f6387SJan Schmidt 	di_args->devid = dev->devid;
33567cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
33577cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3358475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3359a27202fbSJim Meyering 	if (dev->name) {
3360672d5990SMisono Tomohiro 		strncpy(di_args->path, rcu_str_deref(dev->name),
3361672d5990SMisono Tomohiro 				sizeof(di_args->path) - 1);
3362a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
3363a27202fbSJim Meyering 	} else {
336499ba55adSStefan Behrens 		di_args->path[0] = '\0';
3365a27202fbSJim Meyering 	}
3366475f6387SJan Schmidt 
3367475f6387SJan Schmidt out:
3368c5593ca3SDavid Sterba 	rcu_read_unlock();
3369475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3370475f6387SJan Schmidt 		ret = -EFAULT;
3371475f6387SJan Schmidt 
3372475f6387SJan Schmidt 	kfree(di_args);
3373475f6387SJan Schmidt 	return ret;
3374475f6387SJan Schmidt }
3375475f6387SJan Schmidt 
33766ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
33776ef5ed0dSJosef Bacik {
3378496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
33790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
33806ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
33816ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
33826ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
33836ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
33842a2b5d62SJosef Bacik 	struct btrfs_path *path = NULL;
33856ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
33866ef5ed0dSJosef Bacik 	u64 objectid = 0;
33876ef5ed0dSJosef Bacik 	u64 dir_id;
33883c04ce01SMiao Xie 	int ret;
33896ef5ed0dSJosef Bacik 
33906ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
33916ef5ed0dSJosef Bacik 		return -EPERM;
33926ef5ed0dSJosef Bacik 
33933c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
33943c04ce01SMiao Xie 	if (ret)
33953c04ce01SMiao Xie 		return ret;
33963c04ce01SMiao Xie 
33973c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
33983c04ce01SMiao Xie 		ret = -EFAULT;
33993c04ce01SMiao Xie 		goto out;
34003c04ce01SMiao Xie 	}
34016ef5ed0dSJosef Bacik 
34026ef5ed0dSJosef Bacik 	if (!objectid)
34031cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
34046ef5ed0dSJosef Bacik 
340556e9357aSDavid Sterba 	new_root = btrfs_get_fs_root(fs_info, objectid, true);
34063c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
34073c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
34083c04ce01SMiao Xie 		goto out;
34093c04ce01SMiao Xie 	}
34102a2b5d62SJosef Bacik 	if (!is_fstree(new_root->root_key.objectid)) {
34112a2b5d62SJosef Bacik 		ret = -ENOENT;
34122a2b5d62SJosef Bacik 		goto out_free;
34132a2b5d62SJosef Bacik 	}
34146ef5ed0dSJosef Bacik 
34156ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
34163c04ce01SMiao Xie 	if (!path) {
34173c04ce01SMiao Xie 		ret = -ENOMEM;
34182a2b5d62SJosef Bacik 		goto out_free;
34193c04ce01SMiao Xie 	}
34206ef5ed0dSJosef Bacik 
34216ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
342298d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
34233c04ce01SMiao Xie 		ret = PTR_ERR(trans);
34242a2b5d62SJosef Bacik 		goto out_free;
34256ef5ed0dSJosef Bacik 	}
34266ef5ed0dSJosef Bacik 
34270b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
34280b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
34296ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
3430cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
34312a2b5d62SJosef Bacik 		btrfs_release_path(path);
34323a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
34330b246afaSJeff Mahoney 		btrfs_err(fs_info,
34345d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
34353c04ce01SMiao Xie 		ret = -ENOENT;
34362a2b5d62SJosef Bacik 		goto out_free;
34376ef5ed0dSJosef Bacik 	}
34386ef5ed0dSJosef Bacik 
34396ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
34406ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
34416ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
34422a2b5d62SJosef Bacik 	btrfs_release_path(path);
34436ef5ed0dSJosef Bacik 
34440b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
34453a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
34462a2b5d62SJosef Bacik out_free:
344700246528SJosef Bacik 	btrfs_put_root(new_root);
34482a2b5d62SJosef Bacik 	btrfs_free_path(path);
34493c04ce01SMiao Xie out:
34503c04ce01SMiao Xie 	mnt_drop_write_file(file);
34513c04ce01SMiao Xie 	return ret;
34526ef5ed0dSJosef Bacik }
34536ef5ed0dSJosef Bacik 
3454c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
3455bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
3456bf5fc093SJosef Bacik {
345732da5386SDavid Sterba 	struct btrfs_block_group *block_group;
3458bf5fc093SJosef Bacik 
3459bf5fc093SJosef Bacik 	space->total_bytes = 0;
3460bf5fc093SJosef Bacik 	space->used_bytes = 0;
3461bf5fc093SJosef Bacik 	space->flags = 0;
3462bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
3463bf5fc093SJosef Bacik 		space->flags = block_group->flags;
3464b3470b5dSDavid Sterba 		space->total_bytes += block_group->length;
3465bf38be65SDavid Sterba 		space->used_bytes += block_group->used;
3466bf5fc093SJosef Bacik 	}
3467bf5fc093SJosef Bacik }
3468bf5fc093SJosef Bacik 
34692ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
34702ff7e61eSJeff Mahoney 				   void __user *arg)
34711406e432SJosef Bacik {
34721406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
34731406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
34741406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
34757fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
347613f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
34771406e432SJosef Bacik 	struct btrfs_space_info *info;
3478315d8e98SColin Ian King 	static const u64 types[] = {
3479315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
3480bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
3481bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
3482315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3483315d8e98SColin Ian King 	};
3484bf5fc093SJosef Bacik 	int num_types = 4;
34857fde62bfSChris Mason 	int alloc_size;
34861406e432SJosef Bacik 	int ret = 0;
348751788b1bSDan Rosenberg 	u64 slot_count = 0;
3488bf5fc093SJosef Bacik 	int i, c;
34891406e432SJosef Bacik 
34901406e432SJosef Bacik 	if (copy_from_user(&space_args,
34911406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
34921406e432SJosef Bacik 			   sizeof(space_args)))
34931406e432SJosef Bacik 		return -EFAULT;
34941406e432SJosef Bacik 
3495bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
3496bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
3497bf5fc093SJosef Bacik 
3498bf5fc093SJosef Bacik 		info = NULL;
349972804905SJosef Bacik 		list_for_each_entry(tmp, &fs_info->space_info, list) {
3500bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
3501bf5fc093SJosef Bacik 				info = tmp;
3502bf5fc093SJosef Bacik 				break;
3503bf5fc093SJosef Bacik 			}
3504bf5fc093SJosef Bacik 		}
35051406e432SJosef Bacik 
3506bf5fc093SJosef Bacik 		if (!info)
3507bf5fc093SJosef Bacik 			continue;
3508bf5fc093SJosef Bacik 
3509bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
3510bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3511bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
3512bf5fc093SJosef Bacik 				slot_count++;
3513bf5fc093SJosef Bacik 		}
3514bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
3515bf5fc093SJosef Bacik 	}
3516bf5fc093SJosef Bacik 
351736523e95SDavid Sterba 	/*
351836523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
351936523e95SDavid Sterba 	 */
352036523e95SDavid Sterba 	slot_count++;
352136523e95SDavid Sterba 
35227fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
35237fde62bfSChris Mason 	if (space_args.space_slots == 0) {
35247fde62bfSChris Mason 		space_args.total_spaces = slot_count;
35257fde62bfSChris Mason 		goto out;
35267fde62bfSChris Mason 	}
3527bf5fc093SJosef Bacik 
352851788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
3529bf5fc093SJosef Bacik 
35307fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
3531bf5fc093SJosef Bacik 
35327fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
35337fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
35347fde62bfSChris Mason 	 */
353509cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
35367fde62bfSChris Mason 		return -ENOMEM;
35377fde62bfSChris Mason 
35387fde62bfSChris Mason 	space_args.total_spaces = 0;
35398d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
35407fde62bfSChris Mason 	if (!dest)
35417fde62bfSChris Mason 		return -ENOMEM;
35427fde62bfSChris Mason 	dest_orig = dest;
35437fde62bfSChris Mason 
35447fde62bfSChris Mason 	/* now we have a buffer to copy into */
3545bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
3546bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
3547bf5fc093SJosef Bacik 
354851788b1bSDan Rosenberg 		if (!slot_count)
354951788b1bSDan Rosenberg 			break;
355051788b1bSDan Rosenberg 
3551bf5fc093SJosef Bacik 		info = NULL;
355272804905SJosef Bacik 		list_for_each_entry(tmp, &fs_info->space_info, list) {
3553bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
3554bf5fc093SJosef Bacik 				info = tmp;
35557fde62bfSChris Mason 				break;
3556bf5fc093SJosef Bacik 			}
3557bf5fc093SJosef Bacik 		}
35587fde62bfSChris Mason 
3559bf5fc093SJosef Bacik 		if (!info)
3560bf5fc093SJosef Bacik 			continue;
3561bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
3562bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3563bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
3564c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
3565c065f5b1SSu Yue 						     &space);
35667fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
35671406e432SJosef Bacik 				dest++;
35681406e432SJosef Bacik 				space_args.total_spaces++;
356951788b1bSDan Rosenberg 				slot_count--;
35701406e432SJosef Bacik 			}
357151788b1bSDan Rosenberg 			if (!slot_count)
357251788b1bSDan Rosenberg 				break;
3573bf5fc093SJosef Bacik 		}
3574bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
3575bf5fc093SJosef Bacik 	}
35761406e432SJosef Bacik 
357736523e95SDavid Sterba 	/*
357836523e95SDavid Sterba 	 * Add global block reserve
357936523e95SDavid Sterba 	 */
358036523e95SDavid Sterba 	if (slot_count) {
35810b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
358236523e95SDavid Sterba 
358336523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
358436523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
358536523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
358636523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
358736523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
358836523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
358936523e95SDavid Sterba 		space_args.total_spaces++;
359036523e95SDavid Sterba 	}
359136523e95SDavid Sterba 
35922eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
35937fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
35947fde62bfSChris Mason 
35957fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
35967fde62bfSChris Mason 		ret = -EFAULT;
35977fde62bfSChris Mason 
35987fde62bfSChris Mason 	kfree(dest_orig);
35997fde62bfSChris Mason out:
36007fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
36011406e432SJosef Bacik 		ret = -EFAULT;
36021406e432SJosef Bacik 
36031406e432SJosef Bacik 	return ret;
36041406e432SJosef Bacik }
36051406e432SJosef Bacik 
36069a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
36079a8c28beSMiao Xie 					    void __user *argp)
360846204592SSage Weil {
360946204592SSage Weil 	struct btrfs_trans_handle *trans;
361046204592SSage Weil 	u64 transid;
3611db5b493aSTsutomu Itoh 	int ret;
361246204592SSage Weil 
3613d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
3614ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
3615ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
361698d5dc13STsutomu Itoh 			return PTR_ERR(trans);
3617ff7c1d33SMiao Xie 
3618ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
3619ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
3620ff7c1d33SMiao Xie 		goto out;
3621ff7c1d33SMiao Xie 	}
362246204592SSage Weil 	transid = trans->transid;
362332cc4f87SDavid Sterba 	ret = btrfs_commit_transaction_async(trans);
36248b2b2d3cSTsutomu Itoh 	if (ret) {
36253a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3626db5b493aSTsutomu Itoh 		return ret;
36278b2b2d3cSTsutomu Itoh 	}
3628ff7c1d33SMiao Xie out:
362946204592SSage Weil 	if (argp)
363046204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
363146204592SSage Weil 			return -EFAULT;
363246204592SSage Weil 	return 0;
363346204592SSage Weil }
363446204592SSage Weil 
36352ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
36369a8c28beSMiao Xie 					   void __user *argp)
363746204592SSage Weil {
363846204592SSage Weil 	u64 transid;
363946204592SSage Weil 
364046204592SSage Weil 	if (argp) {
364146204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
364246204592SSage Weil 			return -EFAULT;
364346204592SSage Weil 	} else {
364446204592SSage Weil 		transid = 0;  /* current trans */
364546204592SSage Weil 	}
36462ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
364746204592SSage Weil }
364846204592SSage Weil 
3649b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3650475f6387SJan Schmidt {
36510b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
3652475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
3653b8e95489SMiao Xie 	int ret;
3654475f6387SJan Schmidt 
3655475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
3656475f6387SJan Schmidt 		return -EPERM;
3657475f6387SJan Schmidt 
3658475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
3659475f6387SJan Schmidt 	if (IS_ERR(sa))
3660475f6387SJan Schmidt 		return PTR_ERR(sa);
3661475f6387SJan Schmidt 
3662b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3663b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
3664b8e95489SMiao Xie 		if (ret)
3665b8e95489SMiao Xie 			goto out;
3666b8e95489SMiao Xie 	}
3667b8e95489SMiao Xie 
36680b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
366963a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
367063a212abSStefan Behrens 			      0);
3671475f6387SJan Schmidt 
36725afe6ce7SFilipe Manana 	/*
36735afe6ce7SFilipe Manana 	 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
36745afe6ce7SFilipe Manana 	 * error. This is important as it allows user space to know how much
36755afe6ce7SFilipe Manana 	 * progress scrub has done. For example, if scrub is canceled we get
36765afe6ce7SFilipe Manana 	 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
36775afe6ce7SFilipe Manana 	 * space. Later user space can inspect the progress from the structure
36785afe6ce7SFilipe Manana 	 * btrfs_ioctl_scrub_args and resume scrub from where it left off
36795afe6ce7SFilipe Manana 	 * previously (btrfs-progs does this).
36805afe6ce7SFilipe Manana 	 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
36815afe6ce7SFilipe Manana 	 * then return -EFAULT to signal the structure was not copied or it may
36825afe6ce7SFilipe Manana 	 * be corrupt and unreliable due to a partial copy.
36835afe6ce7SFilipe Manana 	 */
36845afe6ce7SFilipe Manana 	if (copy_to_user(arg, sa, sizeof(*sa)))
3685475f6387SJan Schmidt 		ret = -EFAULT;
3686475f6387SJan Schmidt 
3687b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
3688b8e95489SMiao Xie 		mnt_drop_write_file(file);
3689b8e95489SMiao Xie out:
3690475f6387SJan Schmidt 	kfree(sa);
3691475f6387SJan Schmidt 	return ret;
3692475f6387SJan Schmidt }
3693475f6387SJan Schmidt 
36942ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
3695475f6387SJan Schmidt {
3696475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
3697475f6387SJan Schmidt 		return -EPERM;
3698475f6387SJan Schmidt 
36992ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
3700475f6387SJan Schmidt }
3701475f6387SJan Schmidt 
37022ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
3703475f6387SJan Schmidt 				       void __user *arg)
3704475f6387SJan Schmidt {
3705475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
3706475f6387SJan Schmidt 	int ret;
3707475f6387SJan Schmidt 
3708475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
3709475f6387SJan Schmidt 		return -EPERM;
3710475f6387SJan Schmidt 
3711475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
3712475f6387SJan Schmidt 	if (IS_ERR(sa))
3713475f6387SJan Schmidt 		return PTR_ERR(sa);
3714475f6387SJan Schmidt 
37152ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
3716475f6387SJan Schmidt 
37174fa99b00SFilipe Manana 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3718475f6387SJan Schmidt 		ret = -EFAULT;
3719475f6387SJan Schmidt 
3720475f6387SJan Schmidt 	kfree(sa);
3721475f6387SJan Schmidt 	return ret;
3722475f6387SJan Schmidt }
3723475f6387SJan Schmidt 
37242ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
3725b27f7c0cSDavid Sterba 				      void __user *arg)
3726c11d2c23SStefan Behrens {
3727c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
3728c11d2c23SStefan Behrens 	int ret;
3729c11d2c23SStefan Behrens 
3730c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
3731c11d2c23SStefan Behrens 	if (IS_ERR(sa))
3732c11d2c23SStefan Behrens 		return PTR_ERR(sa);
3733c11d2c23SStefan Behrens 
3734b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3735b27f7c0cSDavid Sterba 		kfree(sa);
3736b27f7c0cSDavid Sterba 		return -EPERM;
3737b27f7c0cSDavid Sterba 	}
3738b27f7c0cSDavid Sterba 
37392ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
3740c11d2c23SStefan Behrens 
3741eee99577SFilipe Manana 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3742c11d2c23SStefan Behrens 		ret = -EFAULT;
3743c11d2c23SStefan Behrens 
3744c11d2c23SStefan Behrens 	kfree(sa);
3745c11d2c23SStefan Behrens 	return ret;
3746c11d2c23SStefan Behrens }
3747c11d2c23SStefan Behrens 
37482ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
37492ff7e61eSJeff Mahoney 				    void __user *arg)
37503f6bcfbdSStefan Behrens {
37513f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
37523f6bcfbdSStefan Behrens 	int ret;
37533f6bcfbdSStefan Behrens 
37543f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
37553f6bcfbdSStefan Behrens 		return -EPERM;
37563f6bcfbdSStefan Behrens 
37573f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
37583f6bcfbdSStefan Behrens 	if (IS_ERR(p))
37593f6bcfbdSStefan Behrens 		return PTR_ERR(p);
37603f6bcfbdSStefan Behrens 
37613f6bcfbdSStefan Behrens 	switch (p->cmd) {
37623f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3763bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
3764adfa97cbSIlya Dryomov 			ret = -EROFS;
3765adfa97cbSIlya Dryomov 			goto out;
3766adfa97cbSIlya Dryomov 		}
3767c3e1f96cSGoldwyn Rodrigues 		if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
3768e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
37693f6bcfbdSStefan Behrens 		} else {
37702ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
3771c3e1f96cSGoldwyn Rodrigues 			btrfs_exclop_finish(fs_info);
37723f6bcfbdSStefan Behrens 		}
37733f6bcfbdSStefan Behrens 		break;
37743f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
37750b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
37763f6bcfbdSStefan Behrens 		ret = 0;
37773f6bcfbdSStefan Behrens 		break;
37783f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
377917d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
378097282031SAnand Jain 		ret = 0;
37813f6bcfbdSStefan Behrens 		break;
37823f6bcfbdSStefan Behrens 	default:
37833f6bcfbdSStefan Behrens 		ret = -EINVAL;
37843f6bcfbdSStefan Behrens 		break;
37853f6bcfbdSStefan Behrens 	}
37863f6bcfbdSStefan Behrens 
3787d3a53286SFilipe Manana 	if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
37883f6bcfbdSStefan Behrens 		ret = -EFAULT;
3789adfa97cbSIlya Dryomov out:
37903f6bcfbdSStefan Behrens 	kfree(p);
37913f6bcfbdSStefan Behrens 	return ret;
37923f6bcfbdSStefan Behrens }
37933f6bcfbdSStefan Behrens 
3794d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3795d7728c96SJan Schmidt {
3796d7728c96SJan Schmidt 	int ret = 0;
3797d7728c96SJan Schmidt 	int i;
3798740c3d22SChris Mason 	u64 rel_ptr;
3799d7728c96SJan Schmidt 	int size;
3800806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
3801d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
3802d7728c96SJan Schmidt 	struct btrfs_path *path;
3803d7728c96SJan Schmidt 
380482b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
3805d7728c96SJan Schmidt 		return -EPERM;
3806d7728c96SJan Schmidt 
3807d7728c96SJan Schmidt 	path = btrfs_alloc_path();
3808d7728c96SJan Schmidt 	if (!path) {
3809d7728c96SJan Schmidt 		ret = -ENOMEM;
3810d7728c96SJan Schmidt 		goto out;
3811d7728c96SJan Schmidt 	}
3812d7728c96SJan Schmidt 
3813d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
3814d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
3815d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
3816d7728c96SJan Schmidt 		ipa = NULL;
3817d7728c96SJan Schmidt 		goto out;
3818d7728c96SJan Schmidt 	}
3819d7728c96SJan Schmidt 
3820d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
3821d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
3822d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
3823d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
3824d7728c96SJan Schmidt 		ipath = NULL;
3825d7728c96SJan Schmidt 		goto out;
3826d7728c96SJan Schmidt 	}
3827d7728c96SJan Schmidt 
3828d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
3829d7728c96SJan Schmidt 	if (ret < 0)
3830d7728c96SJan Schmidt 		goto out;
3831d7728c96SJan Schmidt 
3832d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3833745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
3834745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
3835740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
3836d7728c96SJan Schmidt 	}
3837d7728c96SJan Schmidt 
3838718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
3839718dc5faSOmar Sandoval 			   ipath->fspath, size);
3840d7728c96SJan Schmidt 	if (ret) {
3841d7728c96SJan Schmidt 		ret = -EFAULT;
3842d7728c96SJan Schmidt 		goto out;
3843d7728c96SJan Schmidt 	}
3844d7728c96SJan Schmidt 
3845d7728c96SJan Schmidt out:
3846d7728c96SJan Schmidt 	btrfs_free_path(path);
3847d7728c96SJan Schmidt 	free_ipath(ipath);
3848d7728c96SJan Schmidt 	kfree(ipa);
3849d7728c96SJan Schmidt 
3850d7728c96SJan Schmidt 	return ret;
3851d7728c96SJan Schmidt }
3852d7728c96SJan Schmidt 
3853d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3854d7728c96SJan Schmidt {
3855d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
3856d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
3857d7728c96SJan Schmidt 
3858d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
3859d7728c96SJan Schmidt 		inodes->bytes_left -= c;
3860d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
3861d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
3862d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
3863d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
3864d7728c96SJan Schmidt 	} else {
3865d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
3866d7728c96SJan Schmidt 		inodes->bytes_left = 0;
3867d7728c96SJan Schmidt 		inodes->elem_missed += 3;
3868d7728c96SJan Schmidt 	}
3869d7728c96SJan Schmidt 
3870d7728c96SJan Schmidt 	return 0;
3871d7728c96SJan Schmidt }
3872d7728c96SJan Schmidt 
38732ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
3874d24a67b2SZygo Blaxell 					void __user *arg, int version)
3875d7728c96SJan Schmidt {
3876d7728c96SJan Schmidt 	int ret = 0;
3877d7728c96SJan Schmidt 	int size;
3878d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
3879d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
3880d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
3881d24a67b2SZygo Blaxell 	bool ignore_offset;
3882d7728c96SJan Schmidt 
3883d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
3884d7728c96SJan Schmidt 		return -EPERM;
3885d7728c96SJan Schmidt 
3886d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
38877b9ea627SShailendra Verma 	if (IS_ERR(loi))
38887b9ea627SShailendra Verma 		return PTR_ERR(loi);
3889d7728c96SJan Schmidt 
3890d24a67b2SZygo Blaxell 	if (version == 1) {
3891d24a67b2SZygo Blaxell 		ignore_offset = false;
3892b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
3893d24a67b2SZygo Blaxell 	} else {
3894d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
3895d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
3896d24a67b2SZygo Blaxell 			ret = -EINVAL;
3897d24a67b2SZygo Blaxell 			goto out_loi;
3898d24a67b2SZygo Blaxell 		}
3899d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
3900d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
3901d24a67b2SZygo Blaxell 			ret = -EINVAL;
3902d24a67b2SZygo Blaxell 			goto out_loi;
3903d24a67b2SZygo Blaxell 		}
3904d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
3905b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
3906d24a67b2SZygo Blaxell 	}
3907d24a67b2SZygo Blaxell 
3908d7728c96SJan Schmidt 	path = btrfs_alloc_path();
3909d7728c96SJan Schmidt 	if (!path) {
3910d7728c96SJan Schmidt 		ret = -ENOMEM;
3911d7728c96SJan Schmidt 		goto out;
3912d7728c96SJan Schmidt 	}
3913d7728c96SJan Schmidt 
3914d7728c96SJan Schmidt 	inodes = init_data_container(size);
3915d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
3916d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
3917d7728c96SJan Schmidt 		inodes = NULL;
3918d7728c96SJan Schmidt 		goto out;
3919d7728c96SJan Schmidt 	}
3920d7728c96SJan Schmidt 
39212ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
3922d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
3923df031f07SLiu Bo 	if (ret == -EINVAL)
3924d7728c96SJan Schmidt 		ret = -ENOENT;
3925d7728c96SJan Schmidt 	if (ret < 0)
3926d7728c96SJan Schmidt 		goto out;
3927d7728c96SJan Schmidt 
3928718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
3929718dc5faSOmar Sandoval 			   size);
3930d7728c96SJan Schmidt 	if (ret)
3931d7728c96SJan Schmidt 		ret = -EFAULT;
3932d7728c96SJan Schmidt 
3933d7728c96SJan Schmidt out:
3934d7728c96SJan Schmidt 	btrfs_free_path(path);
3935f54de068SDavid Sterba 	kvfree(inodes);
3936d24a67b2SZygo Blaxell out_loi:
3937d7728c96SJan Schmidt 	kfree(loi);
3938d7728c96SJan Schmidt 
3939d7728c96SJan Schmidt 	return ret;
3940d7728c96SJan Schmidt }
3941d7728c96SJan Schmidt 
3942008ef096SDavid Sterba void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
3943c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
3944c9e9f97bSIlya Dryomov {
3945c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3946c9e9f97bSIlya Dryomov 
3947c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
3948c9e9f97bSIlya Dryomov 
39493009a62fSDavid Sterba 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
3950837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3951837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
3952837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3953a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
3954a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3955837d5b6eSIlya Dryomov 
3956c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3957c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3958c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
395919a39dceSIlya Dryomov 
396019a39dceSIlya Dryomov 	spin_lock(&fs_info->balance_lock);
396119a39dceSIlya Dryomov 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
396219a39dceSIlya Dryomov 	spin_unlock(&fs_info->balance_lock);
3963c9e9f97bSIlya Dryomov }
3964c9e9f97bSIlya Dryomov 
39659ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3966c9e9f97bSIlya Dryomov {
3967496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3968c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
3969c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
3970c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
3971ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
3972c9e9f97bSIlya Dryomov 	int ret;
3973c9e9f97bSIlya Dryomov 
3974c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
3975c9e9f97bSIlya Dryomov 		return -EPERM;
3976c9e9f97bSIlya Dryomov 
3977e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
39789ba1f6e4SLiu Bo 	if (ret)
39799ba1f6e4SLiu Bo 		return ret;
39809ba1f6e4SLiu Bo 
3981ed0fb78fSIlya Dryomov again:
3982c3e1f96cSGoldwyn Rodrigues 	if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
3983c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
3984ed0fb78fSIlya Dryomov 		need_unlock = true;
3985ed0fb78fSIlya Dryomov 		goto locked;
3986ed0fb78fSIlya Dryomov 	}
3987ed0fb78fSIlya Dryomov 
3988ed0fb78fSIlya Dryomov 	/*
398901327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
3990ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
3991ed0fb78fSIlya Dryomov 	 *   (2) balance is running
3992ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
3993ed0fb78fSIlya Dryomov 	 */
3994ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
3995ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
3996ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
39973009a62fSDavid Sterba 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
3998ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
3999dccdb07bSDavid Sterba 			/*
4000dccdb07bSDavid Sterba 			 * Lock released to allow other waiters to continue,
4001dccdb07bSDavid Sterba 			 * we'll reexamine the status again.
4002dccdb07bSDavid Sterba 			 */
4003ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4004ed0fb78fSIlya Dryomov 
4005ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
40063009a62fSDavid Sterba 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4007ed0fb78fSIlya Dryomov 				/* this is (3) */
4008ed0fb78fSIlya Dryomov 				need_unlock = false;
4009ed0fb78fSIlya Dryomov 				goto locked;
4010ed0fb78fSIlya Dryomov 			}
4011ed0fb78fSIlya Dryomov 
4012ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4013ed0fb78fSIlya Dryomov 			goto again;
4014ed0fb78fSIlya Dryomov 		} else {
4015ed0fb78fSIlya Dryomov 			/* this is (2) */
4016ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4017ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4018ed0fb78fSIlya Dryomov 			goto out;
4019ed0fb78fSIlya Dryomov 		}
4020ed0fb78fSIlya Dryomov 	} else {
4021ed0fb78fSIlya Dryomov 		/* this is (1) */
4022ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4023e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4024ed0fb78fSIlya Dryomov 		goto out;
4025ed0fb78fSIlya Dryomov 	}
4026ed0fb78fSIlya Dryomov 
4027ed0fb78fSIlya Dryomov locked:
4028c9e9f97bSIlya Dryomov 
4029c9e9f97bSIlya Dryomov 	if (arg) {
4030c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4031c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4032c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4033ed0fb78fSIlya Dryomov 			goto out_unlock;
4034c9e9f97bSIlya Dryomov 		}
4035de322263SIlya Dryomov 
4036de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4037de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4038de322263SIlya Dryomov 				ret = -ENOTCONN;
4039de322263SIlya Dryomov 				goto out_bargs;
4040de322263SIlya Dryomov 			}
4041de322263SIlya Dryomov 
4042de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4043de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4044de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4045de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4046de322263SIlya Dryomov 
4047de322263SIlya Dryomov 			goto do_balance;
4048de322263SIlya Dryomov 		}
4049c9e9f97bSIlya Dryomov 	} else {
4050c9e9f97bSIlya Dryomov 		bargs = NULL;
4051c9e9f97bSIlya Dryomov 	}
4052c9e9f97bSIlya Dryomov 
4053ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4054837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4055837d5b6eSIlya Dryomov 		goto out_bargs;
4056837d5b6eSIlya Dryomov 	}
4057837d5b6eSIlya Dryomov 
40588d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4059c9e9f97bSIlya Dryomov 	if (!bctl) {
4060c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4061c9e9f97bSIlya Dryomov 		goto out_bargs;
4062c9e9f97bSIlya Dryomov 	}
4063c9e9f97bSIlya Dryomov 
4064c9e9f97bSIlya Dryomov 	if (arg) {
4065c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4066c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4067c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4068c9e9f97bSIlya Dryomov 
4069c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4070f43ffb60SIlya Dryomov 	} else {
4071f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4072f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4073c9e9f97bSIlya Dryomov 	}
4074c9e9f97bSIlya Dryomov 
40758eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
40768eb93459SDavid Sterba 		ret = -EINVAL;
40770f89abf5SChristian Engelmayer 		goto out_bctl;
40788eb93459SDavid Sterba 	}
40798eb93459SDavid Sterba 
4080de322263SIlya Dryomov do_balance:
4081c9e9f97bSIlya Dryomov 	/*
4082c3e1f96cSGoldwyn Rodrigues 	 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4083c3e1f96cSGoldwyn Rodrigues 	 * bctl is freed in reset_balance_state, or, if restriper was paused
4084c3e1f96cSGoldwyn Rodrigues 	 * all the way until unmount, in free_fs_info.  The flag should be
4085c3e1f96cSGoldwyn Rodrigues 	 * cleared after reset_balance_state.
4086c9e9f97bSIlya Dryomov 	 */
4087ed0fb78fSIlya Dryomov 	need_unlock = false;
4088ed0fb78fSIlya Dryomov 
40896fcf6e2bSDavid Sterba 	ret = btrfs_balance(fs_info, bctl, bargs);
40900f89abf5SChristian Engelmayer 	bctl = NULL;
4091ed0fb78fSIlya Dryomov 
4092d00c2d9cSFilipe Manana 	if ((ret == 0 || ret == -ECANCELED) && arg) {
4093c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4094c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4095c9e9f97bSIlya Dryomov 	}
4096c9e9f97bSIlya Dryomov 
40970f89abf5SChristian Engelmayer out_bctl:
40980f89abf5SChristian Engelmayer 	kfree(bctl);
4099c9e9f97bSIlya Dryomov out_bargs:
4100c9e9f97bSIlya Dryomov 	kfree(bargs);
4101ed0fb78fSIlya Dryomov out_unlock:
4102c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4103ed0fb78fSIlya Dryomov 	if (need_unlock)
4104c3e1f96cSGoldwyn Rodrigues 		btrfs_exclop_finish(fs_info);
4105ed0fb78fSIlya Dryomov out:
4106e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4107c9e9f97bSIlya Dryomov 	return ret;
4108c9e9f97bSIlya Dryomov }
4109c9e9f97bSIlya Dryomov 
41102ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4111837d5b6eSIlya Dryomov {
4112837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4113837d5b6eSIlya Dryomov 		return -EPERM;
4114837d5b6eSIlya Dryomov 
4115837d5b6eSIlya Dryomov 	switch (cmd) {
4116837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
41170b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4118a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
41190b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4120837d5b6eSIlya Dryomov 	}
4121837d5b6eSIlya Dryomov 
4122837d5b6eSIlya Dryomov 	return -EINVAL;
4123837d5b6eSIlya Dryomov }
4124837d5b6eSIlya Dryomov 
41252ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
412619a39dceSIlya Dryomov 					 void __user *arg)
412719a39dceSIlya Dryomov {
412819a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
412919a39dceSIlya Dryomov 	int ret = 0;
413019a39dceSIlya Dryomov 
413119a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
413219a39dceSIlya Dryomov 		return -EPERM;
413319a39dceSIlya Dryomov 
413419a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
413519a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
413619a39dceSIlya Dryomov 		ret = -ENOTCONN;
413719a39dceSIlya Dryomov 		goto out;
413819a39dceSIlya Dryomov 	}
413919a39dceSIlya Dryomov 
41408d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
414119a39dceSIlya Dryomov 	if (!bargs) {
414219a39dceSIlya Dryomov 		ret = -ENOMEM;
414319a39dceSIlya Dryomov 		goto out;
414419a39dceSIlya Dryomov 	}
414519a39dceSIlya Dryomov 
4146008ef096SDavid Sterba 	btrfs_update_ioctl_balance_args(fs_info, bargs);
414719a39dceSIlya Dryomov 
414819a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
414919a39dceSIlya Dryomov 		ret = -EFAULT;
415019a39dceSIlya Dryomov 
415119a39dceSIlya Dryomov 	kfree(bargs);
415219a39dceSIlya Dryomov out:
415319a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
415419a39dceSIlya Dryomov 	return ret;
415519a39dceSIlya Dryomov }
415619a39dceSIlya Dryomov 
4157905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
41585d13a37bSArne Jansen {
41590b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
41600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
41615d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
41625d13a37bSArne Jansen 	int ret;
41635d13a37bSArne Jansen 
41645d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
41655d13a37bSArne Jansen 		return -EPERM;
41665d13a37bSArne Jansen 
4167905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4168905b0ddaSMiao Xie 	if (ret)
4169905b0ddaSMiao Xie 		return ret;
41705d13a37bSArne Jansen 
41715d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4172905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4173905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4174905b0ddaSMiao Xie 		goto drop_write;
4175905b0ddaSMiao Xie 	}
41765d13a37bSArne Jansen 
41770b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
41785d13a37bSArne Jansen 
41795d13a37bSArne Jansen 	switch (sa->cmd) {
41805d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
4181340f1aa2SNikolay Borisov 		ret = btrfs_quota_enable(fs_info);
41825d13a37bSArne Jansen 		break;
41835d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
4184340f1aa2SNikolay Borisov 		ret = btrfs_quota_disable(fs_info);
41855d13a37bSArne Jansen 		break;
41865d13a37bSArne Jansen 	default:
41875d13a37bSArne Jansen 		ret = -EINVAL;
41885d13a37bSArne Jansen 		break;
41895d13a37bSArne Jansen 	}
41905d13a37bSArne Jansen 
41915d13a37bSArne Jansen 	kfree(sa);
41920b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4193905b0ddaSMiao Xie drop_write:
4194905b0ddaSMiao Xie 	mnt_drop_write_file(file);
41955d13a37bSArne Jansen 	return ret;
41965d13a37bSArne Jansen }
41975d13a37bSArne Jansen 
4198905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
41995d13a37bSArne Jansen {
42000b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
42010b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
42020b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
42035d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
42045d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
42055d13a37bSArne Jansen 	int ret;
42065d13a37bSArne Jansen 	int err;
42075d13a37bSArne Jansen 
42085d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
42095d13a37bSArne Jansen 		return -EPERM;
42105d13a37bSArne Jansen 
4211905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4212905b0ddaSMiao Xie 	if (ret)
4213905b0ddaSMiao Xie 		return ret;
42145d13a37bSArne Jansen 
42155d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4216905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4217905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4218905b0ddaSMiao Xie 		goto drop_write;
4219905b0ddaSMiao Xie 	}
42205d13a37bSArne Jansen 
42215d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
42225d13a37bSArne Jansen 	if (IS_ERR(trans)) {
42235d13a37bSArne Jansen 		ret = PTR_ERR(trans);
42245d13a37bSArne Jansen 		goto out;
42255d13a37bSArne Jansen 	}
42265d13a37bSArne Jansen 
42275d13a37bSArne Jansen 	if (sa->assign) {
42289f8a6ce6SLu Fengqi 		ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
42295d13a37bSArne Jansen 	} else {
423039616c27SLu Fengqi 		ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
42315d13a37bSArne Jansen 	}
42325d13a37bSArne Jansen 
4233e082f563SQu Wenruo 	/* update qgroup status and info */
4234280f8bd2SLu Fengqi 	err = btrfs_run_qgroups(trans);
4235e082f563SQu Wenruo 	if (err < 0)
42360b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4237ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
42383a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
42395d13a37bSArne Jansen 	if (err && !ret)
42405d13a37bSArne Jansen 		ret = err;
42415d13a37bSArne Jansen 
42425d13a37bSArne Jansen out:
42435d13a37bSArne Jansen 	kfree(sa);
4244905b0ddaSMiao Xie drop_write:
4245905b0ddaSMiao Xie 	mnt_drop_write_file(file);
42465d13a37bSArne Jansen 	return ret;
42475d13a37bSArne Jansen }
42485d13a37bSArne Jansen 
4249905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
42505d13a37bSArne Jansen {
42510b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
42520b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
42535d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
42545d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
42555d13a37bSArne Jansen 	int ret;
42565d13a37bSArne Jansen 	int err;
42575d13a37bSArne Jansen 
42585d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
42595d13a37bSArne Jansen 		return -EPERM;
42605d13a37bSArne Jansen 
4261905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4262905b0ddaSMiao Xie 	if (ret)
4263905b0ddaSMiao Xie 		return ret;
42645d13a37bSArne Jansen 
42655d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4266905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4267905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4268905b0ddaSMiao Xie 		goto drop_write;
4269905b0ddaSMiao Xie 	}
42705d13a37bSArne Jansen 
4271d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4272d86e56cfSMiao Xie 		ret = -EINVAL;
4273d86e56cfSMiao Xie 		goto out;
4274d86e56cfSMiao Xie 	}
4275d86e56cfSMiao Xie 
42765d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
42775d13a37bSArne Jansen 	if (IS_ERR(trans)) {
42785d13a37bSArne Jansen 		ret = PTR_ERR(trans);
42795d13a37bSArne Jansen 		goto out;
42805d13a37bSArne Jansen 	}
42815d13a37bSArne Jansen 
42825d13a37bSArne Jansen 	if (sa->create) {
428349a05ecdSLu Fengqi 		ret = btrfs_create_qgroup(trans, sa->qgroupid);
42845d13a37bSArne Jansen 	} else {
42853efbee1dSLu Fengqi 		ret = btrfs_remove_qgroup(trans, sa->qgroupid);
42865d13a37bSArne Jansen 	}
42875d13a37bSArne Jansen 
42883a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
42895d13a37bSArne Jansen 	if (err && !ret)
42905d13a37bSArne Jansen 		ret = err;
42915d13a37bSArne Jansen 
42925d13a37bSArne Jansen out:
42935d13a37bSArne Jansen 	kfree(sa);
4294905b0ddaSMiao Xie drop_write:
4295905b0ddaSMiao Xie 	mnt_drop_write_file(file);
42965d13a37bSArne Jansen 	return ret;
42975d13a37bSArne Jansen }
42985d13a37bSArne Jansen 
4299905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
43005d13a37bSArne Jansen {
43010b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
43020b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
43035d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
43045d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
43055d13a37bSArne Jansen 	int ret;
43065d13a37bSArne Jansen 	int err;
43075d13a37bSArne Jansen 	u64 qgroupid;
43085d13a37bSArne Jansen 
43095d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
43105d13a37bSArne Jansen 		return -EPERM;
43115d13a37bSArne Jansen 
4312905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4313905b0ddaSMiao Xie 	if (ret)
4314905b0ddaSMiao Xie 		return ret;
43155d13a37bSArne Jansen 
43165d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4317905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4318905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4319905b0ddaSMiao Xie 		goto drop_write;
4320905b0ddaSMiao Xie 	}
43215d13a37bSArne Jansen 
43225d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
43235d13a37bSArne Jansen 	if (IS_ERR(trans)) {
43245d13a37bSArne Jansen 		ret = PTR_ERR(trans);
43255d13a37bSArne Jansen 		goto out;
43265d13a37bSArne Jansen 	}
43275d13a37bSArne Jansen 
43285d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
43295d13a37bSArne Jansen 	if (!qgroupid) {
43305d13a37bSArne Jansen 		/* take the current subvol as qgroup */
43315d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
43325d13a37bSArne Jansen 	}
43335d13a37bSArne Jansen 
4334f0042d5eSLu Fengqi 	ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
43355d13a37bSArne Jansen 
43363a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
43375d13a37bSArne Jansen 	if (err && !ret)
43385d13a37bSArne Jansen 		ret = err;
43395d13a37bSArne Jansen 
43405d13a37bSArne Jansen out:
43415d13a37bSArne Jansen 	kfree(sa);
4342905b0ddaSMiao Xie drop_write:
4343905b0ddaSMiao Xie 	mnt_drop_write_file(file);
43445d13a37bSArne Jansen 	return ret;
43455d13a37bSArne Jansen }
43465d13a37bSArne Jansen 
43472f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
43482f232036SJan Schmidt {
43490b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
43500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
43512f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
43522f232036SJan Schmidt 	int ret;
43532f232036SJan Schmidt 
43542f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
43552f232036SJan Schmidt 		return -EPERM;
43562f232036SJan Schmidt 
43572f232036SJan Schmidt 	ret = mnt_want_write_file(file);
43582f232036SJan Schmidt 	if (ret)
43592f232036SJan Schmidt 		return ret;
43602f232036SJan Schmidt 
43612f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
43622f232036SJan Schmidt 	if (IS_ERR(qsa)) {
43632f232036SJan Schmidt 		ret = PTR_ERR(qsa);
43642f232036SJan Schmidt 		goto drop_write;
43652f232036SJan Schmidt 	}
43662f232036SJan Schmidt 
43672f232036SJan Schmidt 	if (qsa->flags) {
43682f232036SJan Schmidt 		ret = -EINVAL;
43692f232036SJan Schmidt 		goto out;
43702f232036SJan Schmidt 	}
43712f232036SJan Schmidt 
43720b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
43732f232036SJan Schmidt 
43742f232036SJan Schmidt out:
43752f232036SJan Schmidt 	kfree(qsa);
43762f232036SJan Schmidt drop_write:
43772f232036SJan Schmidt 	mnt_drop_write_file(file);
43782f232036SJan Schmidt 	return ret;
43792f232036SJan Schmidt }
43802f232036SJan Schmidt 
4381b929c1d8SMarcos Paulo de Souza static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4382b929c1d8SMarcos Paulo de Souza 						void __user *arg)
43832f232036SJan Schmidt {
43840afb603aSGoldwyn Rodrigues 	struct btrfs_ioctl_quota_rescan_args qsa = {0};
43852f232036SJan Schmidt 
43862f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
43872f232036SJan Schmidt 		return -EPERM;
43882f232036SJan Schmidt 
43890b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
43900afb603aSGoldwyn Rodrigues 		qsa.flags = 1;
43910afb603aSGoldwyn Rodrigues 		qsa.progress = fs_info->qgroup_rescan_progress.objectid;
43922f232036SJan Schmidt 	}
43932f232036SJan Schmidt 
43940afb603aSGoldwyn Rodrigues 	if (copy_to_user(arg, &qsa, sizeof(qsa)))
4395991a3daeSAnand Jain 		return -EFAULT;
43962f232036SJan Schmidt 
4397991a3daeSAnand Jain 	return 0;
43982f232036SJan Schmidt }
43992f232036SJan Schmidt 
4400b929c1d8SMarcos Paulo de Souza static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4401b929c1d8SMarcos Paulo de Souza 						void __user *arg)
440257254b6eSJan Schmidt {
440357254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
440457254b6eSJan Schmidt 		return -EPERM;
440557254b6eSJan Schmidt 
44060b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
440757254b6eSJan Schmidt }
440857254b6eSJan Schmidt 
4409abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
4410e4fed17aSChristian Brauner 					    struct user_namespace *mnt_userns,
4411abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
44128ea05e3aSAlexander Block {
4413496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
44140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
44158ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
44168ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
44178ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
441895582b00SDeepa Dinamani 	struct timespec64 ct = current_time(inode);
44198ea05e3aSAlexander Block 	int ret = 0;
4420dd5f9615SStefan Behrens 	int received_uuid_changed;
44218ea05e3aSAlexander Block 
4422e4fed17aSChristian Brauner 	if (!inode_owner_or_capable(mnt_userns, inode))
4423bd60ea0fSDavid Sterba 		return -EPERM;
4424bd60ea0fSDavid Sterba 
44258ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
44268ea05e3aSAlexander Block 	if (ret < 0)
44278ea05e3aSAlexander Block 		return ret;
44288ea05e3aSAlexander Block 
44290b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
44308ea05e3aSAlexander Block 
44314a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
44328ea05e3aSAlexander Block 		ret = -EINVAL;
44338ea05e3aSAlexander Block 		goto out;
44348ea05e3aSAlexander Block 	}
44358ea05e3aSAlexander Block 
44368ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
44378ea05e3aSAlexander Block 		ret = -EROFS;
44388ea05e3aSAlexander Block 		goto out;
44398ea05e3aSAlexander Block 	}
44408ea05e3aSAlexander Block 
4441dd5f9615SStefan Behrens 	/*
4442dd5f9615SStefan Behrens 	 * 1 - root item
4443dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
4444dd5f9615SStefan Behrens 	 */
4445dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
44468ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
44478ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
44488ea05e3aSAlexander Block 		trans = NULL;
44498ea05e3aSAlexander Block 		goto out;
44508ea05e3aSAlexander Block 	}
44518ea05e3aSAlexander Block 
44528ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
44538ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
44548ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
44558ea05e3aSAlexander Block 
4456dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4457dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
4458dd5f9615SStefan Behrens 	if (received_uuid_changed &&
4459d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
4460d1957791SLu Fengqi 		ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
4461dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4462dd5f9615SStefan Behrens 					  root->root_key.objectid);
4463d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
4464d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
4465d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
4466d87ff758SNikolay Borisov 		        goto out;
4467d87ff758SNikolay Borisov 		}
4468d87ff758SNikolay Borisov 	}
44698ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
44708ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
44718ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
44723cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
44733cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
44743cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
44753cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
44768ea05e3aSAlexander Block 
44770b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
44788ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
44798ea05e3aSAlexander Block 	if (ret < 0) {
44803a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
44818ea05e3aSAlexander Block 		goto out;
4482dd5f9615SStefan Behrens 	}
4483dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4484cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, sa->uuid,
4485dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4486dd5f9615SStefan Behrens 					  root->root_key.objectid);
4487dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
448866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
4489efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
4490dd5f9615SStefan Behrens 			goto out;
4491dd5f9615SStefan Behrens 		}
4492dd5f9615SStefan Behrens 	}
44933a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
4494abccd00fSHugo Mills out:
44950b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4496abccd00fSHugo Mills 	mnt_drop_write_file(file);
4497abccd00fSHugo Mills 	return ret;
4498abccd00fSHugo Mills }
4499abccd00fSHugo Mills 
4500abccd00fSHugo Mills #ifdef CONFIG_64BIT
4501abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4502abccd00fSHugo Mills 						void __user *arg)
4503abccd00fSHugo Mills {
4504abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4505abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4506abccd00fSHugo Mills 	int ret = 0;
4507abccd00fSHugo Mills 
4508abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
45097b9ea627SShailendra Verma 	if (IS_ERR(args32))
45107b9ea627SShailendra Verma 		return PTR_ERR(args32);
4511abccd00fSHugo Mills 
45128d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
451384dbeb87SDan Carpenter 	if (!args64) {
451484dbeb87SDan Carpenter 		ret = -ENOMEM;
4515abccd00fSHugo Mills 		goto out;
4516abccd00fSHugo Mills 	}
4517abccd00fSHugo Mills 
4518abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4519abccd00fSHugo Mills 	args64->stransid = args32->stransid;
4520abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
4521abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
4522abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
4523abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
4524abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
4525abccd00fSHugo Mills 	args64->flags = args32->flags;
4526abccd00fSHugo Mills 
4527e4fed17aSChristian Brauner 	ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), args64);
4528abccd00fSHugo Mills 	if (ret)
4529abccd00fSHugo Mills 		goto out;
4530abccd00fSHugo Mills 
4531abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4532abccd00fSHugo Mills 	args32->stransid = args64->stransid;
4533abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
4534abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
4535abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
4536abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
4537abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
4538abccd00fSHugo Mills 	args32->flags = args64->flags;
4539abccd00fSHugo Mills 
4540abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
4541abccd00fSHugo Mills 	if (ret)
4542abccd00fSHugo Mills 		ret = -EFAULT;
4543abccd00fSHugo Mills 
4544abccd00fSHugo Mills out:
4545abccd00fSHugo Mills 	kfree(args32);
4546abccd00fSHugo Mills 	kfree(args64);
4547abccd00fSHugo Mills 	return ret;
4548abccd00fSHugo Mills }
4549abccd00fSHugo Mills #endif
4550abccd00fSHugo Mills 
4551abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
4552abccd00fSHugo Mills 					    void __user *arg)
4553abccd00fSHugo Mills {
4554abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
4555abccd00fSHugo Mills 	int ret = 0;
4556abccd00fSHugo Mills 
4557abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
45587b9ea627SShailendra Verma 	if (IS_ERR(sa))
45597b9ea627SShailendra Verma 		return PTR_ERR(sa);
4560abccd00fSHugo Mills 
4561e4fed17aSChristian Brauner 	ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), sa);
4562abccd00fSHugo Mills 
4563abccd00fSHugo Mills 	if (ret)
4564abccd00fSHugo Mills 		goto out;
4565abccd00fSHugo Mills 
45668ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
45678ea05e3aSAlexander Block 	if (ret)
45688ea05e3aSAlexander Block 		ret = -EFAULT;
45698ea05e3aSAlexander Block 
45708ea05e3aSAlexander Block out:
45718ea05e3aSAlexander Block 	kfree(sa);
45728ea05e3aSAlexander Block 	return ret;
45738ea05e3aSAlexander Block }
45748ea05e3aSAlexander Block 
4575b929c1d8SMarcos Paulo de Souza static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4576b929c1d8SMarcos Paulo de Souza 					void __user *arg)
4577867ab667Sjeff.liu {
4578a1b83ac5SAnand Jain 	size_t len;
4579867ab667Sjeff.liu 	int ret;
4580a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
4581a1b83ac5SAnand Jain 
45820b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
45830b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
45840b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
4585a1b83ac5SAnand Jain 
4586a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
4587867ab667Sjeff.liu 
4588867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
45890b246afaSJeff Mahoney 		btrfs_warn(fs_info,
45900b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
45910b246afaSJeff Mahoney 			   --len);
4592867ab667Sjeff.liu 	}
4593867ab667Sjeff.liu 
4594867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
4595867ab667Sjeff.liu 
4596867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
4597867ab667Sjeff.liu }
4598867ab667Sjeff.liu 
4599a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4600a8bfd4abSjeff.liu {
46010b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
46020b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46030b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
46040b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
4605a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
4606a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
4607a8bfd4abSjeff.liu 	int ret;
4608a8bfd4abSjeff.liu 
4609a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
4610a8bfd4abSjeff.liu 		return -EPERM;
4611a8bfd4abSjeff.liu 
4612a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
4613a8bfd4abSjeff.liu 		return -EFAULT;
4614a8bfd4abSjeff.liu 
4615a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
46160b246afaSJeff Mahoney 		btrfs_err(fs_info,
46175d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
4618a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
4619a8bfd4abSjeff.liu 		return -EINVAL;
4620a8bfd4abSjeff.liu 	}
4621a8bfd4abSjeff.liu 
4622a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
4623a8bfd4abSjeff.liu 	if (ret)
4624a8bfd4abSjeff.liu 		return ret;
4625a8bfd4abSjeff.liu 
4626a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
4627a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
4628a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
4629a8bfd4abSjeff.liu 		goto out_unlock;
4630a8bfd4abSjeff.liu 	}
4631a8bfd4abSjeff.liu 
46320b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
4633a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
46340b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
46353a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
4636a8bfd4abSjeff.liu 
4637a8bfd4abSjeff.liu out_unlock:
4638a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
4639a8bfd4abSjeff.liu 	return ret;
4640a8bfd4abSjeff.liu }
4641a8bfd4abSjeff.liu 
46422eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
46432eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
46442eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
46452eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
46462eaa055fSJeff Mahoney 
4647d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
46482eaa055fSJeff Mahoney {
46494d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
46502eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
46512eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
46522eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
46532eaa055fSJeff Mahoney 	};
46542eaa055fSJeff Mahoney 
46552eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
46562eaa055fSJeff Mahoney 		return -EFAULT;
46572eaa055fSJeff Mahoney 
46582eaa055fSJeff Mahoney 	return 0;
46592eaa055fSJeff Mahoney }
46602eaa055fSJeff Mahoney 
4661b929c1d8SMarcos Paulo de Souza static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
4662b929c1d8SMarcos Paulo de Souza 					void __user *arg)
46632eaa055fSJeff Mahoney {
46640b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
46652eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
46662eaa055fSJeff Mahoney 
46672eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
46682eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
46692eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
46702eaa055fSJeff Mahoney 
46712eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
46722eaa055fSJeff Mahoney 		return -EFAULT;
46732eaa055fSJeff Mahoney 
46742eaa055fSJeff Mahoney 	return 0;
46752eaa055fSJeff Mahoney }
46762eaa055fSJeff Mahoney 
46772ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
46783b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
46792eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
46802eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
46812eaa055fSJeff Mahoney {
4682f10152bcSDavid Sterba 	const char *type = btrfs_feature_set_name(set);
46833b02a68aSJeff Mahoney 	char *names;
46842eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
46852eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
46862eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
46872eaa055fSJeff Mahoney 
46882eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
46892eaa055fSJeff Mahoney 	if (unsupported) {
46903b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
46913b02a68aSJeff Mahoney 		if (names) {
46920b246afaSJeff Mahoney 			btrfs_warn(fs_info,
46933b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
46943b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
46953b02a68aSJeff Mahoney 			kfree(names);
46963b02a68aSJeff Mahoney 		} else
46970b246afaSJeff Mahoney 			btrfs_warn(fs_info,
46982eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
46992eaa055fSJeff Mahoney 				   type, unsupported);
47002eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
47012eaa055fSJeff Mahoney 	}
47022eaa055fSJeff Mahoney 
47032eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
47042eaa055fSJeff Mahoney 	if (disallowed) {
47053b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
47063b02a68aSJeff Mahoney 		if (names) {
47070b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47083b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
47093b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
47103b02a68aSJeff Mahoney 			kfree(names);
47113b02a68aSJeff Mahoney 		} else
47120b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47132eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
47142eaa055fSJeff Mahoney 				   type, disallowed);
47152eaa055fSJeff Mahoney 		return -EPERM;
47162eaa055fSJeff Mahoney 	}
47172eaa055fSJeff Mahoney 
47182eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
47192eaa055fSJeff Mahoney 	if (disallowed) {
47203b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
47213b02a68aSJeff Mahoney 		if (names) {
47220b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47233b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
47243b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
47253b02a68aSJeff Mahoney 			kfree(names);
47263b02a68aSJeff Mahoney 		} else
47270b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47282eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
47292eaa055fSJeff Mahoney 				   type, disallowed);
47302eaa055fSJeff Mahoney 		return -EPERM;
47312eaa055fSJeff Mahoney 	}
47322eaa055fSJeff Mahoney 
47332eaa055fSJeff Mahoney 	return 0;
47342eaa055fSJeff Mahoney }
47352eaa055fSJeff Mahoney 
47362ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
47372ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
47382eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
47392eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
47402eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
47412eaa055fSJeff Mahoney 
47422eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
47432eaa055fSJeff Mahoney {
47440b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47450b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47460b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
47470b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
47482eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
47492eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
47502eaa055fSJeff Mahoney 	u64 newflags;
47512eaa055fSJeff Mahoney 	int ret;
47522eaa055fSJeff Mahoney 
47532eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
47542eaa055fSJeff Mahoney 		return -EPERM;
47552eaa055fSJeff Mahoney 
47562eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
47572eaa055fSJeff Mahoney 		return -EFAULT;
47582eaa055fSJeff Mahoney 
47592eaa055fSJeff Mahoney 	/* Nothing to do */
47602eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
47612eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
47622eaa055fSJeff Mahoney 		return 0;
47632eaa055fSJeff Mahoney 
47642ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
47652eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
47662eaa055fSJeff Mahoney 	if (ret)
47672eaa055fSJeff Mahoney 		return ret;
47682eaa055fSJeff Mahoney 
47692ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
47702eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
47712eaa055fSJeff Mahoney 	if (ret)
47722eaa055fSJeff Mahoney 		return ret;
47732eaa055fSJeff Mahoney 
47742ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
47752eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
47762eaa055fSJeff Mahoney 	if (ret)
47772eaa055fSJeff Mahoney 		return ret;
47782eaa055fSJeff Mahoney 
47797ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
47807ab19625SDavid Sterba 	if (ret)
47817ab19625SDavid Sterba 		return ret;
47827ab19625SDavid Sterba 
47838051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
47847ab19625SDavid Sterba 	if (IS_ERR(trans)) {
47857ab19625SDavid Sterba 		ret = PTR_ERR(trans);
47867ab19625SDavid Sterba 		goto out_drop_write;
47877ab19625SDavid Sterba 	}
47882eaa055fSJeff Mahoney 
47890b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
47902eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
47912eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
47922eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
47932eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
47942eaa055fSJeff Mahoney 
47952eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
47962eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
47972eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
47982eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
47992eaa055fSJeff Mahoney 
48002eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
48012eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
48022eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
48032eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
48040b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
48052eaa055fSJeff Mahoney 
48063a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
48077ab19625SDavid Sterba out_drop_write:
48087ab19625SDavid Sterba 	mnt_drop_write_file(file);
48097ab19625SDavid Sterba 
48107ab19625SDavid Sterba 	return ret;
48112eaa055fSJeff Mahoney }
48122eaa055fSJeff Mahoney 
48132351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
48142351f431SJosef Bacik {
48152351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
48162351f431SJosef Bacik 	int ret;
48172351f431SJosef Bacik 
48182351f431SJosef Bacik 	if (compat) {
48192351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
48202351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
48212351f431SJosef Bacik 
48222351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
48232351f431SJosef Bacik 		if (ret)
48242351f431SJosef Bacik 			return -EFAULT;
48252351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
48262351f431SJosef Bacik 		if (!arg)
48272351f431SJosef Bacik 			return -ENOMEM;
48282351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
48292351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
48302351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
48312351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
48322351f431SJosef Bacik 		arg->flags = args32.flags;
48332351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
48342351f431SJosef Bacik 		       sizeof(args32.reserved));
48352351f431SJosef Bacik #else
48362351f431SJosef Bacik 		return -ENOTTY;
48372351f431SJosef Bacik #endif
48382351f431SJosef Bacik 	} else {
48392351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
48402351f431SJosef Bacik 		if (IS_ERR(arg))
48412351f431SJosef Bacik 			return PTR_ERR(arg);
48422351f431SJosef Bacik 	}
48432351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
48442351f431SJosef Bacik 	kfree(arg);
48452351f431SJosef Bacik 	return ret;
48462351f431SJosef Bacik }
48472351f431SJosef Bacik 
4848f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
4849f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
4850f46b5a66SChristoph Hellwig {
48510b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48530b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
48544bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
4855f46b5a66SChristoph Hellwig 
4856f46b5a66SChristoph Hellwig 	switch (cmd) {
48576cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
48586cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
485940cf931fSEric Sandeen 	case FS_IOC_GETFSLABEL:
4860b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_get_fslabel(fs_info, argp);
486140cf931fSEric Sandeen 	case FS_IOC_SETFSLABEL:
486240cf931fSEric Sandeen 		return btrfs_ioctl_set_fslabel(file, argp);
4863f7039b1dSLi Dongyang 	case FITRIM:
4864b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_fitrim(fs_info, argp);
4865f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
4866fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
4867fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
4868fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
48693de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
4870fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
48716f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
48726f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
487376dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
4874949964c9SMarcos Paulo de Souza 		return btrfs_ioctl_snap_destroy(file, argp, false);
4875949964c9SMarcos Paulo de Souza 	case BTRFS_IOC_SNAP_DESTROY_V2:
4876949964c9SMarcos Paulo de Souza 		return btrfs_ioctl_snap_destroy(file, argp, true);
48770caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
48780caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
48790caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
48800caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
48816ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
48826ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
4883f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
48841e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
48851e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
48861e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
4887f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
4888198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
4889f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
48902ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
4891f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
4892da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
48936b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
48946b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
4895475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
48962ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
4897475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
48982ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
4899f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
49009ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
4901ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
4902ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
4903cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
4904cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
4905ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
4906ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
4907d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
4908d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
4909d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
4910d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
4911d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
4912d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
49131406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
49142ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
49159b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
49169b199859SFilipe David Borba Manana 		int ret;
49179b199859SFilipe David Borba Manana 
49189db4dc24SNikolay Borisov 		ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
49199b199859SFilipe David Borba Manana 		if (ret)
49209b199859SFilipe David Borba Manana 			return ret;
49210b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
49222fad4e83SDavid Sterba 		/*
49232fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
492401327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
49252fad4e83SDavid Sterba 		 * processing uncleaned subvols.
49262fad4e83SDavid Sterba 		 */
49270b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
49289b199859SFilipe David Borba Manana 		return ret;
49299b199859SFilipe David Borba Manana 	}
493046204592SSage Weil 	case BTRFS_IOC_START_SYNC:
49319a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
493246204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
49332ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
4934475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
4935b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
4936475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
49372ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
4938475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
49392ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
4940c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
49419ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
4942837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
49432ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
494419a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
49452ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
49468ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
49478ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
4948abccd00fSHugo Mills #ifdef CONFIG_64BIT
4949abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
4950abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
4951abccd00fSHugo Mills #endif
495231db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
49532351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
49542351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
49552351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
49562351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
49572351f431SJosef Bacik #endif
4958c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
49592ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
49605d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
4961905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
49625d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
4963905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
49645d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
4965905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
49665d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
4967905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
49682f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
49692f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
49702f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
4971b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_quota_rescan_status(fs_info, argp);
497257254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
4973b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
49743f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
49752ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
49762eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
4977d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
49782eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
4979b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_get_features(fs_info, argp);
49802eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
49812eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
4982b64ec075STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_INFO:
4983b64ec075STomohiro Misono 		return btrfs_ioctl_get_subvol_info(file, argp);
498442e4b520STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_ROOTREF:
498542e4b520STomohiro Misono 		return btrfs_ioctl_get_subvol_rootref(file, argp);
498623d0b79dSTomohiro Misono 	case BTRFS_IOC_INO_LOOKUP_USER:
498723d0b79dSTomohiro Misono 		return btrfs_ioctl_ino_lookup_user(file, argp);
498814605409SBoris Burkov 	case FS_IOC_ENABLE_VERITY:
498914605409SBoris Burkov 		return fsverity_ioctl_enable(file, (const void __user *)argp);
499014605409SBoris Burkov 	case FS_IOC_MEASURE_VERITY:
499114605409SBoris Burkov 		return fsverity_ioctl_measure(file, argp);
4992f46b5a66SChristoph Hellwig 	}
4993f46b5a66SChristoph Hellwig 
4994f46b5a66SChristoph Hellwig 	return -ENOTTY;
4995f46b5a66SChristoph Hellwig }
49964c63c245SLuke Dashjr 
49974c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
49984c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
49994c63c245SLuke Dashjr {
50002a362249SJeff Mahoney 	/*
50012a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
50022a362249SJeff Mahoney 	 * handling is necessary.
50032a362249SJeff Mahoney 	 */
50044c63c245SLuke Dashjr 	switch (cmd) {
50054c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
50064c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
50074c63c245SLuke Dashjr 		break;
50084c63c245SLuke Dashjr 	}
50094c63c245SLuke Dashjr 
50104c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
50114c63c245SLuke Dashjr }
50124c63c245SLuke Dashjr #endif
5013