xref: /openbmc/linux/fs/btrfs/ioctl.c (revision efc0e69c)
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 */
85e77fbf99SDavid Sterba 	__u32 version;			/* in */
86e77fbf99SDavid Sterba 	__u8  reserved[28];		/* in */
872351f431SJosef Bacik } __attribute__ ((__packed__));
882351f431SJosef Bacik 
892351f431SJosef Bacik #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
902351f431SJosef Bacik 			       struct btrfs_ioctl_send_args_32)
912351f431SJosef Bacik #endif
92abccd00fSHugo Mills 
936cbff00fSChristoph Hellwig /* Mask out flags that are inappropriate for the given type of inode. */
941905a0f7SDavid Sterba static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
951905a0f7SDavid Sterba 		unsigned int flags)
966cbff00fSChristoph Hellwig {
971905a0f7SDavid Sterba 	if (S_ISDIR(inode->i_mode))
986cbff00fSChristoph Hellwig 		return flags;
991905a0f7SDavid Sterba 	else if (S_ISREG(inode->i_mode))
1006cbff00fSChristoph Hellwig 		return flags & ~FS_DIRSYNC_FL;
1016cbff00fSChristoph Hellwig 	else
1026cbff00fSChristoph Hellwig 		return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
1036cbff00fSChristoph Hellwig }
104f46b5a66SChristoph Hellwig 
1056cbff00fSChristoph Hellwig /*
106a157d4fdSDavid Sterba  * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
107a157d4fdSDavid Sterba  * ioctl.
1086cbff00fSChristoph Hellwig  */
10977eea05eSBoris Burkov static unsigned int btrfs_inode_flags_to_fsflags(struct btrfs_inode *binode)
1106cbff00fSChristoph Hellwig {
1116cbff00fSChristoph Hellwig 	unsigned int iflags = 0;
11277eea05eSBoris Burkov 	u32 flags = binode->flags;
11314605409SBoris Burkov 	u32 ro_flags = binode->ro_flags;
1146cbff00fSChristoph Hellwig 
1156cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_SYNC)
1166cbff00fSChristoph Hellwig 		iflags |= FS_SYNC_FL;
1176cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_IMMUTABLE)
1186cbff00fSChristoph Hellwig 		iflags |= FS_IMMUTABLE_FL;
1196cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_APPEND)
1206cbff00fSChristoph Hellwig 		iflags |= FS_APPEND_FL;
1216cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NODUMP)
1226cbff00fSChristoph Hellwig 		iflags |= FS_NODUMP_FL;
1236cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NOATIME)
1246cbff00fSChristoph Hellwig 		iflags |= FS_NOATIME_FL;
1256cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_DIRSYNC)
1266cbff00fSChristoph Hellwig 		iflags |= FS_DIRSYNC_FL;
127d0092bddSLi Zefan 	if (flags & BTRFS_INODE_NODATACOW)
128d0092bddSLi Zefan 		iflags |= FS_NOCOW_FL;
12914605409SBoris Burkov 	if (ro_flags & BTRFS_INODE_RO_VERITY)
13014605409SBoris Burkov 		iflags |= FS_VERITY_FL;
131d0092bddSLi Zefan 
13213f48dc9SSatoru Takeuchi 	if (flags & BTRFS_INODE_NOCOMPRESS)
133d0092bddSLi Zefan 		iflags |= FS_NOCOMP_FL;
13413f48dc9SSatoru Takeuchi 	else if (flags & BTRFS_INODE_COMPRESS)
13513f48dc9SSatoru Takeuchi 		iflags |= FS_COMPR_FL;
1366cbff00fSChristoph Hellwig 
1376cbff00fSChristoph Hellwig 	return iflags;
1386cbff00fSChristoph Hellwig }
1396cbff00fSChristoph Hellwig 
1406cbff00fSChristoph Hellwig /*
1416cbff00fSChristoph Hellwig  * Update inode->i_flags based on the btrfs internal flags.
1426cbff00fSChristoph Hellwig  */
1437b6a221eSDavid Sterba void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
1446cbff00fSChristoph Hellwig {
1455c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
1463cc79392SFilipe Manana 	unsigned int new_fl = 0;
1476cbff00fSChristoph Hellwig 
1485c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_SYNC)
1493cc79392SFilipe Manana 		new_fl |= S_SYNC;
1505c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_IMMUTABLE)
1513cc79392SFilipe Manana 		new_fl |= S_IMMUTABLE;
1525c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_APPEND)
1533cc79392SFilipe Manana 		new_fl |= S_APPEND;
1545c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_NOATIME)
1553cc79392SFilipe Manana 		new_fl |= S_NOATIME;
1565c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_DIRSYNC)
1573cc79392SFilipe Manana 		new_fl |= S_DIRSYNC;
15814605409SBoris Burkov 	if (binode->ro_flags & BTRFS_INODE_RO_VERITY)
15914605409SBoris Burkov 		new_fl |= S_VERITY;
1603cc79392SFilipe Manana 
1613cc79392SFilipe Manana 	set_mask_bits(&inode->i_flags,
16214605409SBoris Burkov 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC |
16314605409SBoris Burkov 		      S_VERITY, new_fl);
1646cbff00fSChristoph Hellwig }
1656cbff00fSChristoph Hellwig 
166f37c563bSDavid Sterba /*
167f37c563bSDavid Sterba  * Check if @flags are a supported and valid set of FS_*_FL flags and that
168f37c563bSDavid Sterba  * the old and new flags are not conflicting
169f37c563bSDavid Sterba  */
170f37c563bSDavid Sterba static int check_fsflags(unsigned int old_flags, unsigned int flags)
17175e7cb7fSLiu Bo {
17275e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
17375e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
17475e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
175e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
176e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
17775e7cb7fSLiu Bo 		return -EOPNOTSUPP;
17875e7cb7fSLiu Bo 
179f37c563bSDavid Sterba 	/* COMPR and NOCOMP on new/old are valid */
18075e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
18175e7cb7fSLiu Bo 		return -EINVAL;
18275e7cb7fSLiu Bo 
183f37c563bSDavid Sterba 	if ((flags & FS_COMPR_FL) && (flags & FS_NOCOW_FL))
184f37c563bSDavid Sterba 		return -EINVAL;
185f37c563bSDavid Sterba 
186f37c563bSDavid Sterba 	/* NOCOW and compression options are mutually exclusive */
187f37c563bSDavid Sterba 	if ((old_flags & FS_NOCOW_FL) && (flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
188f37c563bSDavid Sterba 		return -EINVAL;
189f37c563bSDavid Sterba 	if ((flags & FS_NOCOW_FL) && (old_flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
190f37c563bSDavid Sterba 		return -EINVAL;
191f37c563bSDavid Sterba 
19275e7cb7fSLiu Bo 	return 0;
19375e7cb7fSLiu Bo }
19475e7cb7fSLiu Bo 
195d206e9c9SNaohiro Aota static int check_fsflags_compatible(struct btrfs_fs_info *fs_info,
196d206e9c9SNaohiro Aota 				    unsigned int flags)
197d206e9c9SNaohiro Aota {
198d206e9c9SNaohiro Aota 	if (btrfs_is_zoned(fs_info) && (flags & FS_NOCOW_FL))
199d206e9c9SNaohiro Aota 		return -EPERM;
200d206e9c9SNaohiro Aota 
201d206e9c9SNaohiro Aota 	return 0;
202d206e9c9SNaohiro Aota }
203d206e9c9SNaohiro Aota 
20497fc2977SMiklos Szeredi /*
20597fc2977SMiklos Szeredi  * Set flags/xflags from the internal inode flags. The remaining items of
20697fc2977SMiklos Szeredi  * fsxattr are zeroed.
20797fc2977SMiklos Szeredi  */
20897fc2977SMiklos Szeredi int btrfs_fileattr_get(struct dentry *dentry, struct fileattr *fa)
2096cbff00fSChristoph Hellwig {
21097fc2977SMiklos Szeredi 	struct btrfs_inode *binode = BTRFS_I(d_inode(dentry));
21197fc2977SMiklos Szeredi 
21277eea05eSBoris Burkov 	fileattr_fill_flags(fa, btrfs_inode_flags_to_fsflags(binode));
21397fc2977SMiklos Szeredi 	return 0;
21497fc2977SMiklos Szeredi }
21597fc2977SMiklos Szeredi 
21697fc2977SMiklos Szeredi int btrfs_fileattr_set(struct user_namespace *mnt_userns,
21797fc2977SMiklos Szeredi 		       struct dentry *dentry, struct fileattr *fa)
21897fc2977SMiklos Szeredi {
21997fc2977SMiklos Szeredi 	struct inode *inode = d_inode(dentry);
2200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2215c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
2225c57b8b6SDavid Sterba 	struct btrfs_root *root = binode->root;
2236cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
2245aca2842SDarrick J. Wong 	unsigned int fsflags, old_fsflags;
2256cbff00fSChristoph Hellwig 	int ret;
226ff9fef55SAnand Jain 	const char *comp = NULL;
227f37c563bSDavid Sterba 	u32 binode_flags;
2286cbff00fSChristoph Hellwig 
229b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
230b83cc969SLi Zefan 		return -EROFS;
231b83cc969SLi Zefan 
23297fc2977SMiklos Szeredi 	if (fileattr_has_fsx(fa))
23397fc2977SMiklos Szeredi 		return -EOPNOTSUPP;
2346cbff00fSChristoph Hellwig 
23597fc2977SMiklos Szeredi 	fsflags = btrfs_mask_fsflags_for_type(inode, fa->flags);
23677eea05eSBoris Burkov 	old_fsflags = btrfs_inode_flags_to_fsflags(binode);
23797fc2977SMiklos Szeredi 	ret = check_fsflags(old_fsflags, fsflags);
238e7848683SJan Kara 	if (ret)
239e7848683SJan Kara 		return ret;
240e7848683SJan Kara 
241d206e9c9SNaohiro Aota 	ret = check_fsflags_compatible(fs_info, fsflags);
242d206e9c9SNaohiro Aota 	if (ret)
24397fc2977SMiklos Szeredi 		return ret;
244d206e9c9SNaohiro Aota 
245f37c563bSDavid Sterba 	binode_flags = binode->flags;
2465c57b8b6SDavid Sterba 	if (fsflags & FS_SYNC_FL)
247d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_SYNC;
2486cbff00fSChristoph Hellwig 	else
249d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_SYNC;
2505c57b8b6SDavid Sterba 	if (fsflags & FS_IMMUTABLE_FL)
251d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_IMMUTABLE;
2526cbff00fSChristoph Hellwig 	else
253d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_IMMUTABLE;
2545c57b8b6SDavid Sterba 	if (fsflags & FS_APPEND_FL)
255d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_APPEND;
2566cbff00fSChristoph Hellwig 	else
257d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_APPEND;
2585c57b8b6SDavid Sterba 	if (fsflags & FS_NODUMP_FL)
259d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NODUMP;
2606cbff00fSChristoph Hellwig 	else
261d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NODUMP;
2625c57b8b6SDavid Sterba 	if (fsflags & FS_NOATIME_FL)
263d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NOATIME;
2646cbff00fSChristoph Hellwig 	else
265d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NOATIME;
26697fc2977SMiklos Szeredi 
26797fc2977SMiklos Szeredi 	/* If coming from FS_IOC_FSSETXATTR then skip unconverted flags */
26897fc2977SMiklos Szeredi 	if (!fa->flags_valid) {
26997fc2977SMiklos Szeredi 		/* 1 item for the inode */
27097fc2977SMiklos Szeredi 		trans = btrfs_start_transaction(root, 1);
2719b8a233bSRitesh Harjani 		if (IS_ERR(trans))
2729b8a233bSRitesh Harjani 			return PTR_ERR(trans);
27397fc2977SMiklos Szeredi 		goto update_flags;
27497fc2977SMiklos Szeredi 	}
27597fc2977SMiklos Szeredi 
2765c57b8b6SDavid Sterba 	if (fsflags & FS_DIRSYNC_FL)
277d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_DIRSYNC;
2786cbff00fSChristoph Hellwig 	else
279d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_DIRSYNC;
2805c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOW_FL) {
28144e5194bSAnand Jain 		if (S_ISREG(inode->i_mode)) {
2827e97b8daSDavid Sterba 			/*
2837e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2847e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2857e97b8daSDavid Sterba 			 * status of the file and will not set it.
2867e97b8daSDavid Sterba 			 */
2877e97b8daSDavid Sterba 			if (inode->i_size == 0)
288d2b8fcfeSAnand Jain 				binode_flags |= BTRFS_INODE_NODATACOW |
289d2b8fcfeSAnand Jain 						BTRFS_INODE_NODATASUM;
2907e97b8daSDavid Sterba 		} else {
291d2b8fcfeSAnand Jain 			binode_flags |= BTRFS_INODE_NODATACOW;
2927e97b8daSDavid Sterba 		}
2937e97b8daSDavid Sterba 	} else {
2947e97b8daSDavid Sterba 		/*
29501327610SNicholas D Steeves 		 * Revert back under same assumptions as above
2967e97b8daSDavid Sterba 		 */
29744e5194bSAnand Jain 		if (S_ISREG(inode->i_mode)) {
2987e97b8daSDavid Sterba 			if (inode->i_size == 0)
299d2b8fcfeSAnand Jain 				binode_flags &= ~(BTRFS_INODE_NODATACOW |
300d2b8fcfeSAnand Jain 						  BTRFS_INODE_NODATASUM);
3017e97b8daSDavid Sterba 		} else {
302d2b8fcfeSAnand Jain 			binode_flags &= ~BTRFS_INODE_NODATACOW;
3037e97b8daSDavid Sterba 		}
3047e97b8daSDavid Sterba 	}
3056cbff00fSChristoph Hellwig 
30675e7cb7fSLiu Bo 	/*
30775e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
30875e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
30975e7cb7fSLiu Bo 	 * things smaller.
31075e7cb7fSLiu Bo 	 */
3115c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOMP_FL) {
312d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_COMPRESS;
313d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NOCOMPRESS;
3145c57b8b6SDavid Sterba 	} else if (fsflags & FS_COMPR_FL) {
31563541927SFilipe David Borba Manana 
31697fc2977SMiklos Szeredi 		if (IS_SWAPFILE(inode))
31797fc2977SMiklos Szeredi 			return -ETXTBSY;
318eede2bf3SOmar Sandoval 
319d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_COMPRESS;
320d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NOCOMPRESS;
32163541927SFilipe David Borba Manana 
32293370509SDavid Sterba 		comp = btrfs_compress_type2str(fs_info->compress_type);
32393370509SDavid Sterba 		if (!comp || comp[0] == 0)
32493370509SDavid Sterba 			comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
325ebcb904dSLi Zefan 	} else {
326d2b8fcfeSAnand Jain 		binode_flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
32775e7cb7fSLiu Bo 	}
3286cbff00fSChristoph Hellwig 
329ff9fef55SAnand Jain 	/*
330ff9fef55SAnand Jain 	 * 1 for inode item
331ff9fef55SAnand Jain 	 * 2 for properties
332ff9fef55SAnand Jain 	 */
333ff9fef55SAnand Jain 	trans = btrfs_start_transaction(root, 3);
33497fc2977SMiklos Szeredi 	if (IS_ERR(trans))
33597fc2977SMiklos Szeredi 		return PTR_ERR(trans);
3366cbff00fSChristoph Hellwig 
337ff9fef55SAnand Jain 	if (comp) {
338ff9fef55SAnand Jain 		ret = btrfs_set_prop(trans, inode, "btrfs.compression", comp,
339ff9fef55SAnand Jain 				     strlen(comp), 0);
340ff9fef55SAnand Jain 		if (ret) {
341ff9fef55SAnand Jain 			btrfs_abort_transaction(trans, ret);
342ff9fef55SAnand Jain 			goto out_end_trans;
343ff9fef55SAnand Jain 		}
344ff9fef55SAnand Jain 	} else {
345ff9fef55SAnand Jain 		ret = btrfs_set_prop(trans, inode, "btrfs.compression", NULL,
346ff9fef55SAnand Jain 				     0, 0);
347ff9fef55SAnand Jain 		if (ret && ret != -ENODATA) {
348ff9fef55SAnand Jain 			btrfs_abort_transaction(trans, ret);
349ff9fef55SAnand Jain 			goto out_end_trans;
350ff9fef55SAnand Jain 		}
351ff9fef55SAnand Jain 	}
352ff9fef55SAnand Jain 
35397fc2977SMiklos Szeredi update_flags:
354d2b8fcfeSAnand Jain 	binode->flags = binode_flags;
3557b6a221eSDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
3560c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
357c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3589a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3596cbff00fSChristoph Hellwig 
360ff9fef55SAnand Jain  out_end_trans:
3613a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
3622d4e6f6aSliubo 	return ret;
3636cbff00fSChristoph Hellwig }
3646cbff00fSChristoph Hellwig 
3650d7ed32cSDavid Sterba /*
3660d7ed32cSDavid Sterba  * Start exclusive operation @type, return true on success
3670d7ed32cSDavid Sterba  */
368c3e1f96cSGoldwyn Rodrigues bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
369c3e1f96cSGoldwyn Rodrigues 			enum btrfs_exclusive_operation type)
370c3e1f96cSGoldwyn Rodrigues {
3710d7ed32cSDavid Sterba 	bool ret = false;
3720d7ed32cSDavid Sterba 
3730d7ed32cSDavid Sterba 	spin_lock(&fs_info->super_lock);
3740d7ed32cSDavid Sterba 	if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
3750d7ed32cSDavid Sterba 		fs_info->exclusive_operation = type;
3760d7ed32cSDavid Sterba 		ret = true;
3770d7ed32cSDavid Sterba 	}
3780d7ed32cSDavid Sterba 	spin_unlock(&fs_info->super_lock);
3790d7ed32cSDavid Sterba 
3800d7ed32cSDavid Sterba 	return ret;
381c3e1f96cSGoldwyn Rodrigues }
382c3e1f96cSGoldwyn Rodrigues 
383578bda9eSDavid Sterba /*
384578bda9eSDavid Sterba  * Conditionally allow to enter the exclusive operation in case it's compatible
385578bda9eSDavid Sterba  * with the running one.  This must be paired with btrfs_exclop_start_unlock and
386578bda9eSDavid Sterba  * btrfs_exclop_finish.
387578bda9eSDavid Sterba  *
388578bda9eSDavid Sterba  * Compatibility:
389578bda9eSDavid Sterba  * - the same type is already running
390578bda9eSDavid Sterba  * - not BTRFS_EXCLOP_NONE - this is intentionally incompatible and the caller
391578bda9eSDavid Sterba  *   must check the condition first that would allow none -> @type
392578bda9eSDavid Sterba  */
393578bda9eSDavid Sterba bool btrfs_exclop_start_try_lock(struct btrfs_fs_info *fs_info,
394578bda9eSDavid Sterba 				 enum btrfs_exclusive_operation type)
395578bda9eSDavid Sterba {
396578bda9eSDavid Sterba 	spin_lock(&fs_info->super_lock);
397578bda9eSDavid Sterba 	if (fs_info->exclusive_operation == type)
398578bda9eSDavid Sterba 		return true;
399578bda9eSDavid Sterba 
400578bda9eSDavid Sterba 	spin_unlock(&fs_info->super_lock);
401578bda9eSDavid Sterba 	return false;
402578bda9eSDavid Sterba }
403578bda9eSDavid Sterba 
404578bda9eSDavid Sterba void btrfs_exclop_start_unlock(struct btrfs_fs_info *fs_info)
405578bda9eSDavid Sterba {
406578bda9eSDavid Sterba 	spin_unlock(&fs_info->super_lock);
407578bda9eSDavid Sterba }
408578bda9eSDavid Sterba 
409c3e1f96cSGoldwyn Rodrigues void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
410c3e1f96cSGoldwyn Rodrigues {
4110d7ed32cSDavid Sterba 	spin_lock(&fs_info->super_lock);
412c3e1f96cSGoldwyn Rodrigues 	WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
4130d7ed32cSDavid Sterba 	spin_unlock(&fs_info->super_lock);
41466a2823cSGoldwyn Rodrigues 	sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
415c3e1f96cSGoldwyn Rodrigues }
416c3e1f96cSGoldwyn Rodrigues 
417*efc0e69cSNikolay Borisov void btrfs_exclop_balance(struct btrfs_fs_info *fs_info,
418*efc0e69cSNikolay Borisov 			  enum btrfs_exclusive_operation op)
419*efc0e69cSNikolay Borisov {
420*efc0e69cSNikolay Borisov 	switch (op) {
421*efc0e69cSNikolay Borisov 	case BTRFS_EXCLOP_BALANCE_PAUSED:
422*efc0e69cSNikolay Borisov 		spin_lock(&fs_info->super_lock);
423*efc0e69cSNikolay Borisov 		ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE ||
424*efc0e69cSNikolay Borisov 		       fs_info->exclusive_operation == BTRFS_EXCLOP_DEV_ADD);
425*efc0e69cSNikolay Borisov 		fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE_PAUSED;
426*efc0e69cSNikolay Borisov 		spin_unlock(&fs_info->super_lock);
427*efc0e69cSNikolay Borisov 		break;
428*efc0e69cSNikolay Borisov 	case BTRFS_EXCLOP_BALANCE:
429*efc0e69cSNikolay Borisov 		spin_lock(&fs_info->super_lock);
430*efc0e69cSNikolay Borisov 		ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED);
431*efc0e69cSNikolay Borisov 		fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
432*efc0e69cSNikolay Borisov 		spin_unlock(&fs_info->super_lock);
433*efc0e69cSNikolay Borisov 		break;
434*efc0e69cSNikolay Borisov 	default:
435*efc0e69cSNikolay Borisov 		btrfs_warn(fs_info,
436*efc0e69cSNikolay Borisov 			"invalid exclop balance operation %d requested", op);
437*efc0e69cSNikolay Borisov 	}
438*efc0e69cSNikolay Borisov }
439*efc0e69cSNikolay Borisov 
4406cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
4416cbff00fSChristoph Hellwig {
442496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4436cbff00fSChristoph Hellwig 
4446cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
4456cbff00fSChristoph Hellwig }
446f46b5a66SChristoph Hellwig 
447b929c1d8SMarcos Paulo de Souza static noinline int btrfs_ioctl_fitrim(struct btrfs_fs_info *fs_info,
448b929c1d8SMarcos Paulo de Souza 					void __user *arg)
449f7039b1dSLi Dongyang {
450f7039b1dSLi Dongyang 	struct btrfs_device *device;
451f7039b1dSLi Dongyang 	struct request_queue *q;
452f7039b1dSLi Dongyang 	struct fstrim_range range;
453f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
454f7039b1dSLi Dongyang 	u64 num_devices = 0;
455f7039b1dSLi Dongyang 	int ret;
456f7039b1dSLi Dongyang 
457f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
458f7039b1dSLi Dongyang 		return -EPERM;
459f7039b1dSLi Dongyang 
460f35f06c3SFilipe Manana 	/*
4611cb3dc3fSNaohiro Aota 	 * btrfs_trim_block_group() depends on space cache, which is not
4621cb3dc3fSNaohiro Aota 	 * available in zoned filesystem. So, disallow fitrim on a zoned
4631cb3dc3fSNaohiro Aota 	 * filesystem for now.
4641cb3dc3fSNaohiro Aota 	 */
4651cb3dc3fSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
4661cb3dc3fSNaohiro Aota 		return -EOPNOTSUPP;
4671cb3dc3fSNaohiro Aota 
4681cb3dc3fSNaohiro Aota 	/*
469f35f06c3SFilipe Manana 	 * If the fs is mounted with nologreplay, which requires it to be
470f35f06c3SFilipe Manana 	 * mounted in RO mode as well, we can not allow discard on free space
471f35f06c3SFilipe Manana 	 * inside block groups, because log trees refer to extents that are not
472f35f06c3SFilipe Manana 	 * pinned in a block group's free space cache (pinning the extents is
473f35f06c3SFilipe Manana 	 * precisely the first phase of replaying a log tree).
474f35f06c3SFilipe Manana 	 */
475f35f06c3SFilipe Manana 	if (btrfs_test_opt(fs_info, NOLOGREPLAY))
476f35f06c3SFilipe Manana 		return -EROFS;
477f35f06c3SFilipe Manana 
4781f78160cSXiao Guangrong 	rcu_read_lock();
4791f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
4801f78160cSXiao Guangrong 				dev_list) {
481f7039b1dSLi Dongyang 		if (!device->bdev)
482f7039b1dSLi Dongyang 			continue;
483f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
484f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
485f7039b1dSLi Dongyang 			num_devices++;
48650d0446eSSeraphime Kirkovski 			minlen = min_t(u64, q->limits.discard_granularity,
487f7039b1dSLi Dongyang 				     minlen);
488f7039b1dSLi Dongyang 		}
489f7039b1dSLi Dongyang 	}
4901f78160cSXiao Guangrong 	rcu_read_unlock();
491f4c697e6SLukas Czerner 
492f7039b1dSLi Dongyang 	if (!num_devices)
493f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
494f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
495f7039b1dSLi Dongyang 		return -EFAULT;
4966ba9fc8eSQu Wenruo 
4976ba9fc8eSQu Wenruo 	/*
4986ba9fc8eSQu Wenruo 	 * NOTE: Don't truncate the range using super->total_bytes.  Bytenr of
4996ba9fc8eSQu Wenruo 	 * block group is in the logical address space, which can be any
5006ba9fc8eSQu Wenruo 	 * sectorsize aligned bytenr in  the range [0, U64_MAX].
5016ba9fc8eSQu Wenruo 	 */
5026ba9fc8eSQu Wenruo 	if (range.len < fs_info->sb->s_blocksize)
503f4c697e6SLukas Czerner 		return -EINVAL;
504f7039b1dSLi Dongyang 
505f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
5062ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
507f7039b1dSLi Dongyang 	if (ret < 0)
508f7039b1dSLi Dongyang 		return ret;
509f7039b1dSLi Dongyang 
510f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
511f7039b1dSLi Dongyang 		return -EFAULT;
512f7039b1dSLi Dongyang 
513f7039b1dSLi Dongyang 	return 0;
514f7039b1dSLi Dongyang }
515f7039b1dSLi Dongyang 
516e1f60a65SDavid Sterba int __pure btrfs_is_empty_uuid(u8 *uuid)
517dd5f9615SStefan Behrens {
51846e0f66aSChris Mason 	int i;
51946e0f66aSChris Mason 
52046e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
52146e0f66aSChris Mason 		if (uuid[i])
52246e0f66aSChris Mason 			return 0;
52346e0f66aSChris Mason 	}
52446e0f66aSChris Mason 	return 1;
525dd5f9615SStefan Behrens }
526dd5f9615SStefan Behrens 
5274d4340c9SChristian Brauner static noinline int create_subvol(struct user_namespace *mnt_userns,
5284d4340c9SChristian Brauner 				  struct inode *dir, struct dentry *dentry,
52952f75f4fSDavid Sterba 				  const char *name, int namelen,
5308696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
531f46b5a66SChristoph Hellwig {
5320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
533f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
534f46b5a66SChristoph Hellwig 	struct btrfs_key key;
53549a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
536f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
537f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
538d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
53976dda93cSYan, Zheng 	struct btrfs_root *new_root;
540d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
54195582b00SDeepa Dinamani 	struct timespec64 cur_time = current_time(dir);
5425662344bSTsutomu Itoh 	struct inode *inode;
543f46b5a66SChristoph Hellwig 	int ret;
544f46b5a66SChristoph Hellwig 	int err;
5452dfb1e43SQu Wenruo 	dev_t anon_dev = 0;
546f46b5a66SChristoph Hellwig 	u64 objectid;
5473de4586cSChris Mason 	u64 index = 0;
548f46b5a66SChristoph Hellwig 
54949a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
55049a3c4d9SDavid Sterba 	if (!root_item)
55149a3c4d9SDavid Sterba 		return -ENOMEM;
55249a3c4d9SDavid Sterba 
553543068a2SNikolay Borisov 	ret = btrfs_get_free_objectid(fs_info->tree_root, &objectid);
5542fbe8c8aSAl Viro 	if (ret)
55549a3c4d9SDavid Sterba 		goto fail_free;
5566a912213SJosef Bacik 
5572dfb1e43SQu Wenruo 	ret = get_anon_bdev(&anon_dev);
5582dfb1e43SQu Wenruo 	if (ret < 0)
5592dfb1e43SQu Wenruo 		goto fail_free;
5602dfb1e43SQu Wenruo 
561e09fe2d2SQu Wenruo 	/*
562e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
56301327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
564e09fe2d2SQu Wenruo 	 */
56549a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
56649a3c4d9SDavid Sterba 		ret = -ENOSPC;
56749a3c4d9SDavid Sterba 		goto fail_free;
56849a3c4d9SDavid Sterba 	}
569e09fe2d2SQu Wenruo 
570d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
5719ed74f2dSJosef Bacik 	/*
572d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
573d5c12070SMiao Xie 	 * of create_snapshot().
5749ed74f2dSJosef Bacik 	 */
575c4c129dbSGu JinXiang 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
576d5c12070SMiao Xie 	if (ret)
57749a3c4d9SDavid Sterba 		goto fail_free;
578f46b5a66SChristoph Hellwig 
579d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
580d5c12070SMiao Xie 	if (IS_ERR(trans)) {
581d5c12070SMiao Xie 		ret = PTR_ERR(trans);
582e85fde51SQu Wenruo 		btrfs_subvolume_release_metadata(root, &block_rsv);
58349a3c4d9SDavid Sterba 		goto fail_free;
584d5c12070SMiao Xie 	}
585d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
586d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
587f46b5a66SChristoph Hellwig 
588a9377422SLu Fengqi 	ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
5896f72c7e2SArne Jansen 	if (ret)
5906f72c7e2SArne Jansen 		goto fail;
5916f72c7e2SArne Jansen 
5929631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
5939631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
5948e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
5958e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
5968e8a1e31SJosef Bacik 		goto fail;
5978e8a1e31SJosef Bacik 	}
598f46b5a66SChristoph Hellwig 
599f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
600f46b5a66SChristoph Hellwig 
60149a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
6023cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
6033cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
6043cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
605da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
6060b246afaSJeff Mahoney 				     fs_info->nodesize);
6073cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
608f46b5a66SChristoph Hellwig 
60949a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
61049a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
6113cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
61208fe4db1SLi Zefan 
61349a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
61449a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
61549a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
61649a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
61749a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
61849a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
619f46b5a66SChristoph Hellwig 
62049a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
62149a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
622807fc790SAndy Shevchenko 	generate_random_guid(root_item->uuid);
62349a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
62449a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
62549a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
62649a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
62749a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
628f46b5a66SChristoph Hellwig 
629925baeddSChris Mason 	btrfs_tree_unlock(leaf);
630f46b5a66SChristoph Hellwig 
63169948022SNikolay Borisov 	btrfs_set_root_dirid(root_item, BTRFS_FIRST_FREE_OBJECTID);
632f46b5a66SChristoph Hellwig 
633f46b5a66SChristoph Hellwig 	key.objectid = objectid;
6345d4f98a2SYan Zheng 	key.offset = 0;
635962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
6360b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
63749a3c4d9SDavid Sterba 				root_item);
63867addf29SFilipe Manana 	if (ret) {
63967addf29SFilipe Manana 		/*
64067addf29SFilipe Manana 		 * Since we don't abort the transaction in this case, free the
64167addf29SFilipe Manana 		 * tree block so that we don't leak space and leave the
64267addf29SFilipe Manana 		 * filesystem in an inconsistent state (an extent item in the
6437a163608SFilipe Manana 		 * extent tree with a backreference for a root that does not
644212a58fdSFilipe Manana 		 * exists).
64567addf29SFilipe Manana 		 */
646212a58fdSFilipe Manana 		btrfs_tree_lock(leaf);
647212a58fdSFilipe Manana 		btrfs_clean_tree_block(leaf);
648212a58fdSFilipe Manana 		btrfs_tree_unlock(leaf);
6497a163608SFilipe Manana 		btrfs_free_tree_block(trans, objectid, leaf, 0, 1);
65067addf29SFilipe Manana 		free_extent_buffer(leaf);
651f46b5a66SChristoph Hellwig 		goto fail;
65267addf29SFilipe Manana 	}
65367addf29SFilipe Manana 
65467addf29SFilipe Manana 	free_extent_buffer(leaf);
65567addf29SFilipe Manana 	leaf = NULL;
656f46b5a66SChristoph Hellwig 
65776dda93cSYan, Zheng 	key.offset = (u64)-1;
6582dfb1e43SQu Wenruo 	new_root = btrfs_get_new_fs_root(fs_info, objectid, anon_dev);
65979787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
6602dfb1e43SQu Wenruo 		free_anon_bdev(anon_dev);
66179787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
66266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
66379787eaaSJeff Mahoney 		goto fail;
66479787eaaSJeff Mahoney 	}
6652dfb1e43SQu Wenruo 	/* Freeing will be done in btrfs_put_root() of new_root */
6662dfb1e43SQu Wenruo 	anon_dev = 0;
66776dda93cSYan, Zheng 
668221581e4SJosef Bacik 	ret = btrfs_record_root_in_trans(trans, new_root);
669221581e4SJosef Bacik 	if (ret) {
670221581e4SJosef Bacik 		btrfs_put_root(new_root);
671221581e4SJosef Bacik 		btrfs_abort_transaction(trans, ret);
672221581e4SJosef Bacik 		goto fail;
673221581e4SJosef Bacik 	}
67476dda93cSYan, Zheng 
6754d4340c9SChristian Brauner 	ret = btrfs_create_subvol_root(trans, new_root, root, mnt_userns);
67600246528SJosef Bacik 	btrfs_put_root(new_root);
677ce598979SMark Fasheh 	if (ret) {
678ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
67966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
680ce598979SMark Fasheh 		goto fail;
681ce598979SMark Fasheh 	}
682ce598979SMark Fasheh 
683f46b5a66SChristoph Hellwig 	/*
684f46b5a66SChristoph Hellwig 	 * insert the directory item
685f46b5a66SChristoph Hellwig 	 */
686877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
68779787eaaSJeff Mahoney 	if (ret) {
68866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
68979787eaaSJeff Mahoney 		goto fail;
69079787eaaSJeff Mahoney 	}
6913de4586cSChris Mason 
692684572dfSLu Fengqi 	ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
6933de4586cSChris Mason 				    BTRFS_FT_DIR, index);
69479787eaaSJeff Mahoney 	if (ret) {
69566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
696f46b5a66SChristoph Hellwig 		goto fail;
69779787eaaSJeff Mahoney 	}
6980660b5afSChris Mason 
6996ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
7009a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
701c7e54b51SJosef Bacik 	if (ret) {
702c7e54b51SJosef Bacik 		btrfs_abort_transaction(trans, ret);
703c7e54b51SJosef Bacik 		goto fail;
704c7e54b51SJosef Bacik 	}
70552c26179SYan Zheng 
7066025c19fSLu Fengqi 	ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
7074a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
708c7e54b51SJosef Bacik 	if (ret) {
709c7e54b51SJosef Bacik 		btrfs_abort_transaction(trans, ret);
710c7e54b51SJosef Bacik 		goto fail;
711c7e54b51SJosef Bacik 	}
7120660b5afSChris Mason 
713cdb345a8SLu Fengqi 	ret = btrfs_uuid_tree_add(trans, root_item->uuid,
7146bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
715dd5f9615SStefan Behrens 	if (ret)
71666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
717dd5f9615SStefan Behrens 
718f46b5a66SChristoph Hellwig fail:
71949a3c4d9SDavid Sterba 	kfree(root_item);
720d5c12070SMiao Xie 	trans->block_rsv = NULL;
721d5c12070SMiao Xie 	trans->bytes_reserved = 0;
722e85fde51SQu Wenruo 	btrfs_subvolume_release_metadata(root, &block_rsv);
723de6e8200SLiu Bo 
7243a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
725f46b5a66SChristoph Hellwig 	if (err && !ret)
726f46b5a66SChristoph Hellwig 		ret = err;
7271a65e24bSChris Mason 
7285662344bSTsutomu Itoh 	if (!ret) {
7295662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
730de6e8200SLiu Bo 		if (IS_ERR(inode))
731de6e8200SLiu Bo 			return PTR_ERR(inode);
7325662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
7335662344bSTsutomu Itoh 	}
734f46b5a66SChristoph Hellwig 	return ret;
73549a3c4d9SDavid Sterba 
73649a3c4d9SDavid Sterba fail_free:
7372dfb1e43SQu Wenruo 	if (anon_dev)
7382dfb1e43SQu Wenruo 		free_anon_bdev(anon_dev);
73949a3c4d9SDavid Sterba 	kfree(root_item);
74049a3c4d9SDavid Sterba 	return ret;
741f46b5a66SChristoph Hellwig }
742f46b5a66SChristoph Hellwig 
743e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
7449babda9fSNikolay Borisov 			   struct dentry *dentry, bool readonly,
745e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
746f46b5a66SChristoph Hellwig {
7470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
7482e4bfab9SYan, Zheng 	struct inode *inode;
749f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
750f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
7512e4bfab9SYan, Zheng 	int ret;
752f46b5a66SChristoph Hellwig 
75392a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
754f46b5a66SChristoph Hellwig 		return -EINVAL;
755f46b5a66SChristoph Hellwig 
756eede2bf3SOmar Sandoval 	if (atomic_read(&root->nr_swapfiles)) {
757eede2bf3SOmar Sandoval 		btrfs_warn(fs_info,
758eede2bf3SOmar Sandoval 			   "cannot snapshot subvolume with active swapfile");
759eede2bf3SOmar Sandoval 		return -ETXTBSY;
760eede2bf3SOmar Sandoval 	}
761eede2bf3SOmar Sandoval 
76223269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
763a1ee7362SDavid Sterba 	if (!pending_snapshot)
764a1ee7362SDavid Sterba 		return -ENOMEM;
765a1ee7362SDavid Sterba 
7662dfb1e43SQu Wenruo 	ret = get_anon_bdev(&pending_snapshot->anon_dev);
7672dfb1e43SQu Wenruo 	if (ret < 0)
7682dfb1e43SQu Wenruo 		goto free_pending;
769b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
77023269bf5SDavid Sterba 			GFP_KERNEL);
7718546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
7728546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
773b0c0ea63SDavid Sterba 		ret = -ENOMEM;
774b0c0ea63SDavid Sterba 		goto free_pending;
775b0c0ea63SDavid Sterba 	}
776b0c0ea63SDavid Sterba 
77766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
77866d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
779d5c12070SMiao Xie 	/*
780d5c12070SMiao Xie 	 * 1 - parent dir inode
781d5c12070SMiao Xie 	 * 2 - dir entries
782d5c12070SMiao Xie 	 * 1 - root item
783d5c12070SMiao Xie 	 * 2 - root ref/backref
784d5c12070SMiao Xie 	 * 1 - root of snapshot
785dd5f9615SStefan Behrens 	 * 1 - UUID item
786d5c12070SMiao Xie 	 */
787d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
788dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
789ee3441b4SJeff Mahoney 					false);
790d5c12070SMiao Xie 	if (ret)
791c11fbb6eSRobbie Ko 		goto free_pending;
792d5c12070SMiao Xie 
793a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
794a22285a6SYan, Zheng 	pending_snapshot->root = root;
795b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
796e9662f70SMiao Xie 	pending_snapshot->dir = dir;
7978696c533SMiao Xie 	pending_snapshot->inherit = inherit;
798a22285a6SYan, Zheng 
799d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
800a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
801a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
802a22285a6SYan, Zheng 		goto fail;
803a22285a6SYan, Zheng 	}
804a22285a6SYan, Zheng 
8050b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
806a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
807a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
8080b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
8099babda9fSNikolay Borisov 
8103a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
811aec8030aSMiao Xie 	if (ret)
812c37b2b62SJosef Bacik 		goto fail;
813a22285a6SYan, Zheng 
814a22285a6SYan, Zheng 	ret = pending_snapshot->error;
815f46b5a66SChristoph Hellwig 	if (ret)
8162e4bfab9SYan, Zheng 		goto fail;
817f46b5a66SChristoph Hellwig 
818d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
819d3797308SChris Mason 	if (ret)
820d3797308SChris Mason 		goto fail;
821d3797308SChris Mason 
8222b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
8232e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
8242e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
8252e4bfab9SYan, Zheng 		goto fail;
8262e4bfab9SYan, Zheng 	}
8275662344bSTsutomu Itoh 
8282e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
8292e4bfab9SYan, Zheng 	ret = 0;
8302dfb1e43SQu Wenruo 	pending_snapshot->anon_dev = 0;
8312e4bfab9SYan, Zheng fail:
8322dfb1e43SQu Wenruo 	/* Prevent double freeing of anon_dev */
8332dfb1e43SQu Wenruo 	if (ret && pending_snapshot->snap)
8342dfb1e43SQu Wenruo 		pending_snapshot->snap->anon_dev = 0;
83500246528SJosef Bacik 	btrfs_put_root(pending_snapshot->snap);
836e85fde51SQu Wenruo 	btrfs_subvolume_release_metadata(root, &pending_snapshot->block_rsv);
837b0c0ea63SDavid Sterba free_pending:
8382dfb1e43SQu Wenruo 	if (pending_snapshot->anon_dev)
8392dfb1e43SQu Wenruo 		free_anon_bdev(pending_snapshot->anon_dev);
840b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
8418546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
842a1ee7362SDavid Sterba 	kfree(pending_snapshot);
843a1ee7362SDavid Sterba 
844f46b5a66SChristoph Hellwig 	return ret;
845f46b5a66SChristoph Hellwig }
846f46b5a66SChristoph Hellwig 
8474260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
8484260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
8494260f7c7SSage Weil  *  whether the type of victim is right.
8504260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
8514260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
8524260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
8534260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
8544260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
8554260f7c7SSage Weil  *	a. be owner of dir, or
8564260f7c7SSage Weil  *	b. be owner of victim, or
8574260f7c7SSage Weil  *	c. have CAP_FOWNER capability
85801327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
8594260f7c7SSage Weil  *     links pointing to it.
8604260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
8614260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
8624260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
8634260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
8644260f7c7SSage Weil  *     nfs_async_unlink().
8654260f7c7SSage Weil  */
8664260f7c7SSage Weil 
867c4ed533bSChristian Brauner static int btrfs_may_delete(struct user_namespace *mnt_userns,
868c4ed533bSChristian Brauner 			    struct inode *dir, struct dentry *victim, int isdir)
8694260f7c7SSage Weil {
8704260f7c7SSage Weil 	int error;
8714260f7c7SSage Weil 
8722b0143b5SDavid Howells 	if (d_really_is_negative(victim))
8734260f7c7SSage Weil 		return -ENOENT;
8744260f7c7SSage Weil 
8752b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
8764fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
8774260f7c7SSage Weil 
878c4ed533bSChristian Brauner 	error = inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
8794260f7c7SSage Weil 	if (error)
8804260f7c7SSage Weil 		return error;
8814260f7c7SSage Weil 	if (IS_APPEND(dir))
8824260f7c7SSage Weil 		return -EPERM;
883c4ed533bSChristian Brauner 	if (check_sticky(mnt_userns, dir, d_inode(victim)) ||
884ba73d987SChristian Brauner 	    IS_APPEND(d_inode(victim)) || IS_IMMUTABLE(d_inode(victim)) ||
885ba73d987SChristian Brauner 	    IS_SWAPFILE(d_inode(victim)))
8864260f7c7SSage Weil 		return -EPERM;
8874260f7c7SSage Weil 	if (isdir) {
888e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
8894260f7c7SSage Weil 			return -ENOTDIR;
8904260f7c7SSage Weil 		if (IS_ROOT(victim))
8914260f7c7SSage Weil 			return -EBUSY;
892e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
8934260f7c7SSage Weil 		return -EISDIR;
8944260f7c7SSage Weil 	if (IS_DEADDIR(dir))
8954260f7c7SSage Weil 		return -ENOENT;
8964260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
8974260f7c7SSage Weil 		return -EBUSY;
8984260f7c7SSage Weil 	return 0;
8994260f7c7SSage Weil }
9004260f7c7SSage Weil 
901cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
9024d4340c9SChristian Brauner static inline int btrfs_may_create(struct user_namespace *mnt_userns,
9034d4340c9SChristian Brauner 				   struct inode *dir, struct dentry *child)
904cb8e7090SChristoph Hellwig {
9052b0143b5SDavid Howells 	if (d_really_is_positive(child))
906cb8e7090SChristoph Hellwig 		return -EEXIST;
907cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
908cb8e7090SChristoph Hellwig 		return -ENOENT;
9094d4340c9SChristian Brauner 	if (!fsuidgid_has_mapping(dir->i_sb, mnt_userns))
9105474bf40SChristian Brauner 		return -EOVERFLOW;
9114d4340c9SChristian Brauner 	return inode_permission(mnt_userns, dir, MAY_WRITE | MAY_EXEC);
912cb8e7090SChristoph Hellwig }
913cb8e7090SChristoph Hellwig 
914cb8e7090SChristoph Hellwig /*
915cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
916cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
917cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
918cb8e7090SChristoph Hellwig  */
91992872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
9204d4340c9SChristian Brauner 				   struct user_namespace *mnt_userns,
92152f75f4fSDavid Sterba 				   const char *name, int namelen,
92272fd032eSSage Weil 				   struct btrfs_root *snap_src,
9239babda9fSNikolay Borisov 				   bool readonly,
9248696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
925cb8e7090SChristoph Hellwig {
9262b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
9270b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
928cb8e7090SChristoph Hellwig 	struct dentry *dentry;
929cb8e7090SChristoph Hellwig 	int error;
930cb8e7090SChristoph Hellwig 
93100235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
93200235411SAl Viro 	if (error == -EINTR)
93300235411SAl Viro 		return error;
934cb8e7090SChristoph Hellwig 
9354d4340c9SChristian Brauner 	dentry = lookup_one(mnt_userns, name, parent->dentry, namelen);
936cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
937cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
938cb8e7090SChristoph Hellwig 		goto out_unlock;
939cb8e7090SChristoph Hellwig 
9404d4340c9SChristian Brauner 	error = btrfs_may_create(mnt_userns, dir, dentry);
941cb8e7090SChristoph Hellwig 	if (error)
942a874a63eSLiu Bo 		goto out_dput;
943cb8e7090SChristoph Hellwig 
9449c52057cSChris Mason 	/*
9459c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
9469c52057cSChris Mason 	 * check for them now when we can safely fail
9479c52057cSChris Mason 	 */
9489c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
9499c52057cSChris Mason 					       dir->i_ino, name,
9509c52057cSChris Mason 					       namelen);
9519c52057cSChris Mason 	if (error)
9529c52057cSChris Mason 		goto out_dput;
9539c52057cSChris Mason 
9540b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
95576dda93cSYan, Zheng 
95676dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
95776dda93cSYan, Zheng 		goto out_up_read;
95876dda93cSYan, Zheng 
9599babda9fSNikolay Borisov 	if (snap_src)
9609babda9fSNikolay Borisov 		error = create_snapshot(snap_src, dir, dentry, readonly, inherit);
9619babda9fSNikolay Borisov 	else
9624d4340c9SChristian Brauner 		error = create_subvol(mnt_userns, dir, dentry, name, namelen, inherit);
9639babda9fSNikolay Borisov 
96476dda93cSYan, Zheng 	if (!error)
96576dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
96676dda93cSYan, Zheng out_up_read:
9670b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
968cb8e7090SChristoph Hellwig out_dput:
969cb8e7090SChristoph Hellwig 	dput(dentry);
970cb8e7090SChristoph Hellwig out_unlock:
97164708539SJosef Bacik 	btrfs_inode_unlock(dir, 0);
972cb8e7090SChristoph Hellwig 	return error;
973cb8e7090SChristoph Hellwig }
974cb8e7090SChristoph Hellwig 
975c11fbb6eSRobbie Ko static noinline int btrfs_mksnapshot(const struct path *parent,
9764d4340c9SChristian Brauner 				   struct user_namespace *mnt_userns,
977c11fbb6eSRobbie Ko 				   const char *name, int namelen,
978c11fbb6eSRobbie Ko 				   struct btrfs_root *root,
979c11fbb6eSRobbie Ko 				   bool readonly,
980c11fbb6eSRobbie Ko 				   struct btrfs_qgroup_inherit *inherit)
981c11fbb6eSRobbie Ko {
982c11fbb6eSRobbie Ko 	int ret;
983c11fbb6eSRobbie Ko 	bool snapshot_force_cow = false;
984c11fbb6eSRobbie Ko 
985c11fbb6eSRobbie Ko 	/*
986c11fbb6eSRobbie Ko 	 * Force new buffered writes to reserve space even when NOCOW is
987c11fbb6eSRobbie Ko 	 * possible. This is to avoid later writeback (running dealloc) to
988c11fbb6eSRobbie Ko 	 * fallback to COW mode and unexpectedly fail with ENOSPC.
989c11fbb6eSRobbie Ko 	 */
990c11fbb6eSRobbie Ko 	btrfs_drew_read_lock(&root->snapshot_lock);
991c11fbb6eSRobbie Ko 
992f9baa501SFilipe Manana 	ret = btrfs_start_delalloc_snapshot(root, false);
993c11fbb6eSRobbie Ko 	if (ret)
994c11fbb6eSRobbie Ko 		goto out;
995c11fbb6eSRobbie Ko 
996c11fbb6eSRobbie Ko 	/*
997c11fbb6eSRobbie Ko 	 * All previous writes have started writeback in NOCOW mode, so now
998c11fbb6eSRobbie Ko 	 * we force future writes to fallback to COW mode during snapshot
999c11fbb6eSRobbie Ko 	 * creation.
1000c11fbb6eSRobbie Ko 	 */
1001c11fbb6eSRobbie Ko 	atomic_inc(&root->snapshot_force_cow);
1002c11fbb6eSRobbie Ko 	snapshot_force_cow = true;
1003c11fbb6eSRobbie Ko 
1004c11fbb6eSRobbie Ko 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
1005c11fbb6eSRobbie Ko 
10064d4340c9SChristian Brauner 	ret = btrfs_mksubvol(parent, mnt_userns, name, namelen,
1007c11fbb6eSRobbie Ko 			     root, readonly, inherit);
1008c11fbb6eSRobbie Ko out:
1009c11fbb6eSRobbie Ko 	if (snapshot_force_cow)
1010c11fbb6eSRobbie Ko 		atomic_dec(&root->snapshot_force_cow);
1011c11fbb6eSRobbie Ko 	btrfs_drew_read_unlock(&root->snapshot_lock);
1012c11fbb6eSRobbie Ko 	return ret;
1013c11fbb6eSRobbie Ko }
1014c11fbb6eSRobbie Ko 
1015e9eec721SQu Wenruo static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start,
1016e9eec721SQu Wenruo 					       bool locked)
101717ce6ef8SLiu Bo {
101817ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1019940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10206c282eb4SLi Zefan 	struct extent_map *em;
102176068caeSQu Wenruo 	const u32 sectorsize = BTRFS_I(inode)->root->fs_info->sectorsize;
1022940100a4SChris Mason 
1023940100a4SChris Mason 	/*
1024940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
1025940100a4SChris Mason 	 * the full extent lock
1026940100a4SChris Mason 	 */
1027940100a4SChris Mason 	read_lock(&em_tree->lock);
102876068caeSQu Wenruo 	em = lookup_extent_mapping(em_tree, start, sectorsize);
1029940100a4SChris Mason 	read_unlock(&em_tree->lock);
1030940100a4SChris Mason 
1031940100a4SChris Mason 	if (!em) {
1032308d9800SFilipe Manana 		struct extent_state *cached = NULL;
103376068caeSQu Wenruo 		u64 end = start + sectorsize - 1;
1034308d9800SFilipe Manana 
1035940100a4SChris Mason 		/* get the big lock and read metadata off disk */
1036e9eec721SQu Wenruo 		if (!locked)
1037ff13db41SDavid Sterba 			lock_extent_bits(io_tree, start, end, &cached);
103876068caeSQu Wenruo 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, sectorsize);
1039e9eec721SQu Wenruo 		if (!locked)
1040e43bbe5eSDavid Sterba 			unlock_extent_cached(io_tree, start, end, &cached);
1041940100a4SChris Mason 
10426cf8bfbfSDan Carpenter 		if (IS_ERR(em))
10436c282eb4SLi Zefan 			return NULL;
1044940100a4SChris Mason 	}
1045940100a4SChris Mason 
10466c282eb4SLi Zefan 	return em;
10476c282eb4SLi Zefan }
10486c282eb4SLi Zefan 
1049e9eec721SQu Wenruo static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em,
1050e9eec721SQu Wenruo 				     bool locked)
10516c282eb4SLi Zefan {
10526c282eb4SLi Zefan 	struct extent_map *next;
10536c282eb4SLi Zefan 	bool ret = true;
10546c282eb4SLi Zefan 
10556c282eb4SLi Zefan 	/* this is the last extent */
10566c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
10576c282eb4SLi Zefan 		return false;
10586c282eb4SLi Zefan 
1059e9eec721SQu Wenruo 	next = defrag_lookup_extent(inode, em->start + em->len, locked);
1060e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1061e9512d72SChris Mason 		ret = false;
1062e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1063ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
10646c282eb4SLi Zefan 		ret = false;
10656c282eb4SLi Zefan 
10666c282eb4SLi Zefan 	free_extent_map(next);
10676c282eb4SLi Zefan 	return ret;
10686c282eb4SLi Zefan }
10696c282eb4SLi Zefan 
10704cb5300bSChris Mason /*
10715767b50cSQu Wenruo  * Prepare one page to be defragged.
10725767b50cSQu Wenruo  *
10735767b50cSQu Wenruo  * This will ensure:
10745767b50cSQu Wenruo  *
10755767b50cSQu Wenruo  * - Returned page is locked and has been set up properly.
10765767b50cSQu Wenruo  * - No ordered extent exists in the page.
10775767b50cSQu Wenruo  * - The page is uptodate.
10785767b50cSQu Wenruo  *
10795767b50cSQu Wenruo  * NOTE: Caller should also wait for page writeback after the cluster is
10805767b50cSQu Wenruo  * prepared, here we don't do writeback wait for each page.
10815767b50cSQu Wenruo  */
10825767b50cSQu Wenruo static struct page *defrag_prepare_one_page(struct btrfs_inode *inode,
10835767b50cSQu Wenruo 					    pgoff_t index)
1084940100a4SChris Mason {
10855767b50cSQu Wenruo 	struct address_space *mapping = inode->vfs_inode.i_mapping;
10865767b50cSQu Wenruo 	gfp_t mask = btrfs_alloc_write_mask(mapping);
10875767b50cSQu Wenruo 	u64 page_start = (u64)index << PAGE_SHIFT;
10885767b50cSQu Wenruo 	u64 page_end = page_start + PAGE_SIZE - 1;
10894cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
10904cb5300bSChris Mason 	struct page *page;
10915767b50cSQu Wenruo 	int ret;
10925767b50cSQu Wenruo 
1093600a45e1SMiao Xie again:
10945767b50cSQu Wenruo 	page = find_or_create_page(mapping, index, mask);
10954cb5300bSChris Mason 	if (!page)
10965767b50cSQu Wenruo 		return ERR_PTR(-ENOMEM);
10975767b50cSQu Wenruo 
109824bcb454SOmar Sandoval 	/*
109924bcb454SOmar Sandoval 	 * Since we can defragment files opened read-only, we can encounter
110024bcb454SOmar Sandoval 	 * transparent huge pages here (see CONFIG_READ_ONLY_THP_FOR_FS). We
110124bcb454SOmar Sandoval 	 * can't do I/O using huge pages yet, so return an error for now.
110224bcb454SOmar Sandoval 	 * Filesystem transparent huge pages are typically only used for
110324bcb454SOmar Sandoval 	 * executables that explicitly enable them, so this isn't very
110424bcb454SOmar Sandoval 	 * restrictive.
110524bcb454SOmar Sandoval 	 */
110624bcb454SOmar Sandoval 	if (PageCompound(page)) {
110724bcb454SOmar Sandoval 		unlock_page(page);
110824bcb454SOmar Sandoval 		put_page(page);
110924bcb454SOmar Sandoval 		return ERR_PTR(-ETXTBSY);
111024bcb454SOmar Sandoval 	}
11114cb5300bSChris Mason 
111232443de3SQu Wenruo 	ret = set_page_extent_mapped(page);
111332443de3SQu Wenruo 	if (ret < 0) {
111432443de3SQu Wenruo 		unlock_page(page);
111532443de3SQu Wenruo 		put_page(page);
11165767b50cSQu Wenruo 		return ERR_PTR(ret);
111732443de3SQu Wenruo 	}
111832443de3SQu Wenruo 
11195767b50cSQu Wenruo 	/* Wait for any existing ordered extent in the range */
1120600a45e1SMiao Xie 	while (1) {
11215767b50cSQu Wenruo 		struct btrfs_ordered_extent *ordered;
11225767b50cSQu Wenruo 
11235767b50cSQu Wenruo 		lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
11245767b50cSQu Wenruo 		ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
11255767b50cSQu Wenruo 		unlock_extent_cached(&inode->io_tree, page_start, page_end,
1126e43bbe5eSDavid Sterba 				     &cached_state);
1127600a45e1SMiao Xie 		if (!ordered)
1128600a45e1SMiao Xie 			break;
1129600a45e1SMiao Xie 
1130600a45e1SMiao Xie 		unlock_page(page);
1131c0a43603SNikolay Borisov 		btrfs_start_ordered_extent(ordered, 1);
1132600a45e1SMiao Xie 		btrfs_put_ordered_extent(ordered);
1133600a45e1SMiao Xie 		lock_page(page);
11341f12bd06SLiu Bo 		/*
11355767b50cSQu Wenruo 		 * We unlocked the page above, so we need check if it was
11365767b50cSQu Wenruo 		 * released or not.
11371f12bd06SLiu Bo 		 */
11385767b50cSQu Wenruo 		if (page->mapping != mapping || !PagePrivate(page)) {
11391f12bd06SLiu Bo 			unlock_page(page);
114009cbfeafSKirill A. Shutemov 			put_page(page);
11411f12bd06SLiu Bo 			goto again;
11421f12bd06SLiu Bo 		}
1143600a45e1SMiao Xie 	}
1144600a45e1SMiao Xie 
11455767b50cSQu Wenruo 	/*
11465767b50cSQu Wenruo 	 * Now the page range has no ordered extent any more.  Read the page to
11475767b50cSQu Wenruo 	 * make it uptodate.
11485767b50cSQu Wenruo 	 */
11494cb5300bSChris Mason 	if (!PageUptodate(page)) {
11504cb5300bSChris Mason 		btrfs_readpage(NULL, page);
11514cb5300bSChris Mason 		lock_page(page);
11525767b50cSQu Wenruo 		if (page->mapping != mapping || !PagePrivate(page)) {
1153600a45e1SMiao Xie 			unlock_page(page);
115409cbfeafSKirill A. Shutemov 			put_page(page);
1155600a45e1SMiao Xie 			goto again;
1156600a45e1SMiao Xie 		}
11575767b50cSQu Wenruo 		if (!PageUptodate(page)) {
11585767b50cSQu Wenruo 			unlock_page(page);
11595767b50cSQu Wenruo 			put_page(page);
11605767b50cSQu Wenruo 			return ERR_PTR(-EIO);
11614cb5300bSChris Mason 		}
11625767b50cSQu Wenruo 	}
11635767b50cSQu Wenruo 	return page;
11645767b50cSQu Wenruo }
11654cb5300bSChris Mason 
1166eb793cf8SQu Wenruo struct defrag_target_range {
1167eb793cf8SQu Wenruo 	struct list_head list;
1168eb793cf8SQu Wenruo 	u64 start;
1169eb793cf8SQu Wenruo 	u64 len;
1170eb793cf8SQu Wenruo };
11714cb5300bSChris Mason 
11724cb5300bSChris Mason /*
1173eb793cf8SQu Wenruo  * Collect all valid target extents.
1174eb793cf8SQu Wenruo  *
1175eb793cf8SQu Wenruo  * @start:	   file offset to lookup
1176eb793cf8SQu Wenruo  * @len:	   length to lookup
1177eb793cf8SQu Wenruo  * @extent_thresh: file extent size threshold, any extent size >= this value
1178eb793cf8SQu Wenruo  *		   will be ignored
1179eb793cf8SQu Wenruo  * @newer_than:    only defrag extents newer than this value
1180eb793cf8SQu Wenruo  * @do_compress:   whether the defrag is doing compression
1181eb793cf8SQu Wenruo  *		   if true, @extent_thresh will be ignored and all regular
1182eb793cf8SQu Wenruo  *		   file extents meeting @newer_than will be targets.
1183e9eec721SQu Wenruo  * @locked:	   if the range has already held extent lock
1184eb793cf8SQu Wenruo  * @target_list:   list of targets file extents
11854cb5300bSChris Mason  */
1186eb793cf8SQu Wenruo static int defrag_collect_targets(struct btrfs_inode *inode,
1187eb793cf8SQu Wenruo 				  u64 start, u64 len, u32 extent_thresh,
1188eb793cf8SQu Wenruo 				  u64 newer_than, bool do_compress,
1189e9eec721SQu Wenruo 				  bool locked, struct list_head *target_list)
1190eb793cf8SQu Wenruo {
1191eb793cf8SQu Wenruo 	u64 cur = start;
1192eb793cf8SQu Wenruo 	int ret = 0;
1193eb793cf8SQu Wenruo 
1194eb793cf8SQu Wenruo 	while (cur < start + len) {
1195eb793cf8SQu Wenruo 		struct extent_map *em;
1196eb793cf8SQu Wenruo 		struct defrag_target_range *new;
1197eb793cf8SQu Wenruo 		bool next_mergeable = true;
1198eb793cf8SQu Wenruo 		u64 range_len;
1199eb793cf8SQu Wenruo 
1200e9eec721SQu Wenruo 		em = defrag_lookup_extent(&inode->vfs_inode, cur, locked);
1201eb793cf8SQu Wenruo 		if (!em)
1202eb793cf8SQu Wenruo 			break;
1203eb793cf8SQu Wenruo 
1204eb793cf8SQu Wenruo 		/* Skip hole/inline/preallocated extents */
1205eb793cf8SQu Wenruo 		if (em->block_start >= EXTENT_MAP_LAST_BYTE ||
1206eb793cf8SQu Wenruo 		    test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1207eb793cf8SQu Wenruo 			goto next;
1208eb793cf8SQu Wenruo 
1209eb793cf8SQu Wenruo 		/* Skip older extent */
1210eb793cf8SQu Wenruo 		if (em->generation < newer_than)
1211eb793cf8SQu Wenruo 			goto next;
1212eb793cf8SQu Wenruo 
1213eb793cf8SQu Wenruo 		/*
1214eb793cf8SQu Wenruo 		 * For do_compress case, we want to compress all valid file
1215eb793cf8SQu Wenruo 		 * extents, thus no @extent_thresh or mergeable check.
1216eb793cf8SQu Wenruo 		 */
1217eb793cf8SQu Wenruo 		if (do_compress)
1218eb793cf8SQu Wenruo 			goto add;
1219eb793cf8SQu Wenruo 
1220eb793cf8SQu Wenruo 		/* Skip too large extent */
1221eb793cf8SQu Wenruo 		if (em->len >= extent_thresh)
1222eb793cf8SQu Wenruo 			goto next;
1223eb793cf8SQu Wenruo 
1224e9eec721SQu Wenruo 		next_mergeable = defrag_check_next_extent(&inode->vfs_inode, em,
1225e9eec721SQu Wenruo 							  locked);
1226eb793cf8SQu Wenruo 		if (!next_mergeable) {
1227eb793cf8SQu Wenruo 			struct defrag_target_range *last;
1228eb793cf8SQu Wenruo 
1229eb793cf8SQu Wenruo 			/* Empty target list, no way to merge with last entry */
1230eb793cf8SQu Wenruo 			if (list_empty(target_list))
1231eb793cf8SQu Wenruo 				goto next;
1232eb793cf8SQu Wenruo 			last = list_entry(target_list->prev,
1233eb793cf8SQu Wenruo 					  struct defrag_target_range, list);
1234eb793cf8SQu Wenruo 			/* Not mergeable with last entry */
1235eb793cf8SQu Wenruo 			if (last->start + last->len != cur)
1236eb793cf8SQu Wenruo 				goto next;
1237eb793cf8SQu Wenruo 
1238eb793cf8SQu Wenruo 			/* Mergeable, fall through to add it to @target_list. */
1239eb793cf8SQu Wenruo 		}
1240eb793cf8SQu Wenruo 
1241eb793cf8SQu Wenruo add:
1242eb793cf8SQu Wenruo 		range_len = min(extent_map_end(em), start + len) - cur;
1243eb793cf8SQu Wenruo 		/*
1244eb793cf8SQu Wenruo 		 * This one is a good target, check if it can be merged into
1245eb793cf8SQu Wenruo 		 * last range of the target list.
1246eb793cf8SQu Wenruo 		 */
1247eb793cf8SQu Wenruo 		if (!list_empty(target_list)) {
1248eb793cf8SQu Wenruo 			struct defrag_target_range *last;
1249eb793cf8SQu Wenruo 
1250eb793cf8SQu Wenruo 			last = list_entry(target_list->prev,
1251eb793cf8SQu Wenruo 					  struct defrag_target_range, list);
1252eb793cf8SQu Wenruo 			ASSERT(last->start + last->len <= cur);
1253eb793cf8SQu Wenruo 			if (last->start + last->len == cur) {
1254eb793cf8SQu Wenruo 				/* Mergeable, enlarge the last entry */
1255eb793cf8SQu Wenruo 				last->len += range_len;
1256eb793cf8SQu Wenruo 				goto next;
1257eb793cf8SQu Wenruo 			}
1258eb793cf8SQu Wenruo 			/* Fall through to allocate a new entry */
1259eb793cf8SQu Wenruo 		}
1260eb793cf8SQu Wenruo 
1261eb793cf8SQu Wenruo 		/* Allocate new defrag_target_range */
1262eb793cf8SQu Wenruo 		new = kmalloc(sizeof(*new), GFP_NOFS);
1263eb793cf8SQu Wenruo 		if (!new) {
1264eb793cf8SQu Wenruo 			free_extent_map(em);
1265eb793cf8SQu Wenruo 			ret = -ENOMEM;
1266eb793cf8SQu Wenruo 			break;
1267eb793cf8SQu Wenruo 		}
1268eb793cf8SQu Wenruo 		new->start = cur;
1269eb793cf8SQu Wenruo 		new->len = range_len;
1270eb793cf8SQu Wenruo 		list_add_tail(&new->list, target_list);
1271eb793cf8SQu Wenruo 
1272eb793cf8SQu Wenruo next:
1273eb793cf8SQu Wenruo 		cur = extent_map_end(em);
1274eb793cf8SQu Wenruo 		free_extent_map(em);
1275eb793cf8SQu Wenruo 	}
1276eb793cf8SQu Wenruo 	if (ret < 0) {
1277eb793cf8SQu Wenruo 		struct defrag_target_range *entry;
1278eb793cf8SQu Wenruo 		struct defrag_target_range *tmp;
1279eb793cf8SQu Wenruo 
1280eb793cf8SQu Wenruo 		list_for_each_entry_safe(entry, tmp, target_list, list) {
1281eb793cf8SQu Wenruo 			list_del_init(&entry->list);
1282eb793cf8SQu Wenruo 			kfree(entry);
1283eb793cf8SQu Wenruo 		}
1284eb793cf8SQu Wenruo 	}
1285eb793cf8SQu Wenruo 	return ret;
1286eb793cf8SQu Wenruo }
1287eb793cf8SQu Wenruo 
128822b398eeSQu Wenruo #define CLUSTER_SIZE	(SZ_256K)
128922b398eeSQu Wenruo 
129022b398eeSQu Wenruo /*
129122b398eeSQu Wenruo  * Defrag one contiguous target range.
129222b398eeSQu Wenruo  *
129322b398eeSQu Wenruo  * @inode:	target inode
129422b398eeSQu Wenruo  * @target:	target range to defrag
129522b398eeSQu Wenruo  * @pages:	locked pages covering the defrag range
129622b398eeSQu Wenruo  * @nr_pages:	number of locked pages
129722b398eeSQu Wenruo  *
129822b398eeSQu Wenruo  * Caller should ensure:
129922b398eeSQu Wenruo  *
130022b398eeSQu Wenruo  * - Pages are prepared
130122b398eeSQu Wenruo  *   Pages should be locked, no ordered extent in the pages range,
130222b398eeSQu Wenruo  *   no writeback.
130322b398eeSQu Wenruo  *
130422b398eeSQu Wenruo  * - Extent bits are locked
130522b398eeSQu Wenruo  */
130622b398eeSQu Wenruo static int defrag_one_locked_target(struct btrfs_inode *inode,
130722b398eeSQu Wenruo 				    struct defrag_target_range *target,
130822b398eeSQu Wenruo 				    struct page **pages, int nr_pages,
130922b398eeSQu Wenruo 				    struct extent_state **cached_state)
131022b398eeSQu Wenruo {
131122b398eeSQu Wenruo 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
131222b398eeSQu Wenruo 	struct extent_changeset *data_reserved = NULL;
131322b398eeSQu Wenruo 	const u64 start = target->start;
131422b398eeSQu Wenruo 	const u64 len = target->len;
131522b398eeSQu Wenruo 	unsigned long last_index = (start + len - 1) >> PAGE_SHIFT;
131622b398eeSQu Wenruo 	unsigned long start_index = start >> PAGE_SHIFT;
131722b398eeSQu Wenruo 	unsigned long first_index = page_index(pages[0]);
131822b398eeSQu Wenruo 	int ret = 0;
131922b398eeSQu Wenruo 	int i;
132022b398eeSQu Wenruo 
132122b398eeSQu Wenruo 	ASSERT(last_index - first_index + 1 <= nr_pages);
132222b398eeSQu Wenruo 
132322b398eeSQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved, start, len);
132422b398eeSQu Wenruo 	if (ret < 0)
132522b398eeSQu Wenruo 		return ret;
132622b398eeSQu Wenruo 	clear_extent_bit(&inode->io_tree, start, start + len - 1,
132722b398eeSQu Wenruo 			 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
132822b398eeSQu Wenruo 			 EXTENT_DEFRAG, 0, 0, cached_state);
132922b398eeSQu Wenruo 	set_extent_defrag(&inode->io_tree, start, start + len - 1, cached_state);
133022b398eeSQu Wenruo 
133122b398eeSQu Wenruo 	/* Update the page status */
133222b398eeSQu Wenruo 	for (i = start_index - first_index; i <= last_index - first_index; i++) {
133322b398eeSQu Wenruo 		ClearPageChecked(pages[i]);
133422b398eeSQu Wenruo 		btrfs_page_clamp_set_dirty(fs_info, pages[i], start, len);
133522b398eeSQu Wenruo 	}
133622b398eeSQu Wenruo 	btrfs_delalloc_release_extents(inode, len);
133722b398eeSQu Wenruo 	extent_changeset_free(data_reserved);
133822b398eeSQu Wenruo 
133922b398eeSQu Wenruo 	return ret;
134022b398eeSQu Wenruo }
134122b398eeSQu Wenruo 
1342e9eec721SQu Wenruo static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
1343e9eec721SQu Wenruo 			    u32 extent_thresh, u64 newer_than, bool do_compress)
1344e9eec721SQu Wenruo {
1345e9eec721SQu Wenruo 	struct extent_state *cached_state = NULL;
1346e9eec721SQu Wenruo 	struct defrag_target_range *entry;
1347e9eec721SQu Wenruo 	struct defrag_target_range *tmp;
1348e9eec721SQu Wenruo 	LIST_HEAD(target_list);
1349e9eec721SQu Wenruo 	struct page **pages;
1350e9eec721SQu Wenruo 	const u32 sectorsize = inode->root->fs_info->sectorsize;
1351e9eec721SQu Wenruo 	u64 last_index = (start + len - 1) >> PAGE_SHIFT;
1352e9eec721SQu Wenruo 	u64 start_index = start >> PAGE_SHIFT;
1353e9eec721SQu Wenruo 	unsigned int nr_pages = last_index - start_index + 1;
1354e9eec721SQu Wenruo 	int ret = 0;
1355e9eec721SQu Wenruo 	int i;
1356e9eec721SQu Wenruo 
1357e9eec721SQu Wenruo 	ASSERT(nr_pages <= CLUSTER_SIZE / PAGE_SIZE);
1358e9eec721SQu Wenruo 	ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(len, sectorsize));
1359e9eec721SQu Wenruo 
1360e9eec721SQu Wenruo 	pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
1361e9eec721SQu Wenruo 	if (!pages)
1362e9eec721SQu Wenruo 		return -ENOMEM;
1363e9eec721SQu Wenruo 
1364e9eec721SQu Wenruo 	/* Prepare all pages */
1365e9eec721SQu Wenruo 	for (i = 0; i < nr_pages; i++) {
1366e9eec721SQu Wenruo 		pages[i] = defrag_prepare_one_page(inode, start_index + i);
1367e9eec721SQu Wenruo 		if (IS_ERR(pages[i])) {
1368e9eec721SQu Wenruo 			ret = PTR_ERR(pages[i]);
1369e9eec721SQu Wenruo 			pages[i] = NULL;
1370e9eec721SQu Wenruo 			goto free_pages;
1371e9eec721SQu Wenruo 		}
1372e9eec721SQu Wenruo 	}
1373e9eec721SQu Wenruo 	for (i = 0; i < nr_pages; i++)
13744cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
13754cb5300bSChris Mason 
1376e9eec721SQu Wenruo 	/* Lock the pages range */
1377e9eec721SQu Wenruo 	lock_extent_bits(&inode->io_tree, start_index << PAGE_SHIFT,
1378e9eec721SQu Wenruo 			 (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1379e9eec721SQu Wenruo 			 &cached_state);
1380e9eec721SQu Wenruo 	/*
1381e9eec721SQu Wenruo 	 * Now we have a consistent view about the extent map, re-check
1382e9eec721SQu Wenruo 	 * which range really needs to be defragged.
1383e9eec721SQu Wenruo 	 *
1384e9eec721SQu Wenruo 	 * And this time we have extent locked already, pass @locked = true
1385e9eec721SQu Wenruo 	 * so that we won't relock the extent range and cause deadlock.
1386e9eec721SQu Wenruo 	 */
1387e9eec721SQu Wenruo 	ret = defrag_collect_targets(inode, start, len, extent_thresh,
1388e9eec721SQu Wenruo 				     newer_than, do_compress, true,
1389e9eec721SQu Wenruo 				     &target_list);
1390e9eec721SQu Wenruo 	if (ret < 0)
1391e9eec721SQu Wenruo 		goto unlock_extent;
13924cb5300bSChris Mason 
1393e9eec721SQu Wenruo 	list_for_each_entry(entry, &target_list, list) {
1394e9eec721SQu Wenruo 		ret = defrag_one_locked_target(inode, entry, pages, nr_pages,
1395e9eec721SQu Wenruo 					       &cached_state);
1396e9eec721SQu Wenruo 		if (ret < 0)
1397e9eec721SQu Wenruo 			break;
1398e9eec721SQu Wenruo 	}
1399e9eec721SQu Wenruo 
1400e9eec721SQu Wenruo 	list_for_each_entry_safe(entry, tmp, &target_list, list) {
1401e9eec721SQu Wenruo 		list_del_init(&entry->list);
1402e9eec721SQu Wenruo 		kfree(entry);
1403e9eec721SQu Wenruo 	}
1404e9eec721SQu Wenruo unlock_extent:
1405e9eec721SQu Wenruo 	unlock_extent_cached(&inode->io_tree, start_index << PAGE_SHIFT,
1406e9eec721SQu Wenruo 			     (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
1407e9eec721SQu Wenruo 			     &cached_state);
1408e9eec721SQu Wenruo free_pages:
1409e9eec721SQu Wenruo 	for (i = 0; i < nr_pages; i++) {
1410e9eec721SQu Wenruo 		if (pages[i]) {
1411e9eec721SQu Wenruo 			unlock_page(pages[i]);
1412e9eec721SQu Wenruo 			put_page(pages[i]);
1413e9eec721SQu Wenruo 		}
1414e9eec721SQu Wenruo 	}
1415e9eec721SQu Wenruo 	kfree(pages);
1416e9eec721SQu Wenruo 	return ret;
1417e9eec721SQu Wenruo }
1418e9eec721SQu Wenruo 
1419b18c3ab2SQu Wenruo static int defrag_one_cluster(struct btrfs_inode *inode,
1420b18c3ab2SQu Wenruo 			      struct file_ra_state *ra,
1421b18c3ab2SQu Wenruo 			      u64 start, u32 len, u32 extent_thresh,
1422b18c3ab2SQu Wenruo 			      u64 newer_than, bool do_compress,
1423b18c3ab2SQu Wenruo 			      unsigned long *sectors_defragged,
1424b18c3ab2SQu Wenruo 			      unsigned long max_sectors)
1425b18c3ab2SQu Wenruo {
1426b18c3ab2SQu Wenruo 	const u32 sectorsize = inode->root->fs_info->sectorsize;
1427b18c3ab2SQu Wenruo 	struct defrag_target_range *entry;
1428b18c3ab2SQu Wenruo 	struct defrag_target_range *tmp;
1429b18c3ab2SQu Wenruo 	LIST_HEAD(target_list);
1430b18c3ab2SQu Wenruo 	int ret;
1431b18c3ab2SQu Wenruo 
1432b18c3ab2SQu Wenruo 	BUILD_BUG_ON(!IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
1433b18c3ab2SQu Wenruo 	ret = defrag_collect_targets(inode, start, len, extent_thresh,
1434b18c3ab2SQu Wenruo 				     newer_than, do_compress, false,
1435b18c3ab2SQu Wenruo 				     &target_list);
1436b18c3ab2SQu Wenruo 	if (ret < 0)
1437b18c3ab2SQu Wenruo 		goto out;
1438b18c3ab2SQu Wenruo 
1439b18c3ab2SQu Wenruo 	list_for_each_entry(entry, &target_list, list) {
1440b18c3ab2SQu Wenruo 		u32 range_len = entry->len;
1441b18c3ab2SQu Wenruo 
1442b18c3ab2SQu Wenruo 		/* Reached the limit */
1443b18c3ab2SQu Wenruo 		if (max_sectors && max_sectors == *sectors_defragged)
1444b18c3ab2SQu Wenruo 			break;
1445b18c3ab2SQu Wenruo 
1446b18c3ab2SQu Wenruo 		if (max_sectors)
1447b18c3ab2SQu Wenruo 			range_len = min_t(u32, range_len,
1448b18c3ab2SQu Wenruo 				(max_sectors - *sectors_defragged) * sectorsize);
1449b18c3ab2SQu Wenruo 
1450b18c3ab2SQu Wenruo 		if (ra)
1451b18c3ab2SQu Wenruo 			page_cache_sync_readahead(inode->vfs_inode.i_mapping,
1452b18c3ab2SQu Wenruo 				ra, NULL, entry->start >> PAGE_SHIFT,
1453b18c3ab2SQu Wenruo 				((entry->start + range_len - 1) >> PAGE_SHIFT) -
1454b18c3ab2SQu Wenruo 				(entry->start >> PAGE_SHIFT) + 1);
1455b18c3ab2SQu Wenruo 		/*
1456b18c3ab2SQu Wenruo 		 * Here we may not defrag any range if holes are punched before
1457b18c3ab2SQu Wenruo 		 * we locked the pages.
1458b18c3ab2SQu Wenruo 		 * But that's fine, it only affects the @sectors_defragged
1459b18c3ab2SQu Wenruo 		 * accounting.
1460b18c3ab2SQu Wenruo 		 */
1461b18c3ab2SQu Wenruo 		ret = defrag_one_range(inode, entry->start, range_len,
1462b18c3ab2SQu Wenruo 				       extent_thresh, newer_than, do_compress);
1463b18c3ab2SQu Wenruo 		if (ret < 0)
1464b18c3ab2SQu Wenruo 			break;
1465b18c3ab2SQu Wenruo 		*sectors_defragged += range_len;
1466b18c3ab2SQu Wenruo 	}
1467b18c3ab2SQu Wenruo out:
1468b18c3ab2SQu Wenruo 	list_for_each_entry_safe(entry, tmp, &target_list, list) {
1469b18c3ab2SQu Wenruo 		list_del_init(&entry->list);
1470b18c3ab2SQu Wenruo 		kfree(entry);
1471b18c3ab2SQu Wenruo 	}
1472b18c3ab2SQu Wenruo 	return ret;
1473b18c3ab2SQu Wenruo }
14747f458a38SFilipe Manana 
14757f458a38SFilipe Manana /*
14761ccc2e8aSQu Wenruo  * Entry point to file defragmentation.
14771ccc2e8aSQu Wenruo  *
14781ccc2e8aSQu Wenruo  * @inode:	   inode to be defragged
14791ccc2e8aSQu Wenruo  * @ra:		   readahead state (can be NUL)
14801ccc2e8aSQu Wenruo  * @range:	   defrag options including range and flags
14811ccc2e8aSQu Wenruo  * @newer_than:	   minimum transid to defrag
14821ccc2e8aSQu Wenruo  * @max_to_defrag: max number of sectors to be defragged, if 0, the whole inode
14831ccc2e8aSQu Wenruo  *		   will be defragged.
14847f458a38SFilipe Manana  */
14851ccc2e8aSQu Wenruo int btrfs_defrag_file(struct inode *inode, struct file_ra_state *ra,
14864cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
14874cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
14884cb5300bSChris Mason {
14890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
14907b508037SQu Wenruo 	unsigned long sectors_defragged = 0;
1491151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
14927b508037SQu Wenruo 	u64 cur;
14937b508037SQu Wenruo 	u64 last_byte;
14941e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
14951ccc2e8aSQu Wenruo 	bool ra_allocated = false;
14967b508037SQu Wenruo 	int compress_type = BTRFS_COMPRESS_ZLIB;
14977b508037SQu Wenruo 	int ret = 0;
14987b508037SQu Wenruo 	u32 extent_thresh = range->extent_thresh;
14994cb5300bSChris Mason 
15000abd5b17SLiu Bo 	if (isize == 0)
15010abd5b17SLiu Bo 		return 0;
15020abd5b17SLiu Bo 
15030abd5b17SLiu Bo 	if (range->start >= isize)
15040abd5b17SLiu Bo 		return -EINVAL;
15051a419d85SLi Zefan 
15061e2ef46dSDavid Sterba 	if (do_compress) {
1507ce96b7ffSChengguang Xu 		if (range->compress_type >= BTRFS_NR_COMPRESS_TYPES)
15081a419d85SLi Zefan 			return -EINVAL;
15091a419d85SLi Zefan 		if (range->compress_type)
15101a419d85SLi Zefan 			compress_type = range->compress_type;
15111a419d85SLi Zefan 	}
1512f46b5a66SChristoph Hellwig 
15130abd5b17SLiu Bo 	if (extent_thresh == 0)
1514ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1515f46b5a66SChristoph Hellwig 
15167b508037SQu Wenruo 	if (range->start + range->len > range->start) {
15177b508037SQu Wenruo 		/* Got a specific range */
15187b508037SQu Wenruo 		last_byte = min(isize, range->start + range->len) - 1;
15197b508037SQu Wenruo 	} else {
15207b508037SQu Wenruo 		/* Defrag until file end */
15217b508037SQu Wenruo 		last_byte = isize - 1;
15227b508037SQu Wenruo 	}
15237b508037SQu Wenruo 
15244cb5300bSChris Mason 	/*
15251ccc2e8aSQu Wenruo 	 * If we were not given a ra, allocate a readahead context. As
15260a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
15270a52d108SDavid Sterba 	 * we don't error out.
15284cb5300bSChris Mason 	 */
15291ccc2e8aSQu Wenruo 	if (!ra) {
15301ccc2e8aSQu Wenruo 		ra_allocated = true;
153163e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
15320a52d108SDavid Sterba 		if (ra)
15334cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
15344cb5300bSChris Mason 	}
15354cb5300bSChris Mason 
15367b508037SQu Wenruo 	/* Align the range */
15377b508037SQu Wenruo 	cur = round_down(range->start, fs_info->sectorsize);
15387b508037SQu Wenruo 	last_byte = round_up(last_byte, fs_info->sectorsize) - 1;
15394cb5300bSChris Mason 
15407b508037SQu Wenruo 	while (cur < last_byte) {
15417b508037SQu Wenruo 		u64 cluster_end;
15421e701a32SChris Mason 
15437b508037SQu Wenruo 		/* The cluster size 256K should always be page aligned */
15447b508037SQu Wenruo 		BUILD_BUG_ON(!IS_ALIGNED(CLUSTER_SIZE, PAGE_SIZE));
15454cb5300bSChris Mason 
15467b508037SQu Wenruo 		/* We want the cluster end at page boundary when possible */
15477b508037SQu Wenruo 		cluster_end = (((cur >> PAGE_SHIFT) +
15487b508037SQu Wenruo 			       (SZ_256K >> PAGE_SHIFT)) << PAGE_SHIFT) - 1;
15497b508037SQu Wenruo 		cluster_end = min(cluster_end, last_byte);
15504cb5300bSChris Mason 
155164708539SJosef Bacik 		btrfs_inode_lock(inode, 0);
1552eede2bf3SOmar Sandoval 		if (IS_SWAPFILE(inode)) {
1553eede2bf3SOmar Sandoval 			ret = -ETXTBSY;
15547b508037SQu Wenruo 			btrfs_inode_unlock(inode, 0);
15557b508037SQu Wenruo 			break;
15567b508037SQu Wenruo 		}
15577b508037SQu Wenruo 		if (!(inode->i_sb->s_flags & SB_ACTIVE)) {
15587b508037SQu Wenruo 			btrfs_inode_unlock(inode, 0);
15597b508037SQu Wenruo 			break;
15607b508037SQu Wenruo 		}
15611e2ef46dSDavid Sterba 		if (do_compress)
1562eec63c65SDavid Sterba 			BTRFS_I(inode)->defrag_compress = compress_type;
15637b508037SQu Wenruo 		ret = defrag_one_cluster(BTRFS_I(inode), ra, cur,
15647b508037SQu Wenruo 				cluster_end + 1 - cur, extent_thresh,
15657b508037SQu Wenruo 				newer_than, do_compress,
15667b508037SQu Wenruo 				&sectors_defragged, max_to_defrag);
156764708539SJosef Bacik 		btrfs_inode_unlock(inode, 0);
15687b508037SQu Wenruo 		if (ret < 0)
15694cb5300bSChris Mason 			break;
15707b508037SQu Wenruo 		cur = cluster_end + 1;
15714cb5300bSChris Mason 	}
1572f46b5a66SChristoph Hellwig 
15737b508037SQu Wenruo 	if (ra_allocated)
15747b508037SQu Wenruo 		kfree(ra);
15757b508037SQu Wenruo 	if (sectors_defragged) {
15767b508037SQu Wenruo 		/*
15777b508037SQu Wenruo 		 * We have defragged some sectors, for compression case they
15787b508037SQu Wenruo 		 * need to be written back immediately.
15797b508037SQu Wenruo 		 */
15807b508037SQu Wenruo 		if (range->flags & BTRFS_DEFRAG_RANGE_START_IO) {
15811e701a32SChris Mason 			filemap_flush(inode->i_mapping);
1582dec8ef90SFilipe Manana 			if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1583dec8ef90SFilipe Manana 				     &BTRFS_I(inode)->runtime_flags))
1584dec8ef90SFilipe Manana 				filemap_flush(inode->i_mapping);
1585dec8ef90SFilipe Manana 		}
15867b508037SQu Wenruo 		if (range->compress_type == BTRFS_COMPRESS_LZO)
15870b246afaSJeff Mahoney 			btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
15887b508037SQu Wenruo 		else if (range->compress_type == BTRFS_COMPRESS_ZSTD)
15895c1aab1dSNick Terrell 			btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
15907b508037SQu Wenruo 		ret = sectors_defragged;
15911a419d85SLi Zefan 	}
15921e2ef46dSDavid Sterba 	if (do_compress) {
159364708539SJosef Bacik 		btrfs_inode_lock(inode, 0);
1594eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
159564708539SJosef Bacik 		btrfs_inode_unlock(inode, 0);
1596633085c7SFilipe David Borba Manana 	}
1597940100a4SChris Mason 	return ret;
1598f46b5a66SChristoph Hellwig }
1599f46b5a66SChristoph Hellwig 
160017aaa434SDavid Sterba /*
160117aaa434SDavid Sterba  * Try to start exclusive operation @type or cancel it if it's running.
160217aaa434SDavid Sterba  *
160317aaa434SDavid Sterba  * Return:
160417aaa434SDavid Sterba  *   0        - normal mode, newly claimed op started
160517aaa434SDavid Sterba  *  >0        - normal mode, something else is running,
160617aaa434SDavid Sterba  *              return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS to user space
160717aaa434SDavid Sterba  * ECANCELED  - cancel mode, successful cancel
160817aaa434SDavid Sterba  * ENOTCONN   - cancel mode, operation not running anymore
160917aaa434SDavid Sterba  */
161017aaa434SDavid Sterba static int exclop_start_or_cancel_reloc(struct btrfs_fs_info *fs_info,
161117aaa434SDavid Sterba 			enum btrfs_exclusive_operation type, bool cancel)
161217aaa434SDavid Sterba {
161317aaa434SDavid Sterba 	if (!cancel) {
161417aaa434SDavid Sterba 		/* Start normal op */
161517aaa434SDavid Sterba 		if (!btrfs_exclop_start(fs_info, type))
161617aaa434SDavid Sterba 			return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
161717aaa434SDavid Sterba 		/* Exclusive operation is now claimed */
161817aaa434SDavid Sterba 		return 0;
161917aaa434SDavid Sterba 	}
162017aaa434SDavid Sterba 
162117aaa434SDavid Sterba 	/* Cancel running op */
162217aaa434SDavid Sterba 	if (btrfs_exclop_start_try_lock(fs_info, type)) {
162317aaa434SDavid Sterba 		/*
162417aaa434SDavid Sterba 		 * This blocks any exclop finish from setting it to NONE, so we
162517aaa434SDavid Sterba 		 * request cancellation. Either it runs and we will wait for it,
162617aaa434SDavid Sterba 		 * or it has finished and no waiting will happen.
162717aaa434SDavid Sterba 		 */
162817aaa434SDavid Sterba 		atomic_inc(&fs_info->reloc_cancel_req);
162917aaa434SDavid Sterba 		btrfs_exclop_start_unlock(fs_info);
163017aaa434SDavid Sterba 
163117aaa434SDavid Sterba 		if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
163217aaa434SDavid Sterba 			wait_on_bit(&fs_info->flags, BTRFS_FS_RELOC_RUNNING,
163317aaa434SDavid Sterba 				    TASK_INTERRUPTIBLE);
163417aaa434SDavid Sterba 
163517aaa434SDavid Sterba 		return -ECANCELED;
163617aaa434SDavid Sterba 	}
163717aaa434SDavid Sterba 
163817aaa434SDavid Sterba 	/* Something else is running or none */
163917aaa434SDavid Sterba 	return -ENOTCONN;
164017aaa434SDavid Sterba }
164117aaa434SDavid Sterba 
1642198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
164376dda93cSYan, Zheng 					void __user *arg)
1644f46b5a66SChristoph Hellwig {
1645562d7b15SJosef Bacik 	BTRFS_DEV_LOOKUP_ARGS(args);
16460b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
16470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1648f46b5a66SChristoph Hellwig 	u64 new_size;
1649f46b5a66SChristoph Hellwig 	u64 old_size;
1650f46b5a66SChristoph Hellwig 	u64 devid = 1;
16510b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1652f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1653f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1654f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1655f46b5a66SChristoph Hellwig 	char *sizestr;
16569a40f122SGui Hecheng 	char *retptr;
1657f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1658f46b5a66SChristoph Hellwig 	int ret = 0;
1659f46b5a66SChristoph Hellwig 	int mod = 0;
1660bb059a37SDavid Sterba 	bool cancel;
1661f46b5a66SChristoph Hellwig 
1662e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1663e441d54dSChris Mason 		return -EPERM;
1664e441d54dSChris Mason 
1665198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1666198605a8SMiao Xie 	if (ret)
1667198605a8SMiao Xie 		return ret;
1668198605a8SMiao Xie 
1669bb059a37SDavid Sterba 	/*
1670bb059a37SDavid Sterba 	 * Read the arguments before checking exclusivity to be able to
1671bb059a37SDavid Sterba 	 * distinguish regular resize and cancel
1672bb059a37SDavid Sterba 	 */
1673dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1674c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1675c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1676bb059a37SDavid Sterba 		goto out_drop;
1677c9e9f97bSIlya Dryomov 	}
16785516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1679f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1680bb059a37SDavid Sterba 	cancel = (strcmp("cancel", sizestr) == 0);
1681bb059a37SDavid Sterba 	ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_RESIZE, cancel);
1682bb059a37SDavid Sterba 	if (ret)
1683bb059a37SDavid Sterba 		goto out_free;
1684bb059a37SDavid Sterba 	/* Exclusive operation is now claimed */
1685bb059a37SDavid Sterba 
1686f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1687f46b5a66SChristoph Hellwig 	if (devstr) {
1688f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1689f46b5a66SChristoph Hellwig 		*devstr = '\0';
1690f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
169158dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
169258dfae63SZhangZhen 		if (ret)
1693bb059a37SDavid Sterba 			goto out_finish;
1694dfd79829SMiao Xie 		if (!devid) {
1695dfd79829SMiao Xie 			ret = -EINVAL;
1696bb059a37SDavid Sterba 			goto out_finish;
1697dfd79829SMiao Xie 		}
16980b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1699f46b5a66SChristoph Hellwig 	}
1700dba60f3fSMiao Xie 
1701562d7b15SJosef Bacik 	args.devid = devid;
1702562d7b15SJosef Bacik 	device = btrfs_find_device(fs_info->fs_devices, &args);
1703f46b5a66SChristoph Hellwig 	if (!device) {
17040b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1705c1c9ff7cSGeert Uytterhoeven 			   devid);
1706dfd79829SMiao Xie 		ret = -ENODEV;
1707bb059a37SDavid Sterba 		goto out_finish;
1708f46b5a66SChristoph Hellwig 	}
1709dba60f3fSMiao Xie 
1710ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
17110b246afaSJeff Mahoney 		btrfs_info(fs_info,
1712efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1713c1c9ff7cSGeert Uytterhoeven 		       devid);
1714dfd79829SMiao Xie 		ret = -EPERM;
1715bb059a37SDavid Sterba 		goto out_finish;
17164e42ae1bSLiu Bo 	}
17174e42ae1bSLiu Bo 
1718f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1719cda00ebaSChristoph Hellwig 		new_size = bdev_nr_bytes(device->bdev);
1720f46b5a66SChristoph Hellwig 	else {
1721f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1722f46b5a66SChristoph Hellwig 			mod = -1;
1723f46b5a66SChristoph Hellwig 			sizestr++;
1724f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1725f46b5a66SChristoph Hellwig 			mod = 1;
1726f46b5a66SChristoph Hellwig 			sizestr++;
1727f46b5a66SChristoph Hellwig 		}
17289a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
17299a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1730f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1731bb059a37SDavid Sterba 			goto out_finish;
1732f46b5a66SChristoph Hellwig 		}
1733f46b5a66SChristoph Hellwig 	}
1734f46b5a66SChristoph Hellwig 
1735401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1736dfd79829SMiao Xie 		ret = -EPERM;
1737bb059a37SDavid Sterba 		goto out_finish;
173863a212abSStefan Behrens 	}
173963a212abSStefan Behrens 
17407cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1741f46b5a66SChristoph Hellwig 
1742f46b5a66SChristoph Hellwig 	if (mod < 0) {
1743f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1744f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1745bb059a37SDavid Sterba 			goto out_finish;
1746f46b5a66SChristoph Hellwig 		}
1747f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1748f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1749eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1750902c68a4SGui Hecheng 			ret = -ERANGE;
1751bb059a37SDavid Sterba 			goto out_finish;
1752eb8052e0SWenliang Fan 		}
1753f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1754f46b5a66SChristoph Hellwig 	}
1755f46b5a66SChristoph Hellwig 
1756ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1757f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1758bb059a37SDavid Sterba 		goto out_finish;
1759f46b5a66SChristoph Hellwig 	}
1760cda00ebaSChristoph Hellwig 	if (new_size > bdev_nr_bytes(device->bdev)) {
1761f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1762bb059a37SDavid Sterba 		goto out_finish;
1763f46b5a66SChristoph Hellwig 	}
1764f46b5a66SChristoph Hellwig 
176547f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1766f46b5a66SChristoph Hellwig 
1767f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1768a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
176998d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
177098d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1771bb059a37SDavid Sterba 			goto out_finish;
177298d5dc13STsutomu Itoh 		}
1773f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
17743a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1775ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1776f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
17770253f40eSjeff.liu 	} /* equal, nothing need to do */
1778f46b5a66SChristoph Hellwig 
1779faf8f7b9SMarcos Paulo de Souza 	if (ret == 0 && new_size != old_size)
1780faf8f7b9SMarcos Paulo de Souza 		btrfs_info_in_rcu(fs_info,
1781faf8f7b9SMarcos Paulo de Souza 			"resize device %s (devid %llu) from %llu to %llu",
1782faf8f7b9SMarcos Paulo de Souza 			rcu_str_deref(device->name), device->devid,
1783faf8f7b9SMarcos Paulo de Souza 			old_size, new_size);
1784bb059a37SDavid Sterba out_finish:
1785bb059a37SDavid Sterba 	btrfs_exclop_finish(fs_info);
1786c9e9f97bSIlya Dryomov out_free:
1787f46b5a66SChristoph Hellwig 	kfree(vol_args);
1788bb059a37SDavid Sterba out_drop:
178918f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1790f46b5a66SChristoph Hellwig 	return ret;
1791f46b5a66SChristoph Hellwig }
1792f46b5a66SChristoph Hellwig 
17935d54c67eSNikolay Borisov static noinline int __btrfs_ioctl_snap_create(struct file *file,
17944d4340c9SChristian Brauner 				struct user_namespace *mnt_userns,
179552f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
17965d54c67eSNikolay Borisov 				bool readonly,
17978696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1798f46b5a66SChristoph Hellwig {
1799f46b5a66SChristoph Hellwig 	int namelen;
18003de4586cSChris Mason 	int ret = 0;
1801f46b5a66SChristoph Hellwig 
1802325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1803325c50e3SJeff Mahoney 		return -ENOTDIR;
1804325c50e3SJeff Mahoney 
1805a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1806a874a63eSLiu Bo 	if (ret)
1807a874a63eSLiu Bo 		goto out;
1808a874a63eSLiu Bo 
180972fd032eSSage Weil 	namelen = strlen(name);
181072fd032eSSage Weil 	if (strchr(name, '/')) {
1811f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1812a874a63eSLiu Bo 		goto out_drop_write;
1813f46b5a66SChristoph Hellwig 	}
1814f46b5a66SChristoph Hellwig 
181516780cabSChris Mason 	if (name[0] == '.' &&
181616780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
181716780cabSChris Mason 		ret = -EEXIST;
1818a874a63eSLiu Bo 		goto out_drop_write;
181916780cabSChris Mason 	}
182016780cabSChris Mason 
18213de4586cSChris Mason 	if (subvol) {
18224d4340c9SChristian Brauner 		ret = btrfs_mksubvol(&file->f_path, mnt_userns, name,
18234d4340c9SChristian Brauner 				     namelen, NULL, readonly, inherit);
1824cb8e7090SChristoph Hellwig 	} else {
18252903ff01SAl Viro 		struct fd src = fdget(fd);
18263de4586cSChris Mason 		struct inode *src_inode;
18272903ff01SAl Viro 		if (!src.file) {
18283de4586cSChris Mason 			ret = -EINVAL;
1829a874a63eSLiu Bo 			goto out_drop_write;
18303de4586cSChris Mason 		}
18313de4586cSChris Mason 
1832496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1833496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1834c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1835efe120a0SFrank Holton 				   "Snapshot src from another FS");
183623ad5b17SKusanagi Kouichi 			ret = -EXDEV;
18374d4340c9SChristian Brauner 		} else if (!inode_owner_or_capable(mnt_userns, src_inode)) {
1838d0242061SDavid Sterba 			/*
1839d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1840d0242061SDavid Sterba 			 * are limited to own subvolumes only
1841d0242061SDavid Sterba 			 */
1842d0242061SDavid Sterba 			ret = -EPERM;
1843ecd18815SAl Viro 		} else {
18444d4340c9SChristian Brauner 			ret = btrfs_mksnapshot(&file->f_path, mnt_userns,
18454d4340c9SChristian Brauner 					       name, namelen,
184672fd032eSSage Weil 					       BTRFS_I(src_inode)->root,
18475d54c67eSNikolay Borisov 					       readonly, inherit);
1848ecd18815SAl Viro 		}
18492903ff01SAl Viro 		fdput(src);
1850cb8e7090SChristoph Hellwig 	}
1851a874a63eSLiu Bo out_drop_write:
1852a874a63eSLiu Bo 	mnt_drop_write_file(file);
1853f46b5a66SChristoph Hellwig out:
185472fd032eSSage Weil 	return ret;
185572fd032eSSage Weil }
185672fd032eSSage Weil 
185772fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1858fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
185972fd032eSSage Weil {
1860fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
186172fd032eSSage Weil 	int ret;
186272fd032eSSage Weil 
1863325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1864325c50e3SJeff Mahoney 		return -ENOTDIR;
1865325c50e3SJeff Mahoney 
1866fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1867fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1868fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1869fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1870fa0d2b9bSLi Zefan 
18714d4340c9SChristian Brauner 	ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
18724d4340c9SChristian Brauner 					vol_args->name, vol_args->fd, subvol,
18734d4340c9SChristian Brauner 					false, NULL);
1874fa0d2b9bSLi Zefan 
1875fa0d2b9bSLi Zefan 	kfree(vol_args);
1876fa0d2b9bSLi Zefan 	return ret;
1877fa0d2b9bSLi Zefan }
1878fa0d2b9bSLi Zefan 
1879fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1880fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1881fa0d2b9bSLi Zefan {
1882fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1883fa0d2b9bSLi Zefan 	int ret;
1884b83cc969SLi Zefan 	bool readonly = false;
18856f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
188672fd032eSSage Weil 
1887325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1888325c50e3SJeff Mahoney 		return -ENOTDIR;
1889325c50e3SJeff Mahoney 
1890fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1891fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1892fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1893fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1894fdfb1e4fSLi Zefan 
1895673990dbSDavid Sterba 	if (vol_args->flags & ~BTRFS_SUBVOL_CREATE_ARGS_MASK) {
1896b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1897c47ca32dSDan Carpenter 		goto free_args;
1898fdfb1e4fSLi Zefan 	}
1899fdfb1e4fSLi Zefan 
1900b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1901b83cc969SLi Zefan 		readonly = true;
19026f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
19035011c5a6SDan Carpenter 		u64 nums;
19045011c5a6SDan Carpenter 
19055011c5a6SDan Carpenter 		if (vol_args->size < sizeof(*inherit) ||
19065011c5a6SDan Carpenter 		    vol_args->size > PAGE_SIZE) {
19076f72c7e2SArne Jansen 			ret = -EINVAL;
1908c47ca32dSDan Carpenter 			goto free_args;
19096f72c7e2SArne Jansen 		}
19106f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
19116f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
19126f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1913c47ca32dSDan Carpenter 			goto free_args;
19146f72c7e2SArne Jansen 		}
19155011c5a6SDan Carpenter 
19165011c5a6SDan Carpenter 		if (inherit->num_qgroups > PAGE_SIZE ||
19175011c5a6SDan Carpenter 		    inherit->num_ref_copies > PAGE_SIZE ||
19185011c5a6SDan Carpenter 		    inherit->num_excl_copies > PAGE_SIZE) {
19195011c5a6SDan Carpenter 			ret = -EINVAL;
19205011c5a6SDan Carpenter 			goto free_inherit;
19215011c5a6SDan Carpenter 		}
19225011c5a6SDan Carpenter 
19235011c5a6SDan Carpenter 		nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
19245011c5a6SDan Carpenter 		       2 * inherit->num_excl_copies;
19255011c5a6SDan Carpenter 		if (vol_args->size != struct_size(inherit, qgroups, nums)) {
19265011c5a6SDan Carpenter 			ret = -EINVAL;
19275011c5a6SDan Carpenter 			goto free_inherit;
19285011c5a6SDan Carpenter 		}
19296f72c7e2SArne Jansen 	}
193075eaa0e2SSage Weil 
19314d4340c9SChristian Brauner 	ret = __btrfs_ioctl_snap_create(file, file_mnt_user_ns(file),
19324d4340c9SChristian Brauner 					vol_args->name, vol_args->fd, subvol,
19334d4340c9SChristian Brauner 					readonly, inherit);
1934c47ca32dSDan Carpenter 	if (ret)
1935c47ca32dSDan Carpenter 		goto free_inherit;
1936c47ca32dSDan Carpenter free_inherit:
19376f72c7e2SArne Jansen 	kfree(inherit);
1938c47ca32dSDan Carpenter free_args:
1939c47ca32dSDan Carpenter 	kfree(vol_args);
1940f46b5a66SChristoph Hellwig 	return ret;
1941f46b5a66SChristoph Hellwig }
1942f46b5a66SChristoph Hellwig 
19430caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
19440caa102dSLi Zefan 						void __user *arg)
19450caa102dSLi Zefan {
1946496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
19470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
19480caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
19490caa102dSLi Zefan 	int ret = 0;
19500caa102dSLi Zefan 	u64 flags = 0;
19510caa102dSLi Zefan 
19524a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
19530caa102dSLi Zefan 		return -EINVAL;
19540caa102dSLi Zefan 
19550b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
19560caa102dSLi Zefan 	if (btrfs_root_readonly(root))
19570caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
19580b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
19590caa102dSLi Zefan 
19600caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
19610caa102dSLi Zefan 		ret = -EFAULT;
19620caa102dSLi Zefan 
19630caa102dSLi Zefan 	return ret;
19640caa102dSLi Zefan }
19650caa102dSLi Zefan 
19660caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
19670caa102dSLi Zefan 					      void __user *arg)
19680caa102dSLi Zefan {
1969496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
19700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
19710caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
19720caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
19730caa102dSLi Zefan 	u64 root_flags;
19740caa102dSLi Zefan 	u64 flags;
19750caa102dSLi Zefan 	int ret = 0;
19760caa102dSLi Zefan 
197739e1674fSChristian Brauner 	if (!inode_owner_or_capable(file_mnt_user_ns(file), inode))
1978bd60ea0fSDavid Sterba 		return -EPERM;
1979bd60ea0fSDavid Sterba 
1980b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1981b9ca0664SLiu Bo 	if (ret)
1982b9ca0664SLiu Bo 		goto out;
19830caa102dSLi Zefan 
19844a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1985b9ca0664SLiu Bo 		ret = -EINVAL;
1986b9ca0664SLiu Bo 		goto out_drop_write;
1987b9ca0664SLiu Bo 	}
19880caa102dSLi Zefan 
1989b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1990b9ca0664SLiu Bo 		ret = -EFAULT;
1991b9ca0664SLiu Bo 		goto out_drop_write;
1992b9ca0664SLiu Bo 	}
19930caa102dSLi Zefan 
1994b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1995b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1996b9ca0664SLiu Bo 		goto out_drop_write;
1997b9ca0664SLiu Bo 	}
19980caa102dSLi Zefan 
19990b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
20000caa102dSLi Zefan 
20010caa102dSLi Zefan 	/* nothing to do */
20020caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
2003b9ca0664SLiu Bo 		goto out_drop_sem;
20040caa102dSLi Zefan 
20050caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
20062c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
20070caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
20080caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
20092c686537SDavid Sterba 	} else {
20102c686537SDavid Sterba 		/*
20112c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
20122c686537SDavid Sterba 		 * send
20132c686537SDavid Sterba 		 */
20142c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
20152c686537SDavid Sterba 		if (root->send_in_progress == 0) {
20160caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
20170caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
20182c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
20192c686537SDavid Sterba 		} else {
20202c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
20210b246afaSJeff Mahoney 			btrfs_warn(fs_info,
20222c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
20232c686537SDavid Sterba 				   root->root_key.objectid);
20242c686537SDavid Sterba 			ret = -EPERM;
20252c686537SDavid Sterba 			goto out_drop_sem;
20262c686537SDavid Sterba 		}
20272c686537SDavid Sterba 	}
20280caa102dSLi Zefan 
20290caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
20300caa102dSLi Zefan 	if (IS_ERR(trans)) {
20310caa102dSLi Zefan 		ret = PTR_ERR(trans);
20320caa102dSLi Zefan 		goto out_reset;
20330caa102dSLi Zefan 	}
20340caa102dSLi Zefan 
20350b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
20360caa102dSLi Zefan 				&root->root_key, &root->root_item);
20379417ebc8SNikolay Borisov 	if (ret < 0) {
20389417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
20399417ebc8SNikolay Borisov 		goto out_reset;
20409417ebc8SNikolay Borisov 	}
20410caa102dSLi Zefan 
20429417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
20439417ebc8SNikolay Borisov 
20440caa102dSLi Zefan out_reset:
20450caa102dSLi Zefan 	if (ret)
20460caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
2047b9ca0664SLiu Bo out_drop_sem:
20480b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
2049b9ca0664SLiu Bo out_drop_write:
2050b9ca0664SLiu Bo 	mnt_drop_write_file(file);
2051b9ca0664SLiu Bo out:
20520caa102dSLi Zefan 	return ret;
20530caa102dSLi Zefan }
20540caa102dSLi Zefan 
2055ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
2056ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
2057ac8e9819SChris Mason {
2058abc6e134SChris Mason 	struct btrfs_key test;
2059abc6e134SChris Mason 	int ret;
2060abc6e134SChris Mason 
2061abc6e134SChris Mason 	test.objectid = sk->min_objectid;
2062abc6e134SChris Mason 	test.type = sk->min_type;
2063abc6e134SChris Mason 	test.offset = sk->min_offset;
2064abc6e134SChris Mason 
2065abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
2066abc6e134SChris Mason 	if (ret < 0)
2067ac8e9819SChris Mason 		return 0;
2068abc6e134SChris Mason 
2069abc6e134SChris Mason 	test.objectid = sk->max_objectid;
2070abc6e134SChris Mason 	test.type = sk->max_type;
2071abc6e134SChris Mason 	test.offset = sk->max_offset;
2072abc6e134SChris Mason 
2073abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
2074abc6e134SChris Mason 	if (ret > 0)
2075ac8e9819SChris Mason 		return 0;
2076ac8e9819SChris Mason 	return 1;
2077ac8e9819SChris Mason }
2078ac8e9819SChris Mason 
2079df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
2080ac8e9819SChris Mason 			       struct btrfs_key *key,
2081ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
20829b6e817dSGerhard Heift 			       size_t *buf_size,
2083ba346b35SGerhard Heift 			       char __user *ubuf,
2084ac8e9819SChris Mason 			       unsigned long *sk_offset,
2085ac8e9819SChris Mason 			       int *num_found)
2086ac8e9819SChris Mason {
2087ac8e9819SChris Mason 	u64 found_transid;
2088ac8e9819SChris Mason 	struct extent_buffer *leaf;
2089ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
2090dd81d459SNaohiro Aota 	struct btrfs_key test;
2091ac8e9819SChris Mason 	unsigned long item_off;
2092ac8e9819SChris Mason 	unsigned long item_len;
2093ac8e9819SChris Mason 	int nritems;
2094ac8e9819SChris Mason 	int i;
2095ac8e9819SChris Mason 	int slot;
2096ac8e9819SChris Mason 	int ret = 0;
2097ac8e9819SChris Mason 
2098ac8e9819SChris Mason 	leaf = path->nodes[0];
2099ac8e9819SChris Mason 	slot = path->slots[0];
2100ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
2101ac8e9819SChris Mason 
2102ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
2103ac8e9819SChris Mason 		i = nritems;
2104ac8e9819SChris Mason 		goto advance_key;
2105ac8e9819SChris Mason 	}
2106ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
2107ac8e9819SChris Mason 
2108ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
2109ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
21103212fa14SJosef Bacik 		item_len = btrfs_item_size(leaf, i);
2111ac8e9819SChris Mason 
211203b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
211303b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
211403b71c6cSGabriel de Perthuis 			continue;
211503b71c6cSGabriel de Perthuis 
21169b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
21178f5f6178SGerhard Heift 			if (*num_found) {
2118ac8e9819SChris Mason 				ret = 1;
21198f5f6178SGerhard Heift 				goto out;
21208f5f6178SGerhard Heift 			}
21218f5f6178SGerhard Heift 
21228f5f6178SGerhard Heift 			/*
21238f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
21248f5f6178SGerhard Heift 			 * handle -EOVERFLOW
21258f5f6178SGerhard Heift 			 */
21268f5f6178SGerhard Heift 
21279b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
2128ac8e9819SChris Mason 			item_len = 0;
21298f5f6178SGerhard Heift 			ret = -EOVERFLOW;
21308f5f6178SGerhard Heift 		}
2131ac8e9819SChris Mason 
21329b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2133ac8e9819SChris Mason 			ret = 1;
213425c9bc2eSGerhard Heift 			goto out;
2135ac8e9819SChris Mason 		}
2136ac8e9819SChris Mason 
2137ac8e9819SChris Mason 		sh.objectid = key->objectid;
2138ac8e9819SChris Mason 		sh.offset = key->offset;
2139ac8e9819SChris Mason 		sh.type = key->type;
2140ac8e9819SChris Mason 		sh.len = item_len;
2141ac8e9819SChris Mason 		sh.transid = found_transid;
2142ac8e9819SChris Mason 
2143a48b73ecSJosef Bacik 		/*
2144a48b73ecSJosef Bacik 		 * Copy search result header. If we fault then loop again so we
2145a48b73ecSJosef Bacik 		 * can fault in the pages and -EFAULT there if there's a
2146a48b73ecSJosef Bacik 		 * problem. Otherwise we'll fault and then copy the buffer in
2147a48b73ecSJosef Bacik 		 * properly this next time through
2148a48b73ecSJosef Bacik 		 */
2149a48b73ecSJosef Bacik 		if (copy_to_user_nofault(ubuf + *sk_offset, &sh, sizeof(sh))) {
2150a48b73ecSJosef Bacik 			ret = 0;
2151ba346b35SGerhard Heift 			goto out;
2152ba346b35SGerhard Heift 		}
2153ba346b35SGerhard Heift 
2154ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2155ac8e9819SChris Mason 
2156ac8e9819SChris Mason 		if (item_len) {
2157ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2158a48b73ecSJosef Bacik 			/*
2159a48b73ecSJosef Bacik 			 * Copy the item, same behavior as above, but reset the
2160a48b73ecSJosef Bacik 			 * * sk_offset so we copy the full thing again.
2161a48b73ecSJosef Bacik 			 */
2162a48b73ecSJosef Bacik 			if (read_extent_buffer_to_user_nofault(leaf, up,
2163ba346b35SGerhard Heift 						item_off, item_len)) {
2164a48b73ecSJosef Bacik 				ret = 0;
2165a48b73ecSJosef Bacik 				*sk_offset -= sizeof(sh);
2166ba346b35SGerhard Heift 				goto out;
2167ba346b35SGerhard Heift 			}
2168ba346b35SGerhard Heift 
2169ac8e9819SChris Mason 			*sk_offset += item_len;
2170ac8e9819SChris Mason 		}
2171e2156867SHugo Mills 		(*num_found)++;
2172ac8e9819SChris Mason 
21738f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
21748f5f6178SGerhard Heift 			goto out;
21758f5f6178SGerhard Heift 
217625c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
217725c9bc2eSGerhard Heift 			ret = 1;
217825c9bc2eSGerhard Heift 			goto out;
217925c9bc2eSGerhard Heift 		}
2180ac8e9819SChris Mason 	}
2181ac8e9819SChris Mason advance_key:
2182ac8e9819SChris Mason 	ret = 0;
2183dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2184dd81d459SNaohiro Aota 	test.type = sk->max_type;
2185dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2186dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2187dd81d459SNaohiro Aota 		ret = 1;
2188dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2189abc6e134SChris Mason 		key->offset++;
2190dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2191abc6e134SChris Mason 		key->offset = 0;
2192abc6e134SChris Mason 		key->type++;
2193dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2194abc6e134SChris Mason 		key->offset = 0;
2195abc6e134SChris Mason 		key->type = 0;
2196abc6e134SChris Mason 		key->objectid++;
2197abc6e134SChris Mason 	} else
2198abc6e134SChris Mason 		ret = 1;
219925c9bc2eSGerhard Heift out:
2200ba346b35SGerhard Heift 	/*
2201ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2202ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2203ba346b35SGerhard Heift 	 *     * all items were found
2204ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2205ba346b35SGerhard Heift 	 *     leaf
2206ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2207ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2208ba346b35SGerhard Heift 	 */
2209ac8e9819SChris Mason 	return ret;
2210ac8e9819SChris Mason }
2211ac8e9819SChris Mason 
2212ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
221312544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
22149b6e817dSGerhard Heift 				 size_t *buf_size,
2215ba346b35SGerhard Heift 				 char __user *ubuf)
2216ac8e9819SChris Mason {
22170b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2218ac8e9819SChris Mason 	struct btrfs_root *root;
2219ac8e9819SChris Mason 	struct btrfs_key key;
2220ac8e9819SChris Mason 	struct btrfs_path *path;
2221ac8e9819SChris Mason 	int ret;
2222ac8e9819SChris Mason 	int num_found = 0;
2223ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2224ac8e9819SChris Mason 
22259b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
22269b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
222712544442SGerhard Heift 		return -EOVERFLOW;
22289b6e817dSGerhard Heift 	}
222912544442SGerhard Heift 
2230ac8e9819SChris Mason 	path = btrfs_alloc_path();
2231ac8e9819SChris Mason 	if (!path)
2232ac8e9819SChris Mason 		return -ENOMEM;
2233ac8e9819SChris Mason 
2234ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2235ac8e9819SChris Mason 		/* search the root of the inode that was passed */
223600246528SJosef Bacik 		root = btrfs_grab_root(BTRFS_I(inode)->root);
2237ac8e9819SChris Mason 	} else {
223856e9357aSDavid Sterba 		root = btrfs_get_fs_root(info, sk->tree_id, true);
2239ac8e9819SChris Mason 		if (IS_ERR(root)) {
2240ac8e9819SChris Mason 			btrfs_free_path(path);
2241ad1e3d56SMisono Tomohiro 			return PTR_ERR(root);
2242ac8e9819SChris Mason 		}
2243ac8e9819SChris Mason 	}
2244ac8e9819SChris Mason 
2245ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2246ac8e9819SChris Mason 	key.type = sk->min_type;
2247ac8e9819SChris Mason 	key.offset = sk->min_offset;
2248ac8e9819SChris Mason 
2249ac8e9819SChris Mason 	while (1) {
2250bb523b40SAndreas Gruenbacher 		ret = -EFAULT;
2251bb523b40SAndreas Gruenbacher 		if (fault_in_writeable(ubuf + sk_offset, *buf_size - sk_offset))
2252a48b73ecSJosef Bacik 			break;
2253a48b73ecSJosef Bacik 
22546174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2255ac8e9819SChris Mason 		if (ret != 0) {
2256ac8e9819SChris Mason 			if (ret > 0)
2257ac8e9819SChris Mason 				ret = 0;
2258ac8e9819SChris Mason 			goto err;
2259ac8e9819SChris Mason 		}
2260df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2261ac8e9819SChris Mason 				 &sk_offset, &num_found);
2262b3b4aa74SDavid Sterba 		btrfs_release_path(path);
226325c9bc2eSGerhard Heift 		if (ret)
2264ac8e9819SChris Mason 			break;
2265ac8e9819SChris Mason 
2266ac8e9819SChris Mason 	}
22678f5f6178SGerhard Heift 	if (ret > 0)
2268ac8e9819SChris Mason 		ret = 0;
2269ac8e9819SChris Mason err:
2270ac8e9819SChris Mason 	sk->nr_items = num_found;
227100246528SJosef Bacik 	btrfs_put_root(root);
2272ac8e9819SChris Mason 	btrfs_free_path(path);
2273ac8e9819SChris Mason 	return ret;
2274ac8e9819SChris Mason }
2275ac8e9819SChris Mason 
2276ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2277ac8e9819SChris Mason 					   void __user *argp)
2278ac8e9819SChris Mason {
2279ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2280ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2281ac8e9819SChris Mason 	struct inode *inode;
2282ac8e9819SChris Mason 	int ret;
22839b6e817dSGerhard Heift 	size_t buf_size;
2284ac8e9819SChris Mason 
2285ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2286ac8e9819SChris Mason 		return -EPERM;
2287ac8e9819SChris Mason 
2288ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2289ac8e9819SChris Mason 
2290ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2291ba346b35SGerhard Heift 		return -EFAULT;
2292ba346b35SGerhard Heift 
2293ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2294ac8e9819SChris Mason 
2295496ad9aaSAl Viro 	inode = file_inode(file);
2296ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
22978f5f6178SGerhard Heift 
22988f5f6178SGerhard Heift 	/*
22998f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
23008f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
23018f5f6178SGerhard Heift 	 */
23028f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
23038f5f6178SGerhard Heift 		ret = 0;
23048f5f6178SGerhard Heift 
2305ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2306ac8e9819SChris Mason 		ret = -EFAULT;
2307ac8e9819SChris Mason 	return ret;
2308ac8e9819SChris Mason }
2309ac8e9819SChris Mason 
2310cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2311cc68a8a5SGerhard Heift 					       void __user *argp)
2312cc68a8a5SGerhard Heift {
2313cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2314cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2315cc68a8a5SGerhard Heift 	struct inode *inode;
2316cc68a8a5SGerhard Heift 	int ret;
2317cc68a8a5SGerhard Heift 	size_t buf_size;
2318ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2319cc68a8a5SGerhard Heift 
2320cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2321cc68a8a5SGerhard Heift 		return -EPERM;
2322cc68a8a5SGerhard Heift 
2323cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2324cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2325cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2326cc68a8a5SGerhard Heift 		return -EFAULT;
2327cc68a8a5SGerhard Heift 
2328cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2329cc68a8a5SGerhard Heift 
2330cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2331cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2332cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2333cc68a8a5SGerhard Heift 
2334cc68a8a5SGerhard Heift 	inode = file_inode(file);
2335cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2336718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2337cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2338cc68a8a5SGerhard Heift 		ret = -EFAULT;
2339cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2340cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2341cc68a8a5SGerhard Heift 		ret = -EFAULT;
2342cc68a8a5SGerhard Heift 
234376dda93cSYan, Zheng 	return ret;
234476dda93cSYan, Zheng }
234576dda93cSYan, Zheng 
234698d377a0STARUISI Hiroaki /*
2347ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2348ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
234998d377a0STARUISI Hiroaki  */
235098d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
235198d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
235298d377a0STARUISI Hiroaki {
235398d377a0STARUISI Hiroaki 	struct btrfs_root *root;
235498d377a0STARUISI Hiroaki 	struct btrfs_key key;
2355ac8e9819SChris Mason 	char *ptr;
235698d377a0STARUISI Hiroaki 	int ret = -1;
235798d377a0STARUISI Hiroaki 	int slot;
235898d377a0STARUISI Hiroaki 	int len;
235998d377a0STARUISI Hiroaki 	int total_len = 0;
236098d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
236198d377a0STARUISI Hiroaki 	struct extent_buffer *l;
236298d377a0STARUISI Hiroaki 	struct btrfs_path *path;
236398d377a0STARUISI Hiroaki 
236498d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
236598d377a0STARUISI Hiroaki 		name[0]='\0';
236698d377a0STARUISI Hiroaki 		return 0;
236798d377a0STARUISI Hiroaki 	}
236898d377a0STARUISI Hiroaki 
236998d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
237098d377a0STARUISI Hiroaki 	if (!path)
237198d377a0STARUISI Hiroaki 		return -ENOMEM;
237298d377a0STARUISI Hiroaki 
2373c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
237498d377a0STARUISI Hiroaki 
237556e9357aSDavid Sterba 	root = btrfs_get_fs_root(info, tree_id, true);
237698d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2377ad1e3d56SMisono Tomohiro 		ret = PTR_ERR(root);
237888234012SJosef Bacik 		root = NULL;
237988234012SJosef Bacik 		goto out;
238088234012SJosef Bacik 	}
238198d377a0STARUISI Hiroaki 
238298d377a0STARUISI Hiroaki 	key.objectid = dirid;
238398d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
23848ad6fcabSChris Mason 	key.offset = (u64)-1;
238598d377a0STARUISI Hiroaki 
238698d377a0STARUISI Hiroaki 	while (1) {
23870ff40a91SMarcos Paulo de Souza 		ret = btrfs_search_backwards(root, &key, path);
238818674c6cSFilipe David Borba Manana 		if (ret < 0)
238918674c6cSFilipe David Borba Manana 			goto out;
239018674c6cSFilipe David Borba Manana 		else if (ret > 0) {
2391ac8e9819SChris Mason 			ret = -ENOENT;
239298d377a0STARUISI Hiroaki 			goto out;
2393ac8e9819SChris Mason 		}
239418674c6cSFilipe David Borba Manana 
239518674c6cSFilipe David Borba Manana 		l = path->nodes[0];
239618674c6cSFilipe David Borba Manana 		slot = path->slots[0];
239798d377a0STARUISI Hiroaki 
239898d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
239998d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
240098d377a0STARUISI Hiroaki 		ptr -= len + 1;
240198d377a0STARUISI Hiroaki 		total_len += len + 1;
2402a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2403a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
240498d377a0STARUISI Hiroaki 			goto out;
2405a696cf35SFilipe David Borba Manana 		}
240698d377a0STARUISI Hiroaki 
240798d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
240898d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
240998d377a0STARUISI Hiroaki 
241098d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
241198d377a0STARUISI Hiroaki 			break;
241298d377a0STARUISI Hiroaki 
2413b3b4aa74SDavid Sterba 		btrfs_release_path(path);
241498d377a0STARUISI Hiroaki 		key.objectid = key.offset;
24158ad6fcabSChris Mason 		key.offset = (u64)-1;
241698d377a0STARUISI Hiroaki 		dirid = key.objectid;
241798d377a0STARUISI Hiroaki 	}
241877906a50SLi Zefan 	memmove(name, ptr, total_len);
241998d377a0STARUISI Hiroaki 	name[total_len] = '\0';
242098d377a0STARUISI Hiroaki 	ret = 0;
242198d377a0STARUISI Hiroaki out:
242200246528SJosef Bacik 	btrfs_put_root(root);
242398d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2424ac8e9819SChris Mason 	return ret;
2425ac8e9819SChris Mason }
2426ac8e9819SChris Mason 
24276623d9a0SChristian Brauner static int btrfs_search_path_in_tree_user(struct user_namespace *mnt_userns,
24286623d9a0SChristian Brauner 				struct inode *inode,
242923d0b79dSTomohiro Misono 				struct btrfs_ioctl_ino_lookup_user_args *args)
243023d0b79dSTomohiro Misono {
243123d0b79dSTomohiro Misono 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
243223d0b79dSTomohiro Misono 	struct super_block *sb = inode->i_sb;
243323d0b79dSTomohiro Misono 	struct btrfs_key upper_limit = BTRFS_I(inode)->location;
243423d0b79dSTomohiro Misono 	u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
243523d0b79dSTomohiro Misono 	u64 dirid = args->dirid;
243623d0b79dSTomohiro Misono 	unsigned long item_off;
243723d0b79dSTomohiro Misono 	unsigned long item_len;
243823d0b79dSTomohiro Misono 	struct btrfs_inode_ref *iref;
243923d0b79dSTomohiro Misono 	struct btrfs_root_ref *rref;
2440b8a49ae1SJosef Bacik 	struct btrfs_root *root = NULL;
244123d0b79dSTomohiro Misono 	struct btrfs_path *path;
244223d0b79dSTomohiro Misono 	struct btrfs_key key, key2;
244323d0b79dSTomohiro Misono 	struct extent_buffer *leaf;
244423d0b79dSTomohiro Misono 	struct inode *temp_inode;
244523d0b79dSTomohiro Misono 	char *ptr;
244623d0b79dSTomohiro Misono 	int slot;
244723d0b79dSTomohiro Misono 	int len;
244823d0b79dSTomohiro Misono 	int total_len = 0;
244923d0b79dSTomohiro Misono 	int ret;
245023d0b79dSTomohiro Misono 
245123d0b79dSTomohiro Misono 	path = btrfs_alloc_path();
245223d0b79dSTomohiro Misono 	if (!path)
245323d0b79dSTomohiro Misono 		return -ENOMEM;
245423d0b79dSTomohiro Misono 
245523d0b79dSTomohiro Misono 	/*
245623d0b79dSTomohiro Misono 	 * If the bottom subvolume does not exist directly under upper_limit,
245723d0b79dSTomohiro Misono 	 * construct the path in from the bottom up.
245823d0b79dSTomohiro Misono 	 */
245923d0b79dSTomohiro Misono 	if (dirid != upper_limit.objectid) {
246023d0b79dSTomohiro Misono 		ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
246123d0b79dSTomohiro Misono 
246256e9357aSDavid Sterba 		root = btrfs_get_fs_root(fs_info, treeid, true);
246323d0b79dSTomohiro Misono 		if (IS_ERR(root)) {
246423d0b79dSTomohiro Misono 			ret = PTR_ERR(root);
246523d0b79dSTomohiro Misono 			goto out;
246623d0b79dSTomohiro Misono 		}
246723d0b79dSTomohiro Misono 
246823d0b79dSTomohiro Misono 		key.objectid = dirid;
246923d0b79dSTomohiro Misono 		key.type = BTRFS_INODE_REF_KEY;
247023d0b79dSTomohiro Misono 		key.offset = (u64)-1;
247123d0b79dSTomohiro Misono 		while (1) {
24720ff40a91SMarcos Paulo de Souza 			ret = btrfs_search_backwards(root, &key, path);
24730ff40a91SMarcos Paulo de Souza 			if (ret < 0)
2474b8a49ae1SJosef Bacik 				goto out_put;
24750ff40a91SMarcos Paulo de Souza 			else if (ret > 0) {
247623d0b79dSTomohiro Misono 				ret = -ENOENT;
2477b8a49ae1SJosef Bacik 				goto out_put;
247823d0b79dSTomohiro Misono 			}
247923d0b79dSTomohiro Misono 
248023d0b79dSTomohiro Misono 			leaf = path->nodes[0];
248123d0b79dSTomohiro Misono 			slot = path->slots[0];
248223d0b79dSTomohiro Misono 
248323d0b79dSTomohiro Misono 			iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
248423d0b79dSTomohiro Misono 			len = btrfs_inode_ref_name_len(leaf, iref);
248523d0b79dSTomohiro Misono 			ptr -= len + 1;
248623d0b79dSTomohiro Misono 			total_len += len + 1;
248723d0b79dSTomohiro Misono 			if (ptr < args->path) {
248823d0b79dSTomohiro Misono 				ret = -ENAMETOOLONG;
2489b8a49ae1SJosef Bacik 				goto out_put;
249023d0b79dSTomohiro Misono 			}
249123d0b79dSTomohiro Misono 
249223d0b79dSTomohiro Misono 			*(ptr + len) = '/';
249323d0b79dSTomohiro Misono 			read_extent_buffer(leaf, ptr,
249423d0b79dSTomohiro Misono 					(unsigned long)(iref + 1), len);
249523d0b79dSTomohiro Misono 
249623d0b79dSTomohiro Misono 			/* Check the read+exec permission of this directory */
249723d0b79dSTomohiro Misono 			ret = btrfs_previous_item(root, path, dirid,
249823d0b79dSTomohiro Misono 						  BTRFS_INODE_ITEM_KEY);
249923d0b79dSTomohiro Misono 			if (ret < 0) {
2500b8a49ae1SJosef Bacik 				goto out_put;
250123d0b79dSTomohiro Misono 			} else if (ret > 0) {
250223d0b79dSTomohiro Misono 				ret = -ENOENT;
2503b8a49ae1SJosef Bacik 				goto out_put;
250423d0b79dSTomohiro Misono 			}
250523d0b79dSTomohiro Misono 
250623d0b79dSTomohiro Misono 			leaf = path->nodes[0];
250723d0b79dSTomohiro Misono 			slot = path->slots[0];
250823d0b79dSTomohiro Misono 			btrfs_item_key_to_cpu(leaf, &key2, slot);
250923d0b79dSTomohiro Misono 			if (key2.objectid != dirid) {
251023d0b79dSTomohiro Misono 				ret = -ENOENT;
2511b8a49ae1SJosef Bacik 				goto out_put;
251223d0b79dSTomohiro Misono 			}
251323d0b79dSTomohiro Misono 
25140202e83fSDavid Sterba 			temp_inode = btrfs_iget(sb, key2.objectid, root);
25153ca57bd6SMisono Tomohiro 			if (IS_ERR(temp_inode)) {
25163ca57bd6SMisono Tomohiro 				ret = PTR_ERR(temp_inode);
2517b8a49ae1SJosef Bacik 				goto out_put;
25183ca57bd6SMisono Tomohiro 			}
25196623d9a0SChristian Brauner 			ret = inode_permission(mnt_userns, temp_inode,
252047291baaSChristian Brauner 					       MAY_READ | MAY_EXEC);
252123d0b79dSTomohiro Misono 			iput(temp_inode);
252223d0b79dSTomohiro Misono 			if (ret) {
252323d0b79dSTomohiro Misono 				ret = -EACCES;
2524b8a49ae1SJosef Bacik 				goto out_put;
252523d0b79dSTomohiro Misono 			}
252623d0b79dSTomohiro Misono 
252723d0b79dSTomohiro Misono 			if (key.offset == upper_limit.objectid)
252823d0b79dSTomohiro Misono 				break;
252923d0b79dSTomohiro Misono 			if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
253023d0b79dSTomohiro Misono 				ret = -EACCES;
2531b8a49ae1SJosef Bacik 				goto out_put;
253223d0b79dSTomohiro Misono 			}
253323d0b79dSTomohiro Misono 
253423d0b79dSTomohiro Misono 			btrfs_release_path(path);
253523d0b79dSTomohiro Misono 			key.objectid = key.offset;
253623d0b79dSTomohiro Misono 			key.offset = (u64)-1;
253723d0b79dSTomohiro Misono 			dirid = key.objectid;
253823d0b79dSTomohiro Misono 		}
253923d0b79dSTomohiro Misono 
254023d0b79dSTomohiro Misono 		memmove(args->path, ptr, total_len);
254123d0b79dSTomohiro Misono 		args->path[total_len] = '\0';
254200246528SJosef Bacik 		btrfs_put_root(root);
2543b8a49ae1SJosef Bacik 		root = NULL;
254423d0b79dSTomohiro Misono 		btrfs_release_path(path);
254523d0b79dSTomohiro Misono 	}
254623d0b79dSTomohiro Misono 
254723d0b79dSTomohiro Misono 	/* Get the bottom subvolume's name from ROOT_REF */
254823d0b79dSTomohiro Misono 	key.objectid = treeid;
254923d0b79dSTomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
255023d0b79dSTomohiro Misono 	key.offset = args->treeid;
2551b8a49ae1SJosef Bacik 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
255223d0b79dSTomohiro Misono 	if (ret < 0) {
255323d0b79dSTomohiro Misono 		goto out;
255423d0b79dSTomohiro Misono 	} else if (ret > 0) {
255523d0b79dSTomohiro Misono 		ret = -ENOENT;
255623d0b79dSTomohiro Misono 		goto out;
255723d0b79dSTomohiro Misono 	}
255823d0b79dSTomohiro Misono 
255923d0b79dSTomohiro Misono 	leaf = path->nodes[0];
256023d0b79dSTomohiro Misono 	slot = path->slots[0];
256123d0b79dSTomohiro Misono 	btrfs_item_key_to_cpu(leaf, &key, slot);
256223d0b79dSTomohiro Misono 
256323d0b79dSTomohiro Misono 	item_off = btrfs_item_ptr_offset(leaf, slot);
25643212fa14SJosef Bacik 	item_len = btrfs_item_size(leaf, slot);
256523d0b79dSTomohiro Misono 	/* Check if dirid in ROOT_REF corresponds to passed dirid */
256623d0b79dSTomohiro Misono 	rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
256723d0b79dSTomohiro Misono 	if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
256823d0b79dSTomohiro Misono 		ret = -EINVAL;
256923d0b79dSTomohiro Misono 		goto out;
257023d0b79dSTomohiro Misono 	}
257123d0b79dSTomohiro Misono 
257223d0b79dSTomohiro Misono 	/* Copy subvolume's name */
257323d0b79dSTomohiro Misono 	item_off += sizeof(struct btrfs_root_ref);
257423d0b79dSTomohiro Misono 	item_len -= sizeof(struct btrfs_root_ref);
257523d0b79dSTomohiro Misono 	read_extent_buffer(leaf, args->name, item_off, item_len);
257623d0b79dSTomohiro Misono 	args->name[item_len] = 0;
257723d0b79dSTomohiro Misono 
2578b8a49ae1SJosef Bacik out_put:
257900246528SJosef Bacik 	btrfs_put_root(root);
258023d0b79dSTomohiro Misono out:
258123d0b79dSTomohiro Misono 	btrfs_free_path(path);
258223d0b79dSTomohiro Misono 	return ret;
258323d0b79dSTomohiro Misono }
258423d0b79dSTomohiro Misono 
2585ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2586ac8e9819SChris Mason 					   void __user *argp)
2587ac8e9819SChris Mason {
2588ac8e9819SChris Mason 	struct btrfs_ioctl_ino_lookup_args *args;
2589ac8e9819SChris Mason 	struct inode *inode;
259001b810b8SDavid Sterba 	int ret = 0;
2591ac8e9819SChris Mason 
25922354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
25932354d08fSJulia Lawall 	if (IS_ERR(args))
25942354d08fSJulia Lawall 		return PTR_ERR(args);
2595c2b96929SDan Carpenter 
2596496ad9aaSAl Viro 	inode = file_inode(file);
2597ac8e9819SChris Mason 
259801b810b8SDavid Sterba 	/*
259901b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
260001b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
260101b810b8SDavid Sterba 	 */
26021b53ac4dSChris Mason 	if (args->treeid == 0)
26031b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
26041b53ac4dSChris Mason 
260501b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
260601b810b8SDavid Sterba 		args->name[0] = 0;
260701b810b8SDavid Sterba 		goto out;
260801b810b8SDavid Sterba 	}
260901b810b8SDavid Sterba 
261001b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
261101b810b8SDavid Sterba 		ret = -EPERM;
261201b810b8SDavid Sterba 		goto out;
261301b810b8SDavid Sterba 	}
261401b810b8SDavid Sterba 
2615ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2616ac8e9819SChris Mason 					args->treeid, args->objectid,
2617ac8e9819SChris Mason 					args->name);
2618ac8e9819SChris Mason 
261901b810b8SDavid Sterba out:
2620ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2621ac8e9819SChris Mason 		ret = -EFAULT;
2622ac8e9819SChris Mason 
2623ac8e9819SChris Mason 	kfree(args);
262498d377a0STARUISI Hiroaki 	return ret;
262598d377a0STARUISI Hiroaki }
262698d377a0STARUISI Hiroaki 
262723d0b79dSTomohiro Misono /*
262823d0b79dSTomohiro Misono  * Version of ino_lookup ioctl (unprivileged)
262923d0b79dSTomohiro Misono  *
263023d0b79dSTomohiro Misono  * The main differences from ino_lookup ioctl are:
263123d0b79dSTomohiro Misono  *
263223d0b79dSTomohiro Misono  *   1. Read + Exec permission will be checked using inode_permission() during
263323d0b79dSTomohiro Misono  *      path construction. -EACCES will be returned in case of failure.
263423d0b79dSTomohiro Misono  *   2. Path construction will be stopped at the inode number which corresponds
263523d0b79dSTomohiro Misono  *      to the fd with which this ioctl is called. If constructed path does not
263623d0b79dSTomohiro Misono  *      exist under fd's inode, -EACCES will be returned.
263723d0b79dSTomohiro Misono  *   3. The name of bottom subvolume is also searched and filled.
263823d0b79dSTomohiro Misono  */
263923d0b79dSTomohiro Misono static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
264023d0b79dSTomohiro Misono {
264123d0b79dSTomohiro Misono 	struct btrfs_ioctl_ino_lookup_user_args *args;
264223d0b79dSTomohiro Misono 	struct inode *inode;
264323d0b79dSTomohiro Misono 	int ret;
264423d0b79dSTomohiro Misono 
264523d0b79dSTomohiro Misono 	args = memdup_user(argp, sizeof(*args));
264623d0b79dSTomohiro Misono 	if (IS_ERR(args))
264723d0b79dSTomohiro Misono 		return PTR_ERR(args);
264823d0b79dSTomohiro Misono 
264923d0b79dSTomohiro Misono 	inode = file_inode(file);
265023d0b79dSTomohiro Misono 
265123d0b79dSTomohiro Misono 	if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
265223d0b79dSTomohiro Misono 	    BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
265323d0b79dSTomohiro Misono 		/*
265423d0b79dSTomohiro Misono 		 * The subvolume does not exist under fd with which this is
265523d0b79dSTomohiro Misono 		 * called
265623d0b79dSTomohiro Misono 		 */
265723d0b79dSTomohiro Misono 		kfree(args);
265823d0b79dSTomohiro Misono 		return -EACCES;
265923d0b79dSTomohiro Misono 	}
266023d0b79dSTomohiro Misono 
26616623d9a0SChristian Brauner 	ret = btrfs_search_path_in_tree_user(file_mnt_user_ns(file), inode, args);
266223d0b79dSTomohiro Misono 
266323d0b79dSTomohiro Misono 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
266423d0b79dSTomohiro Misono 		ret = -EFAULT;
266523d0b79dSTomohiro Misono 
266623d0b79dSTomohiro Misono 	kfree(args);
266723d0b79dSTomohiro Misono 	return ret;
266823d0b79dSTomohiro Misono }
266923d0b79dSTomohiro Misono 
2670b64ec075STomohiro Misono /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2671b64ec075STomohiro Misono static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2672b64ec075STomohiro Misono {
2673b64ec075STomohiro Misono 	struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2674b64ec075STomohiro Misono 	struct btrfs_fs_info *fs_info;
2675b64ec075STomohiro Misono 	struct btrfs_root *root;
2676b64ec075STomohiro Misono 	struct btrfs_path *path;
2677b64ec075STomohiro Misono 	struct btrfs_key key;
2678b64ec075STomohiro Misono 	struct btrfs_root_item *root_item;
2679b64ec075STomohiro Misono 	struct btrfs_root_ref *rref;
2680b64ec075STomohiro Misono 	struct extent_buffer *leaf;
2681b64ec075STomohiro Misono 	unsigned long item_off;
2682b64ec075STomohiro Misono 	unsigned long item_len;
2683b64ec075STomohiro Misono 	struct inode *inode;
2684b64ec075STomohiro Misono 	int slot;
2685b64ec075STomohiro Misono 	int ret = 0;
2686b64ec075STomohiro Misono 
2687b64ec075STomohiro Misono 	path = btrfs_alloc_path();
2688b64ec075STomohiro Misono 	if (!path)
2689b64ec075STomohiro Misono 		return -ENOMEM;
2690b64ec075STomohiro Misono 
2691b64ec075STomohiro Misono 	subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2692b64ec075STomohiro Misono 	if (!subvol_info) {
2693b64ec075STomohiro Misono 		btrfs_free_path(path);
2694b64ec075STomohiro Misono 		return -ENOMEM;
2695b64ec075STomohiro Misono 	}
2696b64ec075STomohiro Misono 
2697b64ec075STomohiro Misono 	inode = file_inode(file);
2698b64ec075STomohiro Misono 	fs_info = BTRFS_I(inode)->root->fs_info;
2699b64ec075STomohiro Misono 
2700b64ec075STomohiro Misono 	/* Get root_item of inode's subvolume */
2701b64ec075STomohiro Misono 	key.objectid = BTRFS_I(inode)->root->root_key.objectid;
270256e9357aSDavid Sterba 	root = btrfs_get_fs_root(fs_info, key.objectid, true);
2703b64ec075STomohiro Misono 	if (IS_ERR(root)) {
2704b64ec075STomohiro Misono 		ret = PTR_ERR(root);
270504734e84SJosef Bacik 		goto out_free;
270604734e84SJosef Bacik 	}
2707b64ec075STomohiro Misono 	root_item = &root->root_item;
2708b64ec075STomohiro Misono 
2709b64ec075STomohiro Misono 	subvol_info->treeid = key.objectid;
2710b64ec075STomohiro Misono 
2711b64ec075STomohiro Misono 	subvol_info->generation = btrfs_root_generation(root_item);
2712b64ec075STomohiro Misono 	subvol_info->flags = btrfs_root_flags(root_item);
2713b64ec075STomohiro Misono 
2714b64ec075STomohiro Misono 	memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2715b64ec075STomohiro Misono 	memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2716b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2717b64ec075STomohiro Misono 	memcpy(subvol_info->received_uuid, root_item->received_uuid,
2718b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2719b64ec075STomohiro Misono 
2720b64ec075STomohiro Misono 	subvol_info->ctransid = btrfs_root_ctransid(root_item);
2721b64ec075STomohiro Misono 	subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2722b64ec075STomohiro Misono 	subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2723b64ec075STomohiro Misono 
2724b64ec075STomohiro Misono 	subvol_info->otransid = btrfs_root_otransid(root_item);
2725b64ec075STomohiro Misono 	subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2726b64ec075STomohiro Misono 	subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2727b64ec075STomohiro Misono 
2728b64ec075STomohiro Misono 	subvol_info->stransid = btrfs_root_stransid(root_item);
2729b64ec075STomohiro Misono 	subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2730b64ec075STomohiro Misono 	subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2731b64ec075STomohiro Misono 
2732b64ec075STomohiro Misono 	subvol_info->rtransid = btrfs_root_rtransid(root_item);
2733b64ec075STomohiro Misono 	subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2734b64ec075STomohiro Misono 	subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2735b64ec075STomohiro Misono 
2736b64ec075STomohiro Misono 	if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2737b64ec075STomohiro Misono 		/* Search root tree for ROOT_BACKREF of this subvolume */
2738b64ec075STomohiro Misono 		key.type = BTRFS_ROOT_BACKREF_KEY;
2739b64ec075STomohiro Misono 		key.offset = 0;
274004734e84SJosef Bacik 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2741b64ec075STomohiro Misono 		if (ret < 0) {
2742b64ec075STomohiro Misono 			goto out;
2743b64ec075STomohiro Misono 		} else if (path->slots[0] >=
2744b64ec075STomohiro Misono 			   btrfs_header_nritems(path->nodes[0])) {
274504734e84SJosef Bacik 			ret = btrfs_next_leaf(fs_info->tree_root, path);
2746b64ec075STomohiro Misono 			if (ret < 0) {
2747b64ec075STomohiro Misono 				goto out;
2748b64ec075STomohiro Misono 			} else if (ret > 0) {
2749b64ec075STomohiro Misono 				ret = -EUCLEAN;
2750b64ec075STomohiro Misono 				goto out;
2751b64ec075STomohiro Misono 			}
2752b64ec075STomohiro Misono 		}
2753b64ec075STomohiro Misono 
2754b64ec075STomohiro Misono 		leaf = path->nodes[0];
2755b64ec075STomohiro Misono 		slot = path->slots[0];
2756b64ec075STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
2757b64ec075STomohiro Misono 		if (key.objectid == subvol_info->treeid &&
2758b64ec075STomohiro Misono 		    key.type == BTRFS_ROOT_BACKREF_KEY) {
2759b64ec075STomohiro Misono 			subvol_info->parent_id = key.offset;
2760b64ec075STomohiro Misono 
2761b64ec075STomohiro Misono 			rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2762b64ec075STomohiro Misono 			subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2763b64ec075STomohiro Misono 
2764b64ec075STomohiro Misono 			item_off = btrfs_item_ptr_offset(leaf, slot)
2765b64ec075STomohiro Misono 					+ sizeof(struct btrfs_root_ref);
27663212fa14SJosef Bacik 			item_len = btrfs_item_size(leaf, slot)
2767b64ec075STomohiro Misono 					- sizeof(struct btrfs_root_ref);
2768b64ec075STomohiro Misono 			read_extent_buffer(leaf, subvol_info->name,
2769b64ec075STomohiro Misono 					   item_off, item_len);
2770b64ec075STomohiro Misono 		} else {
2771b64ec075STomohiro Misono 			ret = -ENOENT;
2772b64ec075STomohiro Misono 			goto out;
2773b64ec075STomohiro Misono 		}
2774b64ec075STomohiro Misono 	}
2775b64ec075STomohiro Misono 
2776b64ec075STomohiro Misono 	if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2777b64ec075STomohiro Misono 		ret = -EFAULT;
2778b64ec075STomohiro Misono 
2779b64ec075STomohiro Misono out:
278000246528SJosef Bacik 	btrfs_put_root(root);
278104734e84SJosef Bacik out_free:
2782b64ec075STomohiro Misono 	btrfs_free_path(path);
2783b091f7feSWaiman Long 	kfree(subvol_info);
2784b64ec075STomohiro Misono 	return ret;
2785b64ec075STomohiro Misono }
2786b64ec075STomohiro Misono 
278742e4b520STomohiro Misono /*
278842e4b520STomohiro Misono  * Return ROOT_REF information of the subvolume containing this inode
278942e4b520STomohiro Misono  * except the subvolume name.
279042e4b520STomohiro Misono  */
279142e4b520STomohiro Misono static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
279242e4b520STomohiro Misono {
279342e4b520STomohiro Misono 	struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
279442e4b520STomohiro Misono 	struct btrfs_root_ref *rref;
279542e4b520STomohiro Misono 	struct btrfs_root *root;
279642e4b520STomohiro Misono 	struct btrfs_path *path;
279742e4b520STomohiro Misono 	struct btrfs_key key;
279842e4b520STomohiro Misono 	struct extent_buffer *leaf;
279942e4b520STomohiro Misono 	struct inode *inode;
280042e4b520STomohiro Misono 	u64 objectid;
280142e4b520STomohiro Misono 	int slot;
280242e4b520STomohiro Misono 	int ret;
280342e4b520STomohiro Misono 	u8 found;
280442e4b520STomohiro Misono 
280542e4b520STomohiro Misono 	path = btrfs_alloc_path();
280642e4b520STomohiro Misono 	if (!path)
280742e4b520STomohiro Misono 		return -ENOMEM;
280842e4b520STomohiro Misono 
280942e4b520STomohiro Misono 	rootrefs = memdup_user(argp, sizeof(*rootrefs));
281042e4b520STomohiro Misono 	if (IS_ERR(rootrefs)) {
281142e4b520STomohiro Misono 		btrfs_free_path(path);
281242e4b520STomohiro Misono 		return PTR_ERR(rootrefs);
281342e4b520STomohiro Misono 	}
281442e4b520STomohiro Misono 
281542e4b520STomohiro Misono 	inode = file_inode(file);
281642e4b520STomohiro Misono 	root = BTRFS_I(inode)->root->fs_info->tree_root;
281742e4b520STomohiro Misono 	objectid = BTRFS_I(inode)->root->root_key.objectid;
281842e4b520STomohiro Misono 
281942e4b520STomohiro Misono 	key.objectid = objectid;
282042e4b520STomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
282142e4b520STomohiro Misono 	key.offset = rootrefs->min_treeid;
282242e4b520STomohiro Misono 	found = 0;
282342e4b520STomohiro Misono 
282442e4b520STomohiro Misono 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
282542e4b520STomohiro Misono 	if (ret < 0) {
282642e4b520STomohiro Misono 		goto out;
282742e4b520STomohiro Misono 	} else if (path->slots[0] >=
282842e4b520STomohiro Misono 		   btrfs_header_nritems(path->nodes[0])) {
282942e4b520STomohiro Misono 		ret = btrfs_next_leaf(root, path);
283042e4b520STomohiro Misono 		if (ret < 0) {
283142e4b520STomohiro Misono 			goto out;
283242e4b520STomohiro Misono 		} else if (ret > 0) {
283342e4b520STomohiro Misono 			ret = -EUCLEAN;
283442e4b520STomohiro Misono 			goto out;
283542e4b520STomohiro Misono 		}
283642e4b520STomohiro Misono 	}
283742e4b520STomohiro Misono 	while (1) {
283842e4b520STomohiro Misono 		leaf = path->nodes[0];
283942e4b520STomohiro Misono 		slot = path->slots[0];
284042e4b520STomohiro Misono 
284142e4b520STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
284242e4b520STomohiro Misono 		if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
284342e4b520STomohiro Misono 			ret = 0;
284442e4b520STomohiro Misono 			goto out;
284542e4b520STomohiro Misono 		}
284642e4b520STomohiro Misono 
284742e4b520STomohiro Misono 		if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
284842e4b520STomohiro Misono 			ret = -EOVERFLOW;
284942e4b520STomohiro Misono 			goto out;
285042e4b520STomohiro Misono 		}
285142e4b520STomohiro Misono 
285242e4b520STomohiro Misono 		rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
285342e4b520STomohiro Misono 		rootrefs->rootref[found].treeid = key.offset;
285442e4b520STomohiro Misono 		rootrefs->rootref[found].dirid =
285542e4b520STomohiro Misono 				  btrfs_root_ref_dirid(leaf, rref);
285642e4b520STomohiro Misono 		found++;
285742e4b520STomohiro Misono 
285842e4b520STomohiro Misono 		ret = btrfs_next_item(root, path);
285942e4b520STomohiro Misono 		if (ret < 0) {
286042e4b520STomohiro Misono 			goto out;
286142e4b520STomohiro Misono 		} else if (ret > 0) {
286242e4b520STomohiro Misono 			ret = -EUCLEAN;
286342e4b520STomohiro Misono 			goto out;
286442e4b520STomohiro Misono 		}
286542e4b520STomohiro Misono 	}
286642e4b520STomohiro Misono 
286742e4b520STomohiro Misono out:
286842e4b520STomohiro Misono 	if (!ret || ret == -EOVERFLOW) {
286942e4b520STomohiro Misono 		rootrefs->num_items = found;
287042e4b520STomohiro Misono 		/* update min_treeid for next search */
287142e4b520STomohiro Misono 		if (found)
287242e4b520STomohiro Misono 			rootrefs->min_treeid =
287342e4b520STomohiro Misono 				rootrefs->rootref[found - 1].treeid + 1;
287442e4b520STomohiro Misono 		if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
287542e4b520STomohiro Misono 			ret = -EFAULT;
287642e4b520STomohiro Misono 	}
287742e4b520STomohiro Misono 
287842e4b520STomohiro Misono 	kfree(rootrefs);
287942e4b520STomohiro Misono 	btrfs_free_path(path);
288042e4b520STomohiro Misono 
288142e4b520STomohiro Misono 	return ret;
288242e4b520STomohiro Misono }
288342e4b520STomohiro Misono 
288476dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2885949964c9SMarcos Paulo de Souza 					     void __user *arg,
2886949964c9SMarcos Paulo de Souza 					     bool destroy_v2)
288776dda93cSYan, Zheng {
288854563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
28890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
289076dda93cSYan, Zheng 	struct dentry *dentry;
28912b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
289276dda93cSYan, Zheng 	struct inode *inode;
289376dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
289476dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
2895949964c9SMarcos Paulo de Souza 	struct btrfs_ioctl_vol_args *vol_args = NULL;
2896949964c9SMarcos Paulo de Souza 	struct btrfs_ioctl_vol_args_v2 *vol_args2 = NULL;
2897c4ed533bSChristian Brauner 	struct user_namespace *mnt_userns = file_mnt_user_ns(file);
2898949964c9SMarcos Paulo de Souza 	char *subvol_name, *subvol_name_ptr = NULL;
2899949964c9SMarcos Paulo de Souza 	int subvol_namelen;
290076dda93cSYan, Zheng 	int err = 0;
2901949964c9SMarcos Paulo de Souza 	bool destroy_parent = false;
290276dda93cSYan, Zheng 
2903949964c9SMarcos Paulo de Souza 	if (destroy_v2) {
2904949964c9SMarcos Paulo de Souza 		vol_args2 = memdup_user(arg, sizeof(*vol_args2));
2905949964c9SMarcos Paulo de Souza 		if (IS_ERR(vol_args2))
2906949964c9SMarcos Paulo de Souza 			return PTR_ERR(vol_args2);
2907325c50e3SJeff Mahoney 
2908949964c9SMarcos Paulo de Souza 		if (vol_args2->flags & ~BTRFS_SUBVOL_DELETE_ARGS_MASK) {
2909949964c9SMarcos Paulo de Souza 			err = -EOPNOTSUPP;
2910949964c9SMarcos Paulo de Souza 			goto out;
2911949964c9SMarcos Paulo de Souza 		}
291276dda93cSYan, Zheng 
2913949964c9SMarcos Paulo de Souza 		/*
2914949964c9SMarcos Paulo de Souza 		 * If SPEC_BY_ID is not set, we are looking for the subvolume by
2915949964c9SMarcos Paulo de Souza 		 * name, same as v1 currently does.
2916949964c9SMarcos Paulo de Souza 		 */
2917949964c9SMarcos Paulo de Souza 		if (!(vol_args2->flags & BTRFS_SUBVOL_SPEC_BY_ID)) {
2918949964c9SMarcos Paulo de Souza 			vol_args2->name[BTRFS_SUBVOL_NAME_MAX] = 0;
2919949964c9SMarcos Paulo de Souza 			subvol_name = vol_args2->name;
2920949964c9SMarcos Paulo de Souza 
2921949964c9SMarcos Paulo de Souza 			err = mnt_want_write_file(file);
2922949964c9SMarcos Paulo de Souza 			if (err)
2923949964c9SMarcos Paulo de Souza 				goto out;
2924949964c9SMarcos Paulo de Souza 		} else {
2925aabb34e7SChristian Brauner 			struct inode *old_dir;
2926c4ed533bSChristian Brauner 
2927949964c9SMarcos Paulo de Souza 			if (vol_args2->subvolid < BTRFS_FIRST_FREE_OBJECTID) {
292876dda93cSYan, Zheng 				err = -EINVAL;
292976dda93cSYan, Zheng 				goto out;
293076dda93cSYan, Zheng 			}
293176dda93cSYan, Zheng 
2932a561be71SAl Viro 			err = mnt_want_write_file(file);
293376dda93cSYan, Zheng 			if (err)
293476dda93cSYan, Zheng 				goto out;
293576dda93cSYan, Zheng 
2936949964c9SMarcos Paulo de Souza 			dentry = btrfs_get_dentry(fs_info->sb,
2937949964c9SMarcos Paulo de Souza 					BTRFS_FIRST_FREE_OBJECTID,
2938949964c9SMarcos Paulo de Souza 					vol_args2->subvolid, 0, 0);
2939949964c9SMarcos Paulo de Souza 			if (IS_ERR(dentry)) {
2940949964c9SMarcos Paulo de Souza 				err = PTR_ERR(dentry);
2941949964c9SMarcos Paulo de Souza 				goto out_drop_write;
2942949964c9SMarcos Paulo de Souza 			}
2943949964c9SMarcos Paulo de Souza 
2944949964c9SMarcos Paulo de Souza 			/*
2945949964c9SMarcos Paulo de Souza 			 * Change the default parent since the subvolume being
2946949964c9SMarcos Paulo de Souza 			 * deleted can be outside of the current mount point.
2947949964c9SMarcos Paulo de Souza 			 */
2948949964c9SMarcos Paulo de Souza 			parent = btrfs_get_parent(dentry);
2949949964c9SMarcos Paulo de Souza 
2950949964c9SMarcos Paulo de Souza 			/*
2951949964c9SMarcos Paulo de Souza 			 * At this point dentry->d_name can point to '/' if the
2952949964c9SMarcos Paulo de Souza 			 * subvolume we want to destroy is outsite of the
2953949964c9SMarcos Paulo de Souza 			 * current mount point, so we need to release the
2954949964c9SMarcos Paulo de Souza 			 * current dentry and execute the lookup to return a new
2955949964c9SMarcos Paulo de Souza 			 * one with ->d_name pointing to the
2956949964c9SMarcos Paulo de Souza 			 * <mount point>/subvol_name.
2957949964c9SMarcos Paulo de Souza 			 */
2958949964c9SMarcos Paulo de Souza 			dput(dentry);
2959949964c9SMarcos Paulo de Souza 			if (IS_ERR(parent)) {
2960949964c9SMarcos Paulo de Souza 				err = PTR_ERR(parent);
2961949964c9SMarcos Paulo de Souza 				goto out_drop_write;
2962949964c9SMarcos Paulo de Souza 			}
2963aabb34e7SChristian Brauner 			old_dir = dir;
2964949964c9SMarcos Paulo de Souza 			dir = d_inode(parent);
2965949964c9SMarcos Paulo de Souza 
2966949964c9SMarcos Paulo de Souza 			/*
2967949964c9SMarcos Paulo de Souza 			 * If v2 was used with SPEC_BY_ID, a new parent was
2968949964c9SMarcos Paulo de Souza 			 * allocated since the subvolume can be outside of the
2969949964c9SMarcos Paulo de Souza 			 * current mount point. Later on we need to release this
2970949964c9SMarcos Paulo de Souza 			 * new parent dentry.
2971949964c9SMarcos Paulo de Souza 			 */
2972949964c9SMarcos Paulo de Souza 			destroy_parent = true;
2973949964c9SMarcos Paulo de Souza 
2974aabb34e7SChristian Brauner 			/*
2975aabb34e7SChristian Brauner 			 * On idmapped mounts, deletion via subvolid is
2976aabb34e7SChristian Brauner 			 * restricted to subvolumes that are immediate
2977aabb34e7SChristian Brauner 			 * ancestors of the inode referenced by the file
2978aabb34e7SChristian Brauner 			 * descriptor in the ioctl. Otherwise the idmapping
2979aabb34e7SChristian Brauner 			 * could potentially be abused to delete subvolumes
2980aabb34e7SChristian Brauner 			 * anywhere in the filesystem the user wouldn't be able
2981aabb34e7SChristian Brauner 			 * to delete without an idmapped mount.
2982aabb34e7SChristian Brauner 			 */
2983aabb34e7SChristian Brauner 			if (old_dir != dir && mnt_userns != &init_user_ns) {
2984aabb34e7SChristian Brauner 				err = -EOPNOTSUPP;
2985aabb34e7SChristian Brauner 				goto free_parent;
2986aabb34e7SChristian Brauner 			}
2987aabb34e7SChristian Brauner 
2988949964c9SMarcos Paulo de Souza 			subvol_name_ptr = btrfs_get_subvol_name_from_objectid(
2989949964c9SMarcos Paulo de Souza 						fs_info, vol_args2->subvolid);
2990949964c9SMarcos Paulo de Souza 			if (IS_ERR(subvol_name_ptr)) {
2991949964c9SMarcos Paulo de Souza 				err = PTR_ERR(subvol_name_ptr);
2992949964c9SMarcos Paulo de Souza 				goto free_parent;
2993949964c9SMarcos Paulo de Souza 			}
29941a9fd417SDavid Sterba 			/* subvol_name_ptr is already nul terminated */
2995949964c9SMarcos Paulo de Souza 			subvol_name = (char *)kbasename(subvol_name_ptr);
2996949964c9SMarcos Paulo de Souza 		}
2997949964c9SMarcos Paulo de Souza 	} else {
2998949964c9SMarcos Paulo de Souza 		vol_args = memdup_user(arg, sizeof(*vol_args));
2999949964c9SMarcos Paulo de Souza 		if (IS_ERR(vol_args))
3000949964c9SMarcos Paulo de Souza 			return PTR_ERR(vol_args);
3001949964c9SMarcos Paulo de Souza 
3002949964c9SMarcos Paulo de Souza 		vol_args->name[BTRFS_PATH_NAME_MAX] = 0;
3003949964c9SMarcos Paulo de Souza 		subvol_name = vol_args->name;
3004949964c9SMarcos Paulo de Souza 
3005949964c9SMarcos Paulo de Souza 		err = mnt_want_write_file(file);
3006949964c9SMarcos Paulo de Souza 		if (err)
3007949964c9SMarcos Paulo de Souza 			goto out;
3008949964c9SMarcos Paulo de Souza 	}
3009949964c9SMarcos Paulo de Souza 
3010949964c9SMarcos Paulo de Souza 	subvol_namelen = strlen(subvol_name);
3011949964c9SMarcos Paulo de Souza 
3012949964c9SMarcos Paulo de Souza 	if (strchr(subvol_name, '/') ||
3013949964c9SMarcos Paulo de Souza 	    strncmp(subvol_name, "..", subvol_namelen) == 0) {
3014949964c9SMarcos Paulo de Souza 		err = -EINVAL;
3015949964c9SMarcos Paulo de Souza 		goto free_subvol_name;
3016949964c9SMarcos Paulo de Souza 	}
3017949964c9SMarcos Paulo de Souza 
3018949964c9SMarcos Paulo de Souza 	if (!S_ISDIR(dir->i_mode)) {
3019949964c9SMarcos Paulo de Souza 		err = -ENOTDIR;
3020949964c9SMarcos Paulo de Souza 		goto free_subvol_name;
3021949964c9SMarcos Paulo de Souza 	}
3022521e0546SDavid Sterba 
302300235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
302400235411SAl Viro 	if (err == -EINTR)
3025949964c9SMarcos Paulo de Souza 		goto free_subvol_name;
3026c4ed533bSChristian Brauner 	dentry = lookup_one(mnt_userns, subvol_name, parent, subvol_namelen);
302776dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
302876dda93cSYan, Zheng 		err = PTR_ERR(dentry);
302976dda93cSYan, Zheng 		goto out_unlock_dir;
303076dda93cSYan, Zheng 	}
303176dda93cSYan, Zheng 
30322b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
303376dda93cSYan, Zheng 		err = -ENOENT;
303476dda93cSYan, Zheng 		goto out_dput;
303576dda93cSYan, Zheng 	}
303676dda93cSYan, Zheng 
30372b0143b5SDavid Howells 	inode = d_inode(dentry);
30384260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
30394260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
30404260f7c7SSage Weil 		/*
30414260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
30424260f7c7SSage Weil 		 * option, when the user has write+exec access to the
30434260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
30444260f7c7SSage Weil 		 * allowed.
30454260f7c7SSage Weil 		 *
30464260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
30474260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
30484260f7c7SSage Weil 		 * otherwise be able to delete.
30494260f7c7SSage Weil 		 *
30504260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
30514260f7c7SSage Weil 		 * rmdir(2).
30524260f7c7SSage Weil 		 */
30534260f7c7SSage Weil 		err = -EPERM;
30540b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
30554260f7c7SSage Weil 			goto out_dput;
30564260f7c7SSage Weil 
30574260f7c7SSage Weil 		/*
30584260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
30594260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
30604260f7c7SSage Weil 		 * must be called on the dentry referencing the root
30614260f7c7SSage Weil 		 * of the subvol, not a random directory contained
30624260f7c7SSage Weil 		 * within it.
30634260f7c7SSage Weil 		 */
30644260f7c7SSage Weil 		err = -EINVAL;
30654260f7c7SSage Weil 		if (root == dest)
30664260f7c7SSage Weil 			goto out_dput;
30674260f7c7SSage Weil 
3068c4ed533bSChristian Brauner 		err = inode_permission(mnt_userns, inode, MAY_WRITE | MAY_EXEC);
30694260f7c7SSage Weil 		if (err)
30704260f7c7SSage Weil 			goto out_dput;
30715c39da5bSMiao Xie 	}
30724260f7c7SSage Weil 
30735c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
3074c4ed533bSChristian Brauner 	err = btrfs_may_delete(mnt_userns, dir, dentry, 1);
30754260f7c7SSage Weil 	if (err)
30764260f7c7SSage Weil 		goto out_dput;
30774260f7c7SSage Weil 
30784a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
307976dda93cSYan, Zheng 		err = -EINVAL;
308076dda93cSYan, Zheng 		goto out_dput;
308176dda93cSYan, Zheng 	}
308276dda93cSYan, Zheng 
308364708539SJosef Bacik 	btrfs_inode_lock(inode, 0);
3084f60a2364SMisono Tomohiro 	err = btrfs_delete_subvolume(dir, dentry);
308564708539SJosef Bacik 	btrfs_inode_unlock(inode, 0);
308646008d9dSAmir Goldstein 	if (!err) {
308746008d9dSAmir Goldstein 		fsnotify_rmdir(dir, dentry);
308876dda93cSYan, Zheng 		d_delete(dentry);
308946008d9dSAmir Goldstein 	}
3090fa6ac876SLiu Bo 
309176dda93cSYan, Zheng out_dput:
309276dda93cSYan, Zheng 	dput(dentry);
309376dda93cSYan, Zheng out_unlock_dir:
309464708539SJosef Bacik 	btrfs_inode_unlock(dir, 0);
3095949964c9SMarcos Paulo de Souza free_subvol_name:
3096949964c9SMarcos Paulo de Souza 	kfree(subvol_name_ptr);
3097949964c9SMarcos Paulo de Souza free_parent:
3098949964c9SMarcos Paulo de Souza 	if (destroy_parent)
3099949964c9SMarcos Paulo de Souza 		dput(parent);
310000235411SAl Viro out_drop_write:
31012a79f17eSAl Viro 	mnt_drop_write_file(file);
310276dda93cSYan, Zheng out:
3103949964c9SMarcos Paulo de Souza 	kfree(vol_args2);
310476dda93cSYan, Zheng 	kfree(vol_args);
310576dda93cSYan, Zheng 	return err;
310676dda93cSYan, Zheng }
310776dda93cSYan, Zheng 
31081e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
3109f46b5a66SChristoph Hellwig {
3110496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3111f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
3112c853a578SGoldwyn Rodrigues 	struct btrfs_ioctl_defrag_range_args range = {0};
3113c146afadSYan Zheng 	int ret;
3114c146afadSYan Zheng 
311525122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
311625122d15SIlya Dryomov 	if (ret)
311725122d15SIlya Dryomov 		return ret;
3118b83cc969SLi Zefan 
311925122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
312025122d15SIlya Dryomov 		ret = -EROFS;
312125122d15SIlya Dryomov 		goto out;
31225ac00addSStefan Behrens 	}
3123f46b5a66SChristoph Hellwig 
3124f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
3125f46b5a66SChristoph Hellwig 	case S_IFDIR:
3126e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
3127e441d54dSChris Mason 			ret = -EPERM;
3128e441d54dSChris Mason 			goto out;
3129e441d54dSChris Mason 		}
3130de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
3131f46b5a66SChristoph Hellwig 		break;
3132f46b5a66SChristoph Hellwig 	case S_IFREG:
3133616d374eSAdam Borowski 		/*
3134616d374eSAdam Borowski 		 * Note that this does not check the file descriptor for write
3135616d374eSAdam Borowski 		 * access. This prevents defragmenting executables that are
3136616d374eSAdam Borowski 		 * running and allows defrag on files open in read-only mode.
3137616d374eSAdam Borowski 		 */
3138616d374eSAdam Borowski 		if (!capable(CAP_SYS_ADMIN) &&
313947291baaSChristian Brauner 		    inode_permission(&init_user_ns, inode, MAY_WRITE)) {
3140616d374eSAdam Borowski 			ret = -EPERM;
3141e441d54dSChris Mason 			goto out;
3142e441d54dSChris Mason 		}
31431e701a32SChris Mason 
31441e701a32SChris Mason 		if (argp) {
3145c853a578SGoldwyn Rodrigues 			if (copy_from_user(&range, argp, sizeof(range))) {
31461e701a32SChris Mason 				ret = -EFAULT;
3147683be16eSDan Carpenter 				goto out;
31481e701a32SChris Mason 			}
31491e701a32SChris Mason 			/* compression requires us to start the IO */
3150c853a578SGoldwyn Rodrigues 			if ((range.flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3151c853a578SGoldwyn Rodrigues 				range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
3152c853a578SGoldwyn Rodrigues 				range.extent_thresh = (u32)-1;
31531e701a32SChris Mason 			}
31541e701a32SChris Mason 		} else {
31551e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
3156c853a578SGoldwyn Rodrigues 			range.len = (u64)-1;
31571e701a32SChris Mason 		}
31581ccc2e8aSQu Wenruo 		ret = btrfs_defrag_file(file_inode(file), &file->f_ra,
3159c853a578SGoldwyn Rodrigues 					&range, BTRFS_OLDEST_GENERATION, 0);
31604cb5300bSChris Mason 		if (ret > 0)
31614cb5300bSChris Mason 			ret = 0;
3162f46b5a66SChristoph Hellwig 		break;
31638929ecfaSYan, Zheng 	default:
31648929ecfaSYan, Zheng 		ret = -EINVAL;
3165f46b5a66SChristoph Hellwig 	}
3166e441d54dSChris Mason out:
316725122d15SIlya Dryomov 	mnt_drop_write_file(file);
3168e441d54dSChris Mason 	return ret;
3169f46b5a66SChristoph Hellwig }
3170f46b5a66SChristoph Hellwig 
31712ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3172f46b5a66SChristoph Hellwig {
3173f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
3174f46b5a66SChristoph Hellwig 	int ret;
3175f46b5a66SChristoph Hellwig 
3176e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
3177e441d54dSChris Mason 		return -EPERM;
3178e441d54dSChris Mason 
3179c3e1f96cSGoldwyn Rodrigues 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_ADD))
3180e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3181c9e9f97bSIlya Dryomov 
3182dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
3183c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
3184c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
3185c9e9f97bSIlya Dryomov 		goto out;
3186c9e9f97bSIlya Dryomov 	}
3187f46b5a66SChristoph Hellwig 
31885516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
31892ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
3190f46b5a66SChristoph Hellwig 
319143d20761SAnand Jain 	if (!ret)
31920b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
319343d20761SAnand Jain 
3194f46b5a66SChristoph Hellwig 	kfree(vol_args);
3195c9e9f97bSIlya Dryomov out:
3196c3e1f96cSGoldwyn Rodrigues 	btrfs_exclop_finish(fs_info);
3197f46b5a66SChristoph Hellwig 	return ret;
3198f46b5a66SChristoph Hellwig }
3199f46b5a66SChristoph Hellwig 
32006b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3201f46b5a66SChristoph Hellwig {
32021a15eb72SJosef Bacik 	BTRFS_DEV_LOOKUP_ARGS(args);
32030b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
32040b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
32056b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
32063fa421deSJosef Bacik 	struct block_device *bdev = NULL;
32073fa421deSJosef Bacik 	fmode_t mode;
3208f46b5a66SChristoph Hellwig 	int ret;
320967ae34b6SDavid Sterba 	bool cancel = false;
3210f46b5a66SChristoph Hellwig 
3211e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
3212e441d54dSChris Mason 		return -EPERM;
3213e441d54dSChris Mason 
3214dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
3215d815b3f2SDan Carpenter 	if (IS_ERR(vol_args))
3216d815b3f2SDan Carpenter 		return PTR_ERR(vol_args);
3217f46b5a66SChristoph Hellwig 
3218748449cdSDavid Sterba 	if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
3219fd4e994bSOmar Sandoval 		ret = -EOPNOTSUPP;
3220fd4e994bSOmar Sandoval 		goto out;
3221fd4e994bSOmar Sandoval 	}
32221a15eb72SJosef Bacik 
32236b526ed7SAnand Jain 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
32241a15eb72SJosef Bacik 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
32251a15eb72SJosef Bacik 		args.devid = vol_args->devid;
32261a15eb72SJosef Bacik 	} else if (!strcmp("cancel", vol_args->name)) {
322767ae34b6SDavid Sterba 		cancel = true;
32281a15eb72SJosef Bacik 	} else {
32291a15eb72SJosef Bacik 		ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
32301a15eb72SJosef Bacik 		if (ret)
32311a15eb72SJosef Bacik 			goto out;
32321a15eb72SJosef Bacik 	}
32331a15eb72SJosef Bacik 
32341a15eb72SJosef Bacik 	ret = mnt_want_write_file(file);
32351a15eb72SJosef Bacik 	if (ret)
32361a15eb72SJosef Bacik 		goto out;
323767ae34b6SDavid Sterba 
323867ae34b6SDavid Sterba 	ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
323967ae34b6SDavid Sterba 					   cancel);
324067ae34b6SDavid Sterba 	if (ret)
32411a15eb72SJosef Bacik 		goto err_drop;
324267ae34b6SDavid Sterba 
32431a15eb72SJosef Bacik 	/* Exclusive operation is now claimed */
32441a15eb72SJosef Bacik 	ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
324567ae34b6SDavid Sterba 
3246c3e1f96cSGoldwyn Rodrigues 	btrfs_exclop_finish(fs_info);
3247183860f6SAnand Jain 
32486b526ed7SAnand Jain 	if (!ret) {
3249735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
32500b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
32516b526ed7SAnand Jain 					vol_args->devid);
32526b526ed7SAnand Jain 		else
32530b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
32546b526ed7SAnand Jain 					vol_args->name);
32556b526ed7SAnand Jain 	}
3256c47ca32dSDan Carpenter err_drop:
32574ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
32583fa421deSJosef Bacik 	if (bdev)
32593fa421deSJosef Bacik 		blkdev_put(bdev, mode);
32601a15eb72SJosef Bacik out:
32611a15eb72SJosef Bacik 	btrfs_put_dev_args_from_path(&args);
32621a15eb72SJosef Bacik 	kfree(vol_args);
3263f46b5a66SChristoph Hellwig 	return ret;
3264f46b5a66SChristoph Hellwig }
3265f46b5a66SChristoph Hellwig 
3266f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3267f46b5a66SChristoph Hellwig {
32681a15eb72SJosef Bacik 	BTRFS_DEV_LOOKUP_ARGS(args);
32690b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
32700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3271f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
32723fa421deSJosef Bacik 	struct block_device *bdev = NULL;
32733fa421deSJosef Bacik 	fmode_t mode;
3274f46b5a66SChristoph Hellwig 	int ret;
327567ae34b6SDavid Sterba 	bool cancel;
3276f46b5a66SChristoph Hellwig 
3277f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
3278f46b5a66SChristoph Hellwig 		return -EPERM;
3279f46b5a66SChristoph Hellwig 
32801a15eb72SJosef Bacik 	vol_args = memdup_user(arg, sizeof(*vol_args));
32811a15eb72SJosef Bacik 	if (IS_ERR(vol_args))
32821a15eb72SJosef Bacik 		return PTR_ERR(vol_args);
32831a15eb72SJosef Bacik 
32841a15eb72SJosef Bacik 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
32851a15eb72SJosef Bacik 	if (!strcmp("cancel", vol_args->name)) {
32861a15eb72SJosef Bacik 		cancel = true;
32871a15eb72SJosef Bacik 	} else {
32881a15eb72SJosef Bacik 		ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
32891a15eb72SJosef Bacik 		if (ret)
32901a15eb72SJosef Bacik 			goto out;
32911a15eb72SJosef Bacik 	}
32921a15eb72SJosef Bacik 
3293f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
3294f46b5a66SChristoph Hellwig 	if (ret)
32951a15eb72SJosef Bacik 		goto out;
3296f46b5a66SChristoph Hellwig 
329767ae34b6SDavid Sterba 	ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
329867ae34b6SDavid Sterba 					   cancel);
329967ae34b6SDavid Sterba 	if (ret == 0) {
33001a15eb72SJosef Bacik 		ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3301f46b5a66SChristoph Hellwig 		if (!ret)
33020b246afaSJeff Mahoney 			btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3303c3e1f96cSGoldwyn Rodrigues 		btrfs_exclop_finish(fs_info);
330467ae34b6SDavid Sterba 	}
330567ae34b6SDavid Sterba 
3306f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
33073fa421deSJosef Bacik 	if (bdev)
33083fa421deSJosef Bacik 		blkdev_put(bdev, mode);
33091a15eb72SJosef Bacik out:
33101a15eb72SJosef Bacik 	btrfs_put_dev_args_from_path(&args);
33111a15eb72SJosef Bacik 	kfree(vol_args);
3312f46b5a66SChristoph Hellwig 	return ret;
3313f46b5a66SChristoph Hellwig }
3314f46b5a66SChristoph Hellwig 
33152ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
33162ff7e61eSJeff Mahoney 				void __user *arg)
3317475f6387SJan Schmidt {
3318027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
3319475f6387SJan Schmidt 	struct btrfs_device *device;
33200b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3321137c5418SJohannes Thumshirn 	u64 flags_in;
3322027ed2f0SLi Zefan 	int ret = 0;
3323475f6387SJan Schmidt 
3324137c5418SJohannes Thumshirn 	fi_args = memdup_user(arg, sizeof(*fi_args));
3325137c5418SJohannes Thumshirn 	if (IS_ERR(fi_args))
3326137c5418SJohannes Thumshirn 		return PTR_ERR(fi_args);
3327137c5418SJohannes Thumshirn 
3328137c5418SJohannes Thumshirn 	flags_in = fi_args->flags;
3329137c5418SJohannes Thumshirn 	memset(fi_args, 0, sizeof(*fi_args));
3330027ed2f0SLi Zefan 
3331d03262c7SDavid Sterba 	rcu_read_lock();
3332027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
3333475f6387SJan Schmidt 
3334d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3335027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
3336027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
3337475f6387SJan Schmidt 	}
3338d03262c7SDavid Sterba 	rcu_read_unlock();
3339475f6387SJan Schmidt 
3340de37aa51SNikolay Borisov 	memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3341bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
3342bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
3343bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
334480a773fbSDavid Sterba 
3345137c5418SJohannes Thumshirn 	if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3346137c5418SJohannes Thumshirn 		fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3347137c5418SJohannes Thumshirn 		fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3348137c5418SJohannes Thumshirn 		fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3349137c5418SJohannes Thumshirn 	}
3350137c5418SJohannes Thumshirn 
33510fb408a5SJohannes Thumshirn 	if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
33520fb408a5SJohannes Thumshirn 		fi_args->generation = fs_info->generation;
33530fb408a5SJohannes Thumshirn 		fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
33540fb408a5SJohannes Thumshirn 	}
33550fb408a5SJohannes Thumshirn 
335649bac897SJohannes Thumshirn 	if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
335749bac897SJohannes Thumshirn 		memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
335849bac897SJohannes Thumshirn 		       sizeof(fi_args->metadata_uuid));
335949bac897SJohannes Thumshirn 		fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
336049bac897SJohannes Thumshirn 	}
336149bac897SJohannes Thumshirn 
3362027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3363027ed2f0SLi Zefan 		ret = -EFAULT;
3364475f6387SJan Schmidt 
3365027ed2f0SLi Zefan 	kfree(fi_args);
3366027ed2f0SLi Zefan 	return ret;
3367475f6387SJan Schmidt }
3368475f6387SJan Schmidt 
33692ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
33702ff7e61eSJeff Mahoney 				 void __user *arg)
3371475f6387SJan Schmidt {
3372562d7b15SJosef Bacik 	BTRFS_DEV_LOOKUP_ARGS(args);
3373475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
3374475f6387SJan Schmidt 	struct btrfs_device *dev;
3375475f6387SJan Schmidt 	int ret = 0;
3376475f6387SJan Schmidt 
3377475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
3378475f6387SJan Schmidt 	if (IS_ERR(di_args))
3379475f6387SJan Schmidt 		return PTR_ERR(di_args);
3380475f6387SJan Schmidt 
3381562d7b15SJosef Bacik 	args.devid = di_args->devid;
3382dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
3383562d7b15SJosef Bacik 		args.uuid = di_args->uuid;
3384475f6387SJan Schmidt 
3385c5593ca3SDavid Sterba 	rcu_read_lock();
3386562d7b15SJosef Bacik 	dev = btrfs_find_device(fs_info->fs_devices, &args);
3387475f6387SJan Schmidt 	if (!dev) {
3388475f6387SJan Schmidt 		ret = -ENODEV;
3389475f6387SJan Schmidt 		goto out;
3390475f6387SJan Schmidt 	}
3391475f6387SJan Schmidt 
3392475f6387SJan Schmidt 	di_args->devid = dev->devid;
33937cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
33947cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3395475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3396a27202fbSJim Meyering 	if (dev->name) {
3397672d5990SMisono Tomohiro 		strncpy(di_args->path, rcu_str_deref(dev->name),
3398672d5990SMisono Tomohiro 				sizeof(di_args->path) - 1);
3399a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
3400a27202fbSJim Meyering 	} else {
340199ba55adSStefan Behrens 		di_args->path[0] = '\0';
3402a27202fbSJim Meyering 	}
3403475f6387SJan Schmidt 
3404475f6387SJan Schmidt out:
3405c5593ca3SDavid Sterba 	rcu_read_unlock();
3406475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3407475f6387SJan Schmidt 		ret = -EFAULT;
3408475f6387SJan Schmidt 
3409475f6387SJan Schmidt 	kfree(di_args);
3410475f6387SJan Schmidt 	return ret;
3411475f6387SJan Schmidt }
3412475f6387SJan Schmidt 
34136ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
34146ef5ed0dSJosef Bacik {
3415496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
34160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
34176ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
34186ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
34196ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
34206ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
34212a2b5d62SJosef Bacik 	struct btrfs_path *path = NULL;
34226ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
34236ef5ed0dSJosef Bacik 	u64 objectid = 0;
34246ef5ed0dSJosef Bacik 	u64 dir_id;
34253c04ce01SMiao Xie 	int ret;
34266ef5ed0dSJosef Bacik 
34276ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
34286ef5ed0dSJosef Bacik 		return -EPERM;
34296ef5ed0dSJosef Bacik 
34303c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
34313c04ce01SMiao Xie 	if (ret)
34323c04ce01SMiao Xie 		return ret;
34333c04ce01SMiao Xie 
34343c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
34353c04ce01SMiao Xie 		ret = -EFAULT;
34363c04ce01SMiao Xie 		goto out;
34373c04ce01SMiao Xie 	}
34386ef5ed0dSJosef Bacik 
34396ef5ed0dSJosef Bacik 	if (!objectid)
34401cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
34416ef5ed0dSJosef Bacik 
344256e9357aSDavid Sterba 	new_root = btrfs_get_fs_root(fs_info, objectid, true);
34433c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
34443c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
34453c04ce01SMiao Xie 		goto out;
34463c04ce01SMiao Xie 	}
34472a2b5d62SJosef Bacik 	if (!is_fstree(new_root->root_key.objectid)) {
34482a2b5d62SJosef Bacik 		ret = -ENOENT;
34492a2b5d62SJosef Bacik 		goto out_free;
34502a2b5d62SJosef Bacik 	}
34516ef5ed0dSJosef Bacik 
34526ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
34533c04ce01SMiao Xie 	if (!path) {
34543c04ce01SMiao Xie 		ret = -ENOMEM;
34552a2b5d62SJosef Bacik 		goto out_free;
34563c04ce01SMiao Xie 	}
34576ef5ed0dSJosef Bacik 
34586ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
345998d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
34603c04ce01SMiao Xie 		ret = PTR_ERR(trans);
34612a2b5d62SJosef Bacik 		goto out_free;
34626ef5ed0dSJosef Bacik 	}
34636ef5ed0dSJosef Bacik 
34640b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
34650b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
34666ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
3467cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
34682a2b5d62SJosef Bacik 		btrfs_release_path(path);
34693a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
34700b246afaSJeff Mahoney 		btrfs_err(fs_info,
34715d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
34723c04ce01SMiao Xie 		ret = -ENOENT;
34732a2b5d62SJosef Bacik 		goto out_free;
34746ef5ed0dSJosef Bacik 	}
34756ef5ed0dSJosef Bacik 
34766ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
34776ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
34786ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
34792a2b5d62SJosef Bacik 	btrfs_release_path(path);
34806ef5ed0dSJosef Bacik 
34810b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
34823a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
34832a2b5d62SJosef Bacik out_free:
348400246528SJosef Bacik 	btrfs_put_root(new_root);
34852a2b5d62SJosef Bacik 	btrfs_free_path(path);
34863c04ce01SMiao Xie out:
34873c04ce01SMiao Xie 	mnt_drop_write_file(file);
34883c04ce01SMiao Xie 	return ret;
34896ef5ed0dSJosef Bacik }
34906ef5ed0dSJosef Bacik 
3491c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
3492bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
3493bf5fc093SJosef Bacik {
349432da5386SDavid Sterba 	struct btrfs_block_group *block_group;
3495bf5fc093SJosef Bacik 
3496bf5fc093SJosef Bacik 	space->total_bytes = 0;
3497bf5fc093SJosef Bacik 	space->used_bytes = 0;
3498bf5fc093SJosef Bacik 	space->flags = 0;
3499bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
3500bf5fc093SJosef Bacik 		space->flags = block_group->flags;
3501b3470b5dSDavid Sterba 		space->total_bytes += block_group->length;
3502bf38be65SDavid Sterba 		space->used_bytes += block_group->used;
3503bf5fc093SJosef Bacik 	}
3504bf5fc093SJosef Bacik }
3505bf5fc093SJosef Bacik 
35062ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
35072ff7e61eSJeff Mahoney 				   void __user *arg)
35081406e432SJosef Bacik {
35091406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
35101406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
35111406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
35127fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
351313f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
35141406e432SJosef Bacik 	struct btrfs_space_info *info;
3515315d8e98SColin Ian King 	static const u64 types[] = {
3516315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
3517bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
3518bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
3519315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3520315d8e98SColin Ian King 	};
3521bf5fc093SJosef Bacik 	int num_types = 4;
35227fde62bfSChris Mason 	int alloc_size;
35231406e432SJosef Bacik 	int ret = 0;
352451788b1bSDan Rosenberg 	u64 slot_count = 0;
3525bf5fc093SJosef Bacik 	int i, c;
35261406e432SJosef Bacik 
35271406e432SJosef Bacik 	if (copy_from_user(&space_args,
35281406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
35291406e432SJosef Bacik 			   sizeof(space_args)))
35301406e432SJosef Bacik 		return -EFAULT;
35311406e432SJosef Bacik 
3532bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
3533bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
3534bf5fc093SJosef Bacik 
3535bf5fc093SJosef Bacik 		info = NULL;
353672804905SJosef Bacik 		list_for_each_entry(tmp, &fs_info->space_info, list) {
3537bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
3538bf5fc093SJosef Bacik 				info = tmp;
3539bf5fc093SJosef Bacik 				break;
3540bf5fc093SJosef Bacik 			}
3541bf5fc093SJosef Bacik 		}
35421406e432SJosef Bacik 
3543bf5fc093SJosef Bacik 		if (!info)
3544bf5fc093SJosef Bacik 			continue;
3545bf5fc093SJosef Bacik 
3546bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
3547bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3548bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
3549bf5fc093SJosef Bacik 				slot_count++;
3550bf5fc093SJosef Bacik 		}
3551bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
3552bf5fc093SJosef Bacik 	}
3553bf5fc093SJosef Bacik 
355436523e95SDavid Sterba 	/*
355536523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
355636523e95SDavid Sterba 	 */
355736523e95SDavid Sterba 	slot_count++;
355836523e95SDavid Sterba 
35597fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
35607fde62bfSChris Mason 	if (space_args.space_slots == 0) {
35617fde62bfSChris Mason 		space_args.total_spaces = slot_count;
35627fde62bfSChris Mason 		goto out;
35637fde62bfSChris Mason 	}
3564bf5fc093SJosef Bacik 
356551788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
3566bf5fc093SJosef Bacik 
35677fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
3568bf5fc093SJosef Bacik 
35697fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
35707fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
35717fde62bfSChris Mason 	 */
357209cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
35737fde62bfSChris Mason 		return -ENOMEM;
35747fde62bfSChris Mason 
35757fde62bfSChris Mason 	space_args.total_spaces = 0;
35768d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
35777fde62bfSChris Mason 	if (!dest)
35787fde62bfSChris Mason 		return -ENOMEM;
35797fde62bfSChris Mason 	dest_orig = dest;
35807fde62bfSChris Mason 
35817fde62bfSChris Mason 	/* now we have a buffer to copy into */
3582bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
3583bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
3584bf5fc093SJosef Bacik 
358551788b1bSDan Rosenberg 		if (!slot_count)
358651788b1bSDan Rosenberg 			break;
358751788b1bSDan Rosenberg 
3588bf5fc093SJosef Bacik 		info = NULL;
358972804905SJosef Bacik 		list_for_each_entry(tmp, &fs_info->space_info, list) {
3590bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
3591bf5fc093SJosef Bacik 				info = tmp;
35927fde62bfSChris Mason 				break;
3593bf5fc093SJosef Bacik 			}
3594bf5fc093SJosef Bacik 		}
35957fde62bfSChris Mason 
3596bf5fc093SJosef Bacik 		if (!info)
3597bf5fc093SJosef Bacik 			continue;
3598bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
3599bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3600bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
3601c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
3602c065f5b1SSu Yue 						     &space);
36037fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
36041406e432SJosef Bacik 				dest++;
36051406e432SJosef Bacik 				space_args.total_spaces++;
360651788b1bSDan Rosenberg 				slot_count--;
36071406e432SJosef Bacik 			}
360851788b1bSDan Rosenberg 			if (!slot_count)
360951788b1bSDan Rosenberg 				break;
3610bf5fc093SJosef Bacik 		}
3611bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
3612bf5fc093SJosef Bacik 	}
36131406e432SJosef Bacik 
361436523e95SDavid Sterba 	/*
361536523e95SDavid Sterba 	 * Add global block reserve
361636523e95SDavid Sterba 	 */
361736523e95SDavid Sterba 	if (slot_count) {
36180b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
361936523e95SDavid Sterba 
362036523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
362136523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
362236523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
362336523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
362436523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
362536523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
362636523e95SDavid Sterba 		space_args.total_spaces++;
362736523e95SDavid Sterba 	}
362836523e95SDavid Sterba 
36292eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
36307fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
36317fde62bfSChris Mason 
36327fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
36337fde62bfSChris Mason 		ret = -EFAULT;
36347fde62bfSChris Mason 
36357fde62bfSChris Mason 	kfree(dest_orig);
36367fde62bfSChris Mason out:
36377fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
36381406e432SJosef Bacik 		ret = -EFAULT;
36391406e432SJosef Bacik 
36401406e432SJosef Bacik 	return ret;
36411406e432SJosef Bacik }
36421406e432SJosef Bacik 
36439a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
36449a8c28beSMiao Xie 					    void __user *argp)
364546204592SSage Weil {
364646204592SSage Weil 	struct btrfs_trans_handle *trans;
364746204592SSage Weil 	u64 transid;
364846204592SSage Weil 
3649d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
3650ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
3651ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
365298d5dc13STsutomu Itoh 			return PTR_ERR(trans);
3653ff7c1d33SMiao Xie 
3654ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
3655ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
3656ff7c1d33SMiao Xie 		goto out;
3657ff7c1d33SMiao Xie 	}
365846204592SSage Weil 	transid = trans->transid;
3659fdfbf020SJosef Bacik 	btrfs_commit_transaction_async(trans);
3660ff7c1d33SMiao Xie out:
366146204592SSage Weil 	if (argp)
366246204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
366346204592SSage Weil 			return -EFAULT;
366446204592SSage Weil 	return 0;
366546204592SSage Weil }
366646204592SSage Weil 
36672ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
36689a8c28beSMiao Xie 					   void __user *argp)
366946204592SSage Weil {
367046204592SSage Weil 	u64 transid;
367146204592SSage Weil 
367246204592SSage Weil 	if (argp) {
367346204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
367446204592SSage Weil 			return -EFAULT;
367546204592SSage Weil 	} else {
367646204592SSage Weil 		transid = 0;  /* current trans */
367746204592SSage Weil 	}
36782ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
367946204592SSage Weil }
368046204592SSage Weil 
3681b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3682475f6387SJan Schmidt {
36830b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
3684475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
3685b8e95489SMiao Xie 	int ret;
3686475f6387SJan Schmidt 
3687475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
3688475f6387SJan Schmidt 		return -EPERM;
3689475f6387SJan Schmidt 
3690475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
3691475f6387SJan Schmidt 	if (IS_ERR(sa))
3692475f6387SJan Schmidt 		return PTR_ERR(sa);
3693475f6387SJan Schmidt 
3694b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3695b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
3696b8e95489SMiao Xie 		if (ret)
3697b8e95489SMiao Xie 			goto out;
3698b8e95489SMiao Xie 	}
3699b8e95489SMiao Xie 
37000b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
370163a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
370263a212abSStefan Behrens 			      0);
3703475f6387SJan Schmidt 
37045afe6ce7SFilipe Manana 	/*
37055afe6ce7SFilipe Manana 	 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
37065afe6ce7SFilipe Manana 	 * error. This is important as it allows user space to know how much
37075afe6ce7SFilipe Manana 	 * progress scrub has done. For example, if scrub is canceled we get
37085afe6ce7SFilipe Manana 	 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
37095afe6ce7SFilipe Manana 	 * space. Later user space can inspect the progress from the structure
37105afe6ce7SFilipe Manana 	 * btrfs_ioctl_scrub_args and resume scrub from where it left off
37115afe6ce7SFilipe Manana 	 * previously (btrfs-progs does this).
37125afe6ce7SFilipe Manana 	 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
37135afe6ce7SFilipe Manana 	 * then return -EFAULT to signal the structure was not copied or it may
37145afe6ce7SFilipe Manana 	 * be corrupt and unreliable due to a partial copy.
37155afe6ce7SFilipe Manana 	 */
37165afe6ce7SFilipe Manana 	if (copy_to_user(arg, sa, sizeof(*sa)))
3717475f6387SJan Schmidt 		ret = -EFAULT;
3718475f6387SJan Schmidt 
3719b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
3720b8e95489SMiao Xie 		mnt_drop_write_file(file);
3721b8e95489SMiao Xie out:
3722475f6387SJan Schmidt 	kfree(sa);
3723475f6387SJan Schmidt 	return ret;
3724475f6387SJan Schmidt }
3725475f6387SJan Schmidt 
37262ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
3727475f6387SJan Schmidt {
3728475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
3729475f6387SJan Schmidt 		return -EPERM;
3730475f6387SJan Schmidt 
37312ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
3732475f6387SJan Schmidt }
3733475f6387SJan Schmidt 
37342ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
3735475f6387SJan Schmidt 				       void __user *arg)
3736475f6387SJan Schmidt {
3737475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
3738475f6387SJan Schmidt 	int ret;
3739475f6387SJan Schmidt 
3740475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
3741475f6387SJan Schmidt 		return -EPERM;
3742475f6387SJan Schmidt 
3743475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
3744475f6387SJan Schmidt 	if (IS_ERR(sa))
3745475f6387SJan Schmidt 		return PTR_ERR(sa);
3746475f6387SJan Schmidt 
37472ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
3748475f6387SJan Schmidt 
37494fa99b00SFilipe Manana 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3750475f6387SJan Schmidt 		ret = -EFAULT;
3751475f6387SJan Schmidt 
3752475f6387SJan Schmidt 	kfree(sa);
3753475f6387SJan Schmidt 	return ret;
3754475f6387SJan Schmidt }
3755475f6387SJan Schmidt 
37562ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
3757b27f7c0cSDavid Sterba 				      void __user *arg)
3758c11d2c23SStefan Behrens {
3759c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
3760c11d2c23SStefan Behrens 	int ret;
3761c11d2c23SStefan Behrens 
3762c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
3763c11d2c23SStefan Behrens 	if (IS_ERR(sa))
3764c11d2c23SStefan Behrens 		return PTR_ERR(sa);
3765c11d2c23SStefan Behrens 
3766b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3767b27f7c0cSDavid Sterba 		kfree(sa);
3768b27f7c0cSDavid Sterba 		return -EPERM;
3769b27f7c0cSDavid Sterba 	}
3770b27f7c0cSDavid Sterba 
37712ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
3772c11d2c23SStefan Behrens 
3773eee99577SFilipe Manana 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3774c11d2c23SStefan Behrens 		ret = -EFAULT;
3775c11d2c23SStefan Behrens 
3776c11d2c23SStefan Behrens 	kfree(sa);
3777c11d2c23SStefan Behrens 	return ret;
3778c11d2c23SStefan Behrens }
3779c11d2c23SStefan Behrens 
37802ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
37812ff7e61eSJeff Mahoney 				    void __user *arg)
37823f6bcfbdSStefan Behrens {
37833f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
37843f6bcfbdSStefan Behrens 	int ret;
37853f6bcfbdSStefan Behrens 
37863f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
37873f6bcfbdSStefan Behrens 		return -EPERM;
37883f6bcfbdSStefan Behrens 
37893f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
37903f6bcfbdSStefan Behrens 	if (IS_ERR(p))
37913f6bcfbdSStefan Behrens 		return PTR_ERR(p);
37923f6bcfbdSStefan Behrens 
37933f6bcfbdSStefan Behrens 	switch (p->cmd) {
37943f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3795bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
3796adfa97cbSIlya Dryomov 			ret = -EROFS;
3797adfa97cbSIlya Dryomov 			goto out;
3798adfa97cbSIlya Dryomov 		}
3799c3e1f96cSGoldwyn Rodrigues 		if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
3800e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
38013f6bcfbdSStefan Behrens 		} else {
38022ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
3803c3e1f96cSGoldwyn Rodrigues 			btrfs_exclop_finish(fs_info);
38043f6bcfbdSStefan Behrens 		}
38053f6bcfbdSStefan Behrens 		break;
38063f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
38070b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
38083f6bcfbdSStefan Behrens 		ret = 0;
38093f6bcfbdSStefan Behrens 		break;
38103f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
381117d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
381297282031SAnand Jain 		ret = 0;
38133f6bcfbdSStefan Behrens 		break;
38143f6bcfbdSStefan Behrens 	default:
38153f6bcfbdSStefan Behrens 		ret = -EINVAL;
38163f6bcfbdSStefan Behrens 		break;
38173f6bcfbdSStefan Behrens 	}
38183f6bcfbdSStefan Behrens 
3819d3a53286SFilipe Manana 	if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
38203f6bcfbdSStefan Behrens 		ret = -EFAULT;
3821adfa97cbSIlya Dryomov out:
38223f6bcfbdSStefan Behrens 	kfree(p);
38233f6bcfbdSStefan Behrens 	return ret;
38243f6bcfbdSStefan Behrens }
38253f6bcfbdSStefan Behrens 
3826d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3827d7728c96SJan Schmidt {
3828d7728c96SJan Schmidt 	int ret = 0;
3829d7728c96SJan Schmidt 	int i;
3830740c3d22SChris Mason 	u64 rel_ptr;
3831d7728c96SJan Schmidt 	int size;
3832806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
3833d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
3834d7728c96SJan Schmidt 	struct btrfs_path *path;
3835d7728c96SJan Schmidt 
383682b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
3837d7728c96SJan Schmidt 		return -EPERM;
3838d7728c96SJan Schmidt 
3839d7728c96SJan Schmidt 	path = btrfs_alloc_path();
3840d7728c96SJan Schmidt 	if (!path) {
3841d7728c96SJan Schmidt 		ret = -ENOMEM;
3842d7728c96SJan Schmidt 		goto out;
3843d7728c96SJan Schmidt 	}
3844d7728c96SJan Schmidt 
3845d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
3846d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
3847d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
3848d7728c96SJan Schmidt 		ipa = NULL;
3849d7728c96SJan Schmidt 		goto out;
3850d7728c96SJan Schmidt 	}
3851d7728c96SJan Schmidt 
3852d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
3853d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
3854d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
3855d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
3856d7728c96SJan Schmidt 		ipath = NULL;
3857d7728c96SJan Schmidt 		goto out;
3858d7728c96SJan Schmidt 	}
3859d7728c96SJan Schmidt 
3860d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
3861d7728c96SJan Schmidt 	if (ret < 0)
3862d7728c96SJan Schmidt 		goto out;
3863d7728c96SJan Schmidt 
3864d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3865745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
3866745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
3867740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
3868d7728c96SJan Schmidt 	}
3869d7728c96SJan Schmidt 
3870718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
3871718dc5faSOmar Sandoval 			   ipath->fspath, size);
3872d7728c96SJan Schmidt 	if (ret) {
3873d7728c96SJan Schmidt 		ret = -EFAULT;
3874d7728c96SJan Schmidt 		goto out;
3875d7728c96SJan Schmidt 	}
3876d7728c96SJan Schmidt 
3877d7728c96SJan Schmidt out:
3878d7728c96SJan Schmidt 	btrfs_free_path(path);
3879d7728c96SJan Schmidt 	free_ipath(ipath);
3880d7728c96SJan Schmidt 	kfree(ipa);
3881d7728c96SJan Schmidt 
3882d7728c96SJan Schmidt 	return ret;
3883d7728c96SJan Schmidt }
3884d7728c96SJan Schmidt 
3885d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3886d7728c96SJan Schmidt {
3887d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
3888d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
3889d7728c96SJan Schmidt 
3890d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
3891d7728c96SJan Schmidt 		inodes->bytes_left -= c;
3892d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
3893d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
3894d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
3895d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
3896d7728c96SJan Schmidt 	} else {
3897d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
3898d7728c96SJan Schmidt 		inodes->bytes_left = 0;
3899d7728c96SJan Schmidt 		inodes->elem_missed += 3;
3900d7728c96SJan Schmidt 	}
3901d7728c96SJan Schmidt 
3902d7728c96SJan Schmidt 	return 0;
3903d7728c96SJan Schmidt }
3904d7728c96SJan Schmidt 
39052ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
3906d24a67b2SZygo Blaxell 					void __user *arg, int version)
3907d7728c96SJan Schmidt {
3908d7728c96SJan Schmidt 	int ret = 0;
3909d7728c96SJan Schmidt 	int size;
3910d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
3911d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
3912d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
3913d24a67b2SZygo Blaxell 	bool ignore_offset;
3914d7728c96SJan Schmidt 
3915d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
3916d7728c96SJan Schmidt 		return -EPERM;
3917d7728c96SJan Schmidt 
3918d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
39197b9ea627SShailendra Verma 	if (IS_ERR(loi))
39207b9ea627SShailendra Verma 		return PTR_ERR(loi);
3921d7728c96SJan Schmidt 
3922d24a67b2SZygo Blaxell 	if (version == 1) {
3923d24a67b2SZygo Blaxell 		ignore_offset = false;
3924b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
3925d24a67b2SZygo Blaxell 	} else {
3926d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
3927d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
3928d24a67b2SZygo Blaxell 			ret = -EINVAL;
3929d24a67b2SZygo Blaxell 			goto out_loi;
3930d24a67b2SZygo Blaxell 		}
3931d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
3932d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
3933d24a67b2SZygo Blaxell 			ret = -EINVAL;
3934d24a67b2SZygo Blaxell 			goto out_loi;
3935d24a67b2SZygo Blaxell 		}
3936d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
3937b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
3938d24a67b2SZygo Blaxell 	}
3939d24a67b2SZygo Blaxell 
3940d7728c96SJan Schmidt 	path = btrfs_alloc_path();
3941d7728c96SJan Schmidt 	if (!path) {
3942d7728c96SJan Schmidt 		ret = -ENOMEM;
3943d7728c96SJan Schmidt 		goto out;
3944d7728c96SJan Schmidt 	}
3945d7728c96SJan Schmidt 
3946d7728c96SJan Schmidt 	inodes = init_data_container(size);
3947d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
3948d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
3949d7728c96SJan Schmidt 		inodes = NULL;
3950d7728c96SJan Schmidt 		goto out;
3951d7728c96SJan Schmidt 	}
3952d7728c96SJan Schmidt 
39532ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
3954d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
3955df031f07SLiu Bo 	if (ret == -EINVAL)
3956d7728c96SJan Schmidt 		ret = -ENOENT;
3957d7728c96SJan Schmidt 	if (ret < 0)
3958d7728c96SJan Schmidt 		goto out;
3959d7728c96SJan Schmidt 
3960718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
3961718dc5faSOmar Sandoval 			   size);
3962d7728c96SJan Schmidt 	if (ret)
3963d7728c96SJan Schmidt 		ret = -EFAULT;
3964d7728c96SJan Schmidt 
3965d7728c96SJan Schmidt out:
3966d7728c96SJan Schmidt 	btrfs_free_path(path);
3967f54de068SDavid Sterba 	kvfree(inodes);
3968d24a67b2SZygo Blaxell out_loi:
3969d7728c96SJan Schmidt 	kfree(loi);
3970d7728c96SJan Schmidt 
3971d7728c96SJan Schmidt 	return ret;
3972d7728c96SJan Schmidt }
3973d7728c96SJan Schmidt 
3974008ef096SDavid Sterba void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
3975c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
3976c9e9f97bSIlya Dryomov {
3977c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3978c9e9f97bSIlya Dryomov 
3979c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
3980c9e9f97bSIlya Dryomov 
39813009a62fSDavid Sterba 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
3982837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3983837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
3984837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3985a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
3986a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3987837d5b6eSIlya Dryomov 
3988c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3989c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3990c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
399119a39dceSIlya Dryomov 
399219a39dceSIlya Dryomov 	spin_lock(&fs_info->balance_lock);
399319a39dceSIlya Dryomov 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
399419a39dceSIlya Dryomov 	spin_unlock(&fs_info->balance_lock);
3995c9e9f97bSIlya Dryomov }
3996c9e9f97bSIlya Dryomov 
39979ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3998c9e9f97bSIlya Dryomov {
3999496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4000c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4001c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4002c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4003ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4004c9e9f97bSIlya Dryomov 	int ret;
4005c9e9f97bSIlya Dryomov 
40066c405b24SNikolay Borisov 	if (!arg)
40076c405b24SNikolay Borisov 		btrfs_warn(fs_info,
40086c405b24SNikolay Borisov 	"IOC_BALANCE ioctl (v1) is deprecated and will be removed in kernel 5.18");
40096c405b24SNikolay Borisov 
4010c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4011c9e9f97bSIlya Dryomov 		return -EPERM;
4012c9e9f97bSIlya Dryomov 
4013e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
40149ba1f6e4SLiu Bo 	if (ret)
40159ba1f6e4SLiu Bo 		return ret;
40169ba1f6e4SLiu Bo 
4017ed0fb78fSIlya Dryomov again:
4018c3e1f96cSGoldwyn Rodrigues 	if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
4019c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4020ed0fb78fSIlya Dryomov 		need_unlock = true;
4021ed0fb78fSIlya Dryomov 		goto locked;
4022ed0fb78fSIlya Dryomov 	}
4023ed0fb78fSIlya Dryomov 
4024ed0fb78fSIlya Dryomov 	/*
402501327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4026ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4027ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4028ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4029ed0fb78fSIlya Dryomov 	 */
4030ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4031ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4032ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
40333009a62fSDavid Sterba 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4034ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4035dccdb07bSDavid Sterba 			/*
4036dccdb07bSDavid Sterba 			 * Lock released to allow other waiters to continue,
4037dccdb07bSDavid Sterba 			 * we'll reexamine the status again.
4038dccdb07bSDavid Sterba 			 */
4039ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4040ed0fb78fSIlya Dryomov 
4041ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
40423009a62fSDavid Sterba 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4043ed0fb78fSIlya Dryomov 				/* this is (3) */
4044ed0fb78fSIlya Dryomov 				need_unlock = false;
4045ed0fb78fSIlya Dryomov 				goto locked;
4046ed0fb78fSIlya Dryomov 			}
4047ed0fb78fSIlya Dryomov 
4048ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4049ed0fb78fSIlya Dryomov 			goto again;
4050ed0fb78fSIlya Dryomov 		} else {
4051ed0fb78fSIlya Dryomov 			/* this is (2) */
4052ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4053ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4054ed0fb78fSIlya Dryomov 			goto out;
4055ed0fb78fSIlya Dryomov 		}
4056ed0fb78fSIlya Dryomov 	} else {
4057ed0fb78fSIlya Dryomov 		/* this is (1) */
4058ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4059e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4060ed0fb78fSIlya Dryomov 		goto out;
4061ed0fb78fSIlya Dryomov 	}
4062ed0fb78fSIlya Dryomov 
4063ed0fb78fSIlya Dryomov locked:
4064c9e9f97bSIlya Dryomov 
4065c9e9f97bSIlya Dryomov 	if (arg) {
4066c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4067c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4068c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4069ed0fb78fSIlya Dryomov 			goto out_unlock;
4070c9e9f97bSIlya Dryomov 		}
4071de322263SIlya Dryomov 
4072de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4073de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4074de322263SIlya Dryomov 				ret = -ENOTCONN;
4075de322263SIlya Dryomov 				goto out_bargs;
4076de322263SIlya Dryomov 			}
4077de322263SIlya Dryomov 
4078de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4079de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4080de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4081de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4082*efc0e69cSNikolay Borisov 			btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE);
4083de322263SIlya Dryomov 
4084de322263SIlya Dryomov 			goto do_balance;
4085de322263SIlya Dryomov 		}
4086c9e9f97bSIlya Dryomov 	} else {
4087c9e9f97bSIlya Dryomov 		bargs = NULL;
4088c9e9f97bSIlya Dryomov 	}
4089c9e9f97bSIlya Dryomov 
4090ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4091837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4092837d5b6eSIlya Dryomov 		goto out_bargs;
4093837d5b6eSIlya Dryomov 	}
4094837d5b6eSIlya Dryomov 
40958d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4096c9e9f97bSIlya Dryomov 	if (!bctl) {
4097c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4098c9e9f97bSIlya Dryomov 		goto out_bargs;
4099c9e9f97bSIlya Dryomov 	}
4100c9e9f97bSIlya Dryomov 
4101c9e9f97bSIlya Dryomov 	if (arg) {
4102c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4103c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4104c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4105c9e9f97bSIlya Dryomov 
4106c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4107f43ffb60SIlya Dryomov 	} else {
4108f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4109f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4110c9e9f97bSIlya Dryomov 	}
4111c9e9f97bSIlya Dryomov 
41128eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
41138eb93459SDavid Sterba 		ret = -EINVAL;
41140f89abf5SChristian Engelmayer 		goto out_bctl;
41158eb93459SDavid Sterba 	}
41168eb93459SDavid Sterba 
4117de322263SIlya Dryomov do_balance:
4118c9e9f97bSIlya Dryomov 	/*
4119c3e1f96cSGoldwyn Rodrigues 	 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4120c3e1f96cSGoldwyn Rodrigues 	 * bctl is freed in reset_balance_state, or, if restriper was paused
4121c3e1f96cSGoldwyn Rodrigues 	 * all the way until unmount, in free_fs_info.  The flag should be
4122c3e1f96cSGoldwyn Rodrigues 	 * cleared after reset_balance_state.
4123c9e9f97bSIlya Dryomov 	 */
4124ed0fb78fSIlya Dryomov 	need_unlock = false;
4125ed0fb78fSIlya Dryomov 
41266fcf6e2bSDavid Sterba 	ret = btrfs_balance(fs_info, bctl, bargs);
41270f89abf5SChristian Engelmayer 	bctl = NULL;
4128ed0fb78fSIlya Dryomov 
4129d00c2d9cSFilipe Manana 	if ((ret == 0 || ret == -ECANCELED) && arg) {
4130c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4131c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4132c9e9f97bSIlya Dryomov 	}
4133c9e9f97bSIlya Dryomov 
41340f89abf5SChristian Engelmayer out_bctl:
41350f89abf5SChristian Engelmayer 	kfree(bctl);
4136c9e9f97bSIlya Dryomov out_bargs:
4137c9e9f97bSIlya Dryomov 	kfree(bargs);
4138ed0fb78fSIlya Dryomov out_unlock:
4139c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4140ed0fb78fSIlya Dryomov 	if (need_unlock)
4141c3e1f96cSGoldwyn Rodrigues 		btrfs_exclop_finish(fs_info);
4142ed0fb78fSIlya Dryomov out:
4143e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4144c9e9f97bSIlya Dryomov 	return ret;
4145c9e9f97bSIlya Dryomov }
4146c9e9f97bSIlya Dryomov 
41472ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4148837d5b6eSIlya Dryomov {
4149837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4150837d5b6eSIlya Dryomov 		return -EPERM;
4151837d5b6eSIlya Dryomov 
4152837d5b6eSIlya Dryomov 	switch (cmd) {
4153837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
41540b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4155a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
41560b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4157837d5b6eSIlya Dryomov 	}
4158837d5b6eSIlya Dryomov 
4159837d5b6eSIlya Dryomov 	return -EINVAL;
4160837d5b6eSIlya Dryomov }
4161837d5b6eSIlya Dryomov 
41622ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
416319a39dceSIlya Dryomov 					 void __user *arg)
416419a39dceSIlya Dryomov {
416519a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
416619a39dceSIlya Dryomov 	int ret = 0;
416719a39dceSIlya Dryomov 
416819a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
416919a39dceSIlya Dryomov 		return -EPERM;
417019a39dceSIlya Dryomov 
417119a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
417219a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
417319a39dceSIlya Dryomov 		ret = -ENOTCONN;
417419a39dceSIlya Dryomov 		goto out;
417519a39dceSIlya Dryomov 	}
417619a39dceSIlya Dryomov 
41778d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
417819a39dceSIlya Dryomov 	if (!bargs) {
417919a39dceSIlya Dryomov 		ret = -ENOMEM;
418019a39dceSIlya Dryomov 		goto out;
418119a39dceSIlya Dryomov 	}
418219a39dceSIlya Dryomov 
4183008ef096SDavid Sterba 	btrfs_update_ioctl_balance_args(fs_info, bargs);
418419a39dceSIlya Dryomov 
418519a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
418619a39dceSIlya Dryomov 		ret = -EFAULT;
418719a39dceSIlya Dryomov 
418819a39dceSIlya Dryomov 	kfree(bargs);
418919a39dceSIlya Dryomov out:
419019a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
419119a39dceSIlya Dryomov 	return ret;
419219a39dceSIlya Dryomov }
419319a39dceSIlya Dryomov 
4194905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
41955d13a37bSArne Jansen {
41960b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
41970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
41985d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
41995d13a37bSArne Jansen 	int ret;
42005d13a37bSArne Jansen 
42015d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
42025d13a37bSArne Jansen 		return -EPERM;
42035d13a37bSArne Jansen 
4204905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4205905b0ddaSMiao Xie 	if (ret)
4206905b0ddaSMiao Xie 		return ret;
42075d13a37bSArne Jansen 
42085d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4209905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4210905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4211905b0ddaSMiao Xie 		goto drop_write;
4212905b0ddaSMiao Xie 	}
42135d13a37bSArne Jansen 
42140b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
42155d13a37bSArne Jansen 
42165d13a37bSArne Jansen 	switch (sa->cmd) {
42175d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
4218340f1aa2SNikolay Borisov 		ret = btrfs_quota_enable(fs_info);
42195d13a37bSArne Jansen 		break;
42205d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
4221340f1aa2SNikolay Borisov 		ret = btrfs_quota_disable(fs_info);
42225d13a37bSArne Jansen 		break;
42235d13a37bSArne Jansen 	default:
42245d13a37bSArne Jansen 		ret = -EINVAL;
42255d13a37bSArne Jansen 		break;
42265d13a37bSArne Jansen 	}
42275d13a37bSArne Jansen 
42285d13a37bSArne Jansen 	kfree(sa);
42290b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4230905b0ddaSMiao Xie drop_write:
4231905b0ddaSMiao Xie 	mnt_drop_write_file(file);
42325d13a37bSArne Jansen 	return ret;
42335d13a37bSArne Jansen }
42345d13a37bSArne Jansen 
4235905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
42365d13a37bSArne Jansen {
42370b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
42380b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
42390b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
42405d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
42415d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
42425d13a37bSArne Jansen 	int ret;
42435d13a37bSArne Jansen 	int err;
42445d13a37bSArne Jansen 
42455d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
42465d13a37bSArne Jansen 		return -EPERM;
42475d13a37bSArne Jansen 
4248905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4249905b0ddaSMiao Xie 	if (ret)
4250905b0ddaSMiao Xie 		return ret;
42515d13a37bSArne Jansen 
42525d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4253905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4254905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4255905b0ddaSMiao Xie 		goto drop_write;
4256905b0ddaSMiao Xie 	}
42575d13a37bSArne Jansen 
42585d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
42595d13a37bSArne Jansen 	if (IS_ERR(trans)) {
42605d13a37bSArne Jansen 		ret = PTR_ERR(trans);
42615d13a37bSArne Jansen 		goto out;
42625d13a37bSArne Jansen 	}
42635d13a37bSArne Jansen 
42645d13a37bSArne Jansen 	if (sa->assign) {
42659f8a6ce6SLu Fengqi 		ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
42665d13a37bSArne Jansen 	} else {
426739616c27SLu Fengqi 		ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
42685d13a37bSArne Jansen 	}
42695d13a37bSArne Jansen 
4270e082f563SQu Wenruo 	/* update qgroup status and info */
4271280f8bd2SLu Fengqi 	err = btrfs_run_qgroups(trans);
4272e082f563SQu Wenruo 	if (err < 0)
42730b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4274ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
42753a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
42765d13a37bSArne Jansen 	if (err && !ret)
42775d13a37bSArne Jansen 		ret = err;
42785d13a37bSArne Jansen 
42795d13a37bSArne Jansen out:
42805d13a37bSArne Jansen 	kfree(sa);
4281905b0ddaSMiao Xie drop_write:
4282905b0ddaSMiao Xie 	mnt_drop_write_file(file);
42835d13a37bSArne Jansen 	return ret;
42845d13a37bSArne Jansen }
42855d13a37bSArne Jansen 
4286905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
42875d13a37bSArne Jansen {
42880b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
42890b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
42905d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
42915d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
42925d13a37bSArne Jansen 	int ret;
42935d13a37bSArne Jansen 	int err;
42945d13a37bSArne Jansen 
42955d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
42965d13a37bSArne Jansen 		return -EPERM;
42975d13a37bSArne Jansen 
4298905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4299905b0ddaSMiao Xie 	if (ret)
4300905b0ddaSMiao Xie 		return ret;
43015d13a37bSArne Jansen 
43025d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4303905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4304905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4305905b0ddaSMiao Xie 		goto drop_write;
4306905b0ddaSMiao Xie 	}
43075d13a37bSArne Jansen 
4308d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4309d86e56cfSMiao Xie 		ret = -EINVAL;
4310d86e56cfSMiao Xie 		goto out;
4311d86e56cfSMiao Xie 	}
4312d86e56cfSMiao Xie 
43135d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
43145d13a37bSArne Jansen 	if (IS_ERR(trans)) {
43155d13a37bSArne Jansen 		ret = PTR_ERR(trans);
43165d13a37bSArne Jansen 		goto out;
43175d13a37bSArne Jansen 	}
43185d13a37bSArne Jansen 
43195d13a37bSArne Jansen 	if (sa->create) {
432049a05ecdSLu Fengqi 		ret = btrfs_create_qgroup(trans, sa->qgroupid);
43215d13a37bSArne Jansen 	} else {
43223efbee1dSLu Fengqi 		ret = btrfs_remove_qgroup(trans, sa->qgroupid);
43235d13a37bSArne Jansen 	}
43245d13a37bSArne Jansen 
43253a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
43265d13a37bSArne Jansen 	if (err && !ret)
43275d13a37bSArne Jansen 		ret = err;
43285d13a37bSArne Jansen 
43295d13a37bSArne Jansen out:
43305d13a37bSArne Jansen 	kfree(sa);
4331905b0ddaSMiao Xie drop_write:
4332905b0ddaSMiao Xie 	mnt_drop_write_file(file);
43335d13a37bSArne Jansen 	return ret;
43345d13a37bSArne Jansen }
43355d13a37bSArne Jansen 
4336905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
43375d13a37bSArne Jansen {
43380b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
43390b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
43405d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
43415d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
43425d13a37bSArne Jansen 	int ret;
43435d13a37bSArne Jansen 	int err;
43445d13a37bSArne Jansen 	u64 qgroupid;
43455d13a37bSArne Jansen 
43465d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
43475d13a37bSArne Jansen 		return -EPERM;
43485d13a37bSArne Jansen 
4349905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4350905b0ddaSMiao Xie 	if (ret)
4351905b0ddaSMiao Xie 		return ret;
43525d13a37bSArne Jansen 
43535d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4354905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4355905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4356905b0ddaSMiao Xie 		goto drop_write;
4357905b0ddaSMiao Xie 	}
43585d13a37bSArne Jansen 
43595d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
43605d13a37bSArne Jansen 	if (IS_ERR(trans)) {
43615d13a37bSArne Jansen 		ret = PTR_ERR(trans);
43625d13a37bSArne Jansen 		goto out;
43635d13a37bSArne Jansen 	}
43645d13a37bSArne Jansen 
43655d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
43665d13a37bSArne Jansen 	if (!qgroupid) {
43675d13a37bSArne Jansen 		/* take the current subvol as qgroup */
43685d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
43695d13a37bSArne Jansen 	}
43705d13a37bSArne Jansen 
4371f0042d5eSLu Fengqi 	ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
43725d13a37bSArne Jansen 
43733a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
43745d13a37bSArne Jansen 	if (err && !ret)
43755d13a37bSArne Jansen 		ret = err;
43765d13a37bSArne Jansen 
43775d13a37bSArne Jansen out:
43785d13a37bSArne Jansen 	kfree(sa);
4379905b0ddaSMiao Xie drop_write:
4380905b0ddaSMiao Xie 	mnt_drop_write_file(file);
43815d13a37bSArne Jansen 	return ret;
43825d13a37bSArne Jansen }
43835d13a37bSArne Jansen 
43842f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
43852f232036SJan Schmidt {
43860b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
43870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
43882f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
43892f232036SJan Schmidt 	int ret;
43902f232036SJan Schmidt 
43912f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
43922f232036SJan Schmidt 		return -EPERM;
43932f232036SJan Schmidt 
43942f232036SJan Schmidt 	ret = mnt_want_write_file(file);
43952f232036SJan Schmidt 	if (ret)
43962f232036SJan Schmidt 		return ret;
43972f232036SJan Schmidt 
43982f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
43992f232036SJan Schmidt 	if (IS_ERR(qsa)) {
44002f232036SJan Schmidt 		ret = PTR_ERR(qsa);
44012f232036SJan Schmidt 		goto drop_write;
44022f232036SJan Schmidt 	}
44032f232036SJan Schmidt 
44042f232036SJan Schmidt 	if (qsa->flags) {
44052f232036SJan Schmidt 		ret = -EINVAL;
44062f232036SJan Schmidt 		goto out;
44072f232036SJan Schmidt 	}
44082f232036SJan Schmidt 
44090b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
44102f232036SJan Schmidt 
44112f232036SJan Schmidt out:
44122f232036SJan Schmidt 	kfree(qsa);
44132f232036SJan Schmidt drop_write:
44142f232036SJan Schmidt 	mnt_drop_write_file(file);
44152f232036SJan Schmidt 	return ret;
44162f232036SJan Schmidt }
44172f232036SJan Schmidt 
4418b929c1d8SMarcos Paulo de Souza static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4419b929c1d8SMarcos Paulo de Souza 						void __user *arg)
44202f232036SJan Schmidt {
44210afb603aSGoldwyn Rodrigues 	struct btrfs_ioctl_quota_rescan_args qsa = {0};
44222f232036SJan Schmidt 
44232f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
44242f232036SJan Schmidt 		return -EPERM;
44252f232036SJan Schmidt 
44260b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
44270afb603aSGoldwyn Rodrigues 		qsa.flags = 1;
44280afb603aSGoldwyn Rodrigues 		qsa.progress = fs_info->qgroup_rescan_progress.objectid;
44292f232036SJan Schmidt 	}
44302f232036SJan Schmidt 
44310afb603aSGoldwyn Rodrigues 	if (copy_to_user(arg, &qsa, sizeof(qsa)))
4432991a3daeSAnand Jain 		return -EFAULT;
44332f232036SJan Schmidt 
4434991a3daeSAnand Jain 	return 0;
44352f232036SJan Schmidt }
44362f232036SJan Schmidt 
4437b929c1d8SMarcos Paulo de Souza static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4438b929c1d8SMarcos Paulo de Souza 						void __user *arg)
443957254b6eSJan Schmidt {
444057254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
444157254b6eSJan Schmidt 		return -EPERM;
444257254b6eSJan Schmidt 
44430b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
444457254b6eSJan Schmidt }
444557254b6eSJan Schmidt 
4446abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
4447e4fed17aSChristian Brauner 					    struct user_namespace *mnt_userns,
4448abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
44498ea05e3aSAlexander Block {
4450496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
44510b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
44528ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
44538ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
44548ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
445595582b00SDeepa Dinamani 	struct timespec64 ct = current_time(inode);
44568ea05e3aSAlexander Block 	int ret = 0;
4457dd5f9615SStefan Behrens 	int received_uuid_changed;
44588ea05e3aSAlexander Block 
4459e4fed17aSChristian Brauner 	if (!inode_owner_or_capable(mnt_userns, inode))
4460bd60ea0fSDavid Sterba 		return -EPERM;
4461bd60ea0fSDavid Sterba 
44628ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
44638ea05e3aSAlexander Block 	if (ret < 0)
44648ea05e3aSAlexander Block 		return ret;
44658ea05e3aSAlexander Block 
44660b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
44678ea05e3aSAlexander Block 
44684a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
44698ea05e3aSAlexander Block 		ret = -EINVAL;
44708ea05e3aSAlexander Block 		goto out;
44718ea05e3aSAlexander Block 	}
44728ea05e3aSAlexander Block 
44738ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
44748ea05e3aSAlexander Block 		ret = -EROFS;
44758ea05e3aSAlexander Block 		goto out;
44768ea05e3aSAlexander Block 	}
44778ea05e3aSAlexander Block 
4478dd5f9615SStefan Behrens 	/*
4479dd5f9615SStefan Behrens 	 * 1 - root item
4480dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
4481dd5f9615SStefan Behrens 	 */
4482dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
44838ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
44848ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
44858ea05e3aSAlexander Block 		trans = NULL;
44868ea05e3aSAlexander Block 		goto out;
44878ea05e3aSAlexander Block 	}
44888ea05e3aSAlexander Block 
44898ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
44908ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
44918ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
44928ea05e3aSAlexander Block 
4493dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4494dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
4495dd5f9615SStefan Behrens 	if (received_uuid_changed &&
4496d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
4497d1957791SLu Fengqi 		ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
4498dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4499dd5f9615SStefan Behrens 					  root->root_key.objectid);
4500d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
4501d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
4502d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
4503d87ff758SNikolay Borisov 		        goto out;
4504d87ff758SNikolay Borisov 		}
4505d87ff758SNikolay Borisov 	}
45068ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
45078ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
45088ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
45093cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
45103cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
45113cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
45123cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
45138ea05e3aSAlexander Block 
45140b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
45158ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
45168ea05e3aSAlexander Block 	if (ret < 0) {
45173a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
45188ea05e3aSAlexander Block 		goto out;
4519dd5f9615SStefan Behrens 	}
4520dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4521cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, sa->uuid,
4522dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4523dd5f9615SStefan Behrens 					  root->root_key.objectid);
4524dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
452566642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
4526efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
4527dd5f9615SStefan Behrens 			goto out;
4528dd5f9615SStefan Behrens 		}
4529dd5f9615SStefan Behrens 	}
45303a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
4531abccd00fSHugo Mills out:
45320b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4533abccd00fSHugo Mills 	mnt_drop_write_file(file);
4534abccd00fSHugo Mills 	return ret;
4535abccd00fSHugo Mills }
4536abccd00fSHugo Mills 
4537abccd00fSHugo Mills #ifdef CONFIG_64BIT
4538abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4539abccd00fSHugo Mills 						void __user *arg)
4540abccd00fSHugo Mills {
4541abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4542abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4543abccd00fSHugo Mills 	int ret = 0;
4544abccd00fSHugo Mills 
4545abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
45467b9ea627SShailendra Verma 	if (IS_ERR(args32))
45477b9ea627SShailendra Verma 		return PTR_ERR(args32);
4548abccd00fSHugo Mills 
45498d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
455084dbeb87SDan Carpenter 	if (!args64) {
455184dbeb87SDan Carpenter 		ret = -ENOMEM;
4552abccd00fSHugo Mills 		goto out;
4553abccd00fSHugo Mills 	}
4554abccd00fSHugo Mills 
4555abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4556abccd00fSHugo Mills 	args64->stransid = args32->stransid;
4557abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
4558abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
4559abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
4560abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
4561abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
4562abccd00fSHugo Mills 	args64->flags = args32->flags;
4563abccd00fSHugo Mills 
4564e4fed17aSChristian Brauner 	ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), args64);
4565abccd00fSHugo Mills 	if (ret)
4566abccd00fSHugo Mills 		goto out;
4567abccd00fSHugo Mills 
4568abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4569abccd00fSHugo Mills 	args32->stransid = args64->stransid;
4570abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
4571abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
4572abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
4573abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
4574abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
4575abccd00fSHugo Mills 	args32->flags = args64->flags;
4576abccd00fSHugo Mills 
4577abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
4578abccd00fSHugo Mills 	if (ret)
4579abccd00fSHugo Mills 		ret = -EFAULT;
4580abccd00fSHugo Mills 
4581abccd00fSHugo Mills out:
4582abccd00fSHugo Mills 	kfree(args32);
4583abccd00fSHugo Mills 	kfree(args64);
4584abccd00fSHugo Mills 	return ret;
4585abccd00fSHugo Mills }
4586abccd00fSHugo Mills #endif
4587abccd00fSHugo Mills 
4588abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
4589abccd00fSHugo Mills 					    void __user *arg)
4590abccd00fSHugo Mills {
4591abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
4592abccd00fSHugo Mills 	int ret = 0;
4593abccd00fSHugo Mills 
4594abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
45957b9ea627SShailendra Verma 	if (IS_ERR(sa))
45967b9ea627SShailendra Verma 		return PTR_ERR(sa);
4597abccd00fSHugo Mills 
4598e4fed17aSChristian Brauner 	ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), sa);
4599abccd00fSHugo Mills 
4600abccd00fSHugo Mills 	if (ret)
4601abccd00fSHugo Mills 		goto out;
4602abccd00fSHugo Mills 
46038ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
46048ea05e3aSAlexander Block 	if (ret)
46058ea05e3aSAlexander Block 		ret = -EFAULT;
46068ea05e3aSAlexander Block 
46078ea05e3aSAlexander Block out:
46088ea05e3aSAlexander Block 	kfree(sa);
46098ea05e3aSAlexander Block 	return ret;
46108ea05e3aSAlexander Block }
46118ea05e3aSAlexander Block 
4612b929c1d8SMarcos Paulo de Souza static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4613b929c1d8SMarcos Paulo de Souza 					void __user *arg)
4614867ab667Sjeff.liu {
4615a1b83ac5SAnand Jain 	size_t len;
4616867ab667Sjeff.liu 	int ret;
4617a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
4618a1b83ac5SAnand Jain 
46190b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
46200b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
46210b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
4622a1b83ac5SAnand Jain 
4623a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
4624867ab667Sjeff.liu 
4625867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
46260b246afaSJeff Mahoney 		btrfs_warn(fs_info,
46270b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
46280b246afaSJeff Mahoney 			   --len);
4629867ab667Sjeff.liu 	}
4630867ab667Sjeff.liu 
4631867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
4632867ab667Sjeff.liu 
4633867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
4634867ab667Sjeff.liu }
4635867ab667Sjeff.liu 
4636a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4637a8bfd4abSjeff.liu {
46380b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
46390b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46400b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
46410b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
4642a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
4643a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
4644a8bfd4abSjeff.liu 	int ret;
4645a8bfd4abSjeff.liu 
4646a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
4647a8bfd4abSjeff.liu 		return -EPERM;
4648a8bfd4abSjeff.liu 
4649a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
4650a8bfd4abSjeff.liu 		return -EFAULT;
4651a8bfd4abSjeff.liu 
4652a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
46530b246afaSJeff Mahoney 		btrfs_err(fs_info,
46545d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
4655a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
4656a8bfd4abSjeff.liu 		return -EINVAL;
4657a8bfd4abSjeff.liu 	}
4658a8bfd4abSjeff.liu 
4659a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
4660a8bfd4abSjeff.liu 	if (ret)
4661a8bfd4abSjeff.liu 		return ret;
4662a8bfd4abSjeff.liu 
4663a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
4664a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
4665a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
4666a8bfd4abSjeff.liu 		goto out_unlock;
4667a8bfd4abSjeff.liu 	}
4668a8bfd4abSjeff.liu 
46690b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
4670a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
46710b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
46723a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
4673a8bfd4abSjeff.liu 
4674a8bfd4abSjeff.liu out_unlock:
4675a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
4676a8bfd4abSjeff.liu 	return ret;
4677a8bfd4abSjeff.liu }
4678a8bfd4abSjeff.liu 
46792eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
46802eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
46812eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
46822eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
46832eaa055fSJeff Mahoney 
4684d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
46852eaa055fSJeff Mahoney {
46864d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
46872eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
46882eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
46892eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
46902eaa055fSJeff Mahoney 	};
46912eaa055fSJeff Mahoney 
46922eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
46932eaa055fSJeff Mahoney 		return -EFAULT;
46942eaa055fSJeff Mahoney 
46952eaa055fSJeff Mahoney 	return 0;
46962eaa055fSJeff Mahoney }
46972eaa055fSJeff Mahoney 
4698b929c1d8SMarcos Paulo de Souza static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
4699b929c1d8SMarcos Paulo de Souza 					void __user *arg)
47002eaa055fSJeff Mahoney {
47010b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
47022eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
47032eaa055fSJeff Mahoney 
47042eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
47052eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
47062eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
47072eaa055fSJeff Mahoney 
47082eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
47092eaa055fSJeff Mahoney 		return -EFAULT;
47102eaa055fSJeff Mahoney 
47112eaa055fSJeff Mahoney 	return 0;
47122eaa055fSJeff Mahoney }
47132eaa055fSJeff Mahoney 
47142ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
47153b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
47162eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
47172eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
47182eaa055fSJeff Mahoney {
4719f10152bcSDavid Sterba 	const char *type = btrfs_feature_set_name(set);
47203b02a68aSJeff Mahoney 	char *names;
47212eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
47222eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
47232eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
47242eaa055fSJeff Mahoney 
47252eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
47262eaa055fSJeff Mahoney 	if (unsupported) {
47273b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
47283b02a68aSJeff Mahoney 		if (names) {
47290b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47303b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
47313b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
47323b02a68aSJeff Mahoney 			kfree(names);
47333b02a68aSJeff Mahoney 		} else
47340b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47352eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
47362eaa055fSJeff Mahoney 				   type, unsupported);
47372eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
47382eaa055fSJeff Mahoney 	}
47392eaa055fSJeff Mahoney 
47402eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
47412eaa055fSJeff Mahoney 	if (disallowed) {
47423b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
47433b02a68aSJeff Mahoney 		if (names) {
47440b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47453b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
47463b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
47473b02a68aSJeff Mahoney 			kfree(names);
47483b02a68aSJeff Mahoney 		} else
47490b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47502eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
47512eaa055fSJeff Mahoney 				   type, disallowed);
47522eaa055fSJeff Mahoney 		return -EPERM;
47532eaa055fSJeff Mahoney 	}
47542eaa055fSJeff Mahoney 
47552eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
47562eaa055fSJeff Mahoney 	if (disallowed) {
47573b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
47583b02a68aSJeff Mahoney 		if (names) {
47590b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47603b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
47613b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
47623b02a68aSJeff Mahoney 			kfree(names);
47633b02a68aSJeff Mahoney 		} else
47640b246afaSJeff Mahoney 			btrfs_warn(fs_info,
47652eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
47662eaa055fSJeff Mahoney 				   type, disallowed);
47672eaa055fSJeff Mahoney 		return -EPERM;
47682eaa055fSJeff Mahoney 	}
47692eaa055fSJeff Mahoney 
47702eaa055fSJeff Mahoney 	return 0;
47712eaa055fSJeff Mahoney }
47722eaa055fSJeff Mahoney 
47732ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
47742ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
47752eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
47762eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
47772eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
47782eaa055fSJeff Mahoney 
47792eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
47802eaa055fSJeff Mahoney {
47810b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47820b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47830b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
47840b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
47852eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
47862eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
47872eaa055fSJeff Mahoney 	u64 newflags;
47882eaa055fSJeff Mahoney 	int ret;
47892eaa055fSJeff Mahoney 
47902eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
47912eaa055fSJeff Mahoney 		return -EPERM;
47922eaa055fSJeff Mahoney 
47932eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
47942eaa055fSJeff Mahoney 		return -EFAULT;
47952eaa055fSJeff Mahoney 
47962eaa055fSJeff Mahoney 	/* Nothing to do */
47972eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
47982eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
47992eaa055fSJeff Mahoney 		return 0;
48002eaa055fSJeff Mahoney 
48012ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
48022eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
48032eaa055fSJeff Mahoney 	if (ret)
48042eaa055fSJeff Mahoney 		return ret;
48052eaa055fSJeff Mahoney 
48062ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
48072eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
48082eaa055fSJeff Mahoney 	if (ret)
48092eaa055fSJeff Mahoney 		return ret;
48102eaa055fSJeff Mahoney 
48112ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
48122eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
48132eaa055fSJeff Mahoney 	if (ret)
48142eaa055fSJeff Mahoney 		return ret;
48152eaa055fSJeff Mahoney 
48167ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
48177ab19625SDavid Sterba 	if (ret)
48187ab19625SDavid Sterba 		return ret;
48197ab19625SDavid Sterba 
48208051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
48217ab19625SDavid Sterba 	if (IS_ERR(trans)) {
48227ab19625SDavid Sterba 		ret = PTR_ERR(trans);
48237ab19625SDavid Sterba 		goto out_drop_write;
48247ab19625SDavid Sterba 	}
48252eaa055fSJeff Mahoney 
48260b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
48272eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
48282eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
48292eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
48302eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
48312eaa055fSJeff Mahoney 
48322eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
48332eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
48342eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
48352eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
48362eaa055fSJeff Mahoney 
48372eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
48382eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
48392eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
48402eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
48410b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
48422eaa055fSJeff Mahoney 
48433a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
48447ab19625SDavid Sterba out_drop_write:
48457ab19625SDavid Sterba 	mnt_drop_write_file(file);
48467ab19625SDavid Sterba 
48477ab19625SDavid Sterba 	return ret;
48482eaa055fSJeff Mahoney }
48492eaa055fSJeff Mahoney 
48502351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
48512351f431SJosef Bacik {
48522351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
48532351f431SJosef Bacik 	int ret;
48542351f431SJosef Bacik 
48552351f431SJosef Bacik 	if (compat) {
48562351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
48572351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
48582351f431SJosef Bacik 
48592351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
48602351f431SJosef Bacik 		if (ret)
48612351f431SJosef Bacik 			return -EFAULT;
48622351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
48632351f431SJosef Bacik 		if (!arg)
48642351f431SJosef Bacik 			return -ENOMEM;
48652351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
48662351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
48672351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
48682351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
48692351f431SJosef Bacik 		arg->flags = args32.flags;
48702351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
48712351f431SJosef Bacik 		       sizeof(args32.reserved));
48722351f431SJosef Bacik #else
48732351f431SJosef Bacik 		return -ENOTTY;
48742351f431SJosef Bacik #endif
48752351f431SJosef Bacik 	} else {
48762351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
48772351f431SJosef Bacik 		if (IS_ERR(arg))
48782351f431SJosef Bacik 			return PTR_ERR(arg);
48792351f431SJosef Bacik 	}
48802351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
48812351f431SJosef Bacik 	kfree(arg);
48822351f431SJosef Bacik 	return ret;
48832351f431SJosef Bacik }
48842351f431SJosef Bacik 
4885f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
4886f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
4887f46b5a66SChristoph Hellwig {
48880b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48900b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
48914bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
4892f46b5a66SChristoph Hellwig 
4893f46b5a66SChristoph Hellwig 	switch (cmd) {
48946cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
48956cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
489640cf931fSEric Sandeen 	case FS_IOC_GETFSLABEL:
4897b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_get_fslabel(fs_info, argp);
489840cf931fSEric Sandeen 	case FS_IOC_SETFSLABEL:
489940cf931fSEric Sandeen 		return btrfs_ioctl_set_fslabel(file, argp);
4900f7039b1dSLi Dongyang 	case FITRIM:
4901b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_fitrim(fs_info, argp);
4902f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
4903fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
4904fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
4905fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
49063de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
4907fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
49086f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
49096f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
491076dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
4911949964c9SMarcos Paulo de Souza 		return btrfs_ioctl_snap_destroy(file, argp, false);
4912949964c9SMarcos Paulo de Souza 	case BTRFS_IOC_SNAP_DESTROY_V2:
4913949964c9SMarcos Paulo de Souza 		return btrfs_ioctl_snap_destroy(file, argp, true);
49140caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
49150caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
49160caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
49170caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
49186ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
49196ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
4920f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
49211e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
49221e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
49231e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
4924f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
4925198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
4926f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
49272ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
4928f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
4929da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
49306b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
49316b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
4932475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
49332ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
4934475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
49352ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
4936f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
49379ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
4938ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
4939ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
4940cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
4941cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
4942ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
4943ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
4944d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
4945d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
4946d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
4947d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
4948d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
4949d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
49501406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
49512ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
49529b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
49539b199859SFilipe David Borba Manana 		int ret;
49549b199859SFilipe David Borba Manana 
49559db4dc24SNikolay Borisov 		ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
49569b199859SFilipe David Borba Manana 		if (ret)
49579b199859SFilipe David Borba Manana 			return ret;
49580b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
49592fad4e83SDavid Sterba 		/*
49602fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
496101327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
49622fad4e83SDavid Sterba 		 * processing uncleaned subvols.
49632fad4e83SDavid Sterba 		 */
49640b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
49659b199859SFilipe David Borba Manana 		return ret;
49669b199859SFilipe David Borba Manana 	}
496746204592SSage Weil 	case BTRFS_IOC_START_SYNC:
49689a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
496946204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
49702ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
4971475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
4972b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
4973475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
49742ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
4975475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
49762ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
4977c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
49789ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
4979837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
49802ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
498119a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
49822ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
49838ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
49848ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
4985abccd00fSHugo Mills #ifdef CONFIG_64BIT
4986abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
4987abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
4988abccd00fSHugo Mills #endif
498931db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
49902351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
49912351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
49922351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
49932351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
49942351f431SJosef Bacik #endif
4995c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
49962ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
49975d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
4998905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
49995d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5000905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
50015d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5002905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
50035d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5004905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
50052f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
50062f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
50072f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5008b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_quota_rescan_status(fs_info, argp);
500957254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5010b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
50113f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
50122ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
50132eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5014d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
50152eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
5016b929c1d8SMarcos Paulo de Souza 		return btrfs_ioctl_get_features(fs_info, argp);
50172eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
50182eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5019b64ec075STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_INFO:
5020b64ec075STomohiro Misono 		return btrfs_ioctl_get_subvol_info(file, argp);
502142e4b520STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_ROOTREF:
502242e4b520STomohiro Misono 		return btrfs_ioctl_get_subvol_rootref(file, argp);
502323d0b79dSTomohiro Misono 	case BTRFS_IOC_INO_LOOKUP_USER:
502423d0b79dSTomohiro Misono 		return btrfs_ioctl_ino_lookup_user(file, argp);
502514605409SBoris Burkov 	case FS_IOC_ENABLE_VERITY:
502614605409SBoris Burkov 		return fsverity_ioctl_enable(file, (const void __user *)argp);
502714605409SBoris Burkov 	case FS_IOC_MEASURE_VERITY:
502814605409SBoris Burkov 		return fsverity_ioctl_measure(file, argp);
5029f46b5a66SChristoph Hellwig 	}
5030f46b5a66SChristoph Hellwig 
5031f46b5a66SChristoph Hellwig 	return -ENOTTY;
5032f46b5a66SChristoph Hellwig }
50334c63c245SLuke Dashjr 
50344c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
50354c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
50364c63c245SLuke Dashjr {
50372a362249SJeff Mahoney 	/*
50382a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
50392a362249SJeff Mahoney 	 * handling is necessary.
50402a362249SJeff Mahoney 	 */
50414c63c245SLuke Dashjr 	switch (cmd) {
50424c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
50434c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
50444c63c245SLuke Dashjr 		break;
50454c63c245SLuke Dashjr 	}
50464c63c245SLuke Dashjr 
50474c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
50484c63c245SLuke Dashjr }
50494c63c245SLuke Dashjr #endif
5050