xref: /openbmc/linux/fs/btrfs/ioctl.c (revision 3ca57bd6)
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/buffer_head.h>
9f46b5a66SChristoph Hellwig #include <linux/file.h>
10f46b5a66SChristoph Hellwig #include <linux/fs.h>
11cb8e7090SChristoph Hellwig #include <linux/fsnotify.h>
12f46b5a66SChristoph Hellwig #include <linux/pagemap.h>
13f46b5a66SChristoph Hellwig #include <linux/highmem.h>
14f46b5a66SChristoph Hellwig #include <linux/time.h>
15f46b5a66SChristoph Hellwig #include <linux/init.h>
16f46b5a66SChristoph Hellwig #include <linux/string.h>
17f46b5a66SChristoph Hellwig #include <linux/backing-dev.h>
18cb8e7090SChristoph Hellwig #include <linux/mount.h>
19f46b5a66SChristoph Hellwig #include <linux/mpage.h>
20cb8e7090SChristoph Hellwig #include <linux/namei.h>
21f46b5a66SChristoph Hellwig #include <linux/swap.h>
22f46b5a66SChristoph Hellwig #include <linux/writeback.h>
23f46b5a66SChristoph Hellwig #include <linux/compat.h>
24f46b5a66SChristoph Hellwig #include <linux/bit_spinlock.h>
25cb8e7090SChristoph Hellwig #include <linux/security.h>
26f46b5a66SChristoph Hellwig #include <linux/xattr.h>
27f54de068SDavid Sterba #include <linux/mm.h>
285a0e3ad6STejun Heo #include <linux/slab.h>
29f7039b1dSLi Dongyang #include <linux/blkdev.h>
308ea05e3aSAlexander Block #include <linux/uuid.h>
3155e301fdSFilipe Brandenburger #include <linux/btrfs.h>
32416161dbSMark Fasheh #include <linux/uaccess.h>
33ae5e165dSJeff Layton #include <linux/iversion.h>
34f46b5a66SChristoph Hellwig #include "ctree.h"
35f46b5a66SChristoph Hellwig #include "disk-io.h"
36f46b5a66SChristoph Hellwig #include "transaction.h"
37f46b5a66SChristoph Hellwig #include "btrfs_inode.h"
38f46b5a66SChristoph Hellwig #include "print-tree.h"
39f46b5a66SChristoph Hellwig #include "volumes.h"
40925baeddSChris Mason #include "locking.h"
41581bb050SLi Zefan #include "inode-map.h"
42d7728c96SJan Schmidt #include "backref.h"
43606686eeSJosef Bacik #include "rcu-string.h"
4431db9f7cSAlexander Block #include "send.h"
453f6bcfbdSStefan Behrens #include "dev-replace.h"
4663541927SFilipe David Borba Manana #include "props.h"
473b02a68aSJeff Mahoney #include "sysfs.h"
48fcebe456SJosef Bacik #include "qgroup.h"
491ec9a1aeSFilipe Manana #include "tree-log.h"
50ebb8765bSAnand Jain #include "compression.h"
51f46b5a66SChristoph Hellwig 
52abccd00fSHugo Mills #ifdef CONFIG_64BIT
53abccd00fSHugo Mills /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
54abccd00fSHugo Mills  * structures are incorrect, as the timespec structure from userspace
55abccd00fSHugo Mills  * is 4 bytes too small. We define these alternatives here to teach
56abccd00fSHugo Mills  * the kernel about the 32-bit struct packing.
57abccd00fSHugo Mills  */
58abccd00fSHugo Mills struct btrfs_ioctl_timespec_32 {
59abccd00fSHugo Mills 	__u64 sec;
60abccd00fSHugo Mills 	__u32 nsec;
61abccd00fSHugo Mills } __attribute__ ((__packed__));
62abccd00fSHugo Mills 
63abccd00fSHugo Mills struct btrfs_ioctl_received_subvol_args_32 {
64abccd00fSHugo Mills 	char	uuid[BTRFS_UUID_SIZE];	/* in */
65abccd00fSHugo Mills 	__u64	stransid;		/* in */
66abccd00fSHugo Mills 	__u64	rtransid;		/* out */
67abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 stime; /* in */
68abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 rtime; /* out */
69abccd00fSHugo Mills 	__u64	flags;			/* in */
70abccd00fSHugo Mills 	__u64	reserved[16];		/* in */
71abccd00fSHugo Mills } __attribute__ ((__packed__));
72abccd00fSHugo Mills 
73abccd00fSHugo Mills #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
74abccd00fSHugo Mills 				struct btrfs_ioctl_received_subvol_args_32)
75abccd00fSHugo Mills #endif
76abccd00fSHugo Mills 
772351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
782351f431SJosef Bacik struct btrfs_ioctl_send_args_32 {
792351f431SJosef Bacik 	__s64 send_fd;			/* in */
802351f431SJosef Bacik 	__u64 clone_sources_count;	/* in */
812351f431SJosef Bacik 	compat_uptr_t clone_sources;	/* in */
822351f431SJosef Bacik 	__u64 parent_root;		/* in */
832351f431SJosef Bacik 	__u64 flags;			/* in */
842351f431SJosef Bacik 	__u64 reserved[4];		/* in */
852351f431SJosef Bacik } __attribute__ ((__packed__));
862351f431SJosef Bacik 
872351f431SJosef Bacik #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
882351f431SJosef Bacik 			       struct btrfs_ioctl_send_args_32)
892351f431SJosef Bacik #endif
90abccd00fSHugo Mills 
91416161dbSMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
921c919a5eSMark Fasheh 		       u64 off, u64 olen, u64 olen_aligned, u64 destoff,
931c919a5eSMark Fasheh 		       int no_time_update);
94416161dbSMark Fasheh 
956cbff00fSChristoph Hellwig /* Mask out flags that are inappropriate for the given type of inode. */
961905a0f7SDavid Sterba static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
971905a0f7SDavid Sterba 		unsigned int flags)
986cbff00fSChristoph Hellwig {
991905a0f7SDavid Sterba 	if (S_ISDIR(inode->i_mode))
1006cbff00fSChristoph Hellwig 		return flags;
1011905a0f7SDavid Sterba 	else if (S_ISREG(inode->i_mode))
1026cbff00fSChristoph Hellwig 		return flags & ~FS_DIRSYNC_FL;
1036cbff00fSChristoph Hellwig 	else
1046cbff00fSChristoph Hellwig 		return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
1056cbff00fSChristoph Hellwig }
106f46b5a66SChristoph Hellwig 
1076cbff00fSChristoph Hellwig /*
108a157d4fdSDavid Sterba  * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
109a157d4fdSDavid Sterba  * ioctl.
1106cbff00fSChristoph Hellwig  */
111a157d4fdSDavid Sterba static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags)
1126cbff00fSChristoph Hellwig {
1136cbff00fSChristoph Hellwig 	unsigned int iflags = 0;
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;
129d0092bddSLi Zefan 
13013f48dc9SSatoru Takeuchi 	if (flags & BTRFS_INODE_NOCOMPRESS)
131d0092bddSLi Zefan 		iflags |= FS_NOCOMP_FL;
13213f48dc9SSatoru Takeuchi 	else if (flags & BTRFS_INODE_COMPRESS)
13313f48dc9SSatoru Takeuchi 		iflags |= FS_COMPR_FL;
1346cbff00fSChristoph Hellwig 
1356cbff00fSChristoph Hellwig 	return iflags;
1366cbff00fSChristoph Hellwig }
1376cbff00fSChristoph Hellwig 
1386cbff00fSChristoph Hellwig /*
1396cbff00fSChristoph Hellwig  * Update inode->i_flags based on the btrfs internal flags.
1406cbff00fSChristoph Hellwig  */
1417b6a221eSDavid Sterba void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
1426cbff00fSChristoph Hellwig {
1435c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
1443cc79392SFilipe Manana 	unsigned int new_fl = 0;
1456cbff00fSChristoph Hellwig 
1465c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_SYNC)
1473cc79392SFilipe Manana 		new_fl |= S_SYNC;
1485c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_IMMUTABLE)
1493cc79392SFilipe Manana 		new_fl |= S_IMMUTABLE;
1505c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_APPEND)
1513cc79392SFilipe Manana 		new_fl |= S_APPEND;
1525c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_NOATIME)
1533cc79392SFilipe Manana 		new_fl |= S_NOATIME;
1545c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_DIRSYNC)
1553cc79392SFilipe Manana 		new_fl |= S_DIRSYNC;
1563cc79392SFilipe Manana 
1573cc79392SFilipe Manana 	set_mask_bits(&inode->i_flags,
1583cc79392SFilipe Manana 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
1593cc79392SFilipe Manana 		      new_fl);
1606cbff00fSChristoph Hellwig }
1616cbff00fSChristoph Hellwig 
1626cbff00fSChristoph Hellwig static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
1636cbff00fSChristoph Hellwig {
1645c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(file_inode(file));
1655c57b8b6SDavid Sterba 	unsigned int flags = btrfs_inode_flags_to_fsflags(binode->flags);
1666cbff00fSChristoph Hellwig 
1676cbff00fSChristoph Hellwig 	if (copy_to_user(arg, &flags, sizeof(flags)))
1686cbff00fSChristoph Hellwig 		return -EFAULT;
1696cbff00fSChristoph Hellwig 	return 0;
1706cbff00fSChristoph Hellwig }
1716cbff00fSChristoph Hellwig 
1725ba76abfSDavid Sterba /* Check if @flags are a supported and valid set of FS_*_FL flags */
1735ba76abfSDavid Sterba static int check_fsflags(unsigned int flags)
17475e7cb7fSLiu Bo {
17575e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
17675e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
17775e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
178e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
179e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
18075e7cb7fSLiu Bo 		return -EOPNOTSUPP;
18175e7cb7fSLiu Bo 
18275e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
18375e7cb7fSLiu Bo 		return -EINVAL;
18475e7cb7fSLiu Bo 
18575e7cb7fSLiu Bo 	return 0;
18675e7cb7fSLiu Bo }
18775e7cb7fSLiu Bo 
1886cbff00fSChristoph Hellwig static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
1896cbff00fSChristoph Hellwig {
190496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
1910b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1925c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
1935c57b8b6SDavid Sterba 	struct btrfs_root *root = binode->root;
1946cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
1955c57b8b6SDavid Sterba 	unsigned int fsflags, old_fsflags;
1966cbff00fSChristoph Hellwig 	int ret;
1975c57b8b6SDavid Sterba 	u64 old_flags;
1985c57b8b6SDavid Sterba 	unsigned int old_i_flags;
1997e97b8daSDavid Sterba 	umode_t mode;
2006cbff00fSChristoph Hellwig 
201bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
202bd60ea0fSDavid Sterba 		return -EPERM;
203bd60ea0fSDavid Sterba 
204b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
205b83cc969SLi Zefan 		return -EROFS;
206b83cc969SLi Zefan 
2075c57b8b6SDavid Sterba 	if (copy_from_user(&fsflags, arg, sizeof(fsflags)))
2086cbff00fSChristoph Hellwig 		return -EFAULT;
2096cbff00fSChristoph Hellwig 
2105c57b8b6SDavid Sterba 	ret = check_fsflags(fsflags);
21175e7cb7fSLiu Bo 	if (ret)
21275e7cb7fSLiu Bo 		return ret;
2136cbff00fSChristoph Hellwig 
214e7848683SJan Kara 	ret = mnt_want_write_file(file);
215e7848683SJan Kara 	if (ret)
216e7848683SJan Kara 		return ret;
217e7848683SJan Kara 
2185955102cSAl Viro 	inode_lock(inode);
2196cbff00fSChristoph Hellwig 
2205c57b8b6SDavid Sterba 	old_flags = binode->flags;
2215c57b8b6SDavid Sterba 	old_i_flags = inode->i_flags;
2227e97b8daSDavid Sterba 	mode = inode->i_mode;
223f062abf0SLi Zefan 
2245c57b8b6SDavid Sterba 	fsflags = btrfs_mask_fsflags_for_type(inode, fsflags);
2255c57b8b6SDavid Sterba 	old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags);
2265c57b8b6SDavid Sterba 	if ((fsflags ^ old_fsflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
2276cbff00fSChristoph Hellwig 		if (!capable(CAP_LINUX_IMMUTABLE)) {
2286cbff00fSChristoph Hellwig 			ret = -EPERM;
2296cbff00fSChristoph Hellwig 			goto out_unlock;
2306cbff00fSChristoph Hellwig 		}
2316cbff00fSChristoph Hellwig 	}
2326cbff00fSChristoph Hellwig 
2335c57b8b6SDavid Sterba 	if (fsflags & FS_SYNC_FL)
2345c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_SYNC;
2356cbff00fSChristoph Hellwig 	else
2365c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_SYNC;
2375c57b8b6SDavid Sterba 	if (fsflags & FS_IMMUTABLE_FL)
2385c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_IMMUTABLE;
2396cbff00fSChristoph Hellwig 	else
2405c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_IMMUTABLE;
2415c57b8b6SDavid Sterba 	if (fsflags & FS_APPEND_FL)
2425c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_APPEND;
2436cbff00fSChristoph Hellwig 	else
2445c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_APPEND;
2455c57b8b6SDavid Sterba 	if (fsflags & FS_NODUMP_FL)
2465c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_NODUMP;
2476cbff00fSChristoph Hellwig 	else
2485c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NODUMP;
2495c57b8b6SDavid Sterba 	if (fsflags & FS_NOATIME_FL)
2505c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_NOATIME;
2516cbff00fSChristoph Hellwig 	else
2525c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NOATIME;
2535c57b8b6SDavid Sterba 	if (fsflags & FS_DIRSYNC_FL)
2545c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_DIRSYNC;
2556cbff00fSChristoph Hellwig 	else
2565c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_DIRSYNC;
2575c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOW_FL) {
2587e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2597e97b8daSDavid Sterba 			/*
2607e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2617e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2627e97b8daSDavid Sterba 			 * status of the file and will not set it.
2637e97b8daSDavid Sterba 			 */
2647e97b8daSDavid Sterba 			if (inode->i_size == 0)
2655c57b8b6SDavid Sterba 				binode->flags |= BTRFS_INODE_NODATACOW
2667e97b8daSDavid Sterba 					      | BTRFS_INODE_NODATASUM;
2677e97b8daSDavid Sterba 		} else {
2685c57b8b6SDavid Sterba 			binode->flags |= BTRFS_INODE_NODATACOW;
2697e97b8daSDavid Sterba 		}
2707e97b8daSDavid Sterba 	} else {
2717e97b8daSDavid Sterba 		/*
27201327610SNicholas D Steeves 		 * Revert back under same assumptions as above
2737e97b8daSDavid Sterba 		 */
2747e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2757e97b8daSDavid Sterba 			if (inode->i_size == 0)
2765c57b8b6SDavid Sterba 				binode->flags &= ~(BTRFS_INODE_NODATACOW
2777e97b8daSDavid Sterba 				             | BTRFS_INODE_NODATASUM);
2787e97b8daSDavid Sterba 		} else {
2795c57b8b6SDavid Sterba 			binode->flags &= ~BTRFS_INODE_NODATACOW;
2807e97b8daSDavid Sterba 		}
2817e97b8daSDavid Sterba 	}
2826cbff00fSChristoph Hellwig 
28375e7cb7fSLiu Bo 	/*
28475e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
28575e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
28675e7cb7fSLiu Bo 	 * things smaller.
28775e7cb7fSLiu Bo 	 */
2885c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOMP_FL) {
2895c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_COMPRESS;
2905c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_NOCOMPRESS;
29163541927SFilipe David Borba Manana 
29263541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
29363541927SFilipe David Borba Manana 		if (ret && ret != -ENODATA)
29463541927SFilipe David Borba Manana 			goto out_drop;
2955c57b8b6SDavid Sterba 	} else if (fsflags & FS_COMPR_FL) {
29663541927SFilipe David Borba Manana 		const char *comp;
29763541927SFilipe David Borba Manana 
2985c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_COMPRESS;
2995c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NOCOMPRESS;
30063541927SFilipe David Borba Manana 
30193370509SDavid Sterba 		comp = btrfs_compress_type2str(fs_info->compress_type);
30293370509SDavid Sterba 		if (!comp || comp[0] == 0)
30393370509SDavid Sterba 			comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
30493370509SDavid Sterba 
30563541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression",
30663541927SFilipe David Borba Manana 				     comp, strlen(comp), 0);
30763541927SFilipe David Borba Manana 		if (ret)
30863541927SFilipe David Borba Manana 			goto out_drop;
30963541927SFilipe David Borba Manana 
310ebcb904dSLi Zefan 	} else {
31178a017a2SFilipe Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
31278a017a2SFilipe Manana 		if (ret && ret != -ENODATA)
31378a017a2SFilipe Manana 			goto out_drop;
3145c57b8b6SDavid Sterba 		binode->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
31575e7cb7fSLiu Bo 	}
3166cbff00fSChristoph Hellwig 
3174da6f1a3SLi Zefan 	trans = btrfs_start_transaction(root, 1);
318f062abf0SLi Zefan 	if (IS_ERR(trans)) {
319f062abf0SLi Zefan 		ret = PTR_ERR(trans);
320f062abf0SLi Zefan 		goto out_drop;
321f062abf0SLi Zefan 	}
3226cbff00fSChristoph Hellwig 
3237b6a221eSDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
3240c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
325c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3266cbff00fSChristoph Hellwig 	ret = btrfs_update_inode(trans, root, inode);
3276cbff00fSChristoph Hellwig 
3283a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
329f062abf0SLi Zefan  out_drop:
330f062abf0SLi Zefan 	if (ret) {
3315c57b8b6SDavid Sterba 		binode->flags = old_flags;
3325c57b8b6SDavid Sterba 		inode->i_flags = old_i_flags;
333f062abf0SLi Zefan 	}
3346cbff00fSChristoph Hellwig 
3356cbff00fSChristoph Hellwig  out_unlock:
3365955102cSAl Viro 	inode_unlock(inode);
337e7848683SJan Kara 	mnt_drop_write_file(file);
3382d4e6f6aSliubo 	return ret;
3396cbff00fSChristoph Hellwig }
3406cbff00fSChristoph Hellwig 
34119f93b3cSDavid Sterba /*
34219f93b3cSDavid Sterba  * Translate btrfs internal inode flags to xflags as expected by the
34319f93b3cSDavid Sterba  * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are
34419f93b3cSDavid Sterba  * silently dropped.
34519f93b3cSDavid Sterba  */
34619f93b3cSDavid Sterba static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags)
34719f93b3cSDavid Sterba {
34819f93b3cSDavid Sterba 	unsigned int xflags = 0;
34919f93b3cSDavid Sterba 
35019f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_APPEND)
35119f93b3cSDavid Sterba 		xflags |= FS_XFLAG_APPEND;
35219f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_IMMUTABLE)
35319f93b3cSDavid Sterba 		xflags |= FS_XFLAG_IMMUTABLE;
35419f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_NOATIME)
35519f93b3cSDavid Sterba 		xflags |= FS_XFLAG_NOATIME;
35619f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_NODUMP)
35719f93b3cSDavid Sterba 		xflags |= FS_XFLAG_NODUMP;
35819f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_SYNC)
35919f93b3cSDavid Sterba 		xflags |= FS_XFLAG_SYNC;
36019f93b3cSDavid Sterba 
36119f93b3cSDavid Sterba 	return xflags;
36219f93b3cSDavid Sterba }
36319f93b3cSDavid Sterba 
36419f93b3cSDavid Sterba /* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */
36519f93b3cSDavid Sterba static int check_xflags(unsigned int flags)
36619f93b3cSDavid Sterba {
36719f93b3cSDavid Sterba 	if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME |
36819f93b3cSDavid Sterba 		      FS_XFLAG_NODUMP | FS_XFLAG_SYNC))
36919f93b3cSDavid Sterba 		return -EOPNOTSUPP;
37019f93b3cSDavid Sterba 	return 0;
37119f93b3cSDavid Sterba }
37219f93b3cSDavid Sterba 
373e4202ac9SDavid Sterba /*
374e4202ac9SDavid Sterba  * Set the xflags from the internal inode flags. The remaining items of fsxattr
375e4202ac9SDavid Sterba  * are zeroed.
376e4202ac9SDavid Sterba  */
377e4202ac9SDavid Sterba static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg)
378e4202ac9SDavid Sterba {
379e4202ac9SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(file_inode(file));
380e4202ac9SDavid Sterba 	struct fsxattr fa;
381e4202ac9SDavid Sterba 
382e4202ac9SDavid Sterba 	memset(&fa, 0, sizeof(fa));
383e4202ac9SDavid Sterba 	fa.fsx_xflags = btrfs_inode_flags_to_xflags(binode->flags);
384e4202ac9SDavid Sterba 
385e4202ac9SDavid Sterba 	if (copy_to_user(arg, &fa, sizeof(fa)))
386e4202ac9SDavid Sterba 		return -EFAULT;
387e4202ac9SDavid Sterba 
388e4202ac9SDavid Sterba 	return 0;
389e4202ac9SDavid Sterba }
390e4202ac9SDavid Sterba 
391025f2121SDavid Sterba static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg)
392025f2121SDavid Sterba {
393025f2121SDavid Sterba 	struct inode *inode = file_inode(file);
394025f2121SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
395025f2121SDavid Sterba 	struct btrfs_root *root = binode->root;
396025f2121SDavid Sterba 	struct btrfs_trans_handle *trans;
397025f2121SDavid Sterba 	struct fsxattr fa;
398025f2121SDavid Sterba 	unsigned old_flags;
399025f2121SDavid Sterba 	unsigned old_i_flags;
400025f2121SDavid Sterba 	int ret = 0;
401025f2121SDavid Sterba 
402025f2121SDavid Sterba 	if (!inode_owner_or_capable(inode))
403025f2121SDavid Sterba 		return -EPERM;
404025f2121SDavid Sterba 
405025f2121SDavid Sterba 	if (btrfs_root_readonly(root))
406025f2121SDavid Sterba 		return -EROFS;
407025f2121SDavid Sterba 
408025f2121SDavid Sterba 	memset(&fa, 0, sizeof(fa));
409025f2121SDavid Sterba 	if (copy_from_user(&fa, arg, sizeof(fa)))
410025f2121SDavid Sterba 		return -EFAULT;
411025f2121SDavid Sterba 
412025f2121SDavid Sterba 	ret = check_xflags(fa.fsx_xflags);
413025f2121SDavid Sterba 	if (ret)
414025f2121SDavid Sterba 		return ret;
415025f2121SDavid Sterba 
416025f2121SDavid Sterba 	if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0)
417025f2121SDavid Sterba 		return -EOPNOTSUPP;
418025f2121SDavid Sterba 
419025f2121SDavid Sterba 	ret = mnt_want_write_file(file);
420025f2121SDavid Sterba 	if (ret)
421025f2121SDavid Sterba 		return ret;
422025f2121SDavid Sterba 
423025f2121SDavid Sterba 	inode_lock(inode);
424025f2121SDavid Sterba 
425025f2121SDavid Sterba 	old_flags = binode->flags;
426025f2121SDavid Sterba 	old_i_flags = inode->i_flags;
427025f2121SDavid Sterba 
428025f2121SDavid Sterba 	/* We need the capabilities to change append-only or immutable inode */
429025f2121SDavid Sterba 	if (((old_flags & (BTRFS_INODE_APPEND | BTRFS_INODE_IMMUTABLE)) ||
430025f2121SDavid Sterba 	     (fa.fsx_xflags & (FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE))) &&
431025f2121SDavid Sterba 	    !capable(CAP_LINUX_IMMUTABLE)) {
432025f2121SDavid Sterba 		ret = -EPERM;
433025f2121SDavid Sterba 		goto out_unlock;
434025f2121SDavid Sterba 	}
435025f2121SDavid Sterba 
436025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_SYNC)
437025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_SYNC;
438025f2121SDavid Sterba 	else
439025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_SYNC;
440025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE)
441025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_IMMUTABLE;
442025f2121SDavid Sterba 	else
443025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_IMMUTABLE;
444025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_APPEND)
445025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_APPEND;
446025f2121SDavid Sterba 	else
447025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_APPEND;
448025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_NODUMP)
449025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_NODUMP;
450025f2121SDavid Sterba 	else
451025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NODUMP;
452025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_NOATIME)
453025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_NOATIME;
454025f2121SDavid Sterba 	else
455025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NOATIME;
456025f2121SDavid Sterba 
457025f2121SDavid Sterba 	/* 1 item for the inode */
458025f2121SDavid Sterba 	trans = btrfs_start_transaction(root, 1);
459025f2121SDavid Sterba 	if (IS_ERR(trans)) {
460025f2121SDavid Sterba 		ret = PTR_ERR(trans);
461025f2121SDavid Sterba 		goto out_unlock;
462025f2121SDavid Sterba 	}
463025f2121SDavid Sterba 
464025f2121SDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
465025f2121SDavid Sterba 	inode_inc_iversion(inode);
466025f2121SDavid Sterba 	inode->i_ctime = current_time(inode);
467025f2121SDavid Sterba 	ret = btrfs_update_inode(trans, root, inode);
468025f2121SDavid Sterba 
469025f2121SDavid Sterba 	btrfs_end_transaction(trans);
470025f2121SDavid Sterba 
471025f2121SDavid Sterba out_unlock:
472025f2121SDavid Sterba 	if (ret) {
473025f2121SDavid Sterba 		binode->flags = old_flags;
474025f2121SDavid Sterba 		inode->i_flags = old_i_flags;
475025f2121SDavid Sterba 	}
476025f2121SDavid Sterba 
477025f2121SDavid Sterba 	inode_unlock(inode);
478025f2121SDavid Sterba 	mnt_drop_write_file(file);
479025f2121SDavid Sterba 
480025f2121SDavid Sterba 	return ret;
481025f2121SDavid Sterba }
482025f2121SDavid Sterba 
4836cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
4846cbff00fSChristoph Hellwig {
485496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4866cbff00fSChristoph Hellwig 
4876cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
4886cbff00fSChristoph Hellwig }
489f46b5a66SChristoph Hellwig 
490f7039b1dSLi Dongyang static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
491f7039b1dSLi Dongyang {
4920b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
4930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
494f7039b1dSLi Dongyang 	struct btrfs_device *device;
495f7039b1dSLi Dongyang 	struct request_queue *q;
496f7039b1dSLi Dongyang 	struct fstrim_range range;
497f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
498f7039b1dSLi Dongyang 	u64 num_devices = 0;
499815745cfSAl Viro 	u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
500f7039b1dSLi Dongyang 	int ret;
501f7039b1dSLi Dongyang 
502f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
503f7039b1dSLi Dongyang 		return -EPERM;
504f7039b1dSLi Dongyang 
5051f78160cSXiao Guangrong 	rcu_read_lock();
5061f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
5071f78160cSXiao Guangrong 				dev_list) {
508f7039b1dSLi Dongyang 		if (!device->bdev)
509f7039b1dSLi Dongyang 			continue;
510f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
511f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
512f7039b1dSLi Dongyang 			num_devices++;
51350d0446eSSeraphime Kirkovski 			minlen = min_t(u64, q->limits.discard_granularity,
514f7039b1dSLi Dongyang 				     minlen);
515f7039b1dSLi Dongyang 		}
516f7039b1dSLi Dongyang 	}
5171f78160cSXiao Guangrong 	rcu_read_unlock();
518f4c697e6SLukas Czerner 
519f7039b1dSLi Dongyang 	if (!num_devices)
520f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
521f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
522f7039b1dSLi Dongyang 		return -EFAULT;
523e515c18bSLukas Czerner 	if (range.start > total_bytes ||
524e515c18bSLukas Czerner 	    range.len < fs_info->sb->s_blocksize)
525f4c697e6SLukas Czerner 		return -EINVAL;
526f7039b1dSLi Dongyang 
527f4c697e6SLukas Czerner 	range.len = min(range.len, total_bytes - range.start);
528f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
5292ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
530f7039b1dSLi Dongyang 	if (ret < 0)
531f7039b1dSLi Dongyang 		return ret;
532f7039b1dSLi Dongyang 
533f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
534f7039b1dSLi Dongyang 		return -EFAULT;
535f7039b1dSLi Dongyang 
536f7039b1dSLi Dongyang 	return 0;
537f7039b1dSLi Dongyang }
538f7039b1dSLi Dongyang 
539dd5f9615SStefan Behrens int btrfs_is_empty_uuid(u8 *uuid)
540dd5f9615SStefan Behrens {
54146e0f66aSChris Mason 	int i;
54246e0f66aSChris Mason 
54346e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
54446e0f66aSChris Mason 		if (uuid[i])
54546e0f66aSChris Mason 			return 0;
54646e0f66aSChris Mason 	}
54746e0f66aSChris Mason 	return 1;
548dd5f9615SStefan Behrens }
549dd5f9615SStefan Behrens 
550d5c12070SMiao Xie static noinline int create_subvol(struct inode *dir,
551cb8e7090SChristoph Hellwig 				  struct dentry *dentry,
55252f75f4fSDavid Sterba 				  const char *name, int namelen,
5536f72c7e2SArne Jansen 				  u64 *async_transid,
5548696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
555f46b5a66SChristoph Hellwig {
5560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
557f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
558f46b5a66SChristoph Hellwig 	struct btrfs_key key;
55949a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
560f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
561f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
562d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
56376dda93cSYan, Zheng 	struct btrfs_root *new_root;
564d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
565c2050a45SDeepa Dinamani 	struct timespec cur_time = current_time(dir);
5665662344bSTsutomu Itoh 	struct inode *inode;
567f46b5a66SChristoph Hellwig 	int ret;
568f46b5a66SChristoph Hellwig 	int err;
569f46b5a66SChristoph Hellwig 	u64 objectid;
570f46b5a66SChristoph Hellwig 	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
5713de4586cSChris Mason 	u64 index = 0;
5728ea05e3aSAlexander Block 	uuid_le new_uuid;
573f46b5a66SChristoph Hellwig 
57449a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
57549a3c4d9SDavid Sterba 	if (!root_item)
57649a3c4d9SDavid Sterba 		return -ENOMEM;
57749a3c4d9SDavid Sterba 
5780b246afaSJeff Mahoney 	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
5792fbe8c8aSAl Viro 	if (ret)
58049a3c4d9SDavid Sterba 		goto fail_free;
5816a912213SJosef Bacik 
582e09fe2d2SQu Wenruo 	/*
583e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
58401327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
585e09fe2d2SQu Wenruo 	 */
58649a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
58749a3c4d9SDavid Sterba 		ret = -ENOSPC;
58849a3c4d9SDavid Sterba 		goto fail_free;
58949a3c4d9SDavid Sterba 	}
590e09fe2d2SQu Wenruo 
591d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
5929ed74f2dSJosef Bacik 	/*
593d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
594d5c12070SMiao Xie 	 * of create_snapshot().
5959ed74f2dSJosef Bacik 	 */
596c4c129dbSGu JinXiang 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
597d5c12070SMiao Xie 	if (ret)
59849a3c4d9SDavid Sterba 		goto fail_free;
599f46b5a66SChristoph Hellwig 
600d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
601d5c12070SMiao Xie 	if (IS_ERR(trans)) {
602d5c12070SMiao Xie 		ret = PTR_ERR(trans);
6037775c818SDavid Sterba 		btrfs_subvolume_release_metadata(fs_info, &block_rsv);
60449a3c4d9SDavid Sterba 		goto fail_free;
605d5c12070SMiao Xie 	}
606d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
607d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
608f46b5a66SChristoph Hellwig 
6090b246afaSJeff Mahoney 	ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
6106f72c7e2SArne Jansen 	if (ret)
6116f72c7e2SArne Jansen 		goto fail;
6126f72c7e2SArne Jansen 
6134d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
6148e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
6158e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
6168e8a1e31SJosef Bacik 		goto fail;
6178e8a1e31SJosef Bacik 	}
618f46b5a66SChristoph Hellwig 
619b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
620f46b5a66SChristoph Hellwig 	btrfs_set_header_bytenr(leaf, leaf->start);
621f46b5a66SChristoph Hellwig 	btrfs_set_header_generation(leaf, trans->transid);
6225d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
623f46b5a66SChristoph Hellwig 	btrfs_set_header_owner(leaf, objectid);
624f46b5a66SChristoph Hellwig 
6250b246afaSJeff Mahoney 	write_extent_buffer_fsid(leaf, fs_info->fsid);
6260b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
627f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
628f46b5a66SChristoph Hellwig 
62949a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
6303cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
6313cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
6323cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
633da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
6340b246afaSJeff Mahoney 				     fs_info->nodesize);
6353cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
636f46b5a66SChristoph Hellwig 
63749a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
63849a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
6393cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
64008fe4db1SLi Zefan 
64149a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
64249a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
64349a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
64449a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
64549a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
64649a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
647f46b5a66SChristoph Hellwig 
64849a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
64949a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
6508ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
65149a3c4d9SDavid Sterba 	memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
65249a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
65349a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
65449a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
65549a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
65649a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
657f46b5a66SChristoph Hellwig 
658925baeddSChris Mason 	btrfs_tree_unlock(leaf);
659f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
660f46b5a66SChristoph Hellwig 	leaf = NULL;
661f46b5a66SChristoph Hellwig 
66249a3c4d9SDavid Sterba 	btrfs_set_root_dirid(root_item, new_dirid);
663f46b5a66SChristoph Hellwig 
664f46b5a66SChristoph Hellwig 	key.objectid = objectid;
6655d4f98a2SYan Zheng 	key.offset = 0;
666962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
6670b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
66849a3c4d9SDavid Sterba 				root_item);
669f46b5a66SChristoph Hellwig 	if (ret)
670f46b5a66SChristoph Hellwig 		goto fail;
671f46b5a66SChristoph Hellwig 
67276dda93cSYan, Zheng 	key.offset = (u64)-1;
6730b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &key);
67479787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
67579787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
67666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
67779787eaaSJeff Mahoney 		goto fail;
67879787eaaSJeff Mahoney 	}
67976dda93cSYan, Zheng 
68076dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
68176dda93cSYan, Zheng 
68263541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
683ce598979SMark Fasheh 	if (ret) {
684ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
68566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
686ce598979SMark Fasheh 		goto fail;
687ce598979SMark Fasheh 	}
688ce598979SMark Fasheh 
689f32e48e9SChandan Rajendra 	mutex_lock(&new_root->objectid_mutex);
690f32e48e9SChandan Rajendra 	new_root->highest_objectid = new_dirid;
691f32e48e9SChandan Rajendra 	mutex_unlock(&new_root->objectid_mutex);
692f32e48e9SChandan Rajendra 
693f46b5a66SChristoph Hellwig 	/*
694f46b5a66SChristoph Hellwig 	 * insert the directory item
695f46b5a66SChristoph Hellwig 	 */
696877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
69779787eaaSJeff Mahoney 	if (ret) {
69866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
69979787eaaSJeff Mahoney 		goto fail;
70079787eaaSJeff Mahoney 	}
7013de4586cSChris Mason 
7023de4586cSChris Mason 	ret = btrfs_insert_dir_item(trans, root,
7038e7611cfSNikolay Borisov 				    name, namelen, BTRFS_I(dir), &key,
7043de4586cSChris Mason 				    BTRFS_FT_DIR, index);
70579787eaaSJeff Mahoney 	if (ret) {
70666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
707f46b5a66SChristoph Hellwig 		goto fail;
70879787eaaSJeff Mahoney 	}
7090660b5afSChris Mason 
7106ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
71152c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
71252c26179SYan Zheng 	BUG_ON(ret);
71352c26179SYan Zheng 
7140b246afaSJeff Mahoney 	ret = btrfs_add_root_ref(trans, fs_info,
7154df27c4dSYan, Zheng 				 objectid, root->root_key.objectid,
7164a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
7170660b5afSChris Mason 	BUG_ON(ret);
7180660b5afSChris Mason 
719cdb345a8SLu Fengqi 	ret = btrfs_uuid_tree_add(trans, root_item->uuid,
7206bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
721dd5f9615SStefan Behrens 	if (ret)
72266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
723dd5f9615SStefan Behrens 
724f46b5a66SChristoph Hellwig fail:
72549a3c4d9SDavid Sterba 	kfree(root_item);
726d5c12070SMiao Xie 	trans->block_rsv = NULL;
727d5c12070SMiao Xie 	trans->bytes_reserved = 0;
7287775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
729de6e8200SLiu Bo 
73072fd032eSSage Weil 	if (async_transid) {
73172fd032eSSage Weil 		*async_transid = trans->transid;
7323a45bb20SJeff Mahoney 		err = btrfs_commit_transaction_async(trans, 1);
73300d71c9cSMiao Xie 		if (err)
7343a45bb20SJeff Mahoney 			err = btrfs_commit_transaction(trans);
73572fd032eSSage Weil 	} else {
7363a45bb20SJeff Mahoney 		err = btrfs_commit_transaction(trans);
73772fd032eSSage Weil 	}
738f46b5a66SChristoph Hellwig 	if (err && !ret)
739f46b5a66SChristoph Hellwig 		ret = err;
7401a65e24bSChris Mason 
7415662344bSTsutomu Itoh 	if (!ret) {
7425662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
743de6e8200SLiu Bo 		if (IS_ERR(inode))
744de6e8200SLiu Bo 			return PTR_ERR(inode);
7455662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
7465662344bSTsutomu Itoh 	}
747f46b5a66SChristoph Hellwig 	return ret;
74849a3c4d9SDavid Sterba 
74949a3c4d9SDavid Sterba fail_free:
75049a3c4d9SDavid Sterba 	kfree(root_item);
75149a3c4d9SDavid Sterba 	return ret;
752f46b5a66SChristoph Hellwig }
753f46b5a66SChristoph Hellwig 
754e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
75561d7e4cbSDavid Sterba 			   struct dentry *dentry,
756e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
757e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
758f46b5a66SChristoph Hellwig {
7590b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
7602e4bfab9SYan, Zheng 	struct inode *inode;
761f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
762f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
7632e4bfab9SYan, Zheng 	int ret;
764f46b5a66SChristoph Hellwig 
76527cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
766f46b5a66SChristoph Hellwig 		return -EINVAL;
767f46b5a66SChristoph Hellwig 
76823269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
769a1ee7362SDavid Sterba 	if (!pending_snapshot)
770a1ee7362SDavid Sterba 		return -ENOMEM;
771a1ee7362SDavid Sterba 
772b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
77323269bf5SDavid Sterba 			GFP_KERNEL);
7748546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
7758546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
776b0c0ea63SDavid Sterba 		ret = -ENOMEM;
777b0c0ea63SDavid Sterba 		goto free_pending;
778b0c0ea63SDavid Sterba 	}
779b0c0ea63SDavid Sterba 
780ea14b57fSDavid Sterba 	atomic_inc(&root->will_be_snapshotted);
7814e857c58SPeter Zijlstra 	smp_mb__after_atomic();
78245bac0f3SLiu Bo 	/* wait for no snapshot writes */
78345bac0f3SLiu Bo 	wait_event(root->subv_writers->wait,
78445bac0f3SLiu Bo 		   percpu_counter_sum(&root->subv_writers->counter) == 0);
7858257b2dcSMiao Xie 
78676f32e24SNikolay Borisov 	ret = btrfs_start_delalloc_inodes(root);
7876a03843dSMiao Xie 	if (ret)
788a1ee7362SDavid Sterba 		goto dec_and_free;
7896a03843dSMiao Xie 
7906374e57aSChris Mason 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
7916a03843dSMiao Xie 
79266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
79366d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
794d5c12070SMiao Xie 	/*
795d5c12070SMiao Xie 	 * 1 - parent dir inode
796d5c12070SMiao Xie 	 * 2 - dir entries
797d5c12070SMiao Xie 	 * 1 - root item
798d5c12070SMiao Xie 	 * 2 - root ref/backref
799d5c12070SMiao Xie 	 * 1 - root of snapshot
800dd5f9615SStefan Behrens 	 * 1 - UUID item
801d5c12070SMiao Xie 	 */
802d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
803dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
804ee3441b4SJeff Mahoney 					false);
805d5c12070SMiao Xie 	if (ret)
806a1ee7362SDavid Sterba 		goto dec_and_free;
807d5c12070SMiao Xie 
808a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
809a22285a6SYan, Zheng 	pending_snapshot->root = root;
810b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
811e9662f70SMiao Xie 	pending_snapshot->dir = dir;
8128696c533SMiao Xie 	pending_snapshot->inherit = inherit;
813a22285a6SYan, Zheng 
814d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
815a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
816a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
817a22285a6SYan, Zheng 		goto fail;
818a22285a6SYan, Zheng 	}
819a22285a6SYan, Zheng 
8200b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
821a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
822a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
8230b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
82472fd032eSSage Weil 	if (async_transid) {
82572fd032eSSage Weil 		*async_transid = trans->transid;
8263a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction_async(trans, 1);
82700d71c9cSMiao Xie 		if (ret)
8283a45bb20SJeff Mahoney 			ret = btrfs_commit_transaction(trans);
82972fd032eSSage Weil 	} else {
8303a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
83172fd032eSSage Weil 	}
832aec8030aSMiao Xie 	if (ret)
833c37b2b62SJosef Bacik 		goto fail;
834a22285a6SYan, Zheng 
835a22285a6SYan, Zheng 	ret = pending_snapshot->error;
836f46b5a66SChristoph Hellwig 	if (ret)
8372e4bfab9SYan, Zheng 		goto fail;
838f46b5a66SChristoph Hellwig 
839d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
840d3797308SChris Mason 	if (ret)
841d3797308SChris Mason 		goto fail;
842d3797308SChris Mason 
8432b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
8442e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
8452e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
8462e4bfab9SYan, Zheng 		goto fail;
8472e4bfab9SYan, Zheng 	}
8485662344bSTsutomu Itoh 
8492e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
8502e4bfab9SYan, Zheng 	ret = 0;
8512e4bfab9SYan, Zheng fail:
8527775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
853a1ee7362SDavid Sterba dec_and_free:
854ea14b57fSDavid Sterba 	if (atomic_dec_and_test(&root->will_be_snapshotted))
8554625956aSPeter Zijlstra 		wake_up_var(&root->will_be_snapshotted);
856b0c0ea63SDavid Sterba free_pending:
857b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
8588546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
859a1ee7362SDavid Sterba 	kfree(pending_snapshot);
860a1ee7362SDavid Sterba 
861f46b5a66SChristoph Hellwig 	return ret;
862f46b5a66SChristoph Hellwig }
863f46b5a66SChristoph Hellwig 
8644260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
8654260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
8664260f7c7SSage Weil  *  whether the type of victim is right.
8674260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
8684260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
8694260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
8704260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
8714260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
8724260f7c7SSage Weil  *	a. be owner of dir, or
8734260f7c7SSage Weil  *	b. be owner of victim, or
8744260f7c7SSage Weil  *	c. have CAP_FOWNER capability
87501327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
8764260f7c7SSage Weil  *     links pointing to it.
8774260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
8784260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
8794260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
8804260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
8814260f7c7SSage Weil  *     nfs_async_unlink().
8824260f7c7SSage Weil  */
8834260f7c7SSage Weil 
8844260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
8854260f7c7SSage Weil {
8864260f7c7SSage Weil 	int error;
8874260f7c7SSage Weil 
8882b0143b5SDavid Howells 	if (d_really_is_negative(victim))
8894260f7c7SSage Weil 		return -ENOENT;
8904260f7c7SSage Weil 
8912b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
8924fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
8934260f7c7SSage Weil 
8944260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
8954260f7c7SSage Weil 	if (error)
8964260f7c7SSage Weil 		return error;
8974260f7c7SSage Weil 	if (IS_APPEND(dir))
8984260f7c7SSage Weil 		return -EPERM;
8992b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
9002b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
9014260f7c7SSage Weil 		return -EPERM;
9024260f7c7SSage Weil 	if (isdir) {
903e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
9044260f7c7SSage Weil 			return -ENOTDIR;
9054260f7c7SSage Weil 		if (IS_ROOT(victim))
9064260f7c7SSage Weil 			return -EBUSY;
907e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
9084260f7c7SSage Weil 		return -EISDIR;
9094260f7c7SSage Weil 	if (IS_DEADDIR(dir))
9104260f7c7SSage Weil 		return -ENOENT;
9114260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
9124260f7c7SSage Weil 		return -EBUSY;
9134260f7c7SSage Weil 	return 0;
9144260f7c7SSage Weil }
9154260f7c7SSage Weil 
916cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
917cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
918cb8e7090SChristoph Hellwig {
9192b0143b5SDavid Howells 	if (d_really_is_positive(child))
920cb8e7090SChristoph Hellwig 		return -EEXIST;
921cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
922cb8e7090SChristoph Hellwig 		return -ENOENT;
923cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
924cb8e7090SChristoph Hellwig }
925cb8e7090SChristoph Hellwig 
926cb8e7090SChristoph Hellwig /*
927cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
928cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
929cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
930cb8e7090SChristoph Hellwig  */
93192872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
93252f75f4fSDavid Sterba 				   const char *name, int namelen,
93372fd032eSSage Weil 				   struct btrfs_root *snap_src,
9346f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
9358696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
936cb8e7090SChristoph Hellwig {
9372b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
9380b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
939cb8e7090SChristoph Hellwig 	struct dentry *dentry;
940cb8e7090SChristoph Hellwig 	int error;
941cb8e7090SChristoph Hellwig 
94200235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
94300235411SAl Viro 	if (error == -EINTR)
94400235411SAl Viro 		return error;
945cb8e7090SChristoph Hellwig 
946cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
947cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
948cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
949cb8e7090SChristoph Hellwig 		goto out_unlock;
950cb8e7090SChristoph Hellwig 
95176dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
952cb8e7090SChristoph Hellwig 	if (error)
953a874a63eSLiu Bo 		goto out_dput;
954cb8e7090SChristoph Hellwig 
9559c52057cSChris Mason 	/*
9569c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
9579c52057cSChris Mason 	 * check for them now when we can safely fail
9589c52057cSChris Mason 	 */
9599c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
9609c52057cSChris Mason 					       dir->i_ino, name,
9619c52057cSChris Mason 					       namelen);
9629c52057cSChris Mason 	if (error)
9639c52057cSChris Mason 		goto out_dput;
9649c52057cSChris Mason 
9650b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
96676dda93cSYan, Zheng 
96776dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
96876dda93cSYan, Zheng 		goto out_up_read;
96976dda93cSYan, Zheng 
9703de4586cSChris Mason 	if (snap_src) {
97161d7e4cbSDavid Sterba 		error = create_snapshot(snap_src, dir, dentry,
9726f72c7e2SArne Jansen 					async_transid, readonly, inherit);
9733de4586cSChris Mason 	} else {
974d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
975d5c12070SMiao Xie 				      async_transid, inherit);
9763de4586cSChris Mason 	}
97776dda93cSYan, Zheng 	if (!error)
97876dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
97976dda93cSYan, Zheng out_up_read:
9800b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
981cb8e7090SChristoph Hellwig out_dput:
982cb8e7090SChristoph Hellwig 	dput(dentry);
983cb8e7090SChristoph Hellwig out_unlock:
9845955102cSAl Viro 	inode_unlock(dir);
985cb8e7090SChristoph Hellwig 	return error;
986cb8e7090SChristoph Hellwig }
987cb8e7090SChristoph Hellwig 
9884cb5300bSChris Mason /*
9894cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
9904cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
9914cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
9924cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
9934cb5300bSChris Mason  * part of the file
9944cb5300bSChris Mason  */
995aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
9964cb5300bSChris Mason {
9974cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9984cb5300bSChris Mason 	struct extent_map *em = NULL;
9994cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10004cb5300bSChris Mason 	u64 end;
10014cb5300bSChris Mason 
10024cb5300bSChris Mason 	read_lock(&em_tree->lock);
100309cbfeafSKirill A. Shutemov 	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
10044cb5300bSChris Mason 	read_unlock(&em_tree->lock);
10054cb5300bSChris Mason 
10064cb5300bSChris Mason 	if (em) {
10074cb5300bSChris Mason 		end = extent_map_end(em);
10084cb5300bSChris Mason 		free_extent_map(em);
10094cb5300bSChris Mason 		if (end - offset > thresh)
10104cb5300bSChris Mason 			return 0;
10114cb5300bSChris Mason 	}
10124cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
10134cb5300bSChris Mason 	thresh /= 2;
10144cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
10154cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
10164cb5300bSChris Mason 	if (end >= thresh)
10174cb5300bSChris Mason 		return 0;
10184cb5300bSChris Mason 	return 1;
10194cb5300bSChris Mason }
10204cb5300bSChris Mason 
10214cb5300bSChris Mason /*
10224cb5300bSChris Mason  * helper function to walk through a file and find extents
10234cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
10244cb5300bSChris Mason  *
10254cb5300bSChris Mason  * This is used by the defragging code to find new and small
10264cb5300bSChris Mason  * extents
10274cb5300bSChris Mason  */
10284cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
10294cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
1030aab110abSDavid Sterba 			    u64 *off, u32 thresh)
10314cb5300bSChris Mason {
10324cb5300bSChris Mason 	struct btrfs_path *path;
10334cb5300bSChris Mason 	struct btrfs_key min_key;
10344cb5300bSChris Mason 	struct extent_buffer *leaf;
10354cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
10364cb5300bSChris Mason 	int type;
10374cb5300bSChris Mason 	int ret;
10384a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
10394cb5300bSChris Mason 
10404cb5300bSChris Mason 	path = btrfs_alloc_path();
10414cb5300bSChris Mason 	if (!path)
10424cb5300bSChris Mason 		return -ENOMEM;
10434cb5300bSChris Mason 
1044a4689d2bSDavid Sterba 	min_key.objectid = ino;
10454cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
10464cb5300bSChris Mason 	min_key.offset = *off;
10474cb5300bSChris Mason 
10484cb5300bSChris Mason 	while (1) {
10496174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
10504cb5300bSChris Mason 		if (ret != 0)
10514cb5300bSChris Mason 			goto none;
1052f094c9bdSFilipe Manana process_slot:
1053a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
10544cb5300bSChris Mason 			goto none;
10554cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
10564cb5300bSChris Mason 			goto none;
10574cb5300bSChris Mason 
10584cb5300bSChris Mason 		leaf = path->nodes[0];
10594cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
10604cb5300bSChris Mason 					struct btrfs_file_extent_item);
10614cb5300bSChris Mason 
10624cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
10634cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
10644cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
10654cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
10664cb5300bSChris Mason 			*off = min_key.offset;
10674cb5300bSChris Mason 			btrfs_free_path(path);
10684cb5300bSChris Mason 			return 0;
10694cb5300bSChris Mason 		}
10704cb5300bSChris Mason 
1071f094c9bdSFilipe Manana 		path->slots[0]++;
1072f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
1073f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1074f094c9bdSFilipe Manana 			goto process_slot;
1075f094c9bdSFilipe Manana 		}
1076f094c9bdSFilipe Manana 
10774cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
10784cb5300bSChris Mason 			goto none;
10794cb5300bSChris Mason 
10804cb5300bSChris Mason 		min_key.offset++;
10814cb5300bSChris Mason 		btrfs_release_path(path);
10824cb5300bSChris Mason 	}
10834cb5300bSChris Mason none:
10844cb5300bSChris Mason 	btrfs_free_path(path);
10854cb5300bSChris Mason 	return -ENOENT;
10864cb5300bSChris Mason }
10874cb5300bSChris Mason 
10886c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
108917ce6ef8SLiu Bo {
109017ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1091940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10926c282eb4SLi Zefan 	struct extent_map *em;
109309cbfeafSKirill A. Shutemov 	u64 len = PAGE_SIZE;
1094940100a4SChris Mason 
1095940100a4SChris Mason 	/*
1096940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
1097940100a4SChris Mason 	 * the full extent lock
1098940100a4SChris Mason 	 */
1099940100a4SChris Mason 	read_lock(&em_tree->lock);
1100940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
1101940100a4SChris Mason 	read_unlock(&em_tree->lock);
1102940100a4SChris Mason 
1103940100a4SChris Mason 	if (!em) {
1104308d9800SFilipe Manana 		struct extent_state *cached = NULL;
1105308d9800SFilipe Manana 		u64 end = start + len - 1;
1106308d9800SFilipe Manana 
1107940100a4SChris Mason 		/* get the big lock and read metadata off disk */
1108ff13db41SDavid Sterba 		lock_extent_bits(io_tree, start, end, &cached);
1109fc4f21b1SNikolay Borisov 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1110e43bbe5eSDavid Sterba 		unlock_extent_cached(io_tree, start, end, &cached);
1111940100a4SChris Mason 
11126cf8bfbfSDan Carpenter 		if (IS_ERR(em))
11136c282eb4SLi Zefan 			return NULL;
1114940100a4SChris Mason 	}
1115940100a4SChris Mason 
11166c282eb4SLi Zefan 	return em;
11176c282eb4SLi Zefan }
11186c282eb4SLi Zefan 
11196c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
11206c282eb4SLi Zefan {
11216c282eb4SLi Zefan 	struct extent_map *next;
11226c282eb4SLi Zefan 	bool ret = true;
11236c282eb4SLi Zefan 
11246c282eb4SLi Zefan 	/* this is the last extent */
11256c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
11266c282eb4SLi Zefan 		return false;
11276c282eb4SLi Zefan 
11286c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
1129e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1130e9512d72SChris Mason 		ret = false;
1131e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1132ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
11336c282eb4SLi Zefan 		ret = false;
11346c282eb4SLi Zefan 
11356c282eb4SLi Zefan 	free_extent_map(next);
11366c282eb4SLi Zefan 	return ret;
11376c282eb4SLi Zefan }
11386c282eb4SLi Zefan 
1139aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1140a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
1141a43a2111SAndrew Mahone 			       int compress)
11426c282eb4SLi Zefan {
11436c282eb4SLi Zefan 	struct extent_map *em;
11446c282eb4SLi Zefan 	int ret = 1;
11456c282eb4SLi Zefan 	bool next_mergeable = true;
11464a3560c4SLiu Bo 	bool prev_mergeable = true;
11476c282eb4SLi Zefan 
11486c282eb4SLi Zefan 	/*
11496c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
11506c282eb4SLi Zefan 	 * defragging it
11516c282eb4SLi Zefan 	 */
11526c282eb4SLi Zefan 	if (start < *defrag_end)
11536c282eb4SLi Zefan 		return 1;
11546c282eb4SLi Zefan 
11556c282eb4SLi Zefan 	*skip = 0;
11566c282eb4SLi Zefan 
11576c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
11586c282eb4SLi Zefan 	if (!em)
11596c282eb4SLi Zefan 		return 0;
11606c282eb4SLi Zefan 
1161940100a4SChris Mason 	/* this will cover holes, and inline extents */
116217ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1163940100a4SChris Mason 		ret = 0;
116417ce6ef8SLiu Bo 		goto out;
116517ce6ef8SLiu Bo 	}
116617ce6ef8SLiu Bo 
11674a3560c4SLiu Bo 	if (!*defrag_end)
11684a3560c4SLiu Bo 		prev_mergeable = false;
11694a3560c4SLiu Bo 
11706c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1171940100a4SChris Mason 	/*
11726c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
11736c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1174940100a4SChris Mason 	 */
1175a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
11764a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1177940100a4SChris Mason 		ret = 0;
117817ce6ef8SLiu Bo out:
1179940100a4SChris Mason 	/*
1180940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1181940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1182940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1183940100a4SChris Mason 	 *
1184940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1185940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1186940100a4SChris Mason 	 */
1187940100a4SChris Mason 	if (ret) {
1188940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1189940100a4SChris Mason 	} else {
1190940100a4SChris Mason 		*last_len = 0;
1191940100a4SChris Mason 		*skip = extent_map_end(em);
1192940100a4SChris Mason 		*defrag_end = 0;
1193940100a4SChris Mason 	}
1194940100a4SChris Mason 
1195940100a4SChris Mason 	free_extent_map(em);
1196940100a4SChris Mason 	return ret;
1197940100a4SChris Mason }
1198940100a4SChris Mason 
11994cb5300bSChris Mason /*
12004cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
12014cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
12024cb5300bSChris Mason  * to COW and defrag.
12034cb5300bSChris Mason  *
12044cb5300bSChris Mason  * It also makes sure the delalloc code has enough
12054cb5300bSChris Mason  * dirty data to avoid making new small extents as part
12064cb5300bSChris Mason  * of the defrag
12074cb5300bSChris Mason  *
12084cb5300bSChris Mason  * It's a good idea to start RA on this range
12094cb5300bSChris Mason  * before calling this.
12104cb5300bSChris Mason  */
12114cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
12124cb5300bSChris Mason 				    struct page **pages,
12134cb5300bSChris Mason 				    unsigned long start_index,
1214c41570c9SJustin Maggard 				    unsigned long num_pages)
1215f46b5a66SChristoph Hellwig {
12164cb5300bSChris Mason 	unsigned long file_end;
12174cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1218f46b5a66SChristoph Hellwig 	u64 page_start;
1219f46b5a66SChristoph Hellwig 	u64 page_end;
12201f12bd06SLiu Bo 	u64 page_cnt;
12214cb5300bSChris Mason 	int ret;
12224cb5300bSChris Mason 	int i;
12234cb5300bSChris Mason 	int i_done;
12244cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
12254cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1226600a45e1SMiao Xie 	struct extent_io_tree *tree;
1227364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
12283b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
12294cb5300bSChris Mason 
123009cbfeafSKirill A. Shutemov 	file_end = (isize - 1) >> PAGE_SHIFT;
12311f12bd06SLiu Bo 	if (!isize || start_index > file_end)
12321f12bd06SLiu Bo 		return 0;
12331f12bd06SLiu Bo 
12341f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
12354cb5300bSChris Mason 
1236364ecf36SQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
123709cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
123809cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
12394cb5300bSChris Mason 	if (ret)
12404cb5300bSChris Mason 		return ret;
12414cb5300bSChris Mason 	i_done = 0;
1242600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
12434cb5300bSChris Mason 
12444cb5300bSChris Mason 	/* step one, lock all the pages */
12451f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
12464cb5300bSChris Mason 		struct page *page;
1247600a45e1SMiao Xie again:
1248a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
12493b16a4e3SJosef Bacik 					   start_index + i, mask);
12504cb5300bSChris Mason 		if (!page)
12514cb5300bSChris Mason 			break;
12524cb5300bSChris Mason 
1253600a45e1SMiao Xie 		page_start = page_offset(page);
125409cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
1255600a45e1SMiao Xie 		while (1) {
1256308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1257ff13db41SDavid Sterba 					 &cached_state);
1258600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1259600a45e1SMiao Xie 							      page_start);
1260308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1261e43bbe5eSDavid Sterba 					     &cached_state);
1262600a45e1SMiao Xie 			if (!ordered)
1263600a45e1SMiao Xie 				break;
1264600a45e1SMiao Xie 
1265600a45e1SMiao Xie 			unlock_page(page);
1266600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1267600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1268600a45e1SMiao Xie 			lock_page(page);
12691f12bd06SLiu Bo 			/*
12701f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
12711f12bd06SLiu Bo 			 * it was released or not.
12721f12bd06SLiu Bo 			 */
12731f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
12741f12bd06SLiu Bo 				unlock_page(page);
127509cbfeafSKirill A. Shutemov 				put_page(page);
12761f12bd06SLiu Bo 				goto again;
12771f12bd06SLiu Bo 			}
1278600a45e1SMiao Xie 		}
1279600a45e1SMiao Xie 
12804cb5300bSChris Mason 		if (!PageUptodate(page)) {
12814cb5300bSChris Mason 			btrfs_readpage(NULL, page);
12824cb5300bSChris Mason 			lock_page(page);
12834cb5300bSChris Mason 			if (!PageUptodate(page)) {
12844cb5300bSChris Mason 				unlock_page(page);
128509cbfeafSKirill A. Shutemov 				put_page(page);
12864cb5300bSChris Mason 				ret = -EIO;
12874cb5300bSChris Mason 				break;
12884cb5300bSChris Mason 			}
12894cb5300bSChris Mason 		}
1290600a45e1SMiao Xie 
1291600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1292600a45e1SMiao Xie 			unlock_page(page);
129309cbfeafSKirill A. Shutemov 			put_page(page);
1294600a45e1SMiao Xie 			goto again;
1295600a45e1SMiao Xie 		}
1296600a45e1SMiao Xie 
12974cb5300bSChris Mason 		pages[i] = page;
12984cb5300bSChris Mason 		i_done++;
12994cb5300bSChris Mason 	}
13004cb5300bSChris Mason 	if (!i_done || ret)
13014cb5300bSChris Mason 		goto out;
13024cb5300bSChris Mason 
13031751e8a6SLinus Torvalds 	if (!(inode->i_sb->s_flags & SB_ACTIVE))
13044cb5300bSChris Mason 		goto out;
13054cb5300bSChris Mason 
13064cb5300bSChris Mason 	/*
13074cb5300bSChris Mason 	 * so now we have a nice long stream of locked
13084cb5300bSChris Mason 	 * and up to date pages, lets wait on them
13094cb5300bSChris Mason 	 */
13104cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
13114cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
13124cb5300bSChris Mason 
13134cb5300bSChris Mason 	page_start = page_offset(pages[0]);
131409cbfeafSKirill A. Shutemov 	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
13154cb5300bSChris Mason 
13164cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1317ff13db41SDavid Sterba 			 page_start, page_end - 1, &cached_state);
13184cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
13194cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
13209e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1321ae0f1625SDavid Sterba 			  &cached_state);
13224cb5300bSChris Mason 
13231f12bd06SLiu Bo 	if (i_done != page_cnt) {
13249e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
13259e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
13269e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
1327bc42bda2SQu Wenruo 		btrfs_delalloc_release_space(inode, data_reserved,
132809cbfeafSKirill A. Shutemov 				start_index << PAGE_SHIFT,
132943b18595SQu Wenruo 				(page_cnt - i_done) << PAGE_SHIFT, true);
13304cb5300bSChris Mason 	}
13314cb5300bSChris Mason 
13324cb5300bSChris Mason 
13339e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1334018ed4f7SDavid Sterba 			  &cached_state);
13354cb5300bSChris Mason 
13364cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1337e43bbe5eSDavid Sterba 			     page_start, page_end - 1, &cached_state);
13384cb5300bSChris Mason 
13394cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
13404cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
13414cb5300bSChris Mason 		ClearPageChecked(pages[i]);
13424cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
13434cb5300bSChris Mason 		set_page_dirty(pages[i]);
13444cb5300bSChris Mason 		unlock_page(pages[i]);
134509cbfeafSKirill A. Shutemov 		put_page(pages[i]);
13464cb5300bSChris Mason 	}
134743b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
134843b18595SQu Wenruo 				       false);
1349364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
13504cb5300bSChris Mason 	return i_done;
13514cb5300bSChris Mason out:
13524cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
13534cb5300bSChris Mason 		unlock_page(pages[i]);
135409cbfeafSKirill A. Shutemov 		put_page(pages[i]);
13554cb5300bSChris Mason 	}
1356bc42bda2SQu Wenruo 	btrfs_delalloc_release_space(inode, data_reserved,
135709cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
135843b18595SQu Wenruo 			page_cnt << PAGE_SHIFT, true);
135943b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
136043b18595SQu Wenruo 				       true);
1361364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
13624cb5300bSChris Mason 	return ret;
13634cb5300bSChris Mason 
13644cb5300bSChris Mason }
13654cb5300bSChris Mason 
13664cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
13674cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
13684cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
13694cb5300bSChris Mason {
13700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
13714cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
13724cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
13734cb5300bSChris Mason 	unsigned long last_index;
1374151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1375940100a4SChris Mason 	u64 last_len = 0;
1376940100a4SChris Mason 	u64 skip = 0;
1377940100a4SChris Mason 	u64 defrag_end = 0;
13784cb5300bSChris Mason 	u64 newer_off = range->start;
1379f46b5a66SChristoph Hellwig 	unsigned long i;
1380008873eaSLi Zefan 	unsigned long ra_index = 0;
1381f46b5a66SChristoph Hellwig 	int ret;
13824cb5300bSChris Mason 	int defrag_count = 0;
13831a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1384aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
138509cbfeafSKirill A. Shutemov 	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1386c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
1387ee22184bSByongho Lee 	u64 new_align = ~((u64)SZ_128K - 1);
13884cb5300bSChris Mason 	struct page **pages = NULL;
13891e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
13904cb5300bSChris Mason 
13910abd5b17SLiu Bo 	if (isize == 0)
13920abd5b17SLiu Bo 		return 0;
13930abd5b17SLiu Bo 
13940abd5b17SLiu Bo 	if (range->start >= isize)
13950abd5b17SLiu Bo 		return -EINVAL;
13961a419d85SLi Zefan 
13971e2ef46dSDavid Sterba 	if (do_compress) {
13981a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
13991a419d85SLi Zefan 			return -EINVAL;
14001a419d85SLi Zefan 		if (range->compress_type)
14011a419d85SLi Zefan 			compress_type = range->compress_type;
14021a419d85SLi Zefan 	}
1403f46b5a66SChristoph Hellwig 
14040abd5b17SLiu Bo 	if (extent_thresh == 0)
1405ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1406f46b5a66SChristoph Hellwig 
14074cb5300bSChris Mason 	/*
14080a52d108SDavid Sterba 	 * If we were not given a file, allocate a readahead context. As
14090a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
14100a52d108SDavid Sterba 	 * we don't error out.
14114cb5300bSChris Mason 	 */
14124cb5300bSChris Mason 	if (!file) {
141363e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
14140a52d108SDavid Sterba 		if (ra)
14154cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
14164cb5300bSChris Mason 	} else {
14174cb5300bSChris Mason 		ra = &file->f_ra;
14184cb5300bSChris Mason 	}
14194cb5300bSChris Mason 
142063e727ecSDavid Sterba 	pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
14214cb5300bSChris Mason 	if (!pages) {
14224cb5300bSChris Mason 		ret = -ENOMEM;
14234cb5300bSChris Mason 		goto out_ra;
14244cb5300bSChris Mason 	}
14254cb5300bSChris Mason 
14264cb5300bSChris Mason 	/* find the last page to defrag */
14271e701a32SChris Mason 	if (range->start + range->len > range->start) {
1428151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
142909cbfeafSKirill A. Shutemov 			 range->start + range->len - 1) >> PAGE_SHIFT;
14301e701a32SChris Mason 	} else {
143109cbfeafSKirill A. Shutemov 		last_index = (isize - 1) >> PAGE_SHIFT;
14321e701a32SChris Mason 	}
14331e701a32SChris Mason 
14344cb5300bSChris Mason 	if (newer_than) {
14354cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
1436ee22184bSByongho Lee 				       &newer_off, SZ_64K);
14374cb5300bSChris Mason 		if (!ret) {
14384cb5300bSChris Mason 			range->start = newer_off;
14394cb5300bSChris Mason 			/*
14404cb5300bSChris Mason 			 * we always align our defrag to help keep
14414cb5300bSChris Mason 			 * the extents in the file evenly spaced
14424cb5300bSChris Mason 			 */
144309cbfeafSKirill A. Shutemov 			i = (newer_off & new_align) >> PAGE_SHIFT;
14444cb5300bSChris Mason 		} else
14454cb5300bSChris Mason 			goto out_ra;
14464cb5300bSChris Mason 	} else {
144709cbfeafSKirill A. Shutemov 		i = range->start >> PAGE_SHIFT;
14484cb5300bSChris Mason 	}
14494cb5300bSChris Mason 	if (!max_to_defrag)
1450070034bdSchandan 		max_to_defrag = last_index - i + 1;
14514cb5300bSChris Mason 
14522a0f7f57SLi Zefan 	/*
14532a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
14542a0f7f57SLi Zefan 	 * written sequentially.
14552a0f7f57SLi Zefan 	 */
14562a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
14572a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
14582a0f7f57SLi Zefan 
1459f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
146009cbfeafSKirill A. Shutemov 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
14614cb5300bSChris Mason 		/*
14624cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
14634cb5300bSChris Mason 		 * the FS
14644cb5300bSChris Mason 		 */
14651751e8a6SLinus Torvalds 		if (!(inode->i_sb->s_flags & SB_ACTIVE))
14664cb5300bSChris Mason 			break;
14674cb5300bSChris Mason 
14680b246afaSJeff Mahoney 		if (btrfs_defrag_cancelled(fs_info)) {
14690b246afaSJeff Mahoney 			btrfs_debug(fs_info, "defrag_file cancelled");
1470210549ebSDavid Sterba 			ret = -EAGAIN;
1471210549ebSDavid Sterba 			break;
1472210549ebSDavid Sterba 		}
1473210549ebSDavid Sterba 
147409cbfeafSKirill A. Shutemov 		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
14756c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
14761e2ef46dSDavid Sterba 					 &defrag_end, do_compress)){
1477940100a4SChris Mason 			unsigned long next;
1478940100a4SChris Mason 			/*
1479940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1480940100a4SChris Mason 			 * bump our counter by the suggested amount
1481940100a4SChris Mason 			 */
148209cbfeafSKirill A. Shutemov 			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1483940100a4SChris Mason 			i = max(i + 1, next);
1484940100a4SChris Mason 			continue;
1485940100a4SChris Mason 		}
1486008873eaSLi Zefan 
1487008873eaSLi Zefan 		if (!newer_than) {
148809cbfeafSKirill A. Shutemov 			cluster = (PAGE_ALIGN(defrag_end) >>
148909cbfeafSKirill A. Shutemov 				   PAGE_SHIFT) - i;
1490008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1491008873eaSLi Zefan 		} else {
1492008873eaSLi Zefan 			cluster = max_cluster;
1493008873eaSLi Zefan 		}
1494008873eaSLi Zefan 
1495008873eaSLi Zefan 		if (i + cluster > ra_index) {
1496008873eaSLi Zefan 			ra_index = max(i, ra_index);
14970a52d108SDavid Sterba 			if (ra)
1498d3c0bab5SDavid Sterba 				page_cache_sync_readahead(inode->i_mapping, ra,
1499d3c0bab5SDavid Sterba 						file, ra_index, cluster);
1500e4826a5bSchandan 			ra_index += cluster;
1501008873eaSLi Zefan 		}
15024cb5300bSChris Mason 
15035955102cSAl Viro 		inode_lock(inode);
15041e2ef46dSDavid Sterba 		if (do_compress)
1505eec63c65SDavid Sterba 			BTRFS_I(inode)->defrag_compress = compress_type;
1506008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1507ecb8bea8SLiu Bo 		if (ret < 0) {
15085955102cSAl Viro 			inode_unlock(inode);
15094cb5300bSChris Mason 			goto out_ra;
1510ecb8bea8SLiu Bo 		}
15114cb5300bSChris Mason 
15124cb5300bSChris Mason 		defrag_count += ret;
1513d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
15145955102cSAl Viro 		inode_unlock(inode);
15154cb5300bSChris Mason 
15164cb5300bSChris Mason 		if (newer_than) {
15174cb5300bSChris Mason 			if (newer_off == (u64)-1)
15184cb5300bSChris Mason 				break;
15194cb5300bSChris Mason 
1520e1f041e1SLiu Bo 			if (ret > 0)
1521e1f041e1SLiu Bo 				i += ret;
1522e1f041e1SLiu Bo 
15234cb5300bSChris Mason 			newer_off = max(newer_off + 1,
152409cbfeafSKirill A. Shutemov 					(u64)i << PAGE_SHIFT);
15254cb5300bSChris Mason 
1526ee22184bSByongho Lee 			ret = find_new_extents(root, inode, newer_than,
1527ee22184bSByongho Lee 					       &newer_off, SZ_64K);
15284cb5300bSChris Mason 			if (!ret) {
15294cb5300bSChris Mason 				range->start = newer_off;
153009cbfeafSKirill A. Shutemov 				i = (newer_off & new_align) >> PAGE_SHIFT;
15314cb5300bSChris Mason 			} else {
15324cb5300bSChris Mason 				break;
1533940100a4SChris Mason 			}
15344cb5300bSChris Mason 		} else {
1535008873eaSLi Zefan 			if (ret > 0) {
1536cbcc8326SLi Zefan 				i += ret;
153709cbfeafSKirill A. Shutemov 				last_len += ret << PAGE_SHIFT;
1538008873eaSLi Zefan 			} else {
1539940100a4SChris Mason 				i++;
1540008873eaSLi Zefan 				last_len = 0;
1541008873eaSLi Zefan 			}
1542f46b5a66SChristoph Hellwig 		}
15434cb5300bSChris Mason 	}
1544f46b5a66SChristoph Hellwig 
1545dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
15461e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1547dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1548dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1549dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1550dec8ef90SFilipe Manana 	}
15511e701a32SChris Mason 
15521a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
15530b246afaSJeff Mahoney 		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
15545c1aab1dSNick Terrell 	} else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
15555c1aab1dSNick Terrell 		btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
15561a419d85SLi Zefan 	}
15571a419d85SLi Zefan 
155860ccf82fSDiego Calleja 	ret = defrag_count;
1559940100a4SChris Mason 
15604cb5300bSChris Mason out_ra:
15611e2ef46dSDavid Sterba 	if (do_compress) {
15625955102cSAl Viro 		inode_lock(inode);
1563eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
15645955102cSAl Viro 		inode_unlock(inode);
1565633085c7SFilipe David Borba Manana 	}
15664cb5300bSChris Mason 	if (!file)
15674cb5300bSChris Mason 		kfree(ra);
15684cb5300bSChris Mason 	kfree(pages);
1569940100a4SChris Mason 	return ret;
1570f46b5a66SChristoph Hellwig }
1571f46b5a66SChristoph Hellwig 
1572198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
157376dda93cSYan, Zheng 					void __user *arg)
1574f46b5a66SChristoph Hellwig {
15750b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
15760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1577f46b5a66SChristoph Hellwig 	u64 new_size;
1578f46b5a66SChristoph Hellwig 	u64 old_size;
1579f46b5a66SChristoph Hellwig 	u64 devid = 1;
15800b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1581f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1582f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1583f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1584f46b5a66SChristoph Hellwig 	char *sizestr;
15859a40f122SGui Hecheng 	char *retptr;
1586f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1587f46b5a66SChristoph Hellwig 	int ret = 0;
1588f46b5a66SChristoph Hellwig 	int mod = 0;
1589f46b5a66SChristoph Hellwig 
1590e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1591e441d54dSChris Mason 		return -EPERM;
1592e441d54dSChris Mason 
1593198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1594198605a8SMiao Xie 	if (ret)
1595198605a8SMiao Xie 		return ret;
1596198605a8SMiao Xie 
1597171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
159897547676SMiao Xie 		mnt_drop_write_file(file);
1599e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1600c9e9f97bSIlya Dryomov 	}
1601c9e9f97bSIlya Dryomov 
1602dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1603c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1604c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1605c9e9f97bSIlya Dryomov 		goto out;
1606c9e9f97bSIlya Dryomov 	}
16075516e595SMark Fasheh 
16085516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1609f46b5a66SChristoph Hellwig 
1610f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1611f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1612f46b5a66SChristoph Hellwig 	if (devstr) {
1613f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1614f46b5a66SChristoph Hellwig 		*devstr = '\0';
1615f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
161658dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
161758dfae63SZhangZhen 		if (ret)
161858dfae63SZhangZhen 			goto out_free;
1619dfd79829SMiao Xie 		if (!devid) {
1620dfd79829SMiao Xie 			ret = -EINVAL;
1621dfd79829SMiao Xie 			goto out_free;
1622dfd79829SMiao Xie 		}
16230b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1624f46b5a66SChristoph Hellwig 	}
1625dba60f3fSMiao Xie 
16260b246afaSJeff Mahoney 	device = btrfs_find_device(fs_info, devid, NULL, NULL);
1627f46b5a66SChristoph Hellwig 	if (!device) {
16280b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1629c1c9ff7cSGeert Uytterhoeven 			   devid);
1630dfd79829SMiao Xie 		ret = -ENODEV;
1631c9e9f97bSIlya Dryomov 		goto out_free;
1632f46b5a66SChristoph Hellwig 	}
1633dba60f3fSMiao Xie 
1634ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
16350b246afaSJeff Mahoney 		btrfs_info(fs_info,
1636efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1637c1c9ff7cSGeert Uytterhoeven 		       devid);
1638dfd79829SMiao Xie 		ret = -EPERM;
16394e42ae1bSLiu Bo 		goto out_free;
16404e42ae1bSLiu Bo 	}
16414e42ae1bSLiu Bo 
1642f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1643f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1644f46b5a66SChristoph Hellwig 	else {
1645f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1646f46b5a66SChristoph Hellwig 			mod = -1;
1647f46b5a66SChristoph Hellwig 			sizestr++;
1648f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1649f46b5a66SChristoph Hellwig 			mod = 1;
1650f46b5a66SChristoph Hellwig 			sizestr++;
1651f46b5a66SChristoph Hellwig 		}
16529a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
16539a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1654f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1655c9e9f97bSIlya Dryomov 			goto out_free;
1656f46b5a66SChristoph Hellwig 		}
1657f46b5a66SChristoph Hellwig 	}
1658f46b5a66SChristoph Hellwig 
1659401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1660dfd79829SMiao Xie 		ret = -EPERM;
166163a212abSStefan Behrens 		goto out_free;
166263a212abSStefan Behrens 	}
166363a212abSStefan Behrens 
16647cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1665f46b5a66SChristoph Hellwig 
1666f46b5a66SChristoph Hellwig 	if (mod < 0) {
1667f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1668f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1669c9e9f97bSIlya Dryomov 			goto out_free;
1670f46b5a66SChristoph Hellwig 		}
1671f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1672f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1673eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1674902c68a4SGui Hecheng 			ret = -ERANGE;
1675eb8052e0SWenliang Fan 			goto out_free;
1676eb8052e0SWenliang Fan 		}
1677f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1678f46b5a66SChristoph Hellwig 	}
1679f46b5a66SChristoph Hellwig 
1680ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1681f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1682c9e9f97bSIlya Dryomov 		goto out_free;
1683f46b5a66SChristoph Hellwig 	}
1684f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1685f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1686c9e9f97bSIlya Dryomov 		goto out_free;
1687f46b5a66SChristoph Hellwig 	}
1688f46b5a66SChristoph Hellwig 
168947f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1690f46b5a66SChristoph Hellwig 
16910b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1692c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1693f46b5a66SChristoph Hellwig 
1694f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1695a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
169698d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
169798d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1698c9e9f97bSIlya Dryomov 			goto out_free;
169998d5dc13STsutomu Itoh 		}
1700f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
17013a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1702ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1703f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
17040253f40eSjeff.liu 	} /* equal, nothing need to do */
1705f46b5a66SChristoph Hellwig 
1706c9e9f97bSIlya Dryomov out_free:
1707f46b5a66SChristoph Hellwig 	kfree(vol_args);
1708c9e9f97bSIlya Dryomov out:
1709171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
171018f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1711f46b5a66SChristoph Hellwig 	return ret;
1712f46b5a66SChristoph Hellwig }
1713f46b5a66SChristoph Hellwig 
171472fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
171552f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
17166f72c7e2SArne Jansen 				u64 *transid, bool readonly,
17178696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1718f46b5a66SChristoph Hellwig {
1719f46b5a66SChristoph Hellwig 	int namelen;
17203de4586cSChris Mason 	int ret = 0;
1721f46b5a66SChristoph Hellwig 
1722325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1723325c50e3SJeff Mahoney 		return -ENOTDIR;
1724325c50e3SJeff Mahoney 
1725a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1726a874a63eSLiu Bo 	if (ret)
1727a874a63eSLiu Bo 		goto out;
1728a874a63eSLiu Bo 
172972fd032eSSage Weil 	namelen = strlen(name);
173072fd032eSSage Weil 	if (strchr(name, '/')) {
1731f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1732a874a63eSLiu Bo 		goto out_drop_write;
1733f46b5a66SChristoph Hellwig 	}
1734f46b5a66SChristoph Hellwig 
173516780cabSChris Mason 	if (name[0] == '.' &&
173616780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
173716780cabSChris Mason 		ret = -EEXIST;
1738a874a63eSLiu Bo 		goto out_drop_write;
173916780cabSChris Mason 	}
174016780cabSChris Mason 
17413de4586cSChris Mason 	if (subvol) {
174272fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
17436f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1744cb8e7090SChristoph Hellwig 	} else {
17452903ff01SAl Viro 		struct fd src = fdget(fd);
17463de4586cSChris Mason 		struct inode *src_inode;
17472903ff01SAl Viro 		if (!src.file) {
17483de4586cSChris Mason 			ret = -EINVAL;
1749a874a63eSLiu Bo 			goto out_drop_write;
17503de4586cSChris Mason 		}
17513de4586cSChris Mason 
1752496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1753496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1754c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1755efe120a0SFrank Holton 				   "Snapshot src from another FS");
175623ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1757d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1758d0242061SDavid Sterba 			/*
1759d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1760d0242061SDavid Sterba 			 * are limited to own subvolumes only
1761d0242061SDavid Sterba 			 */
1762d0242061SDavid Sterba 			ret = -EPERM;
1763ecd18815SAl Viro 		} else {
176472fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
176572fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
17666f72c7e2SArne Jansen 					     transid, readonly, inherit);
1767ecd18815SAl Viro 		}
17682903ff01SAl Viro 		fdput(src);
1769cb8e7090SChristoph Hellwig 	}
1770a874a63eSLiu Bo out_drop_write:
1771a874a63eSLiu Bo 	mnt_drop_write_file(file);
1772f46b5a66SChristoph Hellwig out:
177372fd032eSSage Weil 	return ret;
177472fd032eSSage Weil }
177572fd032eSSage Weil 
177672fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1777fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
177872fd032eSSage Weil {
1779fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
178072fd032eSSage Weil 	int ret;
178172fd032eSSage Weil 
1782325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1783325c50e3SJeff Mahoney 		return -ENOTDIR;
1784325c50e3SJeff Mahoney 
1785fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1786fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1787fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1788fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1789fa0d2b9bSLi Zefan 
1790fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1791b83cc969SLi Zefan 					      vol_args->fd, subvol,
17926f72c7e2SArne Jansen 					      NULL, false, NULL);
1793fa0d2b9bSLi Zefan 
1794fa0d2b9bSLi Zefan 	kfree(vol_args);
1795fa0d2b9bSLi Zefan 	return ret;
1796fa0d2b9bSLi Zefan }
1797fa0d2b9bSLi Zefan 
1798fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1799fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1800fa0d2b9bSLi Zefan {
1801fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1802fa0d2b9bSLi Zefan 	int ret;
1803fdfb1e4fSLi Zefan 	u64 transid = 0;
1804fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1805b83cc969SLi Zefan 	bool readonly = false;
18066f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
180772fd032eSSage Weil 
1808325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1809325c50e3SJeff Mahoney 		return -ENOTDIR;
1810325c50e3SJeff Mahoney 
1811fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1812fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1813fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1814fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1815fdfb1e4fSLi Zefan 
1816b83cc969SLi Zefan 	if (vol_args->flags &
18176f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
18186f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1819b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1820c47ca32dSDan Carpenter 		goto free_args;
1821fdfb1e4fSLi Zefan 	}
1822fdfb1e4fSLi Zefan 
1823fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1824fdfb1e4fSLi Zefan 		ptr = &transid;
1825b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1826b83cc969SLi Zefan 		readonly = true;
18276f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
182809cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
18296f72c7e2SArne Jansen 			ret = -EINVAL;
1830c47ca32dSDan Carpenter 			goto free_args;
18316f72c7e2SArne Jansen 		}
18326f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
18336f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
18346f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1835c47ca32dSDan Carpenter 			goto free_args;
18366f72c7e2SArne Jansen 		}
18376f72c7e2SArne Jansen 	}
183875eaa0e2SSage Weil 
1839fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
18406f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
18418696c533SMiao Xie 					      readonly, inherit);
1842c47ca32dSDan Carpenter 	if (ret)
1843c47ca32dSDan Carpenter 		goto free_inherit;
184475eaa0e2SSage Weil 
1845c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1846fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1847c47ca32dSDan Carpenter 					transid),
1848c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
184975eaa0e2SSage Weil 		ret = -EFAULT;
1850c47ca32dSDan Carpenter 
1851c47ca32dSDan Carpenter free_inherit:
18526f72c7e2SArne Jansen 	kfree(inherit);
1853c47ca32dSDan Carpenter free_args:
1854c47ca32dSDan Carpenter 	kfree(vol_args);
1855f46b5a66SChristoph Hellwig 	return ret;
1856f46b5a66SChristoph Hellwig }
1857f46b5a66SChristoph Hellwig 
18580caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
18590caa102dSLi Zefan 						void __user *arg)
18600caa102dSLi Zefan {
1861496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18620b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18630caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
18640caa102dSLi Zefan 	int ret = 0;
18650caa102dSLi Zefan 	u64 flags = 0;
18660caa102dSLi Zefan 
18674a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
18680caa102dSLi Zefan 		return -EINVAL;
18690caa102dSLi Zefan 
18700b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
18710caa102dSLi Zefan 	if (btrfs_root_readonly(root))
18720caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
18730b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
18740caa102dSLi Zefan 
18750caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
18760caa102dSLi Zefan 		ret = -EFAULT;
18770caa102dSLi Zefan 
18780caa102dSLi Zefan 	return ret;
18790caa102dSLi Zefan }
18800caa102dSLi Zefan 
18810caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
18820caa102dSLi Zefan 					      void __user *arg)
18830caa102dSLi Zefan {
1884496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18860caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
18870caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
18880caa102dSLi Zefan 	u64 root_flags;
18890caa102dSLi Zefan 	u64 flags;
18900caa102dSLi Zefan 	int ret = 0;
18910caa102dSLi Zefan 
1892bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1893bd60ea0fSDavid Sterba 		return -EPERM;
1894bd60ea0fSDavid Sterba 
1895b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1896b9ca0664SLiu Bo 	if (ret)
1897b9ca0664SLiu Bo 		goto out;
18980caa102dSLi Zefan 
18994a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1900b9ca0664SLiu Bo 		ret = -EINVAL;
1901b9ca0664SLiu Bo 		goto out_drop_write;
1902b9ca0664SLiu Bo 	}
19030caa102dSLi Zefan 
1904b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1905b9ca0664SLiu Bo 		ret = -EFAULT;
1906b9ca0664SLiu Bo 		goto out_drop_write;
1907b9ca0664SLiu Bo 	}
19080caa102dSLi Zefan 
1909b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1910b9ca0664SLiu Bo 		ret = -EINVAL;
1911b9ca0664SLiu Bo 		goto out_drop_write;
1912b9ca0664SLiu Bo 	}
19130caa102dSLi Zefan 
1914b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1915b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1916b9ca0664SLiu Bo 		goto out_drop_write;
1917b9ca0664SLiu Bo 	}
19180caa102dSLi Zefan 
19190b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
19200caa102dSLi Zefan 
19210caa102dSLi Zefan 	/* nothing to do */
19220caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1923b9ca0664SLiu Bo 		goto out_drop_sem;
19240caa102dSLi Zefan 
19250caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
19262c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
19270caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
19280caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
19292c686537SDavid Sterba 	} else {
19302c686537SDavid Sterba 		/*
19312c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
19322c686537SDavid Sterba 		 * send
19332c686537SDavid Sterba 		 */
19342c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
19352c686537SDavid Sterba 		if (root->send_in_progress == 0) {
19360caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
19370caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
19382c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19392c686537SDavid Sterba 		} else {
19402c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19410b246afaSJeff Mahoney 			btrfs_warn(fs_info,
19422c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
19432c686537SDavid Sterba 				   root->root_key.objectid);
19442c686537SDavid Sterba 			ret = -EPERM;
19452c686537SDavid Sterba 			goto out_drop_sem;
19462c686537SDavid Sterba 		}
19472c686537SDavid Sterba 	}
19480caa102dSLi Zefan 
19490caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
19500caa102dSLi Zefan 	if (IS_ERR(trans)) {
19510caa102dSLi Zefan 		ret = PTR_ERR(trans);
19520caa102dSLi Zefan 		goto out_reset;
19530caa102dSLi Zefan 	}
19540caa102dSLi Zefan 
19550b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
19560caa102dSLi Zefan 				&root->root_key, &root->root_item);
19579417ebc8SNikolay Borisov 	if (ret < 0) {
19589417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
19599417ebc8SNikolay Borisov 		goto out_reset;
19609417ebc8SNikolay Borisov 	}
19610caa102dSLi Zefan 
19629417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
19639417ebc8SNikolay Borisov 
19640caa102dSLi Zefan out_reset:
19650caa102dSLi Zefan 	if (ret)
19660caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1967b9ca0664SLiu Bo out_drop_sem:
19680b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
1969b9ca0664SLiu Bo out_drop_write:
1970b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1971b9ca0664SLiu Bo out:
19720caa102dSLi Zefan 	return ret;
19730caa102dSLi Zefan }
19740caa102dSLi Zefan 
1975ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1976ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1977ac8e9819SChris Mason {
1978abc6e134SChris Mason 	struct btrfs_key test;
1979abc6e134SChris Mason 	int ret;
1980abc6e134SChris Mason 
1981abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1982abc6e134SChris Mason 	test.type = sk->min_type;
1983abc6e134SChris Mason 	test.offset = sk->min_offset;
1984abc6e134SChris Mason 
1985abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1986abc6e134SChris Mason 	if (ret < 0)
1987ac8e9819SChris Mason 		return 0;
1988abc6e134SChris Mason 
1989abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1990abc6e134SChris Mason 	test.type = sk->max_type;
1991abc6e134SChris Mason 	test.offset = sk->max_offset;
1992abc6e134SChris Mason 
1993abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1994abc6e134SChris Mason 	if (ret > 0)
1995ac8e9819SChris Mason 		return 0;
1996ac8e9819SChris Mason 	return 1;
1997ac8e9819SChris Mason }
1998ac8e9819SChris Mason 
1999df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
2000ac8e9819SChris Mason 			       struct btrfs_key *key,
2001ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
20029b6e817dSGerhard Heift 			       size_t *buf_size,
2003ba346b35SGerhard Heift 			       char __user *ubuf,
2004ac8e9819SChris Mason 			       unsigned long *sk_offset,
2005ac8e9819SChris Mason 			       int *num_found)
2006ac8e9819SChris Mason {
2007ac8e9819SChris Mason 	u64 found_transid;
2008ac8e9819SChris Mason 	struct extent_buffer *leaf;
2009ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
2010dd81d459SNaohiro Aota 	struct btrfs_key test;
2011ac8e9819SChris Mason 	unsigned long item_off;
2012ac8e9819SChris Mason 	unsigned long item_len;
2013ac8e9819SChris Mason 	int nritems;
2014ac8e9819SChris Mason 	int i;
2015ac8e9819SChris Mason 	int slot;
2016ac8e9819SChris Mason 	int ret = 0;
2017ac8e9819SChris Mason 
2018ac8e9819SChris Mason 	leaf = path->nodes[0];
2019ac8e9819SChris Mason 	slot = path->slots[0];
2020ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
2021ac8e9819SChris Mason 
2022ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
2023ac8e9819SChris Mason 		i = nritems;
2024ac8e9819SChris Mason 		goto advance_key;
2025ac8e9819SChris Mason 	}
2026ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
2027ac8e9819SChris Mason 
2028ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
2029ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
2030ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
2031ac8e9819SChris Mason 
203203b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
203303b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
203403b71c6cSGabriel de Perthuis 			continue;
203503b71c6cSGabriel de Perthuis 
20369b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
20378f5f6178SGerhard Heift 			if (*num_found) {
2038ac8e9819SChris Mason 				ret = 1;
20398f5f6178SGerhard Heift 				goto out;
20408f5f6178SGerhard Heift 			}
20418f5f6178SGerhard Heift 
20428f5f6178SGerhard Heift 			/*
20438f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
20448f5f6178SGerhard Heift 			 * handle -EOVERFLOW
20458f5f6178SGerhard Heift 			 */
20468f5f6178SGerhard Heift 
20479b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
2048ac8e9819SChris Mason 			item_len = 0;
20498f5f6178SGerhard Heift 			ret = -EOVERFLOW;
20508f5f6178SGerhard Heift 		}
2051ac8e9819SChris Mason 
20529b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2053ac8e9819SChris Mason 			ret = 1;
205425c9bc2eSGerhard Heift 			goto out;
2055ac8e9819SChris Mason 		}
2056ac8e9819SChris Mason 
2057ac8e9819SChris Mason 		sh.objectid = key->objectid;
2058ac8e9819SChris Mason 		sh.offset = key->offset;
2059ac8e9819SChris Mason 		sh.type = key->type;
2060ac8e9819SChris Mason 		sh.len = item_len;
2061ac8e9819SChris Mason 		sh.transid = found_transid;
2062ac8e9819SChris Mason 
2063ac8e9819SChris Mason 		/* copy search result header */
2064ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2065ba346b35SGerhard Heift 			ret = -EFAULT;
2066ba346b35SGerhard Heift 			goto out;
2067ba346b35SGerhard Heift 		}
2068ba346b35SGerhard Heift 
2069ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2070ac8e9819SChris Mason 
2071ac8e9819SChris Mason 		if (item_len) {
2072ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2073ac8e9819SChris Mason 			/* copy the item */
2074ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
2075ba346b35SGerhard Heift 						       item_off, item_len)) {
2076ba346b35SGerhard Heift 				ret = -EFAULT;
2077ba346b35SGerhard Heift 				goto out;
2078ba346b35SGerhard Heift 			}
2079ba346b35SGerhard Heift 
2080ac8e9819SChris Mason 			*sk_offset += item_len;
2081ac8e9819SChris Mason 		}
2082e2156867SHugo Mills 		(*num_found)++;
2083ac8e9819SChris Mason 
20848f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
20858f5f6178SGerhard Heift 			goto out;
20868f5f6178SGerhard Heift 
208725c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
208825c9bc2eSGerhard Heift 			ret = 1;
208925c9bc2eSGerhard Heift 			goto out;
209025c9bc2eSGerhard Heift 		}
2091ac8e9819SChris Mason 	}
2092ac8e9819SChris Mason advance_key:
2093ac8e9819SChris Mason 	ret = 0;
2094dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2095dd81d459SNaohiro Aota 	test.type = sk->max_type;
2096dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2097dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2098dd81d459SNaohiro Aota 		ret = 1;
2099dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2100abc6e134SChris Mason 		key->offset++;
2101dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2102abc6e134SChris Mason 		key->offset = 0;
2103abc6e134SChris Mason 		key->type++;
2104dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2105abc6e134SChris Mason 		key->offset = 0;
2106abc6e134SChris Mason 		key->type = 0;
2107abc6e134SChris Mason 		key->objectid++;
2108abc6e134SChris Mason 	} else
2109abc6e134SChris Mason 		ret = 1;
211025c9bc2eSGerhard Heift out:
2111ba346b35SGerhard Heift 	/*
2112ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2113ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2114ba346b35SGerhard Heift 	 *     * all items were found
2115ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2116ba346b35SGerhard Heift 	 *     leaf
2117ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2118ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2119ba346b35SGerhard Heift 	 */
2120ac8e9819SChris Mason 	return ret;
2121ac8e9819SChris Mason }
2122ac8e9819SChris Mason 
2123ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
212412544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
21259b6e817dSGerhard Heift 				 size_t *buf_size,
2126ba346b35SGerhard Heift 				 char __user *ubuf)
2127ac8e9819SChris Mason {
21280b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2129ac8e9819SChris Mason 	struct btrfs_root *root;
2130ac8e9819SChris Mason 	struct btrfs_key key;
2131ac8e9819SChris Mason 	struct btrfs_path *path;
2132ac8e9819SChris Mason 	int ret;
2133ac8e9819SChris Mason 	int num_found = 0;
2134ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2135ac8e9819SChris Mason 
21369b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
21379b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
213812544442SGerhard Heift 		return -EOVERFLOW;
21399b6e817dSGerhard Heift 	}
214012544442SGerhard Heift 
2141ac8e9819SChris Mason 	path = btrfs_alloc_path();
2142ac8e9819SChris Mason 	if (!path)
2143ac8e9819SChris Mason 		return -ENOMEM;
2144ac8e9819SChris Mason 
2145ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2146ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2147ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2148ac8e9819SChris Mason 	} else {
2149ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2150ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2151ac8e9819SChris Mason 		key.offset = (u64)-1;
2152ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2153ac8e9819SChris Mason 		if (IS_ERR(root)) {
2154ac8e9819SChris Mason 			btrfs_free_path(path);
2155ad1e3d56SMisono Tomohiro 			return PTR_ERR(root);
2156ac8e9819SChris Mason 		}
2157ac8e9819SChris Mason 	}
2158ac8e9819SChris Mason 
2159ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2160ac8e9819SChris Mason 	key.type = sk->min_type;
2161ac8e9819SChris Mason 	key.offset = sk->min_offset;
2162ac8e9819SChris Mason 
2163ac8e9819SChris Mason 	while (1) {
21646174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2165ac8e9819SChris Mason 		if (ret != 0) {
2166ac8e9819SChris Mason 			if (ret > 0)
2167ac8e9819SChris Mason 				ret = 0;
2168ac8e9819SChris Mason 			goto err;
2169ac8e9819SChris Mason 		}
2170df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2171ac8e9819SChris Mason 				 &sk_offset, &num_found);
2172b3b4aa74SDavid Sterba 		btrfs_release_path(path);
217325c9bc2eSGerhard Heift 		if (ret)
2174ac8e9819SChris Mason 			break;
2175ac8e9819SChris Mason 
2176ac8e9819SChris Mason 	}
21778f5f6178SGerhard Heift 	if (ret > 0)
2178ac8e9819SChris Mason 		ret = 0;
2179ac8e9819SChris Mason err:
2180ac8e9819SChris Mason 	sk->nr_items = num_found;
2181ac8e9819SChris Mason 	btrfs_free_path(path);
2182ac8e9819SChris Mason 	return ret;
2183ac8e9819SChris Mason }
2184ac8e9819SChris Mason 
2185ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2186ac8e9819SChris Mason 					   void __user *argp)
2187ac8e9819SChris Mason {
2188ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2189ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2190ac8e9819SChris Mason 	struct inode *inode;
2191ac8e9819SChris Mason 	int ret;
21929b6e817dSGerhard Heift 	size_t buf_size;
2193ac8e9819SChris Mason 
2194ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2195ac8e9819SChris Mason 		return -EPERM;
2196ac8e9819SChris Mason 
2197ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2198ac8e9819SChris Mason 
2199ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2200ba346b35SGerhard Heift 		return -EFAULT;
2201ba346b35SGerhard Heift 
2202ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2203ac8e9819SChris Mason 
2204496ad9aaSAl Viro 	inode = file_inode(file);
2205ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
22068f5f6178SGerhard Heift 
22078f5f6178SGerhard Heift 	/*
22088f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
22098f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
22108f5f6178SGerhard Heift 	 */
22118f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
22128f5f6178SGerhard Heift 		ret = 0;
22138f5f6178SGerhard Heift 
2214ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2215ac8e9819SChris Mason 		ret = -EFAULT;
2216ac8e9819SChris Mason 	return ret;
2217ac8e9819SChris Mason }
2218ac8e9819SChris Mason 
2219cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2220cc68a8a5SGerhard Heift 					       void __user *argp)
2221cc68a8a5SGerhard Heift {
2222cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2223cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2224cc68a8a5SGerhard Heift 	struct inode *inode;
2225cc68a8a5SGerhard Heift 	int ret;
2226cc68a8a5SGerhard Heift 	size_t buf_size;
2227ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2228cc68a8a5SGerhard Heift 
2229cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2230cc68a8a5SGerhard Heift 		return -EPERM;
2231cc68a8a5SGerhard Heift 
2232cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2233cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2234cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2235cc68a8a5SGerhard Heift 		return -EFAULT;
2236cc68a8a5SGerhard Heift 
2237cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2238cc68a8a5SGerhard Heift 
2239cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2240cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2241cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2242cc68a8a5SGerhard Heift 
2243cc68a8a5SGerhard Heift 	inode = file_inode(file);
2244cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2245718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2246cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2247cc68a8a5SGerhard Heift 		ret = -EFAULT;
2248cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2249cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2250cc68a8a5SGerhard Heift 		ret = -EFAULT;
2251cc68a8a5SGerhard Heift 
225276dda93cSYan, Zheng 	return ret;
225376dda93cSYan, Zheng }
225476dda93cSYan, Zheng 
225598d377a0STARUISI Hiroaki /*
2256ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2257ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
225898d377a0STARUISI Hiroaki  */
225998d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
226098d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
226198d377a0STARUISI Hiroaki {
226298d377a0STARUISI Hiroaki 	struct btrfs_root *root;
226398d377a0STARUISI Hiroaki 	struct btrfs_key key;
2264ac8e9819SChris Mason 	char *ptr;
226598d377a0STARUISI Hiroaki 	int ret = -1;
226698d377a0STARUISI Hiroaki 	int slot;
226798d377a0STARUISI Hiroaki 	int len;
226898d377a0STARUISI Hiroaki 	int total_len = 0;
226998d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
227098d377a0STARUISI Hiroaki 	struct extent_buffer *l;
227198d377a0STARUISI Hiroaki 	struct btrfs_path *path;
227298d377a0STARUISI Hiroaki 
227398d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
227498d377a0STARUISI Hiroaki 		name[0]='\0';
227598d377a0STARUISI Hiroaki 		return 0;
227698d377a0STARUISI Hiroaki 	}
227798d377a0STARUISI Hiroaki 
227898d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
227998d377a0STARUISI Hiroaki 	if (!path)
228098d377a0STARUISI Hiroaki 		return -ENOMEM;
228198d377a0STARUISI Hiroaki 
2282c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
228398d377a0STARUISI Hiroaki 
228498d377a0STARUISI Hiroaki 	key.objectid = tree_id;
228598d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
228698d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
228798d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
228898d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2289ad1e3d56SMisono Tomohiro 		ret = PTR_ERR(root);
22908ad6fcabSChris Mason 		goto out;
229198d377a0STARUISI Hiroaki 	}
229298d377a0STARUISI Hiroaki 
229398d377a0STARUISI Hiroaki 	key.objectid = dirid;
229498d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
22958ad6fcabSChris Mason 	key.offset = (u64)-1;
229698d377a0STARUISI Hiroaki 
229798d377a0STARUISI Hiroaki 	while (1) {
229898d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
229998d377a0STARUISI Hiroaki 		if (ret < 0)
230098d377a0STARUISI Hiroaki 			goto out;
230118674c6cSFilipe David Borba Manana 		else if (ret > 0) {
230218674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
230318674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
230418674c6cSFilipe David Borba Manana 			if (ret < 0)
230518674c6cSFilipe David Borba Manana 				goto out;
230618674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2307ac8e9819SChris Mason 				ret = -ENOENT;
230898d377a0STARUISI Hiroaki 				goto out;
2309ac8e9819SChris Mason 			}
231018674c6cSFilipe David Borba Manana 		}
231118674c6cSFilipe David Borba Manana 
231218674c6cSFilipe David Borba Manana 		l = path->nodes[0];
231318674c6cSFilipe David Borba Manana 		slot = path->slots[0];
231418674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
231598d377a0STARUISI Hiroaki 
231698d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
231798d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
231898d377a0STARUISI Hiroaki 		ptr -= len + 1;
231998d377a0STARUISI Hiroaki 		total_len += len + 1;
2320a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2321a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
232298d377a0STARUISI Hiroaki 			goto out;
2323a696cf35SFilipe David Borba Manana 		}
232498d377a0STARUISI Hiroaki 
232598d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
232698d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
232798d377a0STARUISI Hiroaki 
232898d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
232998d377a0STARUISI Hiroaki 			break;
233098d377a0STARUISI Hiroaki 
2331b3b4aa74SDavid Sterba 		btrfs_release_path(path);
233298d377a0STARUISI Hiroaki 		key.objectid = key.offset;
23338ad6fcabSChris Mason 		key.offset = (u64)-1;
233498d377a0STARUISI Hiroaki 		dirid = key.objectid;
233598d377a0STARUISI Hiroaki 	}
233677906a50SLi Zefan 	memmove(name, ptr, total_len);
233798d377a0STARUISI Hiroaki 	name[total_len] = '\0';
233898d377a0STARUISI Hiroaki 	ret = 0;
233998d377a0STARUISI Hiroaki out:
234098d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2341ac8e9819SChris Mason 	return ret;
2342ac8e9819SChris Mason }
2343ac8e9819SChris Mason 
234423d0b79dSTomohiro Misono static int btrfs_search_path_in_tree_user(struct inode *inode,
234523d0b79dSTomohiro Misono 				struct btrfs_ioctl_ino_lookup_user_args *args)
234623d0b79dSTomohiro Misono {
234723d0b79dSTomohiro Misono 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
234823d0b79dSTomohiro Misono 	struct super_block *sb = inode->i_sb;
234923d0b79dSTomohiro Misono 	struct btrfs_key upper_limit = BTRFS_I(inode)->location;
235023d0b79dSTomohiro Misono 	u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
235123d0b79dSTomohiro Misono 	u64 dirid = args->dirid;
235223d0b79dSTomohiro Misono 	unsigned long item_off;
235323d0b79dSTomohiro Misono 	unsigned long item_len;
235423d0b79dSTomohiro Misono 	struct btrfs_inode_ref *iref;
235523d0b79dSTomohiro Misono 	struct btrfs_root_ref *rref;
235623d0b79dSTomohiro Misono 	struct btrfs_root *root;
235723d0b79dSTomohiro Misono 	struct btrfs_path *path;
235823d0b79dSTomohiro Misono 	struct btrfs_key key, key2;
235923d0b79dSTomohiro Misono 	struct extent_buffer *leaf;
236023d0b79dSTomohiro Misono 	struct inode *temp_inode;
236123d0b79dSTomohiro Misono 	char *ptr;
236223d0b79dSTomohiro Misono 	int slot;
236323d0b79dSTomohiro Misono 	int len;
236423d0b79dSTomohiro Misono 	int total_len = 0;
236523d0b79dSTomohiro Misono 	int ret;
236623d0b79dSTomohiro Misono 
236723d0b79dSTomohiro Misono 	path = btrfs_alloc_path();
236823d0b79dSTomohiro Misono 	if (!path)
236923d0b79dSTomohiro Misono 		return -ENOMEM;
237023d0b79dSTomohiro Misono 
237123d0b79dSTomohiro Misono 	/*
237223d0b79dSTomohiro Misono 	 * If the bottom subvolume does not exist directly under upper_limit,
237323d0b79dSTomohiro Misono 	 * construct the path in from the bottom up.
237423d0b79dSTomohiro Misono 	 */
237523d0b79dSTomohiro Misono 	if (dirid != upper_limit.objectid) {
237623d0b79dSTomohiro Misono 		ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
237723d0b79dSTomohiro Misono 
237823d0b79dSTomohiro Misono 		key.objectid = treeid;
237923d0b79dSTomohiro Misono 		key.type = BTRFS_ROOT_ITEM_KEY;
238023d0b79dSTomohiro Misono 		key.offset = (u64)-1;
238123d0b79dSTomohiro Misono 		root = btrfs_read_fs_root_no_name(fs_info, &key);
238223d0b79dSTomohiro Misono 		if (IS_ERR(root)) {
238323d0b79dSTomohiro Misono 			ret = PTR_ERR(root);
238423d0b79dSTomohiro Misono 			goto out;
238523d0b79dSTomohiro Misono 		}
238623d0b79dSTomohiro Misono 
238723d0b79dSTomohiro Misono 		key.objectid = dirid;
238823d0b79dSTomohiro Misono 		key.type = BTRFS_INODE_REF_KEY;
238923d0b79dSTomohiro Misono 		key.offset = (u64)-1;
239023d0b79dSTomohiro Misono 		while (1) {
239123d0b79dSTomohiro Misono 			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
239223d0b79dSTomohiro Misono 			if (ret < 0) {
239323d0b79dSTomohiro Misono 				goto out;
239423d0b79dSTomohiro Misono 			} else if (ret > 0) {
239523d0b79dSTomohiro Misono 				ret = btrfs_previous_item(root, path, dirid,
239623d0b79dSTomohiro Misono 							  BTRFS_INODE_REF_KEY);
239723d0b79dSTomohiro Misono 				if (ret < 0) {
239823d0b79dSTomohiro Misono 					goto out;
239923d0b79dSTomohiro Misono 				} else if (ret > 0) {
240023d0b79dSTomohiro Misono 					ret = -ENOENT;
240123d0b79dSTomohiro Misono 					goto out;
240223d0b79dSTomohiro Misono 				}
240323d0b79dSTomohiro Misono 			}
240423d0b79dSTomohiro Misono 
240523d0b79dSTomohiro Misono 			leaf = path->nodes[0];
240623d0b79dSTomohiro Misono 			slot = path->slots[0];
240723d0b79dSTomohiro Misono 			btrfs_item_key_to_cpu(leaf, &key, slot);
240823d0b79dSTomohiro Misono 
240923d0b79dSTomohiro Misono 			iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
241023d0b79dSTomohiro Misono 			len = btrfs_inode_ref_name_len(leaf, iref);
241123d0b79dSTomohiro Misono 			ptr -= len + 1;
241223d0b79dSTomohiro Misono 			total_len += len + 1;
241323d0b79dSTomohiro Misono 			if (ptr < args->path) {
241423d0b79dSTomohiro Misono 				ret = -ENAMETOOLONG;
241523d0b79dSTomohiro Misono 				goto out;
241623d0b79dSTomohiro Misono 			}
241723d0b79dSTomohiro Misono 
241823d0b79dSTomohiro Misono 			*(ptr + len) = '/';
241923d0b79dSTomohiro Misono 			read_extent_buffer(leaf, ptr,
242023d0b79dSTomohiro Misono 					(unsigned long)(iref + 1), len);
242123d0b79dSTomohiro Misono 
242223d0b79dSTomohiro Misono 			/* Check the read+exec permission of this directory */
242323d0b79dSTomohiro Misono 			ret = btrfs_previous_item(root, path, dirid,
242423d0b79dSTomohiro Misono 						  BTRFS_INODE_ITEM_KEY);
242523d0b79dSTomohiro Misono 			if (ret < 0) {
242623d0b79dSTomohiro Misono 				goto out;
242723d0b79dSTomohiro Misono 			} else if (ret > 0) {
242823d0b79dSTomohiro Misono 				ret = -ENOENT;
242923d0b79dSTomohiro Misono 				goto out;
243023d0b79dSTomohiro Misono 			}
243123d0b79dSTomohiro Misono 
243223d0b79dSTomohiro Misono 			leaf = path->nodes[0];
243323d0b79dSTomohiro Misono 			slot = path->slots[0];
243423d0b79dSTomohiro Misono 			btrfs_item_key_to_cpu(leaf, &key2, slot);
243523d0b79dSTomohiro Misono 			if (key2.objectid != dirid) {
243623d0b79dSTomohiro Misono 				ret = -ENOENT;
243723d0b79dSTomohiro Misono 				goto out;
243823d0b79dSTomohiro Misono 			}
243923d0b79dSTomohiro Misono 
244023d0b79dSTomohiro Misono 			temp_inode = btrfs_iget(sb, &key2, root, NULL);
24413ca57bd6SMisono Tomohiro 			if (IS_ERR(temp_inode)) {
24423ca57bd6SMisono Tomohiro 				ret = PTR_ERR(temp_inode);
24433ca57bd6SMisono Tomohiro 				goto out;
24443ca57bd6SMisono Tomohiro 			}
244523d0b79dSTomohiro Misono 			ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC);
244623d0b79dSTomohiro Misono 			iput(temp_inode);
244723d0b79dSTomohiro Misono 			if (ret) {
244823d0b79dSTomohiro Misono 				ret = -EACCES;
244923d0b79dSTomohiro Misono 				goto out;
245023d0b79dSTomohiro Misono 			}
245123d0b79dSTomohiro Misono 
245223d0b79dSTomohiro Misono 			if (key.offset == upper_limit.objectid)
245323d0b79dSTomohiro Misono 				break;
245423d0b79dSTomohiro Misono 			if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
245523d0b79dSTomohiro Misono 				ret = -EACCES;
245623d0b79dSTomohiro Misono 				goto out;
245723d0b79dSTomohiro Misono 			}
245823d0b79dSTomohiro Misono 
245923d0b79dSTomohiro Misono 			btrfs_release_path(path);
246023d0b79dSTomohiro Misono 			key.objectid = key.offset;
246123d0b79dSTomohiro Misono 			key.offset = (u64)-1;
246223d0b79dSTomohiro Misono 			dirid = key.objectid;
246323d0b79dSTomohiro Misono 		}
246423d0b79dSTomohiro Misono 
246523d0b79dSTomohiro Misono 		memmove(args->path, ptr, total_len);
246623d0b79dSTomohiro Misono 		args->path[total_len] = '\0';
246723d0b79dSTomohiro Misono 		btrfs_release_path(path);
246823d0b79dSTomohiro Misono 	}
246923d0b79dSTomohiro Misono 
247023d0b79dSTomohiro Misono 	/* Get the bottom subvolume's name from ROOT_REF */
247123d0b79dSTomohiro Misono 	root = fs_info->tree_root;
247223d0b79dSTomohiro Misono 	key.objectid = treeid;
247323d0b79dSTomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
247423d0b79dSTomohiro Misono 	key.offset = args->treeid;
247523d0b79dSTomohiro Misono 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
247623d0b79dSTomohiro Misono 	if (ret < 0) {
247723d0b79dSTomohiro Misono 		goto out;
247823d0b79dSTomohiro Misono 	} else if (ret > 0) {
247923d0b79dSTomohiro Misono 		ret = -ENOENT;
248023d0b79dSTomohiro Misono 		goto out;
248123d0b79dSTomohiro Misono 	}
248223d0b79dSTomohiro Misono 
248323d0b79dSTomohiro Misono 	leaf = path->nodes[0];
248423d0b79dSTomohiro Misono 	slot = path->slots[0];
248523d0b79dSTomohiro Misono 	btrfs_item_key_to_cpu(leaf, &key, slot);
248623d0b79dSTomohiro Misono 
248723d0b79dSTomohiro Misono 	item_off = btrfs_item_ptr_offset(leaf, slot);
248823d0b79dSTomohiro Misono 	item_len = btrfs_item_size_nr(leaf, slot);
248923d0b79dSTomohiro Misono 	/* Check if dirid in ROOT_REF corresponds to passed dirid */
249023d0b79dSTomohiro Misono 	rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
249123d0b79dSTomohiro Misono 	if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
249223d0b79dSTomohiro Misono 		ret = -EINVAL;
249323d0b79dSTomohiro Misono 		goto out;
249423d0b79dSTomohiro Misono 	}
249523d0b79dSTomohiro Misono 
249623d0b79dSTomohiro Misono 	/* Copy subvolume's name */
249723d0b79dSTomohiro Misono 	item_off += sizeof(struct btrfs_root_ref);
249823d0b79dSTomohiro Misono 	item_len -= sizeof(struct btrfs_root_ref);
249923d0b79dSTomohiro Misono 	read_extent_buffer(leaf, args->name, item_off, item_len);
250023d0b79dSTomohiro Misono 	args->name[item_len] = 0;
250123d0b79dSTomohiro Misono 
250223d0b79dSTomohiro Misono out:
250323d0b79dSTomohiro Misono 	btrfs_free_path(path);
250423d0b79dSTomohiro Misono 	return ret;
250523d0b79dSTomohiro Misono }
250623d0b79dSTomohiro Misono 
2507ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2508ac8e9819SChris Mason 					   void __user *argp)
2509ac8e9819SChris Mason {
2510ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2511ac8e9819SChris Mason 	 struct inode *inode;
251201b810b8SDavid Sterba 	int ret = 0;
2513ac8e9819SChris Mason 
25142354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
25152354d08fSJulia Lawall 	if (IS_ERR(args))
25162354d08fSJulia Lawall 		return PTR_ERR(args);
2517c2b96929SDan Carpenter 
2518496ad9aaSAl Viro 	inode = file_inode(file);
2519ac8e9819SChris Mason 
252001b810b8SDavid Sterba 	/*
252101b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
252201b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
252301b810b8SDavid Sterba 	 */
25241b53ac4dSChris Mason 	if (args->treeid == 0)
25251b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
25261b53ac4dSChris Mason 
252701b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
252801b810b8SDavid Sterba 		args->name[0] = 0;
252901b810b8SDavid Sterba 		goto out;
253001b810b8SDavid Sterba 	}
253101b810b8SDavid Sterba 
253201b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
253301b810b8SDavid Sterba 		ret = -EPERM;
253401b810b8SDavid Sterba 		goto out;
253501b810b8SDavid Sterba 	}
253601b810b8SDavid Sterba 
2537ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2538ac8e9819SChris Mason 					args->treeid, args->objectid,
2539ac8e9819SChris Mason 					args->name);
2540ac8e9819SChris Mason 
254101b810b8SDavid Sterba out:
2542ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2543ac8e9819SChris Mason 		ret = -EFAULT;
2544ac8e9819SChris Mason 
2545ac8e9819SChris Mason 	kfree(args);
254698d377a0STARUISI Hiroaki 	return ret;
254798d377a0STARUISI Hiroaki }
254898d377a0STARUISI Hiroaki 
254923d0b79dSTomohiro Misono /*
255023d0b79dSTomohiro Misono  * Version of ino_lookup ioctl (unprivileged)
255123d0b79dSTomohiro Misono  *
255223d0b79dSTomohiro Misono  * The main differences from ino_lookup ioctl are:
255323d0b79dSTomohiro Misono  *
255423d0b79dSTomohiro Misono  *   1. Read + Exec permission will be checked using inode_permission() during
255523d0b79dSTomohiro Misono  *      path construction. -EACCES will be returned in case of failure.
255623d0b79dSTomohiro Misono  *   2. Path construction will be stopped at the inode number which corresponds
255723d0b79dSTomohiro Misono  *      to the fd with which this ioctl is called. If constructed path does not
255823d0b79dSTomohiro Misono  *      exist under fd's inode, -EACCES will be returned.
255923d0b79dSTomohiro Misono  *   3. The name of bottom subvolume is also searched and filled.
256023d0b79dSTomohiro Misono  */
256123d0b79dSTomohiro Misono static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
256223d0b79dSTomohiro Misono {
256323d0b79dSTomohiro Misono 	struct btrfs_ioctl_ino_lookup_user_args *args;
256423d0b79dSTomohiro Misono 	struct inode *inode;
256523d0b79dSTomohiro Misono 	int ret;
256623d0b79dSTomohiro Misono 
256723d0b79dSTomohiro Misono 	args = memdup_user(argp, sizeof(*args));
256823d0b79dSTomohiro Misono 	if (IS_ERR(args))
256923d0b79dSTomohiro Misono 		return PTR_ERR(args);
257023d0b79dSTomohiro Misono 
257123d0b79dSTomohiro Misono 	inode = file_inode(file);
257223d0b79dSTomohiro Misono 
257323d0b79dSTomohiro Misono 	if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
257423d0b79dSTomohiro Misono 	    BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
257523d0b79dSTomohiro Misono 		/*
257623d0b79dSTomohiro Misono 		 * The subvolume does not exist under fd with which this is
257723d0b79dSTomohiro Misono 		 * called
257823d0b79dSTomohiro Misono 		 */
257923d0b79dSTomohiro Misono 		kfree(args);
258023d0b79dSTomohiro Misono 		return -EACCES;
258123d0b79dSTomohiro Misono 	}
258223d0b79dSTomohiro Misono 
258323d0b79dSTomohiro Misono 	ret = btrfs_search_path_in_tree_user(inode, args);
258423d0b79dSTomohiro Misono 
258523d0b79dSTomohiro Misono 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
258623d0b79dSTomohiro Misono 		ret = -EFAULT;
258723d0b79dSTomohiro Misono 
258823d0b79dSTomohiro Misono 	kfree(args);
258923d0b79dSTomohiro Misono 	return ret;
259023d0b79dSTomohiro Misono }
259123d0b79dSTomohiro Misono 
2592b64ec075STomohiro Misono /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2593b64ec075STomohiro Misono static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2594b64ec075STomohiro Misono {
2595b64ec075STomohiro Misono 	struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2596b64ec075STomohiro Misono 	struct btrfs_fs_info *fs_info;
2597b64ec075STomohiro Misono 	struct btrfs_root *root;
2598b64ec075STomohiro Misono 	struct btrfs_path *path;
2599b64ec075STomohiro Misono 	struct btrfs_key key;
2600b64ec075STomohiro Misono 	struct btrfs_root_item *root_item;
2601b64ec075STomohiro Misono 	struct btrfs_root_ref *rref;
2602b64ec075STomohiro Misono 	struct extent_buffer *leaf;
2603b64ec075STomohiro Misono 	unsigned long item_off;
2604b64ec075STomohiro Misono 	unsigned long item_len;
2605b64ec075STomohiro Misono 	struct inode *inode;
2606b64ec075STomohiro Misono 	int slot;
2607b64ec075STomohiro Misono 	int ret = 0;
2608b64ec075STomohiro Misono 
2609b64ec075STomohiro Misono 	path = btrfs_alloc_path();
2610b64ec075STomohiro Misono 	if (!path)
2611b64ec075STomohiro Misono 		return -ENOMEM;
2612b64ec075STomohiro Misono 
2613b64ec075STomohiro Misono 	subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2614b64ec075STomohiro Misono 	if (!subvol_info) {
2615b64ec075STomohiro Misono 		btrfs_free_path(path);
2616b64ec075STomohiro Misono 		return -ENOMEM;
2617b64ec075STomohiro Misono 	}
2618b64ec075STomohiro Misono 
2619b64ec075STomohiro Misono 	inode = file_inode(file);
2620b64ec075STomohiro Misono 	fs_info = BTRFS_I(inode)->root->fs_info;
2621b64ec075STomohiro Misono 
2622b64ec075STomohiro Misono 	/* Get root_item of inode's subvolume */
2623b64ec075STomohiro Misono 	key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2624b64ec075STomohiro Misono 	key.type = BTRFS_ROOT_ITEM_KEY;
2625b64ec075STomohiro Misono 	key.offset = (u64)-1;
2626b64ec075STomohiro Misono 	root = btrfs_read_fs_root_no_name(fs_info, &key);
2627b64ec075STomohiro Misono 	if (IS_ERR(root)) {
2628b64ec075STomohiro Misono 		ret = PTR_ERR(root);
2629b64ec075STomohiro Misono 		goto out;
2630b64ec075STomohiro Misono 	}
2631b64ec075STomohiro Misono 	root_item = &root->root_item;
2632b64ec075STomohiro Misono 
2633b64ec075STomohiro Misono 	subvol_info->treeid = key.objectid;
2634b64ec075STomohiro Misono 
2635b64ec075STomohiro Misono 	subvol_info->generation = btrfs_root_generation(root_item);
2636b64ec075STomohiro Misono 	subvol_info->flags = btrfs_root_flags(root_item);
2637b64ec075STomohiro Misono 
2638b64ec075STomohiro Misono 	memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2639b64ec075STomohiro Misono 	memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2640b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2641b64ec075STomohiro Misono 	memcpy(subvol_info->received_uuid, root_item->received_uuid,
2642b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2643b64ec075STomohiro Misono 
2644b64ec075STomohiro Misono 	subvol_info->ctransid = btrfs_root_ctransid(root_item);
2645b64ec075STomohiro Misono 	subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2646b64ec075STomohiro Misono 	subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2647b64ec075STomohiro Misono 
2648b64ec075STomohiro Misono 	subvol_info->otransid = btrfs_root_otransid(root_item);
2649b64ec075STomohiro Misono 	subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2650b64ec075STomohiro Misono 	subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2651b64ec075STomohiro Misono 
2652b64ec075STomohiro Misono 	subvol_info->stransid = btrfs_root_stransid(root_item);
2653b64ec075STomohiro Misono 	subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2654b64ec075STomohiro Misono 	subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2655b64ec075STomohiro Misono 
2656b64ec075STomohiro Misono 	subvol_info->rtransid = btrfs_root_rtransid(root_item);
2657b64ec075STomohiro Misono 	subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2658b64ec075STomohiro Misono 	subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2659b64ec075STomohiro Misono 
2660b64ec075STomohiro Misono 	if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2661b64ec075STomohiro Misono 		/* Search root tree for ROOT_BACKREF of this subvolume */
2662b64ec075STomohiro Misono 		root = fs_info->tree_root;
2663b64ec075STomohiro Misono 
2664b64ec075STomohiro Misono 		key.type = BTRFS_ROOT_BACKREF_KEY;
2665b64ec075STomohiro Misono 		key.offset = 0;
2666b64ec075STomohiro Misono 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2667b64ec075STomohiro Misono 		if (ret < 0) {
2668b64ec075STomohiro Misono 			goto out;
2669b64ec075STomohiro Misono 		} else if (path->slots[0] >=
2670b64ec075STomohiro Misono 			   btrfs_header_nritems(path->nodes[0])) {
2671b64ec075STomohiro Misono 			ret = btrfs_next_leaf(root, path);
2672b64ec075STomohiro Misono 			if (ret < 0) {
2673b64ec075STomohiro Misono 				goto out;
2674b64ec075STomohiro Misono 			} else if (ret > 0) {
2675b64ec075STomohiro Misono 				ret = -EUCLEAN;
2676b64ec075STomohiro Misono 				goto out;
2677b64ec075STomohiro Misono 			}
2678b64ec075STomohiro Misono 		}
2679b64ec075STomohiro Misono 
2680b64ec075STomohiro Misono 		leaf = path->nodes[0];
2681b64ec075STomohiro Misono 		slot = path->slots[0];
2682b64ec075STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
2683b64ec075STomohiro Misono 		if (key.objectid == subvol_info->treeid &&
2684b64ec075STomohiro Misono 		    key.type == BTRFS_ROOT_BACKREF_KEY) {
2685b64ec075STomohiro Misono 			subvol_info->parent_id = key.offset;
2686b64ec075STomohiro Misono 
2687b64ec075STomohiro Misono 			rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2688b64ec075STomohiro Misono 			subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2689b64ec075STomohiro Misono 
2690b64ec075STomohiro Misono 			item_off = btrfs_item_ptr_offset(leaf, slot)
2691b64ec075STomohiro Misono 					+ sizeof(struct btrfs_root_ref);
2692b64ec075STomohiro Misono 			item_len = btrfs_item_size_nr(leaf, slot)
2693b64ec075STomohiro Misono 					- sizeof(struct btrfs_root_ref);
2694b64ec075STomohiro Misono 			read_extent_buffer(leaf, subvol_info->name,
2695b64ec075STomohiro Misono 					   item_off, item_len);
2696b64ec075STomohiro Misono 		} else {
2697b64ec075STomohiro Misono 			ret = -ENOENT;
2698b64ec075STomohiro Misono 			goto out;
2699b64ec075STomohiro Misono 		}
2700b64ec075STomohiro Misono 	}
2701b64ec075STomohiro Misono 
2702b64ec075STomohiro Misono 	if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2703b64ec075STomohiro Misono 		ret = -EFAULT;
2704b64ec075STomohiro Misono 
2705b64ec075STomohiro Misono out:
2706b64ec075STomohiro Misono 	btrfs_free_path(path);
2707b64ec075STomohiro Misono 	kzfree(subvol_info);
2708b64ec075STomohiro Misono 	return ret;
2709b64ec075STomohiro Misono }
2710b64ec075STomohiro Misono 
271142e4b520STomohiro Misono /*
271242e4b520STomohiro Misono  * Return ROOT_REF information of the subvolume containing this inode
271342e4b520STomohiro Misono  * except the subvolume name.
271442e4b520STomohiro Misono  */
271542e4b520STomohiro Misono static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
271642e4b520STomohiro Misono {
271742e4b520STomohiro Misono 	struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
271842e4b520STomohiro Misono 	struct btrfs_root_ref *rref;
271942e4b520STomohiro Misono 	struct btrfs_root *root;
272042e4b520STomohiro Misono 	struct btrfs_path *path;
272142e4b520STomohiro Misono 	struct btrfs_key key;
272242e4b520STomohiro Misono 	struct extent_buffer *leaf;
272342e4b520STomohiro Misono 	struct inode *inode;
272442e4b520STomohiro Misono 	u64 objectid;
272542e4b520STomohiro Misono 	int slot;
272642e4b520STomohiro Misono 	int ret;
272742e4b520STomohiro Misono 	u8 found;
272842e4b520STomohiro Misono 
272942e4b520STomohiro Misono 	path = btrfs_alloc_path();
273042e4b520STomohiro Misono 	if (!path)
273142e4b520STomohiro Misono 		return -ENOMEM;
273242e4b520STomohiro Misono 
273342e4b520STomohiro Misono 	rootrefs = memdup_user(argp, sizeof(*rootrefs));
273442e4b520STomohiro Misono 	if (IS_ERR(rootrefs)) {
273542e4b520STomohiro Misono 		btrfs_free_path(path);
273642e4b520STomohiro Misono 		return PTR_ERR(rootrefs);
273742e4b520STomohiro Misono 	}
273842e4b520STomohiro Misono 
273942e4b520STomohiro Misono 	inode = file_inode(file);
274042e4b520STomohiro Misono 	root = BTRFS_I(inode)->root->fs_info->tree_root;
274142e4b520STomohiro Misono 	objectid = BTRFS_I(inode)->root->root_key.objectid;
274242e4b520STomohiro Misono 
274342e4b520STomohiro Misono 	key.objectid = objectid;
274442e4b520STomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
274542e4b520STomohiro Misono 	key.offset = rootrefs->min_treeid;
274642e4b520STomohiro Misono 	found = 0;
274742e4b520STomohiro Misono 
274842e4b520STomohiro Misono 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
274942e4b520STomohiro Misono 	if (ret < 0) {
275042e4b520STomohiro Misono 		goto out;
275142e4b520STomohiro Misono 	} else if (path->slots[0] >=
275242e4b520STomohiro Misono 		   btrfs_header_nritems(path->nodes[0])) {
275342e4b520STomohiro Misono 		ret = btrfs_next_leaf(root, path);
275442e4b520STomohiro Misono 		if (ret < 0) {
275542e4b520STomohiro Misono 			goto out;
275642e4b520STomohiro Misono 		} else if (ret > 0) {
275742e4b520STomohiro Misono 			ret = -EUCLEAN;
275842e4b520STomohiro Misono 			goto out;
275942e4b520STomohiro Misono 		}
276042e4b520STomohiro Misono 	}
276142e4b520STomohiro Misono 	while (1) {
276242e4b520STomohiro Misono 		leaf = path->nodes[0];
276342e4b520STomohiro Misono 		slot = path->slots[0];
276442e4b520STomohiro Misono 
276542e4b520STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
276642e4b520STomohiro Misono 		if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
276742e4b520STomohiro Misono 			ret = 0;
276842e4b520STomohiro Misono 			goto out;
276942e4b520STomohiro Misono 		}
277042e4b520STomohiro Misono 
277142e4b520STomohiro Misono 		if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
277242e4b520STomohiro Misono 			ret = -EOVERFLOW;
277342e4b520STomohiro Misono 			goto out;
277442e4b520STomohiro Misono 		}
277542e4b520STomohiro Misono 
277642e4b520STomohiro Misono 		rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
277742e4b520STomohiro Misono 		rootrefs->rootref[found].treeid = key.offset;
277842e4b520STomohiro Misono 		rootrefs->rootref[found].dirid =
277942e4b520STomohiro Misono 				  btrfs_root_ref_dirid(leaf, rref);
278042e4b520STomohiro Misono 		found++;
278142e4b520STomohiro Misono 
278242e4b520STomohiro Misono 		ret = btrfs_next_item(root, path);
278342e4b520STomohiro Misono 		if (ret < 0) {
278442e4b520STomohiro Misono 			goto out;
278542e4b520STomohiro Misono 		} else if (ret > 0) {
278642e4b520STomohiro Misono 			ret = -EUCLEAN;
278742e4b520STomohiro Misono 			goto out;
278842e4b520STomohiro Misono 		}
278942e4b520STomohiro Misono 	}
279042e4b520STomohiro Misono 
279142e4b520STomohiro Misono out:
279242e4b520STomohiro Misono 	if (!ret || ret == -EOVERFLOW) {
279342e4b520STomohiro Misono 		rootrefs->num_items = found;
279442e4b520STomohiro Misono 		/* update min_treeid for next search */
279542e4b520STomohiro Misono 		if (found)
279642e4b520STomohiro Misono 			rootrefs->min_treeid =
279742e4b520STomohiro Misono 				rootrefs->rootref[found - 1].treeid + 1;
279842e4b520STomohiro Misono 		if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
279942e4b520STomohiro Misono 			ret = -EFAULT;
280042e4b520STomohiro Misono 	}
280142e4b520STomohiro Misono 
280242e4b520STomohiro Misono 	kfree(rootrefs);
280342e4b520STomohiro Misono 	btrfs_free_path(path);
280442e4b520STomohiro Misono 
280542e4b520STomohiro Misono 	return ret;
280642e4b520STomohiro Misono }
280742e4b520STomohiro Misono 
280876dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
280976dda93cSYan, Zheng 					     void __user *arg)
281076dda93cSYan, Zheng {
281154563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
28120b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
281376dda93cSYan, Zheng 	struct dentry *dentry;
28142b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
281576dda93cSYan, Zheng 	struct inode *inode;
281676dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
281776dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
281876dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
281976dda93cSYan, Zheng 	int namelen;
282076dda93cSYan, Zheng 	int err = 0;
282176dda93cSYan, Zheng 
2822325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2823325c50e3SJeff Mahoney 		return -ENOTDIR;
2824325c50e3SJeff Mahoney 
282576dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
282676dda93cSYan, Zheng 	if (IS_ERR(vol_args))
282776dda93cSYan, Zheng 		return PTR_ERR(vol_args);
282876dda93cSYan, Zheng 
282976dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
283076dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
283176dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
283276dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
283376dda93cSYan, Zheng 		err = -EINVAL;
283476dda93cSYan, Zheng 		goto out;
283576dda93cSYan, Zheng 	}
283676dda93cSYan, Zheng 
2837a561be71SAl Viro 	err = mnt_want_write_file(file);
283876dda93cSYan, Zheng 	if (err)
283976dda93cSYan, Zheng 		goto out;
284076dda93cSYan, Zheng 
2841521e0546SDavid Sterba 
284200235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
284300235411SAl Viro 	if (err == -EINTR)
284400235411SAl Viro 		goto out_drop_write;
284576dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
284676dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
284776dda93cSYan, Zheng 		err = PTR_ERR(dentry);
284876dda93cSYan, Zheng 		goto out_unlock_dir;
284976dda93cSYan, Zheng 	}
285076dda93cSYan, Zheng 
28512b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
285276dda93cSYan, Zheng 		err = -ENOENT;
285376dda93cSYan, Zheng 		goto out_dput;
285476dda93cSYan, Zheng 	}
285576dda93cSYan, Zheng 
28562b0143b5SDavid Howells 	inode = d_inode(dentry);
28574260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
28584260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
28594260f7c7SSage Weil 		/*
28604260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
28614260f7c7SSage Weil 		 * option, when the user has write+exec access to the
28624260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
28634260f7c7SSage Weil 		 * allowed.
28644260f7c7SSage Weil 		 *
28654260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
28664260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
28674260f7c7SSage Weil 		 * otherwise be able to delete.
28684260f7c7SSage Weil 		 *
28694260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
28704260f7c7SSage Weil 		 * rmdir(2).
28714260f7c7SSage Weil 		 */
28724260f7c7SSage Weil 		err = -EPERM;
28730b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
28744260f7c7SSage Weil 			goto out_dput;
28754260f7c7SSage Weil 
28764260f7c7SSage Weil 		/*
28774260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
28784260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
28794260f7c7SSage Weil 		 * must be called on the dentry referencing the root
28804260f7c7SSage Weil 		 * of the subvol, not a random directory contained
28814260f7c7SSage Weil 		 * within it.
28824260f7c7SSage Weil 		 */
28834260f7c7SSage Weil 		err = -EINVAL;
28844260f7c7SSage Weil 		if (root == dest)
28854260f7c7SSage Weil 			goto out_dput;
28864260f7c7SSage Weil 
28874260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
28884260f7c7SSage Weil 		if (err)
28894260f7c7SSage Weil 			goto out_dput;
28905c39da5bSMiao Xie 	}
28914260f7c7SSage Weil 
28925c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
28934260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
28944260f7c7SSage Weil 	if (err)
28954260f7c7SSage Weil 		goto out_dput;
28964260f7c7SSage Weil 
28974a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
289876dda93cSYan, Zheng 		err = -EINVAL;
289976dda93cSYan, Zheng 		goto out_dput;
290076dda93cSYan, Zheng 	}
290176dda93cSYan, Zheng 
29025955102cSAl Viro 	inode_lock(inode);
2903f60a2364SMisono Tomohiro 	err = btrfs_delete_subvolume(dir, dentry);
29045955102cSAl Viro 	inode_unlock(inode);
2905f60a2364SMisono Tomohiro 	if (!err)
290676dda93cSYan, Zheng 		d_delete(dentry);
2907fa6ac876SLiu Bo 
290876dda93cSYan, Zheng out_dput:
290976dda93cSYan, Zheng 	dput(dentry);
291076dda93cSYan, Zheng out_unlock_dir:
29115955102cSAl Viro 	inode_unlock(dir);
291200235411SAl Viro out_drop_write:
29132a79f17eSAl Viro 	mnt_drop_write_file(file);
291476dda93cSYan, Zheng out:
291576dda93cSYan, Zheng 	kfree(vol_args);
291676dda93cSYan, Zheng 	return err;
291776dda93cSYan, Zheng }
291876dda93cSYan, Zheng 
29191e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2920f46b5a66SChristoph Hellwig {
2921496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2922f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
29231e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2924c146afadSYan Zheng 	int ret;
2925c146afadSYan Zheng 
292625122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
292725122d15SIlya Dryomov 	if (ret)
292825122d15SIlya Dryomov 		return ret;
2929b83cc969SLi Zefan 
293025122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
293125122d15SIlya Dryomov 		ret = -EROFS;
293225122d15SIlya Dryomov 		goto out;
29335ac00addSStefan Behrens 	}
2934f46b5a66SChristoph Hellwig 
2935f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2936f46b5a66SChristoph Hellwig 	case S_IFDIR:
2937e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2938e441d54dSChris Mason 			ret = -EPERM;
2939e441d54dSChris Mason 			goto out;
2940e441d54dSChris Mason 		}
2941de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
2942f46b5a66SChristoph Hellwig 		break;
2943f46b5a66SChristoph Hellwig 	case S_IFREG:
2944e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2945e441d54dSChris Mason 			ret = -EINVAL;
2946e441d54dSChris Mason 			goto out;
2947e441d54dSChris Mason 		}
29481e701a32SChris Mason 
29491e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
29501e701a32SChris Mason 		if (!range) {
29511e701a32SChris Mason 			ret = -ENOMEM;
29521e701a32SChris Mason 			goto out;
29531e701a32SChris Mason 		}
29541e701a32SChris Mason 
29551e701a32SChris Mason 		if (argp) {
29561e701a32SChris Mason 			if (copy_from_user(range, argp,
29571e701a32SChris Mason 					   sizeof(*range))) {
29581e701a32SChris Mason 				ret = -EFAULT;
29591e701a32SChris Mason 				kfree(range);
2960683be16eSDan Carpenter 				goto out;
29611e701a32SChris Mason 			}
29621e701a32SChris Mason 			/* compression requires us to start the IO */
29631e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
29641e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
29651e701a32SChris Mason 				range->extent_thresh = (u32)-1;
29661e701a32SChris Mason 			}
29671e701a32SChris Mason 		} else {
29681e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
29691e701a32SChris Mason 			range->len = (u64)-1;
29701e701a32SChris Mason 		}
2971496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
29727c829b72SAnand Jain 					range, BTRFS_OLDEST_GENERATION, 0);
29734cb5300bSChris Mason 		if (ret > 0)
29744cb5300bSChris Mason 			ret = 0;
29751e701a32SChris Mason 		kfree(range);
2976f46b5a66SChristoph Hellwig 		break;
29778929ecfaSYan, Zheng 	default:
29788929ecfaSYan, Zheng 		ret = -EINVAL;
2979f46b5a66SChristoph Hellwig 	}
2980e441d54dSChris Mason out:
298125122d15SIlya Dryomov 	mnt_drop_write_file(file);
2982e441d54dSChris Mason 	return ret;
2983f46b5a66SChristoph Hellwig }
2984f46b5a66SChristoph Hellwig 
29852ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2986f46b5a66SChristoph Hellwig {
2987f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2988f46b5a66SChristoph Hellwig 	int ret;
2989f46b5a66SChristoph Hellwig 
2990e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2991e441d54dSChris Mason 		return -EPERM;
2992e441d54dSChris Mason 
2993171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2994e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2995c9e9f97bSIlya Dryomov 
2996dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2997c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2998c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2999c9e9f97bSIlya Dryomov 		goto out;
3000c9e9f97bSIlya Dryomov 	}
3001f46b5a66SChristoph Hellwig 
30025516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
30032ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
3004f46b5a66SChristoph Hellwig 
300543d20761SAnand Jain 	if (!ret)
30060b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
300743d20761SAnand Jain 
3008f46b5a66SChristoph Hellwig 	kfree(vol_args);
3009c9e9f97bSIlya Dryomov out:
3010171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3011f46b5a66SChristoph Hellwig 	return ret;
3012f46b5a66SChristoph Hellwig }
3013f46b5a66SChristoph Hellwig 
30146b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3015f46b5a66SChristoph Hellwig {
30160b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
30170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
30186b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
3019f46b5a66SChristoph Hellwig 	int ret;
3020f46b5a66SChristoph Hellwig 
3021e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
3022e441d54dSChris Mason 		return -EPERM;
3023e441d54dSChris Mason 
3024da24927bSMiao Xie 	ret = mnt_want_write_file(file);
3025da24927bSMiao Xie 	if (ret)
3026da24927bSMiao Xie 		return ret;
3027c146afadSYan Zheng 
3028dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
3029c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
3030c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
3031c47ca32dSDan Carpenter 		goto err_drop;
3032c9e9f97bSIlya Dryomov 	}
3033f46b5a66SChristoph Hellwig 
30346b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
3035fd4e994bSOmar Sandoval 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
3036fd4e994bSOmar Sandoval 		ret = -EOPNOTSUPP;
3037fd4e994bSOmar Sandoval 		goto out;
3038fd4e994bSOmar Sandoval 	}
3039f46b5a66SChristoph Hellwig 
3040171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3041183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3042183860f6SAnand Jain 		goto out;
3043183860f6SAnand Jain 	}
3044183860f6SAnand Jain 
3045735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
30462ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
30476b526ed7SAnand Jain 	} else {
30486b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
30492ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
30506b526ed7SAnand Jain 	}
3051171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3052183860f6SAnand Jain 
30536b526ed7SAnand Jain 	if (!ret) {
3054735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
30550b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
30566b526ed7SAnand Jain 					vol_args->devid);
30576b526ed7SAnand Jain 		else
30580b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
30596b526ed7SAnand Jain 					vol_args->name);
30606b526ed7SAnand Jain 	}
3061183860f6SAnand Jain out:
3062183860f6SAnand Jain 	kfree(vol_args);
3063c47ca32dSDan Carpenter err_drop:
30644ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
3065f46b5a66SChristoph Hellwig 	return ret;
3066f46b5a66SChristoph Hellwig }
3067f46b5a66SChristoph Hellwig 
3068f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3069f46b5a66SChristoph Hellwig {
30700b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
30710b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3072f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
3073f46b5a66SChristoph Hellwig 	int ret;
3074f46b5a66SChristoph Hellwig 
3075f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
3076f46b5a66SChristoph Hellwig 		return -EPERM;
3077f46b5a66SChristoph Hellwig 
3078f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
3079f46b5a66SChristoph Hellwig 	if (ret)
3080f46b5a66SChristoph Hellwig 		return ret;
3081f46b5a66SChristoph Hellwig 
3082171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3083f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
308458d7bbf8SDavid Sterba 		goto out_drop_write;
308558d7bbf8SDavid Sterba 	}
308658d7bbf8SDavid Sterba 
308758d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
308858d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
308958d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
3090f46b5a66SChristoph Hellwig 		goto out;
3091f46b5a66SChristoph Hellwig 	}
3092f46b5a66SChristoph Hellwig 
309358d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
30942ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3095f46b5a66SChristoph Hellwig 
3096f46b5a66SChristoph Hellwig 	if (!ret)
30970b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3098f46b5a66SChristoph Hellwig 	kfree(vol_args);
309958d7bbf8SDavid Sterba out:
3100171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
310158d7bbf8SDavid Sterba out_drop_write:
3102f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
310358d7bbf8SDavid Sterba 
3104f46b5a66SChristoph Hellwig 	return ret;
3105f46b5a66SChristoph Hellwig }
3106f46b5a66SChristoph Hellwig 
31072ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
31082ff7e61eSJeff Mahoney 				void __user *arg)
3109475f6387SJan Schmidt {
3110027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
3111475f6387SJan Schmidt 	struct btrfs_device *device;
31120b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3113027ed2f0SLi Zefan 	int ret = 0;
3114475f6387SJan Schmidt 
3115027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
3116027ed2f0SLi Zefan 	if (!fi_args)
3117027ed2f0SLi Zefan 		return -ENOMEM;
3118027ed2f0SLi Zefan 
3119d03262c7SDavid Sterba 	rcu_read_lock();
3120027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
3121475f6387SJan Schmidt 
3122d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3123027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
3124027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
3125475f6387SJan Schmidt 	}
3126d03262c7SDavid Sterba 	rcu_read_unlock();
3127475f6387SJan Schmidt 
3128d03262c7SDavid Sterba 	memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
3129bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
3130bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
3131bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
313280a773fbSDavid Sterba 
3133027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3134027ed2f0SLi Zefan 		ret = -EFAULT;
3135475f6387SJan Schmidt 
3136027ed2f0SLi Zefan 	kfree(fi_args);
3137027ed2f0SLi Zefan 	return ret;
3138475f6387SJan Schmidt }
3139475f6387SJan Schmidt 
31402ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
31412ff7e61eSJeff Mahoney 				 void __user *arg)
3142475f6387SJan Schmidt {
3143475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
3144475f6387SJan Schmidt 	struct btrfs_device *dev;
3145475f6387SJan Schmidt 	int ret = 0;
3146475f6387SJan Schmidt 	char *s_uuid = NULL;
3147475f6387SJan Schmidt 
3148475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
3149475f6387SJan Schmidt 	if (IS_ERR(di_args))
3150475f6387SJan Schmidt 		return PTR_ERR(di_args);
3151475f6387SJan Schmidt 
3152dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
3153475f6387SJan Schmidt 		s_uuid = di_args->uuid;
3154475f6387SJan Schmidt 
3155c5593ca3SDavid Sterba 	rcu_read_lock();
31560b246afaSJeff Mahoney 	dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
3157475f6387SJan Schmidt 
3158475f6387SJan Schmidt 	if (!dev) {
3159475f6387SJan Schmidt 		ret = -ENODEV;
3160475f6387SJan Schmidt 		goto out;
3161475f6387SJan Schmidt 	}
3162475f6387SJan Schmidt 
3163475f6387SJan Schmidt 	di_args->devid = dev->devid;
31647cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
31657cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3166475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3167a27202fbSJim Meyering 	if (dev->name) {
3168606686eeSJosef Bacik 		struct rcu_string *name;
3169606686eeSJosef Bacik 
3170606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
31716670d4c2SXiongfeng Wang 		strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
3172a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
3173a27202fbSJim Meyering 	} else {
317499ba55adSStefan Behrens 		di_args->path[0] = '\0';
3175a27202fbSJim Meyering 	}
3176475f6387SJan Schmidt 
3177475f6387SJan Schmidt out:
3178c5593ca3SDavid Sterba 	rcu_read_unlock();
3179475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3180475f6387SJan Schmidt 		ret = -EFAULT;
3181475f6387SJan Schmidt 
3182475f6387SJan Schmidt 	kfree(di_args);
3183475f6387SJan Schmidt 	return ret;
3184475f6387SJan Schmidt }
3185475f6387SJan Schmidt 
3186f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
3187416161dbSMark Fasheh {
3188416161dbSMark Fasheh 	struct page *page;
3189416161dbSMark Fasheh 
3190416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
3191416161dbSMark Fasheh 	if (!page)
319231314002SFilipe Manana 		return ERR_PTR(-ENOMEM);
3193416161dbSMark Fasheh 
3194416161dbSMark Fasheh 	if (!PageUptodate(page)) {
319531314002SFilipe Manana 		int ret;
319631314002SFilipe Manana 
319731314002SFilipe Manana 		ret = btrfs_readpage(NULL, page);
319831314002SFilipe Manana 		if (ret)
319931314002SFilipe Manana 			return ERR_PTR(ret);
3200416161dbSMark Fasheh 		lock_page(page);
3201416161dbSMark Fasheh 		if (!PageUptodate(page)) {
3202416161dbSMark Fasheh 			unlock_page(page);
320309cbfeafSKirill A. Shutemov 			put_page(page);
320431314002SFilipe Manana 			return ERR_PTR(-EIO);
3205416161dbSMark Fasheh 		}
320631314002SFilipe Manana 		if (page->mapping != inode->i_mapping) {
3207416161dbSMark Fasheh 			unlock_page(page);
320809cbfeafSKirill A. Shutemov 			put_page(page);
320931314002SFilipe Manana 			return ERR_PTR(-EAGAIN);
3210416161dbSMark Fasheh 		}
3211416161dbSMark Fasheh 	}
3212416161dbSMark Fasheh 
3213416161dbSMark Fasheh 	return page;
3214416161dbSMark Fasheh }
3215416161dbSMark Fasheh 
3216f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
3217f4414602SMark Fasheh 			       int num_pages, u64 off)
3218f4414602SMark Fasheh {
3219f4414602SMark Fasheh 	int i;
322009cbfeafSKirill A. Shutemov 	pgoff_t index = off >> PAGE_SHIFT;
3221f4414602SMark Fasheh 
3222f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
322331314002SFilipe Manana again:
3224f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
322531314002SFilipe Manana 		if (IS_ERR(pages[i])) {
322631314002SFilipe Manana 			int err = PTR_ERR(pages[i]);
322731314002SFilipe Manana 
322831314002SFilipe Manana 			if (err == -EAGAIN)
322931314002SFilipe Manana 				goto again;
323031314002SFilipe Manana 			pages[i] = NULL;
323131314002SFilipe Manana 			return err;
323231314002SFilipe Manana 		}
3233f4414602SMark Fasheh 	}
3234f4414602SMark Fasheh 	return 0;
3235f4414602SMark Fasheh }
3236f4414602SMark Fasheh 
3237e0bd70c6SFilipe Manana static int lock_extent_range(struct inode *inode, u64 off, u64 len,
3238e0bd70c6SFilipe Manana 			     bool retry_range_locking)
323977fe20dcSMark Fasheh {
3240e0bd70c6SFilipe Manana 	/*
3241e0bd70c6SFilipe Manana 	 * Do any pending delalloc/csum calculations on inode, one way or
3242e0bd70c6SFilipe Manana 	 * another, and lock file content.
3243e0bd70c6SFilipe Manana 	 * The locking order is:
3244e0bd70c6SFilipe Manana 	 *
3245e0bd70c6SFilipe Manana 	 *   1) pages
3246e0bd70c6SFilipe Manana 	 *   2) range in the inode's io tree
3247e0bd70c6SFilipe Manana 	 */
324877fe20dcSMark Fasheh 	while (1) {
324977fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
325077fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
325177fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
325277fe20dcSMark Fasheh 							    off + len - 1);
3253ff5df9b8SFilipe Manana 		if ((!ordered ||
3254ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
3255ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
325677fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
3257ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
3258ff5df9b8SFilipe Manana 			if (ordered)
3259ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
326077fe20dcSMark Fasheh 			break;
3261ff5df9b8SFilipe Manana 		}
326277fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
326377fe20dcSMark Fasheh 		if (ordered)
326477fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
3265e0bd70c6SFilipe Manana 		if (!retry_range_locking)
3266e0bd70c6SFilipe Manana 			return -EAGAIN;
326777fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
326877fe20dcSMark Fasheh 	}
3269e0bd70c6SFilipe Manana 	return 0;
327077fe20dcSMark Fasheh }
327177fe20dcSMark Fasheh 
3272f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
3273416161dbSMark Fasheh {
32745955102cSAl Viro 	inode_unlock(inode1);
32755955102cSAl Viro 	inode_unlock(inode2);
3276416161dbSMark Fasheh }
3277416161dbSMark Fasheh 
3278f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
3279f4414602SMark Fasheh {
3280f4414602SMark Fasheh 	if (inode1 < inode2)
3281f4414602SMark Fasheh 		swap(inode1, inode2);
3282f4414602SMark Fasheh 
32835955102cSAl Viro 	inode_lock_nested(inode1, I_MUTEX_PARENT);
32845955102cSAl Viro 	inode_lock_nested(inode2, I_MUTEX_CHILD);
3285f4414602SMark Fasheh }
3286f4414602SMark Fasheh 
3287f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
3288f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
3289f4414602SMark Fasheh {
3290f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3291f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3292f4414602SMark Fasheh }
3293f4414602SMark Fasheh 
3294e0bd70c6SFilipe Manana static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
3295e0bd70c6SFilipe Manana 				    struct inode *inode2, u64 loff2, u64 len,
3296e0bd70c6SFilipe Manana 				    bool retry_range_locking)
3297416161dbSMark Fasheh {
3298e0bd70c6SFilipe Manana 	int ret;
3299e0bd70c6SFilipe Manana 
3300416161dbSMark Fasheh 	if (inode1 < inode2) {
3301416161dbSMark Fasheh 		swap(inode1, inode2);
3302416161dbSMark Fasheh 		swap(loff1, loff2);
3303416161dbSMark Fasheh 	}
3304e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
3305e0bd70c6SFilipe Manana 	if (ret)
3306e0bd70c6SFilipe Manana 		return ret;
3307e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
3308e0bd70c6SFilipe Manana 	if (ret)
3309e0bd70c6SFilipe Manana 		unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
3310e0bd70c6SFilipe Manana 			      loff1 + len - 1);
3311e0bd70c6SFilipe Manana 	return ret;
3312416161dbSMark Fasheh }
3313f4414602SMark Fasheh 
3314f4414602SMark Fasheh struct cmp_pages {
3315f4414602SMark Fasheh 	int		num_pages;
3316f4414602SMark Fasheh 	struct page	**src_pages;
3317f4414602SMark Fasheh 	struct page	**dst_pages;
3318f4414602SMark Fasheh };
3319f4414602SMark Fasheh 
3320f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
3321f4414602SMark Fasheh {
3322f4414602SMark Fasheh 	int i;
3323f4414602SMark Fasheh 	struct page *pg;
3324f4414602SMark Fasheh 
3325f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
3326f4414602SMark Fasheh 		pg = cmp->src_pages[i];
3327e0bd70c6SFilipe Manana 		if (pg) {
3328e0bd70c6SFilipe Manana 			unlock_page(pg);
332909cbfeafSKirill A. Shutemov 			put_page(pg);
3330e0bd70c6SFilipe Manana 		}
3331f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
3332e0bd70c6SFilipe Manana 		if (pg) {
3333e0bd70c6SFilipe Manana 			unlock_page(pg);
333409cbfeafSKirill A. Shutemov 			put_page(pg);
3335f4414602SMark Fasheh 		}
3336e0bd70c6SFilipe Manana 	}
3337f4414602SMark Fasheh }
3338f4414602SMark Fasheh 
3339f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
3340f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
3341f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
3342f4414602SMark Fasheh {
3343f4414602SMark Fasheh 	int ret;
334409cbfeafSKirill A. Shutemov 	int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
3345f4414602SMark Fasheh 
3346f4414602SMark Fasheh 	cmp->num_pages = num_pages;
3347f4414602SMark Fasheh 
334867b07bd4STimofey Titovets 	ret = gather_extent_pages(src, cmp->src_pages, num_pages, loff);
3349f4414602SMark Fasheh 	if (ret)
3350f4414602SMark Fasheh 		goto out;
3351f4414602SMark Fasheh 
335267b07bd4STimofey Titovets 	ret = gather_extent_pages(dst, cmp->dst_pages, num_pages, dst_loff);
3353f4414602SMark Fasheh 
3354f4414602SMark Fasheh out:
3355f4414602SMark Fasheh 	if (ret)
3356f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
335778ad4ce0SNaohiro Aota 	return ret;
3358416161dbSMark Fasheh }
3359416161dbSMark Fasheh 
33601a287cfeSDavid Sterba static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
3361416161dbSMark Fasheh {
3362416161dbSMark Fasheh 	int ret = 0;
3363f4414602SMark Fasheh 	int i;
3364416161dbSMark Fasheh 	struct page *src_page, *dst_page;
336509cbfeafSKirill A. Shutemov 	unsigned int cmp_len = PAGE_SIZE;
3366416161dbSMark Fasheh 	void *addr, *dst_addr;
3367416161dbSMark Fasheh 
3368f4414602SMark Fasheh 	i = 0;
3369416161dbSMark Fasheh 	while (len) {
337009cbfeafSKirill A. Shutemov 		if (len < PAGE_SIZE)
3371416161dbSMark Fasheh 			cmp_len = len;
3372416161dbSMark Fasheh 
3373f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
3374f4414602SMark Fasheh 
3375f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
3376f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
3377e0bd70c6SFilipe Manana 		ASSERT(PageLocked(src_page));
3378e0bd70c6SFilipe Manana 		ASSERT(PageLocked(dst_page));
3379f4414602SMark Fasheh 
3380416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
3381416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
3382416161dbSMark Fasheh 
3383416161dbSMark Fasheh 		flush_dcache_page(src_page);
3384416161dbSMark Fasheh 		flush_dcache_page(dst_page);
3385416161dbSMark Fasheh 
3386416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
33872b3909f8SDarrick J. Wong 			ret = -EBADE;
3388416161dbSMark Fasheh 
3389416161dbSMark Fasheh 		kunmap_atomic(addr);
3390416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
3391416161dbSMark Fasheh 
3392416161dbSMark Fasheh 		if (ret)
3393416161dbSMark Fasheh 			break;
3394416161dbSMark Fasheh 
3395416161dbSMark Fasheh 		len -= cmp_len;
3396f4414602SMark Fasheh 		i++;
3397416161dbSMark Fasheh 	}
3398416161dbSMark Fasheh 
3399416161dbSMark Fasheh 	return ret;
3400416161dbSMark Fasheh }
3401416161dbSMark Fasheh 
3402e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3403e1d227a4SMark Fasheh 				     u64 olen)
3404416161dbSMark Fasheh {
3405e1d227a4SMark Fasheh 	u64 len = *plen;
3406416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3407416161dbSMark Fasheh 
3408e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
3409416161dbSMark Fasheh 		return -EINVAL;
3410e1d227a4SMark Fasheh 
3411e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
3412e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
3413e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
3414e1d227a4SMark Fasheh 
3415416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
3416416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3417416161dbSMark Fasheh 		return -EINVAL;
3418416161dbSMark Fasheh 
3419416161dbSMark Fasheh 	return 0;
3420416161dbSMark Fasheh }
3421416161dbSMark Fasheh 
34223973909dSTimofey Titovets static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 olen,
342367b07bd4STimofey Titovets 				   struct inode *dst, u64 dst_loff,
342467b07bd4STimofey Titovets 				   struct cmp_pages *cmp)
3425416161dbSMark Fasheh {
3426416161dbSMark Fasheh 	int ret;
3427e1d227a4SMark Fasheh 	u64 len = olen;
3428fc4badd9SOmar Sandoval 	bool same_inode = (src == dst);
34290efa9f48SMark Fasheh 	u64 same_lock_start = 0;
34300efa9f48SMark Fasheh 	u64 same_lock_len = 0;
3431416161dbSMark Fasheh 
34320efa9f48SMark Fasheh 	ret = extent_same_check_offsets(src, loff, &len, olen);
34330efa9f48SMark Fasheh 	if (ret)
34343973909dSTimofey Titovets 		return ret;
3435fc4badd9SOmar Sandoval 
3436fc4badd9SOmar Sandoval 	ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3437f4dfe687SFilipe Manana 	if (ret)
34383973909dSTimofey Titovets 		return ret;
34390efa9f48SMark Fasheh 
3440fc4badd9SOmar Sandoval 	if (same_inode) {
34410efa9f48SMark Fasheh 		/*
34420efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
34430efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
34440efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
34450efa9f48SMark Fasheh 		 *
34460efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
34470efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
34480efa9f48SMark Fasheh 		 * reject the request.
34490efa9f48SMark Fasheh 		 *
34500efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
34510efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
34520efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
34530efa9f48SMark Fasheh 		 * i_size.
34540efa9f48SMark Fasheh 		 */
34553973909dSTimofey Titovets 		if (len != olen)
34563973909dSTimofey Titovets 			return -EINVAL;
34570efa9f48SMark Fasheh 
34580efa9f48SMark Fasheh 		/* Check for overlapping ranges */
34593973909dSTimofey Titovets 		if (dst_loff + len > loff && dst_loff < loff + len)
34603973909dSTimofey Titovets 			return -EINVAL;
34610efa9f48SMark Fasheh 
34620efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
34630efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
34640efa9f48SMark Fasheh 	}
3465416161dbSMark Fasheh 
3466e0bd70c6SFilipe Manana again:
346767b07bd4STimofey Titovets 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, cmp);
3468f4414602SMark Fasheh 	if (ret)
34693973909dSTimofey Titovets 		return ret;
3470f4414602SMark Fasheh 
34710efa9f48SMark Fasheh 	if (same_inode)
3472e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, same_lock_start, same_lock_len,
3473e0bd70c6SFilipe Manana 					false);
34740efa9f48SMark Fasheh 	else
3475e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3476e0bd70c6SFilipe Manana 					       false);
3477e0bd70c6SFilipe Manana 	/*
3478e0bd70c6SFilipe Manana 	 * If one of the inodes has dirty pages in the respective range or
3479e0bd70c6SFilipe Manana 	 * ordered extents, we need to flush dellaloc and wait for all ordered
3480e0bd70c6SFilipe Manana 	 * extents in the range. We must unlock the pages and the ranges in the
3481e0bd70c6SFilipe Manana 	 * io trees to avoid deadlocks when flushing delalloc (requires locking
3482e0bd70c6SFilipe Manana 	 * pages) and when waiting for ordered extents to complete (they require
3483e0bd70c6SFilipe Manana 	 * range locking).
3484e0bd70c6SFilipe Manana 	 */
3485e0bd70c6SFilipe Manana 	if (ret == -EAGAIN) {
3486e0bd70c6SFilipe Manana 		/*
3487e0bd70c6SFilipe Manana 		 * Ranges in the io trees already unlocked. Now unlock all
3488e0bd70c6SFilipe Manana 		 * pages before waiting for all IO to complete.
3489e0bd70c6SFilipe Manana 		 */
349067b07bd4STimofey Titovets 		btrfs_cmp_data_free(cmp);
3491e0bd70c6SFilipe Manana 		if (same_inode) {
3492e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, same_lock_start,
3493e0bd70c6SFilipe Manana 						 same_lock_len);
3494e0bd70c6SFilipe Manana 		} else {
3495e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, loff, len);
3496e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(dst, dst_loff, len);
3497e0bd70c6SFilipe Manana 		}
3498e0bd70c6SFilipe Manana 		goto again;
3499e0bd70c6SFilipe Manana 	}
3500e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3501e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3502e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
350367b07bd4STimofey Titovets 		btrfs_cmp_data_free(cmp);
3504e0bd70c6SFilipe Manana 		return ret;
3505e0bd70c6SFilipe Manana 	}
3506f4414602SMark Fasheh 
3507207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
350867b07bd4STimofey Titovets 	ret = btrfs_cmp_data(olen, cmp);
3509416161dbSMark Fasheh 	if (ret == 0)
35101c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3511416161dbSMark Fasheh 
35120efa9f48SMark Fasheh 	if (same_inode)
35130efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
35140efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
35150efa9f48SMark Fasheh 	else
3516f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3517f4414602SMark Fasheh 
351867b07bd4STimofey Titovets 	btrfs_cmp_data_free(cmp);
35193973909dSTimofey Titovets 
35203973909dSTimofey Titovets 	return ret;
35213973909dSTimofey Titovets }
35223973909dSTimofey Titovets 
3523b6728768STimofey Titovets #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3524b6728768STimofey Titovets 
35253973909dSTimofey Titovets static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
35263973909dSTimofey Titovets 			     struct inode *dst, u64 dst_loff)
35273973909dSTimofey Titovets {
35283973909dSTimofey Titovets 	int ret;
352967b07bd4STimofey Titovets 	struct cmp_pages cmp;
353067b07bd4STimofey Titovets 	int num_pages = PAGE_ALIGN(BTRFS_MAX_DEDUPE_LEN) >> PAGE_SHIFT;
35313973909dSTimofey Titovets 	bool same_inode = (src == dst);
3532b6728768STimofey Titovets 	u64 i, tail_len, chunk_count;
35333973909dSTimofey Titovets 
35343973909dSTimofey Titovets 	if (olen == 0)
35353973909dSTimofey Titovets 		return 0;
35363973909dSTimofey Titovets 
35373973909dSTimofey Titovets 	if (same_inode)
35383973909dSTimofey Titovets 		inode_lock(src);
35393973909dSTimofey Titovets 	else
35403973909dSTimofey Titovets 		btrfs_double_inode_lock(src, dst);
35413973909dSTimofey Titovets 
35423973909dSTimofey Titovets 	/* don't make the dst file partly checksummed */
35433973909dSTimofey Titovets 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
35443973909dSTimofey Titovets 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
35453973909dSTimofey Titovets 		ret = -EINVAL;
35463973909dSTimofey Titovets 		goto out_unlock;
35473973909dSTimofey Titovets 	}
35483973909dSTimofey Titovets 
3549b6728768STimofey Titovets 	tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3550b6728768STimofey Titovets 	chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
355167b07bd4STimofey Titovets 	if (chunk_count == 0)
355267b07bd4STimofey Titovets 		num_pages = PAGE_ALIGN(tail_len) >> PAGE_SHIFT;
355367b07bd4STimofey Titovets 
355467b07bd4STimofey Titovets 	/*
355567b07bd4STimofey Titovets 	 * If deduping ranges in the same inode, locking rules make it
355667b07bd4STimofey Titovets 	 * mandatory to always lock pages in ascending order to avoid deadlocks
355767b07bd4STimofey Titovets 	 * with concurrent tasks (such as starting writeback/delalloc).
355867b07bd4STimofey Titovets 	 */
355967b07bd4STimofey Titovets 	if (same_inode && dst_loff < loff)
356067b07bd4STimofey Titovets 		swap(loff, dst_loff);
356167b07bd4STimofey Titovets 
356267b07bd4STimofey Titovets 	/*
356367b07bd4STimofey Titovets 	 * We must gather up all the pages before we initiate our extent
356467b07bd4STimofey Titovets 	 * locking. We use an array for the page pointers. Size of the array is
356567b07bd4STimofey Titovets 	 * bounded by len, which is in turn bounded by BTRFS_MAX_DEDUPE_LEN.
356667b07bd4STimofey Titovets 	 */
3567bf5091c8SDavid Sterba 	cmp.src_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3568bf5091c8SDavid Sterba 				       GFP_KERNEL | __GFP_ZERO);
3569bf5091c8SDavid Sterba 	cmp.dst_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3570bf5091c8SDavid Sterba 				       GFP_KERNEL | __GFP_ZERO);
357167b07bd4STimofey Titovets 	if (!cmp.src_pages || !cmp.dst_pages) {
3572bf5091c8SDavid Sterba 		ret = -ENOMEM;
3573bf5091c8SDavid Sterba 		goto out_free;
357467b07bd4STimofey Titovets 	}
3575b6728768STimofey Titovets 
3576b6728768STimofey Titovets 	for (i = 0; i < chunk_count; i++) {
3577b6728768STimofey Titovets 		ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
357867b07bd4STimofey Titovets 					      dst, dst_loff, &cmp);
3579b6728768STimofey Titovets 		if (ret)
3580b6728768STimofey Titovets 			goto out_unlock;
3581b6728768STimofey Titovets 
3582b6728768STimofey Titovets 		loff += BTRFS_MAX_DEDUPE_LEN;
3583b6728768STimofey Titovets 		dst_loff += BTRFS_MAX_DEDUPE_LEN;
3584b6728768STimofey Titovets 	}
3585b6728768STimofey Titovets 
3586b6728768STimofey Titovets 	if (tail_len > 0)
358767b07bd4STimofey Titovets 		ret = btrfs_extent_same_range(src, loff, tail_len, dst,
358867b07bd4STimofey Titovets 					      dst_loff, &cmp);
35893973909dSTimofey Titovets 
3590416161dbSMark Fasheh out_unlock:
35910efa9f48SMark Fasheh 	if (same_inode)
35925955102cSAl Viro 		inode_unlock(src);
35930efa9f48SMark Fasheh 	else
3594f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3595416161dbSMark Fasheh 
3596bf5091c8SDavid Sterba out_free:
3597bf5091c8SDavid Sterba 	kvfree(cmp.src_pages);
3598bf5091c8SDavid Sterba 	kvfree(cmp.dst_pages);
359967b07bd4STimofey Titovets 
3600416161dbSMark Fasheh 	return ret;
3601416161dbSMark Fasheh }
3602416161dbSMark Fasheh 
36032b3909f8SDarrick J. Wong ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
36042b3909f8SDarrick J. Wong 				struct file *dst_file, u64 dst_loff)
3605416161dbSMark Fasheh {
36062b3909f8SDarrick J. Wong 	struct inode *src = file_inode(src_file);
36072b3909f8SDarrick J. Wong 	struct inode *dst = file_inode(dst_file);
3608416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
36092b3909f8SDarrick J. Wong 	ssize_t res;
3610416161dbSMark Fasheh 
361109cbfeafSKirill A. Shutemov 	if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3612416161dbSMark Fasheh 		/*
3613416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3614416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3615416161dbSMark Fasheh 		 * this situation without an update.
3616416161dbSMark Fasheh 		 */
36172b3909f8SDarrick J. Wong 		return -EINVAL;
3618416161dbSMark Fasheh 	}
3619416161dbSMark Fasheh 
36202b3909f8SDarrick J. Wong 	res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
36212b3909f8SDarrick J. Wong 	if (res)
36222b3909f8SDarrick J. Wong 		return res;
36232b3909f8SDarrick J. Wong 	return olen;
3624416161dbSMark Fasheh }
3625416161dbSMark Fasheh 
3626f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3627f82a9901SFilipe Manana 				     struct inode *inode,
3628f82a9901SFilipe Manana 				     u64 endoff,
3629f82a9901SFilipe Manana 				     const u64 destoff,
36301c919a5eSMark Fasheh 				     const u64 olen,
36311c919a5eSMark Fasheh 				     int no_time_update)
3632f82a9901SFilipe Manana {
3633f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3634f82a9901SFilipe Manana 	int ret;
3635f82a9901SFilipe Manana 
3636f82a9901SFilipe Manana 	inode_inc_iversion(inode);
36371c919a5eSMark Fasheh 	if (!no_time_update)
3638c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3639f82a9901SFilipe Manana 	/*
3640f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3641f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3642f82a9901SFilipe Manana 	 */
3643f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3644f82a9901SFilipe Manana 		endoff = destoff + olen;
3645f82a9901SFilipe Manana 	if (endoff > inode->i_size)
36466ef06d27SNikolay Borisov 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3647f82a9901SFilipe Manana 
3648f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3649f82a9901SFilipe Manana 	if (ret) {
365066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
36513a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3652f82a9901SFilipe Manana 		goto out;
3653f82a9901SFilipe Manana 	}
36543a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
3655f82a9901SFilipe Manana out:
3656f82a9901SFilipe Manana 	return ret;
3657f82a9901SFilipe Manana }
3658f82a9901SFilipe Manana 
3659a2f392e4SNikolay Borisov static void clone_update_extent_map(struct btrfs_inode *inode,
36607ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
36617ffbb598SFilipe Manana 				    const struct btrfs_path *path,
36627ffbb598SFilipe Manana 				    const u64 hole_offset,
36637ffbb598SFilipe Manana 				    const u64 hole_len)
36647ffbb598SFilipe Manana {
3665a2f392e4SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
36667ffbb598SFilipe Manana 	struct extent_map *em;
36677ffbb598SFilipe Manana 	int ret;
36687ffbb598SFilipe Manana 
36697ffbb598SFilipe Manana 	em = alloc_extent_map();
36707ffbb598SFilipe Manana 	if (!em) {
3671a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
36727ffbb598SFilipe Manana 		return;
36737ffbb598SFilipe Manana 	}
36747ffbb598SFilipe Manana 
367514f59796SFilipe Manana 	if (path) {
367614f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
367714f59796SFilipe Manana 
367814f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
367914f59796SFilipe Manana 				    struct btrfs_file_extent_item);
3680a2f392e4SNikolay Borisov 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
36817ffbb598SFilipe Manana 		em->generation = -1;
36827ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
36837ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
36847ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3685a2f392e4SNikolay Borisov 					&inode->runtime_flags);
36867ffbb598SFilipe Manana 	} else {
36877ffbb598SFilipe Manana 		em->start = hole_offset;
36887ffbb598SFilipe Manana 		em->len = hole_len;
36897ffbb598SFilipe Manana 		em->ram_bytes = em->len;
36907ffbb598SFilipe Manana 		em->orig_start = hole_offset;
36917ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
36927ffbb598SFilipe Manana 		em->block_len = 0;
36937ffbb598SFilipe Manana 		em->orig_block_len = 0;
36947ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
36957ffbb598SFilipe Manana 		em->generation = trans->transid;
36967ffbb598SFilipe Manana 	}
36977ffbb598SFilipe Manana 
36987ffbb598SFilipe Manana 	while (1) {
36997ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
37007ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
37017ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
37027ffbb598SFilipe Manana 		if (ret != -EEXIST) {
37037ffbb598SFilipe Manana 			free_extent_map(em);
37047ffbb598SFilipe Manana 			break;
37057ffbb598SFilipe Manana 		}
3706a2f392e4SNikolay Borisov 		btrfs_drop_extent_cache(inode, em->start,
37077ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
37087ffbb598SFilipe Manana 	}
37097ffbb598SFilipe Manana 
3710ee39b432SDavid Sterba 	if (ret)
3711a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
37127ffbb598SFilipe Manana }
37137ffbb598SFilipe Manana 
37148039d87dSFilipe Manana /*
37158039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
37168039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
37178039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
37188039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
37198039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
37208039d87dSFilipe Manana  *
37218039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
37228039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
37238039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
37248039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
37258039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
37268039d87dSFilipe Manana  * i_mutex, which we are holding here).
37278039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
37288039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
37298039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
37308039d87dSFilipe Manana  *
37318039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
37328039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
37338039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
37348039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
37358039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
37368039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
37378039d87dSFilipe Manana  * the former.
37388039d87dSFilipe Manana  */
37394a0ab9d7SDavid Sterba static int clone_copy_inline_extent(struct inode *dst,
37408039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
37418039d87dSFilipe Manana 				    struct btrfs_path *path,
37428039d87dSFilipe Manana 				    struct btrfs_key *new_key,
37438039d87dSFilipe Manana 				    const u64 drop_start,
37448039d87dSFilipe Manana 				    const u64 datal,
37458039d87dSFilipe Manana 				    const u64 skip,
37468039d87dSFilipe Manana 				    const u64 size,
37478039d87dSFilipe Manana 				    char *inline_data)
37488039d87dSFilipe Manana {
37490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
37508039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
37518039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
37520b246afaSJeff Mahoney 				      fs_info->sectorsize);
37538039d87dSFilipe Manana 	int ret;
37548039d87dSFilipe Manana 	struct btrfs_key key;
37558039d87dSFilipe Manana 
37568039d87dSFilipe Manana 	if (new_key->offset > 0)
37578039d87dSFilipe Manana 		return -EOPNOTSUPP;
37588039d87dSFilipe Manana 
37594a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(dst));
37608039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
37618039d87dSFilipe Manana 	key.offset = 0;
37628039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
37638039d87dSFilipe Manana 	if (ret < 0) {
37648039d87dSFilipe Manana 		return ret;
37658039d87dSFilipe Manana 	} else if (ret > 0) {
37668039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
37678039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
37688039d87dSFilipe Manana 			if (ret < 0)
37698039d87dSFilipe Manana 				return ret;
37708039d87dSFilipe Manana 			else if (ret > 0)
37718039d87dSFilipe Manana 				goto copy_inline_extent;
37728039d87dSFilipe Manana 		}
37738039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
37744a0cc7caSNikolay Borisov 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
37758039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
37768039d87dSFilipe Manana 			ASSERT(key.offset > 0);
37778039d87dSFilipe Manana 			return -EOPNOTSUPP;
37788039d87dSFilipe Manana 		}
37798039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
37808039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
37818039d87dSFilipe Manana 		u64 ext_len;
37828039d87dSFilipe Manana 
37838039d87dSFilipe Manana 		/*
37848039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
37858039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
37868039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
37878039d87dSFilipe Manana 		 */
37888039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
37898039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
37908039d87dSFilipe Manana 		/*
37918039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
37928039d87dSFilipe Manana 		 * following it.
37938039d87dSFilipe Manana 		 */
37948039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
37958039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
37968039d87dSFilipe Manana 			goto copy_inline_extent;
37978039d87dSFilipe Manana 
37988039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
37998039d87dSFilipe Manana 		if (ext_len > aligned_end)
38008039d87dSFilipe Manana 			return -EOPNOTSUPP;
38018039d87dSFilipe Manana 
38028039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
38038039d87dSFilipe Manana 		if (ret < 0) {
38048039d87dSFilipe Manana 			return ret;
38058039d87dSFilipe Manana 		} else if (ret == 0) {
38068039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
38078039d87dSFilipe Manana 					      path->slots[0]);
38084a0cc7caSNikolay Borisov 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
38098039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
38108039d87dSFilipe Manana 				return -EOPNOTSUPP;
38118039d87dSFilipe Manana 		}
38128039d87dSFilipe Manana 	}
38138039d87dSFilipe Manana 
38148039d87dSFilipe Manana copy_inline_extent:
38158039d87dSFilipe Manana 	/*
38168039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
38178039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
38188039d87dSFilipe Manana 	 */
38198039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
38208039d87dSFilipe Manana 		/*
38218039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
38228039d87dSFilipe Manana 		 * This would require copying the data from the source inline
38238039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
38248039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
38258039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
38268039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
38278039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
38288039d87dSFilipe Manana 		 * inline extent).
38298039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
38308039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
38318039d87dSFilipe Manana 		 */
38328039d87dSFilipe Manana 		return -EOPNOTSUPP;
38338039d87dSFilipe Manana 	}
38348039d87dSFilipe Manana 
38358039d87dSFilipe Manana 	btrfs_release_path(path);
38368039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
38378039d87dSFilipe Manana 	if (ret)
38388039d87dSFilipe Manana 		return ret;
38398039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
38408039d87dSFilipe Manana 	if (ret)
38418039d87dSFilipe Manana 		return ret;
38428039d87dSFilipe Manana 
38438039d87dSFilipe Manana 	if (skip) {
38448039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
38458039d87dSFilipe Manana 
38468039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
38478039d87dSFilipe Manana 	}
38488039d87dSFilipe Manana 
38498039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
38508039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
38518039d87dSFilipe Manana 						  path->slots[0]),
38528039d87dSFilipe Manana 			    size);
38538039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
38548039d87dSFilipe Manana 
38558039d87dSFilipe Manana 	return 0;
38568039d87dSFilipe Manana }
38578039d87dSFilipe Manana 
385832b7c687SMark Fasheh /**
385932b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
386032b7c687SMark Fasheh  *
386132b7c687SMark Fasheh  * @src: Inode to clone from
386232b7c687SMark Fasheh  * @inode: Inode to clone to
386332b7c687SMark Fasheh  * @off: Offset within source to start clone from
386432b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
38651c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
386632b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
38671c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
386832b7c687SMark Fasheh  */
386932b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3870f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
38711c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3872f46b5a66SChristoph Hellwig {
38730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3874f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
387532b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3876f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
387732b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
387832b7c687SMark Fasheh 	char *buf = NULL;
3879ae01a0abSYan Zheng 	struct btrfs_key key;
3880f46b5a66SChristoph Hellwig 	u32 nritems;
3881f46b5a66SChristoph Hellwig 	int slot;
3882ae01a0abSYan Zheng 	int ret;
3883f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3884f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3885ae01a0abSYan Zheng 
3886ae01a0abSYan Zheng 	ret = -ENOMEM;
3887752ade68SMichal Hocko 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3888ae01a0abSYan Zheng 	if (!buf)
388932b7c687SMark Fasheh 		return ret;
3890ae01a0abSYan Zheng 
3891ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3892ae01a0abSYan Zheng 	if (!path) {
389315351955SDavid Sterba 		kvfree(buf);
389432b7c687SMark Fasheh 		return ret;
3895ae01a0abSYan Zheng 	}
389632b7c687SMark Fasheh 
3897e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3898c5c9cd4dSSage Weil 	/* clone data */
38994a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(src));
3900ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
39012c463823SFilipe Manana 	key.offset = off;
3902f46b5a66SChristoph Hellwig 
3903f46b5a66SChristoph Hellwig 	while (1) {
3904de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3905df858e76SFilipe Manana 
3906f46b5a66SChristoph Hellwig 		/*
3907f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3908f46b5a66SChristoph Hellwig 		 * tree.
3909f46b5a66SChristoph Hellwig 		 */
3910e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3911362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3912362a20c5SDavid Sterba 				0, 0);
3913f46b5a66SChristoph Hellwig 		if (ret < 0)
3914f46b5a66SChristoph Hellwig 			goto out;
39152c463823SFilipe Manana 		/*
39162c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
39172c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
39182c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
39192c463823SFilipe Manana 		 */
39202c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
39212c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
39222c463823SFilipe Manana 					      path->slots[0] - 1);
39232c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
39242c463823SFilipe Manana 				path->slots[0]--;
39252c463823SFilipe Manana 		}
3926f46b5a66SChristoph Hellwig 
3927ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3928e4355f34SFilipe David Borba Manana process_slot:
3929ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3930362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3931f46b5a66SChristoph Hellwig 			if (ret < 0)
3932f46b5a66SChristoph Hellwig 				goto out;
3933f46b5a66SChristoph Hellwig 			if (ret > 0)
3934f46b5a66SChristoph Hellwig 				break;
3935ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3936f46b5a66SChristoph Hellwig 		}
3937f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3938f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3939f46b5a66SChristoph Hellwig 
3940ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3941962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
39424a0cc7caSNikolay Borisov 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3943f46b5a66SChristoph Hellwig 			break;
3944f46b5a66SChristoph Hellwig 
3945962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3946c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3947c5c9cd4dSSage Weil 			int type;
394831840ae1SZheng Yan 			u32 size;
394931840ae1SZheng Yan 			struct btrfs_key new_key;
3950c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3951c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3952c5c9cd4dSSage Weil 			u8 comp;
3953f82a9901SFilipe Manana 			u64 drop_start;
395431840ae1SZheng Yan 
3955c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3956c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3957c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3958c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3959c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3960c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3961d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3962d397712bSChris Mason 								      extent);
3963d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3964d397712bSChris Mason 								 extent);
3965c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3966d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3967d397712bSChris Mason 								    extent);
3968c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3969c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3970c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3971c5c9cd4dSSage Weil 								    extent);
3972c5c9cd4dSSage Weil 			}
397331840ae1SZheng Yan 
39742c463823SFilipe Manana 			/*
39752c463823SFilipe Manana 			 * The first search might have left us at an extent
39762c463823SFilipe Manana 			 * item that ends before our target range's start, can
39772c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
39782c463823SFilipe Manana 			 */
39792c463823SFilipe Manana 			if (key.offset + datal <= off) {
3980e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3981e4355f34SFilipe David Borba Manana 				goto process_slot;
39822c463823SFilipe Manana 			} else if (key.offset >= off + len) {
39832c463823SFilipe Manana 				break;
3984e4355f34SFilipe David Borba Manana 			}
3985df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3986e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3987e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3988e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3989e4355f34SFilipe David Borba Manana 					   size);
3990e4355f34SFilipe David Borba Manana 
3991e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3992e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3993c5c9cd4dSSage Weil 
399431840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
39954a0cc7caSNikolay Borisov 			new_key.objectid = btrfs_ino(BTRFS_I(inode));
39964d728ec7SLi Zefan 			if (off <= key.offset)
3997c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
39984d728ec7SLi Zefan 			else
39994d728ec7SLi Zefan 				new_key.offset = destoff;
4000c5c9cd4dSSage Weil 
4001b6f3409bSSage Weil 			/*
4002f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
4003f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
4004f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
4005f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
4006f82a9901SFilipe Manana 			 * partially overlaps it).
4007f82a9901SFilipe Manana 			 */
4008f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
4009f82a9901SFilipe Manana 				drop_start = last_dest_end;
4010f82a9901SFilipe Manana 			else
4011f82a9901SFilipe Manana 				drop_start = new_key.offset;
4012f82a9901SFilipe Manana 
4013f82a9901SFilipe Manana 			/*
4014b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
4015b6f3409bSSage Weil 			 * 1 - add new extent
4016b6f3409bSSage Weil 			 * 1 - inode update
4017b6f3409bSSage Weil 			 */
4018b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
4019a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
4020a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
4021a22285a6SYan, Zheng 				goto out;
4022a22285a6SYan, Zheng 			}
4023a22285a6SYan, Zheng 
4024c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
4025c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
4026d72c0842SLi Zefan 				/*
4027d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
4028d72c0842SLi Zefan 				 * | ------------- extent ------------- |
4029d72c0842SLi Zefan 				 */
4030d72c0842SLi Zefan 
403193915584SAntonio Ospite 				/* subtract range b */
4032d72c0842SLi Zefan 				if (key.offset + datal > off + len)
4033d72c0842SLi Zefan 					datal = off + len - key.offset;
4034d72c0842SLi Zefan 
403593915584SAntonio Ospite 				/* subtract range a */
4036a22285a6SYan, Zheng 				if (off > key.offset) {
4037a22285a6SYan, Zheng 					datao += off - key.offset;
4038a22285a6SYan, Zheng 					datal -= off - key.offset;
4039a22285a6SYan, Zheng 				}
4040a22285a6SYan, Zheng 
40415dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
4042f82a9901SFilipe Manana 							 drop_start,
4043a22285a6SYan, Zheng 							 new_key.offset + datal,
40442671485dSJosef Bacik 							 1);
404579787eaaSJeff Mahoney 				if (ret) {
40463f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
404700fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
404866642832SJeff Mahoney 									ret);
40493a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
405079787eaaSJeff Mahoney 					goto out;
405179787eaaSJeff Mahoney 				}
4052a22285a6SYan, Zheng 
405331840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
405431840ae1SZheng Yan 							      &new_key, size);
405579787eaaSJeff Mahoney 				if (ret) {
405666642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
40573a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
405879787eaaSJeff Mahoney 					goto out;
405979787eaaSJeff Mahoney 				}
406031840ae1SZheng Yan 
406131840ae1SZheng Yan 				leaf = path->nodes[0];
406231840ae1SZheng Yan 				slot = path->slots[0];
406331840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
406431840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
406531840ae1SZheng Yan 					    size);
4066ae01a0abSYan Zheng 
4067f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
4068f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
4069c5c9cd4dSSage Weil 
4070c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
4071c5c9cd4dSSage Weil 				if (!disko)
4072c5c9cd4dSSage Weil 					datao = 0;
4073c5c9cd4dSSage Weil 
4074c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
4075c5c9cd4dSSage Weil 							     datao);
4076c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
4077c5c9cd4dSSage Weil 								datal);
4078fcebe456SJosef Bacik 
4079c5c9cd4dSSage Weil 				if (disko) {
4080c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
40812ff7e61eSJeff Mahoney 					ret = btrfs_inc_extent_ref(trans,
408284f7d8e6SJosef Bacik 							root,
40835d4f98a2SYan Zheng 							disko, diskl, 0,
4084f46b5a66SChristoph Hellwig 							root->root_key.objectid,
40854a0cc7caSNikolay Borisov 							btrfs_ino(BTRFS_I(inode)),
4086b06c4bf5SFilipe Manana 							new_key.offset - datao);
408779787eaaSJeff Mahoney 					if (ret) {
408879787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
408979787eaaSJeff Mahoney 									ret);
40903a45bb20SJeff Mahoney 						btrfs_end_transaction(trans);
409179787eaaSJeff Mahoney 						goto out;
409279787eaaSJeff Mahoney 
409379787eaaSJeff Mahoney 					}
4094f46b5a66SChristoph Hellwig 				}
4095c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
4096c5c9cd4dSSage Weil 				u64 skip = 0;
4097c5c9cd4dSSage Weil 				u64 trim = 0;
4098ed958762SFilipe Manana 
4099c5c9cd4dSSage Weil 				if (off > key.offset) {
4100c5c9cd4dSSage Weil 					skip = off - key.offset;
4101c5c9cd4dSSage Weil 					new_key.offset += skip;
410231840ae1SZheng Yan 				}
4103d397712bSChris Mason 
4104c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
4105c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
4106d397712bSChris Mason 
4107c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
4108c5c9cd4dSSage Weil 					ret = -EINVAL;
41093a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
4110c5c9cd4dSSage Weil 					goto out;
411131840ae1SZheng Yan 				}
4112c5c9cd4dSSage Weil 				size -= skip + trim;
4113c5c9cd4dSSage Weil 				datal -= skip + trim;
4114a22285a6SYan, Zheng 
41154a0ab9d7SDavid Sterba 				ret = clone_copy_inline_extent(inode,
41168039d87dSFilipe Manana 							       trans, path,
41178039d87dSFilipe Manana 							       &new_key,
4118f82a9901SFilipe Manana 							       drop_start,
41198039d87dSFilipe Manana 							       datal,
41208039d87dSFilipe Manana 							       skip, size, buf);
412179787eaaSJeff Mahoney 				if (ret) {
41223f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
41233a29bc09SChris Mason 						btrfs_abort_transaction(trans,
412479787eaaSJeff Mahoney 									ret);
41253a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
412679787eaaSJeff Mahoney 					goto out;
412779787eaaSJeff Mahoney 				}
4128c5c9cd4dSSage Weil 				leaf = path->nodes[0];
4129c5c9cd4dSSage Weil 				slot = path->slots[0];
4130c5c9cd4dSSage Weil 			}
4131c5c9cd4dSSage Weil 
41327ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
41337ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
4134a2f392e4SNikolay Borisov 				clone_update_extent_map(BTRFS_I(inode), trans,
413514f59796SFilipe Manana 						NULL, drop_start,
41367ffbb598SFilipe Manana 						new_key.offset - drop_start);
41377ffbb598SFilipe Manana 
4138a2f392e4SNikolay Borisov 			clone_update_extent_map(BTRFS_I(inode), trans,
4139a2f392e4SNikolay Borisov 					path, 0, 0);
41407ffbb598SFilipe Manana 
4141c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
4142b3b4aa74SDavid Sterba 			btrfs_release_path(path);
4143c5c9cd4dSSage Weil 
414462e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
41450b246afaSJeff Mahoney 					      fs_info->sectorsize);
4146f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
4147f82a9901SFilipe Manana 							last_dest_end,
41481c919a5eSMark Fasheh 							destoff, olen,
41491c919a5eSMark Fasheh 							no_time_update);
4150f82a9901SFilipe Manana 			if (ret)
415179787eaaSJeff Mahoney 				goto out;
41522c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
41532c463823SFilipe Manana 				break;
4154a22285a6SYan, Zheng 		}
4155b3b4aa74SDavid Sterba 		btrfs_release_path(path);
4156df858e76SFilipe Manana 		key.offset = next_key_min_offset;
415769ae5e44SWang Xiaoguang 
415869ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
415969ae5e44SWang Xiaoguang 			ret = -EINTR;
416069ae5e44SWang Xiaoguang 			goto out;
416169ae5e44SWang Xiaoguang 		}
4162ae01a0abSYan Zheng 	}
4163f46b5a66SChristoph Hellwig 	ret = 0;
416432b7c687SMark Fasheh 
4165f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
4166f82a9901SFilipe Manana 		/*
4167f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
4168f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
4169f82a9901SFilipe Manana 		 */
4170b3b4aa74SDavid Sterba 		btrfs_release_path(path);
4171f82a9901SFilipe Manana 
4172f82a9901SFilipe Manana 		/*
4173f82a9901SFilipe Manana 		 * 1 - remove extent(s)
4174f82a9901SFilipe Manana 		 * 1 - inode update
4175f82a9901SFilipe Manana 		 */
4176f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
4177f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
4178f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
4179f82a9901SFilipe Manana 			goto out;
4180f82a9901SFilipe Manana 		}
4181f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
4182f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
4183f82a9901SFilipe Manana 		if (ret) {
4184f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
418566642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
41863a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
4187f82a9901SFilipe Manana 			goto out;
4188f82a9901SFilipe Manana 		}
4189a2f392e4SNikolay Borisov 		clone_update_extent_map(BTRFS_I(inode), trans, NULL,
4190a2f392e4SNikolay Borisov 				last_dest_end,
419114f59796SFilipe Manana 				destoff + len - last_dest_end);
4192f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
41931c919a5eSMark Fasheh 						destoff, olen, no_time_update);
4194f82a9901SFilipe Manana 	}
4195f82a9901SFilipe Manana 
4196f46b5a66SChristoph Hellwig out:
419732b7c687SMark Fasheh 	btrfs_free_path(path);
419815351955SDavid Sterba 	kvfree(buf);
419932b7c687SMark Fasheh 	return ret;
420032b7c687SMark Fasheh }
420132b7c687SMark Fasheh 
42023db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
420332b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
420432b7c687SMark Fasheh {
420554563d41SAl Viro 	struct inode *inode = file_inode(file);
42063db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
42070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
420832b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
420932b7c687SMark Fasheh 	int ret;
421032b7c687SMark Fasheh 	u64 len = olen;
42110b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
42123db11b2eSZach Brown 	int same_inode = src == inode;
421332b7c687SMark Fasheh 
421432b7c687SMark Fasheh 	/*
421532b7c687SMark Fasheh 	 * TODO:
421632b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
421732b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
421832b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
421932b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
422000fdf13aSLiu Bo 	 *
422100fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
422200fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
422332b7c687SMark Fasheh 	 */
422432b7c687SMark Fasheh 
422532b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
422632b7c687SMark Fasheh 		return -EROFS;
422732b7c687SMark Fasheh 
42283db11b2eSZach Brown 	if (file_src->f_path.mnt != file->f_path.mnt ||
42293db11b2eSZach Brown 	    src->i_sb != inode->i_sb)
42303db11b2eSZach Brown 		return -EXDEV;
423132b7c687SMark Fasheh 
423232b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
42333db11b2eSZach Brown 		return -EISDIR;
423432b7c687SMark Fasheh 
423532b7c687SMark Fasheh 	if (!same_inode) {
4236293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
423732b7c687SMark Fasheh 	} else {
42385955102cSAl Viro 		inode_lock(src);
423932b7c687SMark Fasheh 	}
424032b7c687SMark Fasheh 
4241b5c40d59SOmar Sandoval 	/* don't make the dst file partly checksummed */
4242b5c40d59SOmar Sandoval 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
4243b5c40d59SOmar Sandoval 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
4244b5c40d59SOmar Sandoval 		ret = -EINVAL;
4245b5c40d59SOmar Sandoval 		goto out_unlock;
4246b5c40d59SOmar Sandoval 	}
4247b5c40d59SOmar Sandoval 
424832b7c687SMark Fasheh 	/* determine range to clone */
424932b7c687SMark Fasheh 	ret = -EINVAL;
425032b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
425132b7c687SMark Fasheh 		goto out_unlock;
425232b7c687SMark Fasheh 	if (len == 0)
425332b7c687SMark Fasheh 		olen = len = src->i_size - off;
425432b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
425532b7c687SMark Fasheh 	if (off + len == src->i_size)
425632b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
425732b7c687SMark Fasheh 
4258ccccf3d6SFilipe Manana 	if (len == 0) {
4259ccccf3d6SFilipe Manana 		ret = 0;
4260ccccf3d6SFilipe Manana 		goto out_unlock;
4261ccccf3d6SFilipe Manana 	}
4262ccccf3d6SFilipe Manana 
426332b7c687SMark Fasheh 	/* verify the end result is block aligned */
426432b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
426532b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
426632b7c687SMark Fasheh 		goto out_unlock;
426732b7c687SMark Fasheh 
426832b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
426932b7c687SMark Fasheh 	if (same_inode) {
427032b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
427132b7c687SMark Fasheh 			goto out_unlock;
427232b7c687SMark Fasheh 	}
427332b7c687SMark Fasheh 
427432b7c687SMark Fasheh 	if (destoff > inode->i_size) {
427532b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
427632b7c687SMark Fasheh 		if (ret)
427732b7c687SMark Fasheh 			goto out_unlock;
427832b7c687SMark Fasheh 	}
427932b7c687SMark Fasheh 
4280c125b8bfSFilipe Manana 	/*
4281c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
4282c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
4283c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
4284c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
4285c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
4286c125b8bfSFilipe Manana 	 */
4287c125b8bfSFilipe Manana 	if (same_inode) {
4288c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
4289c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
429032b7c687SMark Fasheh 
4291e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, lock_start, lock_len, true);
4292c125b8bfSFilipe Manana 	} else {
4293e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
4294e0bd70c6SFilipe Manana 					       true);
4295e0bd70c6SFilipe Manana 	}
4296e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
4297e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
4298e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
4299e0bd70c6SFilipe Manana 		goto out_unlock;
4300c125b8bfSFilipe Manana 	}
430132b7c687SMark Fasheh 
43021c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
430332b7c687SMark Fasheh 
4304c125b8bfSFilipe Manana 	if (same_inode) {
4305c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
4306c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
4307c125b8bfSFilipe Manana 
4308c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
4309c125b8bfSFilipe Manana 	} else {
4310293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
4311c125b8bfSFilipe Manana 	}
4312c125b8bfSFilipe Manana 	/*
4313c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
4314c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
4315c125b8bfSFilipe Manana 	 */
431665bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
431709cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
431809cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
4319f46b5a66SChristoph Hellwig out_unlock:
4320293a8489SMark Fasheh 	if (!same_inode)
4321293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
4322293a8489SMark Fasheh 	else
43235955102cSAl Viro 		inode_unlock(src);
43243db11b2eSZach Brown 	return ret;
43253db11b2eSZach Brown }
43263db11b2eSZach Brown 
432704b38d60SChristoph Hellwig int btrfs_clone_file_range(struct file *src_file, loff_t off,
432804b38d60SChristoph Hellwig 		struct file *dst_file, loff_t destoff, u64 len)
43293db11b2eSZach Brown {
433004b38d60SChristoph Hellwig 	return btrfs_clone_files(dst_file, src_file, off, len, destoff);
4331c5c9cd4dSSage Weil }
4332c5c9cd4dSSage Weil 
43336ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
43346ef5ed0dSJosef Bacik {
4335496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
43360b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
43376ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
43386ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
43396ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
43406ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
43416ef5ed0dSJosef Bacik 	struct btrfs_path *path;
43426ef5ed0dSJosef Bacik 	struct btrfs_key location;
43436ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
43446ef5ed0dSJosef Bacik 	u64 objectid = 0;
43456ef5ed0dSJosef Bacik 	u64 dir_id;
43463c04ce01SMiao Xie 	int ret;
43476ef5ed0dSJosef Bacik 
43486ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
43496ef5ed0dSJosef Bacik 		return -EPERM;
43506ef5ed0dSJosef Bacik 
43513c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
43523c04ce01SMiao Xie 	if (ret)
43533c04ce01SMiao Xie 		return ret;
43543c04ce01SMiao Xie 
43553c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
43563c04ce01SMiao Xie 		ret = -EFAULT;
43573c04ce01SMiao Xie 		goto out;
43583c04ce01SMiao Xie 	}
43596ef5ed0dSJosef Bacik 
43606ef5ed0dSJosef Bacik 	if (!objectid)
43611cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
43626ef5ed0dSJosef Bacik 
43636ef5ed0dSJosef Bacik 	location.objectid = objectid;
43646ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
43656ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
43666ef5ed0dSJosef Bacik 
43670b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
43683c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
43693c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
43703c04ce01SMiao Xie 		goto out;
43713c04ce01SMiao Xie 	}
43726d6d2829Ssatoru takeuchi 	if (!is_fstree(new_root->objectid)) {
43736d6d2829Ssatoru takeuchi 		ret = -ENOENT;
43746d6d2829Ssatoru takeuchi 		goto out;
43756d6d2829Ssatoru takeuchi 	}
43766ef5ed0dSJosef Bacik 
43776ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
43783c04ce01SMiao Xie 	if (!path) {
43793c04ce01SMiao Xie 		ret = -ENOMEM;
43803c04ce01SMiao Xie 		goto out;
43813c04ce01SMiao Xie 	}
43826ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
43836ef5ed0dSJosef Bacik 
43846ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
438598d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
43866ef5ed0dSJosef Bacik 		btrfs_free_path(path);
43873c04ce01SMiao Xie 		ret = PTR_ERR(trans);
43883c04ce01SMiao Xie 		goto out;
43896ef5ed0dSJosef Bacik 	}
43906ef5ed0dSJosef Bacik 
43910b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
43920b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
43936ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
4394cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
43956ef5ed0dSJosef Bacik 		btrfs_free_path(path);
43963a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
43970b246afaSJeff Mahoney 		btrfs_err(fs_info,
43985d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
43993c04ce01SMiao Xie 		ret = -ENOENT;
44003c04ce01SMiao Xie 		goto out;
44016ef5ed0dSJosef Bacik 	}
44026ef5ed0dSJosef Bacik 
44036ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
44046ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
44056ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
44066ef5ed0dSJosef Bacik 	btrfs_free_path(path);
44076ef5ed0dSJosef Bacik 
44080b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
44093a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
44103c04ce01SMiao Xie out:
44113c04ce01SMiao Xie 	mnt_drop_write_file(file);
44123c04ce01SMiao Xie 	return ret;
44136ef5ed0dSJosef Bacik }
44146ef5ed0dSJosef Bacik 
4415c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
4416bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
4417bf5fc093SJosef Bacik {
4418bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4419bf5fc093SJosef Bacik 
4420bf5fc093SJosef Bacik 	space->total_bytes = 0;
4421bf5fc093SJosef Bacik 	space->used_bytes = 0;
4422bf5fc093SJosef Bacik 	space->flags = 0;
4423bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4424bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4425bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4426bf5fc093SJosef Bacik 		space->used_bytes +=
4427bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4428bf5fc093SJosef Bacik 	}
4429bf5fc093SJosef Bacik }
4430bf5fc093SJosef Bacik 
44312ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
44322ff7e61eSJeff Mahoney 				   void __user *arg)
44331406e432SJosef Bacik {
44341406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
44351406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
44361406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
44377fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
443813f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
44391406e432SJosef Bacik 	struct btrfs_space_info *info;
4440315d8e98SColin Ian King 	static const u64 types[] = {
4441315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
4442bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
4443bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
4444315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4445315d8e98SColin Ian King 	};
4446bf5fc093SJosef Bacik 	int num_types = 4;
44477fde62bfSChris Mason 	int alloc_size;
44481406e432SJosef Bacik 	int ret = 0;
444951788b1bSDan Rosenberg 	u64 slot_count = 0;
4450bf5fc093SJosef Bacik 	int i, c;
44511406e432SJosef Bacik 
44521406e432SJosef Bacik 	if (copy_from_user(&space_args,
44531406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
44541406e432SJosef Bacik 			   sizeof(space_args)))
44551406e432SJosef Bacik 		return -EFAULT;
44561406e432SJosef Bacik 
4457bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4458bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4459bf5fc093SJosef Bacik 
4460bf5fc093SJosef Bacik 		info = NULL;
44617fde62bfSChris Mason 		rcu_read_lock();
44620b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4463bf5fc093SJosef Bacik 					list) {
4464bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4465bf5fc093SJosef Bacik 				info = tmp;
4466bf5fc093SJosef Bacik 				break;
4467bf5fc093SJosef Bacik 			}
4468bf5fc093SJosef Bacik 		}
44697fde62bfSChris Mason 		rcu_read_unlock();
44701406e432SJosef Bacik 
4471bf5fc093SJosef Bacik 		if (!info)
4472bf5fc093SJosef Bacik 			continue;
4473bf5fc093SJosef Bacik 
4474bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4475bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4476bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4477bf5fc093SJosef Bacik 				slot_count++;
4478bf5fc093SJosef Bacik 		}
4479bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4480bf5fc093SJosef Bacik 	}
4481bf5fc093SJosef Bacik 
448236523e95SDavid Sterba 	/*
448336523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
448436523e95SDavid Sterba 	 */
448536523e95SDavid Sterba 	slot_count++;
448636523e95SDavid Sterba 
44877fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
44887fde62bfSChris Mason 	if (space_args.space_slots == 0) {
44897fde62bfSChris Mason 		space_args.total_spaces = slot_count;
44907fde62bfSChris Mason 		goto out;
44917fde62bfSChris Mason 	}
4492bf5fc093SJosef Bacik 
449351788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4494bf5fc093SJosef Bacik 
44957fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4496bf5fc093SJosef Bacik 
44977fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
44987fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
44997fde62bfSChris Mason 	 */
450009cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
45017fde62bfSChris Mason 		return -ENOMEM;
45027fde62bfSChris Mason 
45037fde62bfSChris Mason 	space_args.total_spaces = 0;
45048d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
45057fde62bfSChris Mason 	if (!dest)
45067fde62bfSChris Mason 		return -ENOMEM;
45077fde62bfSChris Mason 	dest_orig = dest;
45087fde62bfSChris Mason 
45097fde62bfSChris Mason 	/* now we have a buffer to copy into */
4510bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4511bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4512bf5fc093SJosef Bacik 
451351788b1bSDan Rosenberg 		if (!slot_count)
451451788b1bSDan Rosenberg 			break;
451551788b1bSDan Rosenberg 
4516bf5fc093SJosef Bacik 		info = NULL;
45171406e432SJosef Bacik 		rcu_read_lock();
45180b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4519bf5fc093SJosef Bacik 					list) {
4520bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4521bf5fc093SJosef Bacik 				info = tmp;
45227fde62bfSChris Mason 				break;
4523bf5fc093SJosef Bacik 			}
4524bf5fc093SJosef Bacik 		}
4525bf5fc093SJosef Bacik 		rcu_read_unlock();
45267fde62bfSChris Mason 
4527bf5fc093SJosef Bacik 		if (!info)
4528bf5fc093SJosef Bacik 			continue;
4529bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4530bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4531bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
4532c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
4533c065f5b1SSu Yue 						     &space);
45347fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
45351406e432SJosef Bacik 				dest++;
45361406e432SJosef Bacik 				space_args.total_spaces++;
453751788b1bSDan Rosenberg 				slot_count--;
45381406e432SJosef Bacik 			}
453951788b1bSDan Rosenberg 			if (!slot_count)
454051788b1bSDan Rosenberg 				break;
4541bf5fc093SJosef Bacik 		}
4542bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4543bf5fc093SJosef Bacik 	}
45441406e432SJosef Bacik 
454536523e95SDavid Sterba 	/*
454636523e95SDavid Sterba 	 * Add global block reserve
454736523e95SDavid Sterba 	 */
454836523e95SDavid Sterba 	if (slot_count) {
45490b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
455036523e95SDavid Sterba 
455136523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
455236523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
455336523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
455436523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
455536523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
455636523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
455736523e95SDavid Sterba 		space_args.total_spaces++;
455836523e95SDavid Sterba 	}
455936523e95SDavid Sterba 
45602eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
45617fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
45627fde62bfSChris Mason 
45637fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
45647fde62bfSChris Mason 		ret = -EFAULT;
45657fde62bfSChris Mason 
45667fde62bfSChris Mason 	kfree(dest_orig);
45677fde62bfSChris Mason out:
45687fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
45691406e432SJosef Bacik 		ret = -EFAULT;
45701406e432SJosef Bacik 
45711406e432SJosef Bacik 	return ret;
45721406e432SJosef Bacik }
45731406e432SJosef Bacik 
45749a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
45759a8c28beSMiao Xie 					    void __user *argp)
457646204592SSage Weil {
457746204592SSage Weil 	struct btrfs_trans_handle *trans;
457846204592SSage Weil 	u64 transid;
4579db5b493aSTsutomu Itoh 	int ret;
458046204592SSage Weil 
4581d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4582ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4583ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
458498d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4585ff7c1d33SMiao Xie 
4586ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4587ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4588ff7c1d33SMiao Xie 		goto out;
4589ff7c1d33SMiao Xie 	}
459046204592SSage Weil 	transid = trans->transid;
45913a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction_async(trans, 0);
45928b2b2d3cSTsutomu Itoh 	if (ret) {
45933a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
4594db5b493aSTsutomu Itoh 		return ret;
45958b2b2d3cSTsutomu Itoh 	}
4596ff7c1d33SMiao Xie out:
459746204592SSage Weil 	if (argp)
459846204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
459946204592SSage Weil 			return -EFAULT;
460046204592SSage Weil 	return 0;
460146204592SSage Weil }
460246204592SSage Weil 
46032ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
46049a8c28beSMiao Xie 					   void __user *argp)
460546204592SSage Weil {
460646204592SSage Weil 	u64 transid;
460746204592SSage Weil 
460846204592SSage Weil 	if (argp) {
460946204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
461046204592SSage Weil 			return -EFAULT;
461146204592SSage Weil 	} else {
461246204592SSage Weil 		transid = 0;  /* current trans */
461346204592SSage Weil 	}
46142ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
461546204592SSage Weil }
461646204592SSage Weil 
4617b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4618475f6387SJan Schmidt {
46190b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4620475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4621b8e95489SMiao Xie 	int ret;
4622475f6387SJan Schmidt 
4623475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4624475f6387SJan Schmidt 		return -EPERM;
4625475f6387SJan Schmidt 
4626475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4627475f6387SJan Schmidt 	if (IS_ERR(sa))
4628475f6387SJan Schmidt 		return PTR_ERR(sa);
4629475f6387SJan Schmidt 
4630b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4631b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4632b8e95489SMiao Xie 		if (ret)
4633b8e95489SMiao Xie 			goto out;
4634b8e95489SMiao Xie 	}
4635b8e95489SMiao Xie 
46360b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
463763a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
463863a212abSStefan Behrens 			      0);
4639475f6387SJan Schmidt 
4640475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4641475f6387SJan Schmidt 		ret = -EFAULT;
4642475f6387SJan Schmidt 
4643b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4644b8e95489SMiao Xie 		mnt_drop_write_file(file);
4645b8e95489SMiao Xie out:
4646475f6387SJan Schmidt 	kfree(sa);
4647475f6387SJan Schmidt 	return ret;
4648475f6387SJan Schmidt }
4649475f6387SJan Schmidt 
46502ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4651475f6387SJan Schmidt {
4652475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4653475f6387SJan Schmidt 		return -EPERM;
4654475f6387SJan Schmidt 
46552ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4656475f6387SJan Schmidt }
4657475f6387SJan Schmidt 
46582ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4659475f6387SJan Schmidt 				       void __user *arg)
4660475f6387SJan Schmidt {
4661475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4662475f6387SJan Schmidt 	int ret;
4663475f6387SJan Schmidt 
4664475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4665475f6387SJan Schmidt 		return -EPERM;
4666475f6387SJan Schmidt 
4667475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4668475f6387SJan Schmidt 	if (IS_ERR(sa))
4669475f6387SJan Schmidt 		return PTR_ERR(sa);
4670475f6387SJan Schmidt 
46712ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4672475f6387SJan Schmidt 
4673475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4674475f6387SJan Schmidt 		ret = -EFAULT;
4675475f6387SJan Schmidt 
4676475f6387SJan Schmidt 	kfree(sa);
4677475f6387SJan Schmidt 	return ret;
4678475f6387SJan Schmidt }
4679475f6387SJan Schmidt 
46802ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4681b27f7c0cSDavid Sterba 				      void __user *arg)
4682c11d2c23SStefan Behrens {
4683c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4684c11d2c23SStefan Behrens 	int ret;
4685c11d2c23SStefan Behrens 
4686c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4687c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4688c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4689c11d2c23SStefan Behrens 
4690b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4691b27f7c0cSDavid Sterba 		kfree(sa);
4692b27f7c0cSDavid Sterba 		return -EPERM;
4693b27f7c0cSDavid Sterba 	}
4694b27f7c0cSDavid Sterba 
46952ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4696c11d2c23SStefan Behrens 
4697c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4698c11d2c23SStefan Behrens 		ret = -EFAULT;
4699c11d2c23SStefan Behrens 
4700c11d2c23SStefan Behrens 	kfree(sa);
4701c11d2c23SStefan Behrens 	return ret;
4702c11d2c23SStefan Behrens }
4703c11d2c23SStefan Behrens 
47042ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
47052ff7e61eSJeff Mahoney 				    void __user *arg)
47063f6bcfbdSStefan Behrens {
47073f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
47083f6bcfbdSStefan Behrens 	int ret;
47093f6bcfbdSStefan Behrens 
47103f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
47113f6bcfbdSStefan Behrens 		return -EPERM;
47123f6bcfbdSStefan Behrens 
47133f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
47143f6bcfbdSStefan Behrens 	if (IS_ERR(p))
47153f6bcfbdSStefan Behrens 		return PTR_ERR(p);
47163f6bcfbdSStefan Behrens 
47173f6bcfbdSStefan Behrens 	switch (p->cmd) {
47183f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4719bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
4720adfa97cbSIlya Dryomov 			ret = -EROFS;
4721adfa97cbSIlya Dryomov 			goto out;
4722adfa97cbSIlya Dryomov 		}
4723171938e5SDavid Sterba 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4724e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
47253f6bcfbdSStefan Behrens 		} else {
47262ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4727171938e5SDavid Sterba 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
47283f6bcfbdSStefan Behrens 		}
47293f6bcfbdSStefan Behrens 		break;
47303f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
47310b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
47323f6bcfbdSStefan Behrens 		ret = 0;
47333f6bcfbdSStefan Behrens 		break;
47343f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
473517d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
473697282031SAnand Jain 		ret = 0;
47373f6bcfbdSStefan Behrens 		break;
47383f6bcfbdSStefan Behrens 	default:
47393f6bcfbdSStefan Behrens 		ret = -EINVAL;
47403f6bcfbdSStefan Behrens 		break;
47413f6bcfbdSStefan Behrens 	}
47423f6bcfbdSStefan Behrens 
47433f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
47443f6bcfbdSStefan Behrens 		ret = -EFAULT;
4745adfa97cbSIlya Dryomov out:
47463f6bcfbdSStefan Behrens 	kfree(p);
47473f6bcfbdSStefan Behrens 	return ret;
47483f6bcfbdSStefan Behrens }
47493f6bcfbdSStefan Behrens 
4750d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4751d7728c96SJan Schmidt {
4752d7728c96SJan Schmidt 	int ret = 0;
4753d7728c96SJan Schmidt 	int i;
4754740c3d22SChris Mason 	u64 rel_ptr;
4755d7728c96SJan Schmidt 	int size;
4756806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4757d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4758d7728c96SJan Schmidt 	struct btrfs_path *path;
4759d7728c96SJan Schmidt 
476082b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4761d7728c96SJan Schmidt 		return -EPERM;
4762d7728c96SJan Schmidt 
4763d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4764d7728c96SJan Schmidt 	if (!path) {
4765d7728c96SJan Schmidt 		ret = -ENOMEM;
4766d7728c96SJan Schmidt 		goto out;
4767d7728c96SJan Schmidt 	}
4768d7728c96SJan Schmidt 
4769d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4770d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4771d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4772d7728c96SJan Schmidt 		ipa = NULL;
4773d7728c96SJan Schmidt 		goto out;
4774d7728c96SJan Schmidt 	}
4775d7728c96SJan Schmidt 
4776d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4777d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4778d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4779d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4780d7728c96SJan Schmidt 		ipath = NULL;
4781d7728c96SJan Schmidt 		goto out;
4782d7728c96SJan Schmidt 	}
4783d7728c96SJan Schmidt 
4784d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4785d7728c96SJan Schmidt 	if (ret < 0)
4786d7728c96SJan Schmidt 		goto out;
4787d7728c96SJan Schmidt 
4788d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4789745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4790745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4791740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4792d7728c96SJan Schmidt 	}
4793d7728c96SJan Schmidt 
4794718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4795718dc5faSOmar Sandoval 			   ipath->fspath, size);
4796d7728c96SJan Schmidt 	if (ret) {
4797d7728c96SJan Schmidt 		ret = -EFAULT;
4798d7728c96SJan Schmidt 		goto out;
4799d7728c96SJan Schmidt 	}
4800d7728c96SJan Schmidt 
4801d7728c96SJan Schmidt out:
4802d7728c96SJan Schmidt 	btrfs_free_path(path);
4803d7728c96SJan Schmidt 	free_ipath(ipath);
4804d7728c96SJan Schmidt 	kfree(ipa);
4805d7728c96SJan Schmidt 
4806d7728c96SJan Schmidt 	return ret;
4807d7728c96SJan Schmidt }
4808d7728c96SJan Schmidt 
4809d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4810d7728c96SJan Schmidt {
4811d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4812d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4813d7728c96SJan Schmidt 
4814d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4815d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4816d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4817d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4818d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4819d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4820d7728c96SJan Schmidt 	} else {
4821d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4822d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4823d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4824d7728c96SJan Schmidt 	}
4825d7728c96SJan Schmidt 
4826d7728c96SJan Schmidt 	return 0;
4827d7728c96SJan Schmidt }
4828d7728c96SJan Schmidt 
48292ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4830d24a67b2SZygo Blaxell 					void __user *arg, int version)
4831d7728c96SJan Schmidt {
4832d7728c96SJan Schmidt 	int ret = 0;
4833d7728c96SJan Schmidt 	int size;
4834d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4835d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4836d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4837d24a67b2SZygo Blaxell 	bool ignore_offset;
4838d7728c96SJan Schmidt 
4839d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4840d7728c96SJan Schmidt 		return -EPERM;
4841d7728c96SJan Schmidt 
4842d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
48437b9ea627SShailendra Verma 	if (IS_ERR(loi))
48447b9ea627SShailendra Verma 		return PTR_ERR(loi);
4845d7728c96SJan Schmidt 
4846d24a67b2SZygo Blaxell 	if (version == 1) {
4847d24a67b2SZygo Blaxell 		ignore_offset = false;
4848b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
4849d24a67b2SZygo Blaxell 	} else {
4850d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
4851d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4852d24a67b2SZygo Blaxell 			ret = -EINVAL;
4853d24a67b2SZygo Blaxell 			goto out_loi;
4854d24a67b2SZygo Blaxell 		}
4855d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
4856d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4857d24a67b2SZygo Blaxell 			ret = -EINVAL;
4858d24a67b2SZygo Blaxell 			goto out_loi;
4859d24a67b2SZygo Blaxell 		}
4860d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4861b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
4862d24a67b2SZygo Blaxell 	}
4863d24a67b2SZygo Blaxell 
4864d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4865d7728c96SJan Schmidt 	if (!path) {
4866d7728c96SJan Schmidt 		ret = -ENOMEM;
4867d7728c96SJan Schmidt 		goto out;
4868d7728c96SJan Schmidt 	}
4869d7728c96SJan Schmidt 
4870d7728c96SJan Schmidt 	inodes = init_data_container(size);
4871d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4872d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4873d7728c96SJan Schmidt 		inodes = NULL;
4874d7728c96SJan Schmidt 		goto out;
4875d7728c96SJan Schmidt 	}
4876d7728c96SJan Schmidt 
48772ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4878d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
4879df031f07SLiu Bo 	if (ret == -EINVAL)
4880d7728c96SJan Schmidt 		ret = -ENOENT;
4881d7728c96SJan Schmidt 	if (ret < 0)
4882d7728c96SJan Schmidt 		goto out;
4883d7728c96SJan Schmidt 
4884718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4885718dc5faSOmar Sandoval 			   size);
4886d7728c96SJan Schmidt 	if (ret)
4887d7728c96SJan Schmidt 		ret = -EFAULT;
4888d7728c96SJan Schmidt 
4889d7728c96SJan Schmidt out:
4890d7728c96SJan Schmidt 	btrfs_free_path(path);
4891f54de068SDavid Sterba 	kvfree(inodes);
4892d24a67b2SZygo Blaxell out_loi:
4893d7728c96SJan Schmidt 	kfree(loi);
4894d7728c96SJan Schmidt 
4895d7728c96SJan Schmidt 	return ret;
4896d7728c96SJan Schmidt }
4897d7728c96SJan Schmidt 
4898008ef096SDavid Sterba void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4899c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4900c9e9f97bSIlya Dryomov {
4901c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4902c9e9f97bSIlya Dryomov 
4903c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4904c9e9f97bSIlya Dryomov 
49053009a62fSDavid Sterba 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4906837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4907837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4908837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4909a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4910a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4911837d5b6eSIlya Dryomov 
4912c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4913c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4914c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
491519a39dceSIlya Dryomov 
491619a39dceSIlya Dryomov 	spin_lock(&fs_info->balance_lock);
491719a39dceSIlya Dryomov 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
491819a39dceSIlya Dryomov 	spin_unlock(&fs_info->balance_lock);
4919c9e9f97bSIlya Dryomov }
4920c9e9f97bSIlya Dryomov 
49219ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4922c9e9f97bSIlya Dryomov {
4923496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4924c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4925c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4926c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4927ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4928c9e9f97bSIlya Dryomov 	int ret;
4929c9e9f97bSIlya Dryomov 
4930c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4931c9e9f97bSIlya Dryomov 		return -EPERM;
4932c9e9f97bSIlya Dryomov 
4933e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
49349ba1f6e4SLiu Bo 	if (ret)
49359ba1f6e4SLiu Bo 		return ret;
49369ba1f6e4SLiu Bo 
4937ed0fb78fSIlya Dryomov again:
4938171938e5SDavid Sterba 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4939c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4940ed0fb78fSIlya Dryomov 		need_unlock = true;
4941ed0fb78fSIlya Dryomov 		goto locked;
4942ed0fb78fSIlya Dryomov 	}
4943ed0fb78fSIlya Dryomov 
4944ed0fb78fSIlya Dryomov 	/*
494501327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4946ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4947ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4948ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4949ed0fb78fSIlya Dryomov 	 */
4950ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4951ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4952ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
49533009a62fSDavid Sterba 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4954ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4955dccdb07bSDavid Sterba 			/*
4956dccdb07bSDavid Sterba 			 * Lock released to allow other waiters to continue,
4957dccdb07bSDavid Sterba 			 * we'll reexamine the status again.
4958dccdb07bSDavid Sterba 			 */
4959ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4960ed0fb78fSIlya Dryomov 
4961ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
49623009a62fSDavid Sterba 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4963ed0fb78fSIlya Dryomov 				/* this is (3) */
4964ed0fb78fSIlya Dryomov 				need_unlock = false;
4965ed0fb78fSIlya Dryomov 				goto locked;
4966ed0fb78fSIlya Dryomov 			}
4967ed0fb78fSIlya Dryomov 
4968ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4969ed0fb78fSIlya Dryomov 			goto again;
4970ed0fb78fSIlya Dryomov 		} else {
4971ed0fb78fSIlya Dryomov 			/* this is (2) */
4972ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4973ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4974ed0fb78fSIlya Dryomov 			goto out;
4975ed0fb78fSIlya Dryomov 		}
4976ed0fb78fSIlya Dryomov 	} else {
4977ed0fb78fSIlya Dryomov 		/* this is (1) */
4978ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4979e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4980ed0fb78fSIlya Dryomov 		goto out;
4981ed0fb78fSIlya Dryomov 	}
4982ed0fb78fSIlya Dryomov 
4983ed0fb78fSIlya Dryomov locked:
4984171938e5SDavid Sterba 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4985c9e9f97bSIlya Dryomov 
4986c9e9f97bSIlya Dryomov 	if (arg) {
4987c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4988c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4989c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4990ed0fb78fSIlya Dryomov 			goto out_unlock;
4991c9e9f97bSIlya Dryomov 		}
4992de322263SIlya Dryomov 
4993de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4994de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4995de322263SIlya Dryomov 				ret = -ENOTCONN;
4996de322263SIlya Dryomov 				goto out_bargs;
4997de322263SIlya Dryomov 			}
4998de322263SIlya Dryomov 
4999de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
5000de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
5001de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
5002de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
5003de322263SIlya Dryomov 
5004de322263SIlya Dryomov 			goto do_balance;
5005de322263SIlya Dryomov 		}
5006c9e9f97bSIlya Dryomov 	} else {
5007c9e9f97bSIlya Dryomov 		bargs = NULL;
5008c9e9f97bSIlya Dryomov 	}
5009c9e9f97bSIlya Dryomov 
5010ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
5011837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
5012837d5b6eSIlya Dryomov 		goto out_bargs;
5013837d5b6eSIlya Dryomov 	}
5014837d5b6eSIlya Dryomov 
50158d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
5016c9e9f97bSIlya Dryomov 	if (!bctl) {
5017c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
5018c9e9f97bSIlya Dryomov 		goto out_bargs;
5019c9e9f97bSIlya Dryomov 	}
5020c9e9f97bSIlya Dryomov 
5021c9e9f97bSIlya Dryomov 	if (arg) {
5022c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
5023c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
5024c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
5025c9e9f97bSIlya Dryomov 
5026c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
5027f43ffb60SIlya Dryomov 	} else {
5028f43ffb60SIlya Dryomov 		/* balance everything - no filters */
5029f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
5030c9e9f97bSIlya Dryomov 	}
5031c9e9f97bSIlya Dryomov 
50328eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
50338eb93459SDavid Sterba 		ret = -EINVAL;
50340f89abf5SChristian Engelmayer 		goto out_bctl;
50358eb93459SDavid Sterba 	}
50368eb93459SDavid Sterba 
5037de322263SIlya Dryomov do_balance:
5038c9e9f97bSIlya Dryomov 	/*
5039149196a2SDavid Sterba 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
5040149196a2SDavid Sterba 	 * btrfs_balance.  bctl is freed in reset_balance_state, or, if
5041149196a2SDavid Sterba 	 * restriper was paused all the way until unmount, in free_fs_info.
5042149196a2SDavid Sterba 	 * The flag should be cleared after reset_balance_state.
5043c9e9f97bSIlya Dryomov 	 */
5044ed0fb78fSIlya Dryomov 	need_unlock = false;
5045ed0fb78fSIlya Dryomov 
50466fcf6e2bSDavid Sterba 	ret = btrfs_balance(fs_info, bctl, bargs);
50470f89abf5SChristian Engelmayer 	bctl = NULL;
5048ed0fb78fSIlya Dryomov 
5049c9e9f97bSIlya Dryomov 	if (arg) {
5050c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
5051c9e9f97bSIlya Dryomov 			ret = -EFAULT;
5052c9e9f97bSIlya Dryomov 	}
5053c9e9f97bSIlya Dryomov 
50540f89abf5SChristian Engelmayer out_bctl:
50550f89abf5SChristian Engelmayer 	kfree(bctl);
5056c9e9f97bSIlya Dryomov out_bargs:
5057c9e9f97bSIlya Dryomov 	kfree(bargs);
5058ed0fb78fSIlya Dryomov out_unlock:
5059c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
5060ed0fb78fSIlya Dryomov 	if (need_unlock)
5061171938e5SDavid Sterba 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
5062ed0fb78fSIlya Dryomov out:
5063e54bfa31SLiu Bo 	mnt_drop_write_file(file);
5064c9e9f97bSIlya Dryomov 	return ret;
5065c9e9f97bSIlya Dryomov }
5066c9e9f97bSIlya Dryomov 
50672ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
5068837d5b6eSIlya Dryomov {
5069837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
5070837d5b6eSIlya Dryomov 		return -EPERM;
5071837d5b6eSIlya Dryomov 
5072837d5b6eSIlya Dryomov 	switch (cmd) {
5073837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
50740b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
5075a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
50760b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
5077837d5b6eSIlya Dryomov 	}
5078837d5b6eSIlya Dryomov 
5079837d5b6eSIlya Dryomov 	return -EINVAL;
5080837d5b6eSIlya Dryomov }
5081837d5b6eSIlya Dryomov 
50822ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
508319a39dceSIlya Dryomov 					 void __user *arg)
508419a39dceSIlya Dryomov {
508519a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
508619a39dceSIlya Dryomov 	int ret = 0;
508719a39dceSIlya Dryomov 
508819a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
508919a39dceSIlya Dryomov 		return -EPERM;
509019a39dceSIlya Dryomov 
509119a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
509219a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
509319a39dceSIlya Dryomov 		ret = -ENOTCONN;
509419a39dceSIlya Dryomov 		goto out;
509519a39dceSIlya Dryomov 	}
509619a39dceSIlya Dryomov 
50978d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
509819a39dceSIlya Dryomov 	if (!bargs) {
509919a39dceSIlya Dryomov 		ret = -ENOMEM;
510019a39dceSIlya Dryomov 		goto out;
510119a39dceSIlya Dryomov 	}
510219a39dceSIlya Dryomov 
5103008ef096SDavid Sterba 	btrfs_update_ioctl_balance_args(fs_info, bargs);
510419a39dceSIlya Dryomov 
510519a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
510619a39dceSIlya Dryomov 		ret = -EFAULT;
510719a39dceSIlya Dryomov 
510819a39dceSIlya Dryomov 	kfree(bargs);
510919a39dceSIlya Dryomov out:
511019a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
511119a39dceSIlya Dryomov 	return ret;
511219a39dceSIlya Dryomov }
511319a39dceSIlya Dryomov 
5114905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
51155d13a37bSArne Jansen {
51160b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51185d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
51195d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
51205d13a37bSArne Jansen 	int ret;
51215d13a37bSArne Jansen 	int err;
51225d13a37bSArne Jansen 
51235d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
51245d13a37bSArne Jansen 		return -EPERM;
51255d13a37bSArne Jansen 
5126905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5127905b0ddaSMiao Xie 	if (ret)
5128905b0ddaSMiao Xie 		return ret;
51295d13a37bSArne Jansen 
51305d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5131905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5132905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5133905b0ddaSMiao Xie 		goto drop_write;
5134905b0ddaSMiao Xie 	}
51355d13a37bSArne Jansen 
51360b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
51370b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 2);
51385d13a37bSArne Jansen 	if (IS_ERR(trans)) {
51395d13a37bSArne Jansen 		ret = PTR_ERR(trans);
51405d13a37bSArne Jansen 		goto out;
51415d13a37bSArne Jansen 	}
51425d13a37bSArne Jansen 
51435d13a37bSArne Jansen 	switch (sa->cmd) {
51445d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
51450b246afaSJeff Mahoney 		ret = btrfs_quota_enable(trans, fs_info);
51465d13a37bSArne Jansen 		break;
51475d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
51480b246afaSJeff Mahoney 		ret = btrfs_quota_disable(trans, fs_info);
51495d13a37bSArne Jansen 		break;
51505d13a37bSArne Jansen 	default:
51515d13a37bSArne Jansen 		ret = -EINVAL;
51525d13a37bSArne Jansen 		break;
51535d13a37bSArne Jansen 	}
51545d13a37bSArne Jansen 
51553a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
51565d13a37bSArne Jansen 	if (err && !ret)
51575d13a37bSArne Jansen 		ret = err;
51585d13a37bSArne Jansen out:
51595d13a37bSArne Jansen 	kfree(sa);
51600b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5161905b0ddaSMiao Xie drop_write:
5162905b0ddaSMiao Xie 	mnt_drop_write_file(file);
51635d13a37bSArne Jansen 	return ret;
51645d13a37bSArne Jansen }
51655d13a37bSArne Jansen 
5166905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
51675d13a37bSArne Jansen {
51680b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51700b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
51715d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
51725d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
51735d13a37bSArne Jansen 	int ret;
51745d13a37bSArne Jansen 	int err;
51755d13a37bSArne Jansen 
51765d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
51775d13a37bSArne Jansen 		return -EPERM;
51785d13a37bSArne Jansen 
5179905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5180905b0ddaSMiao Xie 	if (ret)
5181905b0ddaSMiao Xie 		return ret;
51825d13a37bSArne Jansen 
51835d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5184905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5185905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5186905b0ddaSMiao Xie 		goto drop_write;
5187905b0ddaSMiao Xie 	}
51885d13a37bSArne Jansen 
51895d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
51905d13a37bSArne Jansen 	if (IS_ERR(trans)) {
51915d13a37bSArne Jansen 		ret = PTR_ERR(trans);
51925d13a37bSArne Jansen 		goto out;
51935d13a37bSArne Jansen 	}
51945d13a37bSArne Jansen 
51955d13a37bSArne Jansen 	if (sa->assign) {
51960b246afaSJeff Mahoney 		ret = btrfs_add_qgroup_relation(trans, fs_info,
51975d13a37bSArne Jansen 						sa->src, sa->dst);
51985d13a37bSArne Jansen 	} else {
51990b246afaSJeff Mahoney 		ret = btrfs_del_qgroup_relation(trans, fs_info,
52005d13a37bSArne Jansen 						sa->src, sa->dst);
52015d13a37bSArne Jansen 	}
52025d13a37bSArne Jansen 
5203e082f563SQu Wenruo 	/* update qgroup status and info */
52040b246afaSJeff Mahoney 	err = btrfs_run_qgroups(trans, fs_info);
5205e082f563SQu Wenruo 	if (err < 0)
52060b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
5207ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
52083a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
52095d13a37bSArne Jansen 	if (err && !ret)
52105d13a37bSArne Jansen 		ret = err;
52115d13a37bSArne Jansen 
52125d13a37bSArne Jansen out:
52135d13a37bSArne Jansen 	kfree(sa);
5214905b0ddaSMiao Xie drop_write:
5215905b0ddaSMiao Xie 	mnt_drop_write_file(file);
52165d13a37bSArne Jansen 	return ret;
52175d13a37bSArne Jansen }
52185d13a37bSArne Jansen 
5219905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
52205d13a37bSArne Jansen {
52210b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52230b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
52245d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
52255d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
52265d13a37bSArne Jansen 	int ret;
52275d13a37bSArne Jansen 	int err;
52285d13a37bSArne Jansen 
52295d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
52305d13a37bSArne Jansen 		return -EPERM;
52315d13a37bSArne Jansen 
5232905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5233905b0ddaSMiao Xie 	if (ret)
5234905b0ddaSMiao Xie 		return ret;
52355d13a37bSArne Jansen 
52365d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5237905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5238905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5239905b0ddaSMiao Xie 		goto drop_write;
5240905b0ddaSMiao Xie 	}
52415d13a37bSArne Jansen 
5242d86e56cfSMiao Xie 	if (!sa->qgroupid) {
5243d86e56cfSMiao Xie 		ret = -EINVAL;
5244d86e56cfSMiao Xie 		goto out;
5245d86e56cfSMiao Xie 	}
5246d86e56cfSMiao Xie 
52475d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
52485d13a37bSArne Jansen 	if (IS_ERR(trans)) {
52495d13a37bSArne Jansen 		ret = PTR_ERR(trans);
52505d13a37bSArne Jansen 		goto out;
52515d13a37bSArne Jansen 	}
52525d13a37bSArne Jansen 
52535d13a37bSArne Jansen 	if (sa->create) {
52540b246afaSJeff Mahoney 		ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
52555d13a37bSArne Jansen 	} else {
52560b246afaSJeff Mahoney 		ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
52575d13a37bSArne Jansen 	}
52585d13a37bSArne Jansen 
52593a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
52605d13a37bSArne Jansen 	if (err && !ret)
52615d13a37bSArne Jansen 		ret = err;
52625d13a37bSArne Jansen 
52635d13a37bSArne Jansen out:
52645d13a37bSArne Jansen 	kfree(sa);
5265905b0ddaSMiao Xie drop_write:
5266905b0ddaSMiao Xie 	mnt_drop_write_file(file);
52675d13a37bSArne Jansen 	return ret;
52685d13a37bSArne Jansen }
52695d13a37bSArne Jansen 
5270905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
52715d13a37bSArne Jansen {
52720b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52740b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
52755d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
52765d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
52775d13a37bSArne Jansen 	int ret;
52785d13a37bSArne Jansen 	int err;
52795d13a37bSArne Jansen 	u64 qgroupid;
52805d13a37bSArne Jansen 
52815d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
52825d13a37bSArne Jansen 		return -EPERM;
52835d13a37bSArne Jansen 
5284905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5285905b0ddaSMiao Xie 	if (ret)
5286905b0ddaSMiao Xie 		return ret;
52875d13a37bSArne Jansen 
52885d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5289905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5290905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5291905b0ddaSMiao Xie 		goto drop_write;
5292905b0ddaSMiao Xie 	}
52935d13a37bSArne Jansen 
52945d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
52955d13a37bSArne Jansen 	if (IS_ERR(trans)) {
52965d13a37bSArne Jansen 		ret = PTR_ERR(trans);
52975d13a37bSArne Jansen 		goto out;
52985d13a37bSArne Jansen 	}
52995d13a37bSArne Jansen 
53005d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
53015d13a37bSArne Jansen 	if (!qgroupid) {
53025d13a37bSArne Jansen 		/* take the current subvol as qgroup */
53035d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
53045d13a37bSArne Jansen 	}
53055d13a37bSArne Jansen 
53060b246afaSJeff Mahoney 	ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
53075d13a37bSArne Jansen 
53083a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
53095d13a37bSArne Jansen 	if (err && !ret)
53105d13a37bSArne Jansen 		ret = err;
53115d13a37bSArne Jansen 
53125d13a37bSArne Jansen out:
53135d13a37bSArne Jansen 	kfree(sa);
5314905b0ddaSMiao Xie drop_write:
5315905b0ddaSMiao Xie 	mnt_drop_write_file(file);
53165d13a37bSArne Jansen 	return ret;
53175d13a37bSArne Jansen }
53185d13a37bSArne Jansen 
53192f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
53202f232036SJan Schmidt {
53210b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53232f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
53242f232036SJan Schmidt 	int ret;
53252f232036SJan Schmidt 
53262f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
53272f232036SJan Schmidt 		return -EPERM;
53282f232036SJan Schmidt 
53292f232036SJan Schmidt 	ret = mnt_want_write_file(file);
53302f232036SJan Schmidt 	if (ret)
53312f232036SJan Schmidt 		return ret;
53322f232036SJan Schmidt 
53332f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
53342f232036SJan Schmidt 	if (IS_ERR(qsa)) {
53352f232036SJan Schmidt 		ret = PTR_ERR(qsa);
53362f232036SJan Schmidt 		goto drop_write;
53372f232036SJan Schmidt 	}
53382f232036SJan Schmidt 
53392f232036SJan Schmidt 	if (qsa->flags) {
53402f232036SJan Schmidt 		ret = -EINVAL;
53412f232036SJan Schmidt 		goto out;
53422f232036SJan Schmidt 	}
53432f232036SJan Schmidt 
53440b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
53452f232036SJan Schmidt 
53462f232036SJan Schmidt out:
53472f232036SJan Schmidt 	kfree(qsa);
53482f232036SJan Schmidt drop_write:
53492f232036SJan Schmidt 	mnt_drop_write_file(file);
53502f232036SJan Schmidt 	return ret;
53512f232036SJan Schmidt }
53522f232036SJan Schmidt 
53532f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
53542f232036SJan Schmidt {
53550b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53572f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
53582f232036SJan Schmidt 	int ret = 0;
53592f232036SJan Schmidt 
53602f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
53612f232036SJan Schmidt 		return -EPERM;
53622f232036SJan Schmidt 
53638d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
53642f232036SJan Schmidt 	if (!qsa)
53652f232036SJan Schmidt 		return -ENOMEM;
53662f232036SJan Schmidt 
53670b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
53682f232036SJan Schmidt 		qsa->flags = 1;
53690b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
53702f232036SJan Schmidt 	}
53712f232036SJan Schmidt 
53722f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
53732f232036SJan Schmidt 		ret = -EFAULT;
53742f232036SJan Schmidt 
53752f232036SJan Schmidt 	kfree(qsa);
53762f232036SJan Schmidt 	return ret;
53772f232036SJan Schmidt }
53782f232036SJan Schmidt 
537957254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
538057254b6eSJan Schmidt {
53810b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53820b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
538357254b6eSJan Schmidt 
538457254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
538557254b6eSJan Schmidt 		return -EPERM;
538657254b6eSJan Schmidt 
53870b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
538857254b6eSJan Schmidt }
538957254b6eSJan Schmidt 
5390abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
5391abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
53928ea05e3aSAlexander Block {
5393496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
53940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53958ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
53968ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
53978ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
5398c2050a45SDeepa Dinamani 	struct timespec ct = current_time(inode);
53998ea05e3aSAlexander Block 	int ret = 0;
5400dd5f9615SStefan Behrens 	int received_uuid_changed;
54018ea05e3aSAlexander Block 
5402bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
5403bd60ea0fSDavid Sterba 		return -EPERM;
5404bd60ea0fSDavid Sterba 
54058ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
54068ea05e3aSAlexander Block 	if (ret < 0)
54078ea05e3aSAlexander Block 		return ret;
54088ea05e3aSAlexander Block 
54090b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
54108ea05e3aSAlexander Block 
54114a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
54128ea05e3aSAlexander Block 		ret = -EINVAL;
54138ea05e3aSAlexander Block 		goto out;
54148ea05e3aSAlexander Block 	}
54158ea05e3aSAlexander Block 
54168ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
54178ea05e3aSAlexander Block 		ret = -EROFS;
54188ea05e3aSAlexander Block 		goto out;
54198ea05e3aSAlexander Block 	}
54208ea05e3aSAlexander Block 
5421dd5f9615SStefan Behrens 	/*
5422dd5f9615SStefan Behrens 	 * 1 - root item
5423dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5424dd5f9615SStefan Behrens 	 */
5425dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
54268ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
54278ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
54288ea05e3aSAlexander Block 		trans = NULL;
54298ea05e3aSAlexander Block 		goto out;
54308ea05e3aSAlexander Block 	}
54318ea05e3aSAlexander Block 
54328ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
54338ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
54348ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
54358ea05e3aSAlexander Block 
5436dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5437dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5438dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5439d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
5440d1957791SLu Fengqi 		ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
5441dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5442dd5f9615SStefan Behrens 					  root->root_key.objectid);
5443d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
5444d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
5445d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
5446d87ff758SNikolay Borisov 		        goto out;
5447d87ff758SNikolay Borisov 		}
5448d87ff758SNikolay Borisov 	}
54498ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
54508ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
54518ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
54523cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
54533cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
54543cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
54553cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
54568ea05e3aSAlexander Block 
54570b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
54588ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
54598ea05e3aSAlexander Block 	if (ret < 0) {
54603a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
54618ea05e3aSAlexander Block 		goto out;
5462dd5f9615SStefan Behrens 	}
5463dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5464cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, sa->uuid,
5465dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5466dd5f9615SStefan Behrens 					  root->root_key.objectid);
5467dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
546866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
5469efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
5470dd5f9615SStefan Behrens 			goto out;
5471dd5f9615SStefan Behrens 		}
5472dd5f9615SStefan Behrens 	}
54733a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5474abccd00fSHugo Mills out:
54750b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5476abccd00fSHugo Mills 	mnt_drop_write_file(file);
5477abccd00fSHugo Mills 	return ret;
5478abccd00fSHugo Mills }
5479abccd00fSHugo Mills 
5480abccd00fSHugo Mills #ifdef CONFIG_64BIT
5481abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5482abccd00fSHugo Mills 						void __user *arg)
5483abccd00fSHugo Mills {
5484abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5485abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5486abccd00fSHugo Mills 	int ret = 0;
5487abccd00fSHugo Mills 
5488abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
54897b9ea627SShailendra Verma 	if (IS_ERR(args32))
54907b9ea627SShailendra Verma 		return PTR_ERR(args32);
5491abccd00fSHugo Mills 
54928d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
549384dbeb87SDan Carpenter 	if (!args64) {
549484dbeb87SDan Carpenter 		ret = -ENOMEM;
5495abccd00fSHugo Mills 		goto out;
5496abccd00fSHugo Mills 	}
5497abccd00fSHugo Mills 
5498abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5499abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5500abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5501abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5502abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5503abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5504abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5505abccd00fSHugo Mills 	args64->flags = args32->flags;
5506abccd00fSHugo Mills 
5507abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5508abccd00fSHugo Mills 	if (ret)
5509abccd00fSHugo Mills 		goto out;
5510abccd00fSHugo Mills 
5511abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5512abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5513abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5514abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5515abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5516abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5517abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5518abccd00fSHugo Mills 	args32->flags = args64->flags;
5519abccd00fSHugo Mills 
5520abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5521abccd00fSHugo Mills 	if (ret)
5522abccd00fSHugo Mills 		ret = -EFAULT;
5523abccd00fSHugo Mills 
5524abccd00fSHugo Mills out:
5525abccd00fSHugo Mills 	kfree(args32);
5526abccd00fSHugo Mills 	kfree(args64);
5527abccd00fSHugo Mills 	return ret;
5528abccd00fSHugo Mills }
5529abccd00fSHugo Mills #endif
5530abccd00fSHugo Mills 
5531abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5532abccd00fSHugo Mills 					    void __user *arg)
5533abccd00fSHugo Mills {
5534abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5535abccd00fSHugo Mills 	int ret = 0;
5536abccd00fSHugo Mills 
5537abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
55387b9ea627SShailendra Verma 	if (IS_ERR(sa))
55397b9ea627SShailendra Verma 		return PTR_ERR(sa);
5540abccd00fSHugo Mills 
5541abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5542abccd00fSHugo Mills 
5543abccd00fSHugo Mills 	if (ret)
5544abccd00fSHugo Mills 		goto out;
5545abccd00fSHugo Mills 
55468ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
55478ea05e3aSAlexander Block 	if (ret)
55488ea05e3aSAlexander Block 		ret = -EFAULT;
55498ea05e3aSAlexander Block 
55508ea05e3aSAlexander Block out:
55518ea05e3aSAlexander Block 	kfree(sa);
55528ea05e3aSAlexander Block 	return ret;
55538ea05e3aSAlexander Block }
55548ea05e3aSAlexander Block 
5555867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5556867ab667Sjeff.liu {
55570b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
55580b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5559a1b83ac5SAnand Jain 	size_t len;
5560867ab667Sjeff.liu 	int ret;
5561a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5562a1b83ac5SAnand Jain 
55630b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
55640b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
55650b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
5566a1b83ac5SAnand Jain 
5567a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5568867ab667Sjeff.liu 
5569867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
55700b246afaSJeff Mahoney 		btrfs_warn(fs_info,
55710b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
55720b246afaSJeff Mahoney 			   --len);
5573867ab667Sjeff.liu 	}
5574867ab667Sjeff.liu 
5575867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5576867ab667Sjeff.liu 
5577867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5578867ab667Sjeff.liu }
5579867ab667Sjeff.liu 
5580a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5581a8bfd4abSjeff.liu {
55820b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
55830b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
55840b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
55850b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
5586a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5587a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5588a8bfd4abSjeff.liu 	int ret;
5589a8bfd4abSjeff.liu 
5590a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5591a8bfd4abSjeff.liu 		return -EPERM;
5592a8bfd4abSjeff.liu 
5593a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5594a8bfd4abSjeff.liu 		return -EFAULT;
5595a8bfd4abSjeff.liu 
5596a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
55970b246afaSJeff Mahoney 		btrfs_err(fs_info,
55985d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5599a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5600a8bfd4abSjeff.liu 		return -EINVAL;
5601a8bfd4abSjeff.liu 	}
5602a8bfd4abSjeff.liu 
5603a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5604a8bfd4abSjeff.liu 	if (ret)
5605a8bfd4abSjeff.liu 		return ret;
5606a8bfd4abSjeff.liu 
5607a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5608a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5609a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5610a8bfd4abSjeff.liu 		goto out_unlock;
5611a8bfd4abSjeff.liu 	}
5612a8bfd4abSjeff.liu 
56130b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5614a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
56150b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
56163a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5617a8bfd4abSjeff.liu 
5618a8bfd4abSjeff.liu out_unlock:
5619a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5620a8bfd4abSjeff.liu 	return ret;
5621a8bfd4abSjeff.liu }
5622a8bfd4abSjeff.liu 
56232eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
56242eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
56252eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
56262eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
56272eaa055fSJeff Mahoney 
5628d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
56292eaa055fSJeff Mahoney {
56304d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
56312eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
56322eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
56332eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
56342eaa055fSJeff Mahoney 	};
56352eaa055fSJeff Mahoney 
56362eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
56372eaa055fSJeff Mahoney 		return -EFAULT;
56382eaa055fSJeff Mahoney 
56392eaa055fSJeff Mahoney 	return 0;
56402eaa055fSJeff Mahoney }
56412eaa055fSJeff Mahoney 
56422eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
56432eaa055fSJeff Mahoney {
56440b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
56450b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
56460b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
56472eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
56482eaa055fSJeff Mahoney 
56492eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
56502eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
56512eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
56522eaa055fSJeff Mahoney 
56532eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
56542eaa055fSJeff Mahoney 		return -EFAULT;
56552eaa055fSJeff Mahoney 
56562eaa055fSJeff Mahoney 	return 0;
56572eaa055fSJeff Mahoney }
56582eaa055fSJeff Mahoney 
56592ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
56603b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
56612eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
56622eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
56632eaa055fSJeff Mahoney {
56643b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
56653b02a68aSJeff Mahoney 	char *names;
56662eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
56672eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
56682eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
56692eaa055fSJeff Mahoney 
56702eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
56712eaa055fSJeff Mahoney 	if (unsupported) {
56723b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
56733b02a68aSJeff Mahoney 		if (names) {
56740b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56753b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
56763b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
56773b02a68aSJeff Mahoney 			kfree(names);
56783b02a68aSJeff Mahoney 		} else
56790b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56802eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
56812eaa055fSJeff Mahoney 				   type, unsupported);
56822eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
56832eaa055fSJeff Mahoney 	}
56842eaa055fSJeff Mahoney 
56852eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
56862eaa055fSJeff Mahoney 	if (disallowed) {
56873b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
56883b02a68aSJeff Mahoney 		if (names) {
56890b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56903b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
56913b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
56923b02a68aSJeff Mahoney 			kfree(names);
56933b02a68aSJeff Mahoney 		} else
56940b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56952eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
56962eaa055fSJeff Mahoney 				   type, disallowed);
56972eaa055fSJeff Mahoney 		return -EPERM;
56982eaa055fSJeff Mahoney 	}
56992eaa055fSJeff Mahoney 
57002eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
57012eaa055fSJeff Mahoney 	if (disallowed) {
57023b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
57033b02a68aSJeff Mahoney 		if (names) {
57040b246afaSJeff Mahoney 			btrfs_warn(fs_info,
57053b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
57063b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
57073b02a68aSJeff Mahoney 			kfree(names);
57083b02a68aSJeff Mahoney 		} else
57090b246afaSJeff Mahoney 			btrfs_warn(fs_info,
57102eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
57112eaa055fSJeff Mahoney 				   type, disallowed);
57122eaa055fSJeff Mahoney 		return -EPERM;
57132eaa055fSJeff Mahoney 	}
57142eaa055fSJeff Mahoney 
57152eaa055fSJeff Mahoney 	return 0;
57162eaa055fSJeff Mahoney }
57172eaa055fSJeff Mahoney 
57182ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
57192ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
57202eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
57212eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
57222eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
57232eaa055fSJeff Mahoney 
57242eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
57252eaa055fSJeff Mahoney {
57260b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
57270b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
57280b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
57290b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
57302eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
57312eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
57322eaa055fSJeff Mahoney 	u64 newflags;
57332eaa055fSJeff Mahoney 	int ret;
57342eaa055fSJeff Mahoney 
57352eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
57362eaa055fSJeff Mahoney 		return -EPERM;
57372eaa055fSJeff Mahoney 
57382eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
57392eaa055fSJeff Mahoney 		return -EFAULT;
57402eaa055fSJeff Mahoney 
57412eaa055fSJeff Mahoney 	/* Nothing to do */
57422eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
57432eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
57442eaa055fSJeff Mahoney 		return 0;
57452eaa055fSJeff Mahoney 
57462ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
57472eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
57482eaa055fSJeff Mahoney 	if (ret)
57492eaa055fSJeff Mahoney 		return ret;
57502eaa055fSJeff Mahoney 
57512ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
57522eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
57532eaa055fSJeff Mahoney 	if (ret)
57542eaa055fSJeff Mahoney 		return ret;
57552eaa055fSJeff Mahoney 
57562ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
57572eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
57582eaa055fSJeff Mahoney 	if (ret)
57592eaa055fSJeff Mahoney 		return ret;
57602eaa055fSJeff Mahoney 
57617ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
57627ab19625SDavid Sterba 	if (ret)
57637ab19625SDavid Sterba 		return ret;
57647ab19625SDavid Sterba 
57658051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
57667ab19625SDavid Sterba 	if (IS_ERR(trans)) {
57677ab19625SDavid Sterba 		ret = PTR_ERR(trans);
57687ab19625SDavid Sterba 		goto out_drop_write;
57697ab19625SDavid Sterba 	}
57702eaa055fSJeff Mahoney 
57710b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
57722eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
57732eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
57742eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
57752eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
57762eaa055fSJeff Mahoney 
57772eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
57782eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
57792eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
57802eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
57812eaa055fSJeff Mahoney 
57822eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
57832eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
57842eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
57852eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
57860b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
57872eaa055fSJeff Mahoney 
57883a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
57897ab19625SDavid Sterba out_drop_write:
57907ab19625SDavid Sterba 	mnt_drop_write_file(file);
57917ab19625SDavid Sterba 
57927ab19625SDavid Sterba 	return ret;
57932eaa055fSJeff Mahoney }
57942eaa055fSJeff Mahoney 
57952351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
57962351f431SJosef Bacik {
57972351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
57982351f431SJosef Bacik 	int ret;
57992351f431SJosef Bacik 
58002351f431SJosef Bacik 	if (compat) {
58012351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
58022351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
58032351f431SJosef Bacik 
58042351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
58052351f431SJosef Bacik 		if (ret)
58062351f431SJosef Bacik 			return -EFAULT;
58072351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
58082351f431SJosef Bacik 		if (!arg)
58092351f431SJosef Bacik 			return -ENOMEM;
58102351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
58112351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
58122351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
58132351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
58142351f431SJosef Bacik 		arg->flags = args32.flags;
58152351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
58162351f431SJosef Bacik 		       sizeof(args32.reserved));
58172351f431SJosef Bacik #else
58182351f431SJosef Bacik 		return -ENOTTY;
58192351f431SJosef Bacik #endif
58202351f431SJosef Bacik 	} else {
58212351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
58222351f431SJosef Bacik 		if (IS_ERR(arg))
58232351f431SJosef Bacik 			return PTR_ERR(arg);
58242351f431SJosef Bacik 	}
58252351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
58262351f431SJosef Bacik 	kfree(arg);
58272351f431SJosef Bacik 	return ret;
58282351f431SJosef Bacik }
58292351f431SJosef Bacik 
5830f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5831f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5832f46b5a66SChristoph Hellwig {
58330b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
58340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
58350b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
58364bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5837f46b5a66SChristoph Hellwig 
5838f46b5a66SChristoph Hellwig 	switch (cmd) {
58396cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
58406cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
58416cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
58426cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
58436cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
58446cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5845f7039b1dSLi Dongyang 	case FITRIM:
5846f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5847f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5848fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5849fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5850fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
58513de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5852fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
58536f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
58546f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
585576dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
585676dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
58570caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
58580caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
58590caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
58600caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
58616ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
58626ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5863f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
58641e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
58651e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
58661e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5867f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5868198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5869f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
58702ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5871f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5872da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
58736b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
58746b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5875475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
58762ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5877475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
58782ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5879f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
58809ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5881ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5882ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5883cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5884cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5885ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5886ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5887d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5888d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5889d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5890d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5891d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
5892d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
58931406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
58942ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
58959b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
58969b199859SFilipe David Borba Manana 		int ret;
58979b199859SFilipe David Borba Manana 
589882b3e53bSNikolay Borisov 		ret = btrfs_start_delalloc_roots(fs_info, -1);
58999b199859SFilipe David Borba Manana 		if (ret)
59009b199859SFilipe David Borba Manana 			return ret;
59010b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
59022fad4e83SDavid Sterba 		/*
59032fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
590401327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
59052fad4e83SDavid Sterba 		 * processing uncleaned subvols.
59062fad4e83SDavid Sterba 		 */
59070b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
59089b199859SFilipe David Borba Manana 		return ret;
59099b199859SFilipe David Borba Manana 	}
591046204592SSage Weil 	case BTRFS_IOC_START_SYNC:
59119a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
591246204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
59132ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5914475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5915b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5916475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
59172ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5918475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
59192ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5920c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
59219ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5922837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
59232ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
592419a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
59252ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
59268ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
59278ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5928abccd00fSHugo Mills #ifdef CONFIG_64BIT
5929abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5930abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5931abccd00fSHugo Mills #endif
593231db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
59332351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
59342351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
59352351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
59362351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
59372351f431SJosef Bacik #endif
5938c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
59392ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
59405d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5941905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
59425d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5943905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
59445d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5945905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
59465d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5947905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
59482f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
59492f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
59502f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
59512f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
595257254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
595357254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
59543f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
59552ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5956867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5957867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5958a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5959a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
59602eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5961d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
59622eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
59632eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
59642eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
59652eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5966e4202ac9SDavid Sterba 	case FS_IOC_FSGETXATTR:
5967e4202ac9SDavid Sterba 		return btrfs_ioctl_fsgetxattr(file, argp);
5968025f2121SDavid Sterba 	case FS_IOC_FSSETXATTR:
5969025f2121SDavid Sterba 		return btrfs_ioctl_fssetxattr(file, argp);
5970b64ec075STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_INFO:
5971b64ec075STomohiro Misono 		return btrfs_ioctl_get_subvol_info(file, argp);
597242e4b520STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_ROOTREF:
597342e4b520STomohiro Misono 		return btrfs_ioctl_get_subvol_rootref(file, argp);
597423d0b79dSTomohiro Misono 	case BTRFS_IOC_INO_LOOKUP_USER:
597523d0b79dSTomohiro Misono 		return btrfs_ioctl_ino_lookup_user(file, argp);
5976f46b5a66SChristoph Hellwig 	}
5977f46b5a66SChristoph Hellwig 
5978f46b5a66SChristoph Hellwig 	return -ENOTTY;
5979f46b5a66SChristoph Hellwig }
59804c63c245SLuke Dashjr 
59814c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
59824c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
59834c63c245SLuke Dashjr {
59842a362249SJeff Mahoney 	/*
59852a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
59862a362249SJeff Mahoney 	 * handling is necessary.
59872a362249SJeff Mahoney 	 */
59884c63c245SLuke Dashjr 	switch (cmd) {
59894c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
59904c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
59914c63c245SLuke Dashjr 		break;
59924c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
59934c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
59944c63c245SLuke Dashjr 		break;
59954c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
59964c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
59974c63c245SLuke Dashjr 		break;
59984c63c245SLuke Dashjr 	}
59994c63c245SLuke Dashjr 
60004c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
60014c63c245SLuke Dashjr }
60024c63c245SLuke Dashjr #endif
6003