xref: /openbmc/linux/fs/btrfs/ioctl.c (revision fd4e994b)
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;
572d5c12070SMiao Xie 	u64 qgroup_reserved;
5738ea05e3aSAlexander Block 	uuid_le new_uuid;
574f46b5a66SChristoph Hellwig 
57549a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
57649a3c4d9SDavid Sterba 	if (!root_item)
57749a3c4d9SDavid Sterba 		return -ENOMEM;
57849a3c4d9SDavid Sterba 
5790b246afaSJeff Mahoney 	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
5802fbe8c8aSAl Viro 	if (ret)
58149a3c4d9SDavid Sterba 		goto fail_free;
5826a912213SJosef Bacik 
583e09fe2d2SQu Wenruo 	/*
584e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
58501327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
586e09fe2d2SQu Wenruo 	 */
58749a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
58849a3c4d9SDavid Sterba 		ret = -ENOSPC;
58949a3c4d9SDavid Sterba 		goto fail_free;
59049a3c4d9SDavid Sterba 	}
591e09fe2d2SQu Wenruo 
592d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
5939ed74f2dSJosef Bacik 	/*
594d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
595d5c12070SMiao Xie 	 * of create_snapshot().
5969ed74f2dSJosef Bacik 	 */
597d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
598dd5f9615SStefan Behrens 					       8, &qgroup_reserved, false);
599d5c12070SMiao Xie 	if (ret)
60049a3c4d9SDavid Sterba 		goto fail_free;
601f46b5a66SChristoph Hellwig 
602d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
603d5c12070SMiao Xie 	if (IS_ERR(trans)) {
604d5c12070SMiao Xie 		ret = PTR_ERR(trans);
6057775c818SDavid Sterba 		btrfs_subvolume_release_metadata(fs_info, &block_rsv);
60649a3c4d9SDavid Sterba 		goto fail_free;
607d5c12070SMiao Xie 	}
608d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
609d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
610f46b5a66SChristoph Hellwig 
6110b246afaSJeff Mahoney 	ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
6126f72c7e2SArne Jansen 	if (ret)
6136f72c7e2SArne Jansen 		goto fail;
6146f72c7e2SArne Jansen 
6154d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
6168e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
6178e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
6188e8a1e31SJosef Bacik 		goto fail;
6198e8a1e31SJosef Bacik 	}
620f46b5a66SChristoph Hellwig 
621b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
622f46b5a66SChristoph Hellwig 	btrfs_set_header_bytenr(leaf, leaf->start);
623f46b5a66SChristoph Hellwig 	btrfs_set_header_generation(leaf, trans->transid);
6245d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
625f46b5a66SChristoph Hellwig 	btrfs_set_header_owner(leaf, objectid);
626f46b5a66SChristoph Hellwig 
6270b246afaSJeff Mahoney 	write_extent_buffer_fsid(leaf, fs_info->fsid);
6280b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
629f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
630f46b5a66SChristoph Hellwig 
63149a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
6323cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
6333cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
6343cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
635da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
6360b246afaSJeff Mahoney 				     fs_info->nodesize);
6373cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
638f46b5a66SChristoph Hellwig 
63949a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
64049a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
6413cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
64208fe4db1SLi Zefan 
64349a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
64449a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
64549a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
64649a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
64749a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
64849a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
649f46b5a66SChristoph Hellwig 
65049a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
65149a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
6528ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
65349a3c4d9SDavid Sterba 	memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
65449a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
65549a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
65649a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
65749a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
65849a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
659f46b5a66SChristoph Hellwig 
660925baeddSChris Mason 	btrfs_tree_unlock(leaf);
661f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
662f46b5a66SChristoph Hellwig 	leaf = NULL;
663f46b5a66SChristoph Hellwig 
66449a3c4d9SDavid Sterba 	btrfs_set_root_dirid(root_item, new_dirid);
665f46b5a66SChristoph Hellwig 
666f46b5a66SChristoph Hellwig 	key.objectid = objectid;
6675d4f98a2SYan Zheng 	key.offset = 0;
668962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
6690b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
67049a3c4d9SDavid Sterba 				root_item);
671f46b5a66SChristoph Hellwig 	if (ret)
672f46b5a66SChristoph Hellwig 		goto fail;
673f46b5a66SChristoph Hellwig 
67476dda93cSYan, Zheng 	key.offset = (u64)-1;
6750b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &key);
67679787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
67779787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
67866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
67979787eaaSJeff Mahoney 		goto fail;
68079787eaaSJeff Mahoney 	}
68176dda93cSYan, Zheng 
68276dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
68376dda93cSYan, Zheng 
68463541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
685ce598979SMark Fasheh 	if (ret) {
686ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
68766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
688ce598979SMark Fasheh 		goto fail;
689ce598979SMark Fasheh 	}
690ce598979SMark Fasheh 
691f32e48e9SChandan Rajendra 	mutex_lock(&new_root->objectid_mutex);
692f32e48e9SChandan Rajendra 	new_root->highest_objectid = new_dirid;
693f32e48e9SChandan Rajendra 	mutex_unlock(&new_root->objectid_mutex);
694f32e48e9SChandan Rajendra 
695f46b5a66SChristoph Hellwig 	/*
696f46b5a66SChristoph Hellwig 	 * insert the directory item
697f46b5a66SChristoph Hellwig 	 */
698877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
69979787eaaSJeff Mahoney 	if (ret) {
70066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
70179787eaaSJeff Mahoney 		goto fail;
70279787eaaSJeff Mahoney 	}
7033de4586cSChris Mason 
7043de4586cSChris Mason 	ret = btrfs_insert_dir_item(trans, root,
7058e7611cfSNikolay Borisov 				    name, namelen, BTRFS_I(dir), &key,
7063de4586cSChris Mason 				    BTRFS_FT_DIR, index);
70779787eaaSJeff Mahoney 	if (ret) {
70866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
709f46b5a66SChristoph Hellwig 		goto fail;
71079787eaaSJeff Mahoney 	}
7110660b5afSChris Mason 
7126ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
71352c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
71452c26179SYan Zheng 	BUG_ON(ret);
71552c26179SYan Zheng 
7160b246afaSJeff Mahoney 	ret = btrfs_add_root_ref(trans, fs_info,
7174df27c4dSYan, Zheng 				 objectid, root->root_key.objectid,
7184a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
7190660b5afSChris Mason 	BUG_ON(ret);
7200660b5afSChris Mason 
7210b246afaSJeff Mahoney 	ret = btrfs_uuid_tree_add(trans, fs_info, root_item->uuid,
7226bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
723dd5f9615SStefan Behrens 	if (ret)
72466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
725dd5f9615SStefan Behrens 
726f46b5a66SChristoph Hellwig fail:
72749a3c4d9SDavid Sterba 	kfree(root_item);
728d5c12070SMiao Xie 	trans->block_rsv = NULL;
729d5c12070SMiao Xie 	trans->bytes_reserved = 0;
7307775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
731de6e8200SLiu Bo 
73272fd032eSSage Weil 	if (async_transid) {
73372fd032eSSage Weil 		*async_transid = trans->transid;
7343a45bb20SJeff Mahoney 		err = btrfs_commit_transaction_async(trans, 1);
73500d71c9cSMiao Xie 		if (err)
7363a45bb20SJeff Mahoney 			err = btrfs_commit_transaction(trans);
73772fd032eSSage Weil 	} else {
7383a45bb20SJeff Mahoney 		err = btrfs_commit_transaction(trans);
73972fd032eSSage Weil 	}
740f46b5a66SChristoph Hellwig 	if (err && !ret)
741f46b5a66SChristoph Hellwig 		ret = err;
7421a65e24bSChris Mason 
7435662344bSTsutomu Itoh 	if (!ret) {
7445662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
745de6e8200SLiu Bo 		if (IS_ERR(inode))
746de6e8200SLiu Bo 			return PTR_ERR(inode);
7475662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
7485662344bSTsutomu Itoh 	}
749f46b5a66SChristoph Hellwig 	return ret;
75049a3c4d9SDavid Sterba 
75149a3c4d9SDavid Sterba fail_free:
75249a3c4d9SDavid Sterba 	kfree(root_item);
75349a3c4d9SDavid Sterba 	return ret;
754f46b5a66SChristoph Hellwig }
755f46b5a66SChristoph Hellwig 
756e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
75761d7e4cbSDavid Sterba 			   struct dentry *dentry,
758e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
759e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
760f46b5a66SChristoph Hellwig {
7610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
7622e4bfab9SYan, Zheng 	struct inode *inode;
763f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
764f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
7652e4bfab9SYan, Zheng 	int ret;
766f46b5a66SChristoph Hellwig 
76727cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
768f46b5a66SChristoph Hellwig 		return -EINVAL;
769f46b5a66SChristoph Hellwig 
77023269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
771a1ee7362SDavid Sterba 	if (!pending_snapshot)
772a1ee7362SDavid Sterba 		return -ENOMEM;
773a1ee7362SDavid Sterba 
774b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
77523269bf5SDavid Sterba 			GFP_KERNEL);
7768546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
7778546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
778b0c0ea63SDavid Sterba 		ret = -ENOMEM;
779b0c0ea63SDavid Sterba 		goto free_pending;
780b0c0ea63SDavid Sterba 	}
781b0c0ea63SDavid Sterba 
782ea14b57fSDavid Sterba 	atomic_inc(&root->will_be_snapshotted);
7834e857c58SPeter Zijlstra 	smp_mb__after_atomic();
78445bac0f3SLiu Bo 	/* wait for no snapshot writes */
78545bac0f3SLiu Bo 	wait_event(root->subv_writers->wait,
78645bac0f3SLiu Bo 		   percpu_counter_sum(&root->subv_writers->counter) == 0);
7878257b2dcSMiao Xie 
78876f32e24SNikolay Borisov 	ret = btrfs_start_delalloc_inodes(root);
7896a03843dSMiao Xie 	if (ret)
790a1ee7362SDavid Sterba 		goto dec_and_free;
7916a03843dSMiao Xie 
7926374e57aSChris Mason 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
7936a03843dSMiao Xie 
79466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
79566d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
796d5c12070SMiao Xie 	/*
797d5c12070SMiao Xie 	 * 1 - parent dir inode
798d5c12070SMiao Xie 	 * 2 - dir entries
799d5c12070SMiao Xie 	 * 1 - root item
800d5c12070SMiao Xie 	 * 2 - root ref/backref
801d5c12070SMiao Xie 	 * 1 - root of snapshot
802dd5f9615SStefan Behrens 	 * 1 - UUID item
803d5c12070SMiao Xie 	 */
804d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
805dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
806ee3441b4SJeff Mahoney 					&pending_snapshot->qgroup_reserved,
807ee3441b4SJeff Mahoney 					false);
808d5c12070SMiao Xie 	if (ret)
809a1ee7362SDavid Sterba 		goto dec_and_free;
810d5c12070SMiao Xie 
811a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
812a22285a6SYan, Zheng 	pending_snapshot->root = root;
813b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
814e9662f70SMiao Xie 	pending_snapshot->dir = dir;
8158696c533SMiao Xie 	pending_snapshot->inherit = inherit;
816a22285a6SYan, Zheng 
817d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
818a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
819a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
820a22285a6SYan, Zheng 		goto fail;
821a22285a6SYan, Zheng 	}
822a22285a6SYan, Zheng 
8230b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
824a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
825a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
8260b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
82772fd032eSSage Weil 	if (async_transid) {
82872fd032eSSage Weil 		*async_transid = trans->transid;
8293a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction_async(trans, 1);
83000d71c9cSMiao Xie 		if (ret)
8313a45bb20SJeff Mahoney 			ret = btrfs_commit_transaction(trans);
83272fd032eSSage Weil 	} else {
8333a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
83472fd032eSSage Weil 	}
835aec8030aSMiao Xie 	if (ret)
836c37b2b62SJosef Bacik 		goto fail;
837a22285a6SYan, Zheng 
838a22285a6SYan, Zheng 	ret = pending_snapshot->error;
839f46b5a66SChristoph Hellwig 	if (ret)
8402e4bfab9SYan, Zheng 		goto fail;
841f46b5a66SChristoph Hellwig 
842d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
843d3797308SChris Mason 	if (ret)
844d3797308SChris Mason 		goto fail;
845d3797308SChris Mason 
8462b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
8472e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
8482e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
8492e4bfab9SYan, Zheng 		goto fail;
8502e4bfab9SYan, Zheng 	}
8515662344bSTsutomu Itoh 
8522e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
8532e4bfab9SYan, Zheng 	ret = 0;
8542e4bfab9SYan, Zheng fail:
8557775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
856a1ee7362SDavid Sterba dec_and_free:
857ea14b57fSDavid Sterba 	if (atomic_dec_and_test(&root->will_be_snapshotted))
8584625956aSPeter Zijlstra 		wake_up_var(&root->will_be_snapshotted);
859b0c0ea63SDavid Sterba free_pending:
860b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
8618546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
862a1ee7362SDavid Sterba 	kfree(pending_snapshot);
863a1ee7362SDavid Sterba 
864f46b5a66SChristoph Hellwig 	return ret;
865f46b5a66SChristoph Hellwig }
866f46b5a66SChristoph Hellwig 
8674260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
8684260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
8694260f7c7SSage Weil  *  whether the type of victim is right.
8704260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
8714260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
8724260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
8734260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
8744260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
8754260f7c7SSage Weil  *	a. be owner of dir, or
8764260f7c7SSage Weil  *	b. be owner of victim, or
8774260f7c7SSage Weil  *	c. have CAP_FOWNER capability
87801327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
8794260f7c7SSage Weil  *     links pointing to it.
8804260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
8814260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
8824260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
8834260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
8844260f7c7SSage Weil  *     nfs_async_unlink().
8854260f7c7SSage Weil  */
8864260f7c7SSage Weil 
8874260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
8884260f7c7SSage Weil {
8894260f7c7SSage Weil 	int error;
8904260f7c7SSage Weil 
8912b0143b5SDavid Howells 	if (d_really_is_negative(victim))
8924260f7c7SSage Weil 		return -ENOENT;
8934260f7c7SSage Weil 
8942b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
8954fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
8964260f7c7SSage Weil 
8974260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
8984260f7c7SSage Weil 	if (error)
8994260f7c7SSage Weil 		return error;
9004260f7c7SSage Weil 	if (IS_APPEND(dir))
9014260f7c7SSage Weil 		return -EPERM;
9022b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
9032b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
9044260f7c7SSage Weil 		return -EPERM;
9054260f7c7SSage Weil 	if (isdir) {
906e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
9074260f7c7SSage Weil 			return -ENOTDIR;
9084260f7c7SSage Weil 		if (IS_ROOT(victim))
9094260f7c7SSage Weil 			return -EBUSY;
910e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
9114260f7c7SSage Weil 		return -EISDIR;
9124260f7c7SSage Weil 	if (IS_DEADDIR(dir))
9134260f7c7SSage Weil 		return -ENOENT;
9144260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
9154260f7c7SSage Weil 		return -EBUSY;
9164260f7c7SSage Weil 	return 0;
9174260f7c7SSage Weil }
9184260f7c7SSage Weil 
919cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
920cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
921cb8e7090SChristoph Hellwig {
9222b0143b5SDavid Howells 	if (d_really_is_positive(child))
923cb8e7090SChristoph Hellwig 		return -EEXIST;
924cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
925cb8e7090SChristoph Hellwig 		return -ENOENT;
926cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
927cb8e7090SChristoph Hellwig }
928cb8e7090SChristoph Hellwig 
929cb8e7090SChristoph Hellwig /*
930cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
931cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
932cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
933cb8e7090SChristoph Hellwig  */
93492872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
93552f75f4fSDavid Sterba 				   const char *name, int namelen,
93672fd032eSSage Weil 				   struct btrfs_root *snap_src,
9376f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
9388696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
939cb8e7090SChristoph Hellwig {
9402b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
9410b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
942cb8e7090SChristoph Hellwig 	struct dentry *dentry;
943cb8e7090SChristoph Hellwig 	int error;
944cb8e7090SChristoph Hellwig 
94500235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
94600235411SAl Viro 	if (error == -EINTR)
94700235411SAl Viro 		return error;
948cb8e7090SChristoph Hellwig 
949cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
950cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
951cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
952cb8e7090SChristoph Hellwig 		goto out_unlock;
953cb8e7090SChristoph Hellwig 
95476dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
955cb8e7090SChristoph Hellwig 	if (error)
956a874a63eSLiu Bo 		goto out_dput;
957cb8e7090SChristoph Hellwig 
9589c52057cSChris Mason 	/*
9599c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
9609c52057cSChris Mason 	 * check for them now when we can safely fail
9619c52057cSChris Mason 	 */
9629c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
9639c52057cSChris Mason 					       dir->i_ino, name,
9649c52057cSChris Mason 					       namelen);
9659c52057cSChris Mason 	if (error)
9669c52057cSChris Mason 		goto out_dput;
9679c52057cSChris Mason 
9680b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
96976dda93cSYan, Zheng 
97076dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
97176dda93cSYan, Zheng 		goto out_up_read;
97276dda93cSYan, Zheng 
9733de4586cSChris Mason 	if (snap_src) {
97461d7e4cbSDavid Sterba 		error = create_snapshot(snap_src, dir, dentry,
9756f72c7e2SArne Jansen 					async_transid, readonly, inherit);
9763de4586cSChris Mason 	} else {
977d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
978d5c12070SMiao Xie 				      async_transid, inherit);
9793de4586cSChris Mason 	}
98076dda93cSYan, Zheng 	if (!error)
98176dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
98276dda93cSYan, Zheng out_up_read:
9830b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
984cb8e7090SChristoph Hellwig out_dput:
985cb8e7090SChristoph Hellwig 	dput(dentry);
986cb8e7090SChristoph Hellwig out_unlock:
9875955102cSAl Viro 	inode_unlock(dir);
988cb8e7090SChristoph Hellwig 	return error;
989cb8e7090SChristoph Hellwig }
990cb8e7090SChristoph Hellwig 
9914cb5300bSChris Mason /*
9924cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
9934cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
9944cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
9954cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
9964cb5300bSChris Mason  * part of the file
9974cb5300bSChris Mason  */
998aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
9994cb5300bSChris Mason {
10004cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10014cb5300bSChris Mason 	struct extent_map *em = NULL;
10024cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10034cb5300bSChris Mason 	u64 end;
10044cb5300bSChris Mason 
10054cb5300bSChris Mason 	read_lock(&em_tree->lock);
100609cbfeafSKirill A. Shutemov 	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
10074cb5300bSChris Mason 	read_unlock(&em_tree->lock);
10084cb5300bSChris Mason 
10094cb5300bSChris Mason 	if (em) {
10104cb5300bSChris Mason 		end = extent_map_end(em);
10114cb5300bSChris Mason 		free_extent_map(em);
10124cb5300bSChris Mason 		if (end - offset > thresh)
10134cb5300bSChris Mason 			return 0;
10144cb5300bSChris Mason 	}
10154cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
10164cb5300bSChris Mason 	thresh /= 2;
10174cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
10184cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
10194cb5300bSChris Mason 	if (end >= thresh)
10204cb5300bSChris Mason 		return 0;
10214cb5300bSChris Mason 	return 1;
10224cb5300bSChris Mason }
10234cb5300bSChris Mason 
10244cb5300bSChris Mason /*
10254cb5300bSChris Mason  * helper function to walk through a file and find extents
10264cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
10274cb5300bSChris Mason  *
10284cb5300bSChris Mason  * This is used by the defragging code to find new and small
10294cb5300bSChris Mason  * extents
10304cb5300bSChris Mason  */
10314cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
10324cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
1033aab110abSDavid Sterba 			    u64 *off, u32 thresh)
10344cb5300bSChris Mason {
10354cb5300bSChris Mason 	struct btrfs_path *path;
10364cb5300bSChris Mason 	struct btrfs_key min_key;
10374cb5300bSChris Mason 	struct extent_buffer *leaf;
10384cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
10394cb5300bSChris Mason 	int type;
10404cb5300bSChris Mason 	int ret;
10414a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
10424cb5300bSChris Mason 
10434cb5300bSChris Mason 	path = btrfs_alloc_path();
10444cb5300bSChris Mason 	if (!path)
10454cb5300bSChris Mason 		return -ENOMEM;
10464cb5300bSChris Mason 
1047a4689d2bSDavid Sterba 	min_key.objectid = ino;
10484cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
10494cb5300bSChris Mason 	min_key.offset = *off;
10504cb5300bSChris Mason 
10514cb5300bSChris Mason 	while (1) {
10526174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
10534cb5300bSChris Mason 		if (ret != 0)
10544cb5300bSChris Mason 			goto none;
1055f094c9bdSFilipe Manana process_slot:
1056a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
10574cb5300bSChris Mason 			goto none;
10584cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
10594cb5300bSChris Mason 			goto none;
10604cb5300bSChris Mason 
10614cb5300bSChris Mason 		leaf = path->nodes[0];
10624cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
10634cb5300bSChris Mason 					struct btrfs_file_extent_item);
10644cb5300bSChris Mason 
10654cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
10664cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
10674cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
10684cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
10694cb5300bSChris Mason 			*off = min_key.offset;
10704cb5300bSChris Mason 			btrfs_free_path(path);
10714cb5300bSChris Mason 			return 0;
10724cb5300bSChris Mason 		}
10734cb5300bSChris Mason 
1074f094c9bdSFilipe Manana 		path->slots[0]++;
1075f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
1076f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1077f094c9bdSFilipe Manana 			goto process_slot;
1078f094c9bdSFilipe Manana 		}
1079f094c9bdSFilipe Manana 
10804cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
10814cb5300bSChris Mason 			goto none;
10824cb5300bSChris Mason 
10834cb5300bSChris Mason 		min_key.offset++;
10844cb5300bSChris Mason 		btrfs_release_path(path);
10854cb5300bSChris Mason 	}
10864cb5300bSChris Mason none:
10874cb5300bSChris Mason 	btrfs_free_path(path);
10884cb5300bSChris Mason 	return -ENOENT;
10894cb5300bSChris Mason }
10904cb5300bSChris Mason 
10916c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
109217ce6ef8SLiu Bo {
109317ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1094940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10956c282eb4SLi Zefan 	struct extent_map *em;
109609cbfeafSKirill A. Shutemov 	u64 len = PAGE_SIZE;
1097940100a4SChris Mason 
1098940100a4SChris Mason 	/*
1099940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
1100940100a4SChris Mason 	 * the full extent lock
1101940100a4SChris Mason 	 */
1102940100a4SChris Mason 	read_lock(&em_tree->lock);
1103940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
1104940100a4SChris Mason 	read_unlock(&em_tree->lock);
1105940100a4SChris Mason 
1106940100a4SChris Mason 	if (!em) {
1107308d9800SFilipe Manana 		struct extent_state *cached = NULL;
1108308d9800SFilipe Manana 		u64 end = start + len - 1;
1109308d9800SFilipe Manana 
1110940100a4SChris Mason 		/* get the big lock and read metadata off disk */
1111ff13db41SDavid Sterba 		lock_extent_bits(io_tree, start, end, &cached);
1112fc4f21b1SNikolay Borisov 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1113e43bbe5eSDavid Sterba 		unlock_extent_cached(io_tree, start, end, &cached);
1114940100a4SChris Mason 
11156cf8bfbfSDan Carpenter 		if (IS_ERR(em))
11166c282eb4SLi Zefan 			return NULL;
1117940100a4SChris Mason 	}
1118940100a4SChris Mason 
11196c282eb4SLi Zefan 	return em;
11206c282eb4SLi Zefan }
11216c282eb4SLi Zefan 
11226c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
11236c282eb4SLi Zefan {
11246c282eb4SLi Zefan 	struct extent_map *next;
11256c282eb4SLi Zefan 	bool ret = true;
11266c282eb4SLi Zefan 
11276c282eb4SLi Zefan 	/* this is the last extent */
11286c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
11296c282eb4SLi Zefan 		return false;
11306c282eb4SLi Zefan 
11316c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
1132e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1133e9512d72SChris Mason 		ret = false;
1134e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1135ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
11366c282eb4SLi Zefan 		ret = false;
11376c282eb4SLi Zefan 
11386c282eb4SLi Zefan 	free_extent_map(next);
11396c282eb4SLi Zefan 	return ret;
11406c282eb4SLi Zefan }
11416c282eb4SLi Zefan 
1142aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1143a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
1144a43a2111SAndrew Mahone 			       int compress)
11456c282eb4SLi Zefan {
11466c282eb4SLi Zefan 	struct extent_map *em;
11476c282eb4SLi Zefan 	int ret = 1;
11486c282eb4SLi Zefan 	bool next_mergeable = true;
11494a3560c4SLiu Bo 	bool prev_mergeable = true;
11506c282eb4SLi Zefan 
11516c282eb4SLi Zefan 	/*
11526c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
11536c282eb4SLi Zefan 	 * defragging it
11546c282eb4SLi Zefan 	 */
11556c282eb4SLi Zefan 	if (start < *defrag_end)
11566c282eb4SLi Zefan 		return 1;
11576c282eb4SLi Zefan 
11586c282eb4SLi Zefan 	*skip = 0;
11596c282eb4SLi Zefan 
11606c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
11616c282eb4SLi Zefan 	if (!em)
11626c282eb4SLi Zefan 		return 0;
11636c282eb4SLi Zefan 
1164940100a4SChris Mason 	/* this will cover holes, and inline extents */
116517ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1166940100a4SChris Mason 		ret = 0;
116717ce6ef8SLiu Bo 		goto out;
116817ce6ef8SLiu Bo 	}
116917ce6ef8SLiu Bo 
11704a3560c4SLiu Bo 	if (!*defrag_end)
11714a3560c4SLiu Bo 		prev_mergeable = false;
11724a3560c4SLiu Bo 
11736c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1174940100a4SChris Mason 	/*
11756c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
11766c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1177940100a4SChris Mason 	 */
1178a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
11794a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1180940100a4SChris Mason 		ret = 0;
118117ce6ef8SLiu Bo out:
1182940100a4SChris Mason 	/*
1183940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1184940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1185940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1186940100a4SChris Mason 	 *
1187940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1188940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1189940100a4SChris Mason 	 */
1190940100a4SChris Mason 	if (ret) {
1191940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1192940100a4SChris Mason 	} else {
1193940100a4SChris Mason 		*last_len = 0;
1194940100a4SChris Mason 		*skip = extent_map_end(em);
1195940100a4SChris Mason 		*defrag_end = 0;
1196940100a4SChris Mason 	}
1197940100a4SChris Mason 
1198940100a4SChris Mason 	free_extent_map(em);
1199940100a4SChris Mason 	return ret;
1200940100a4SChris Mason }
1201940100a4SChris Mason 
12024cb5300bSChris Mason /*
12034cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
12044cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
12054cb5300bSChris Mason  * to COW and defrag.
12064cb5300bSChris Mason  *
12074cb5300bSChris Mason  * It also makes sure the delalloc code has enough
12084cb5300bSChris Mason  * dirty data to avoid making new small extents as part
12094cb5300bSChris Mason  * of the defrag
12104cb5300bSChris Mason  *
12114cb5300bSChris Mason  * It's a good idea to start RA on this range
12124cb5300bSChris Mason  * before calling this.
12134cb5300bSChris Mason  */
12144cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
12154cb5300bSChris Mason 				    struct page **pages,
12164cb5300bSChris Mason 				    unsigned long start_index,
1217c41570c9SJustin Maggard 				    unsigned long num_pages)
1218f46b5a66SChristoph Hellwig {
12194cb5300bSChris Mason 	unsigned long file_end;
12204cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1221f46b5a66SChristoph Hellwig 	u64 page_start;
1222f46b5a66SChristoph Hellwig 	u64 page_end;
12231f12bd06SLiu Bo 	u64 page_cnt;
12244cb5300bSChris Mason 	int ret;
12254cb5300bSChris Mason 	int i;
12264cb5300bSChris Mason 	int i_done;
12274cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
12284cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1229600a45e1SMiao Xie 	struct extent_io_tree *tree;
1230364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
12313b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
12324cb5300bSChris Mason 
123309cbfeafSKirill A. Shutemov 	file_end = (isize - 1) >> PAGE_SHIFT;
12341f12bd06SLiu Bo 	if (!isize || start_index > file_end)
12351f12bd06SLiu Bo 		return 0;
12361f12bd06SLiu Bo 
12371f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
12384cb5300bSChris Mason 
1239364ecf36SQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
124009cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
124109cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
12424cb5300bSChris Mason 	if (ret)
12434cb5300bSChris Mason 		return ret;
12444cb5300bSChris Mason 	i_done = 0;
1245600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
12464cb5300bSChris Mason 
12474cb5300bSChris Mason 	/* step one, lock all the pages */
12481f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
12494cb5300bSChris Mason 		struct page *page;
1250600a45e1SMiao Xie again:
1251a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
12523b16a4e3SJosef Bacik 					   start_index + i, mask);
12534cb5300bSChris Mason 		if (!page)
12544cb5300bSChris Mason 			break;
12554cb5300bSChris Mason 
1256600a45e1SMiao Xie 		page_start = page_offset(page);
125709cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
1258600a45e1SMiao Xie 		while (1) {
1259308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1260ff13db41SDavid Sterba 					 &cached_state);
1261600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1262600a45e1SMiao Xie 							      page_start);
1263308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1264e43bbe5eSDavid Sterba 					     &cached_state);
1265600a45e1SMiao Xie 			if (!ordered)
1266600a45e1SMiao Xie 				break;
1267600a45e1SMiao Xie 
1268600a45e1SMiao Xie 			unlock_page(page);
1269600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1270600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1271600a45e1SMiao Xie 			lock_page(page);
12721f12bd06SLiu Bo 			/*
12731f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
12741f12bd06SLiu Bo 			 * it was released or not.
12751f12bd06SLiu Bo 			 */
12761f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
12771f12bd06SLiu Bo 				unlock_page(page);
127809cbfeafSKirill A. Shutemov 				put_page(page);
12791f12bd06SLiu Bo 				goto again;
12801f12bd06SLiu Bo 			}
1281600a45e1SMiao Xie 		}
1282600a45e1SMiao Xie 
12834cb5300bSChris Mason 		if (!PageUptodate(page)) {
12844cb5300bSChris Mason 			btrfs_readpage(NULL, page);
12854cb5300bSChris Mason 			lock_page(page);
12864cb5300bSChris Mason 			if (!PageUptodate(page)) {
12874cb5300bSChris Mason 				unlock_page(page);
128809cbfeafSKirill A. Shutemov 				put_page(page);
12894cb5300bSChris Mason 				ret = -EIO;
12904cb5300bSChris Mason 				break;
12914cb5300bSChris Mason 			}
12924cb5300bSChris Mason 		}
1293600a45e1SMiao Xie 
1294600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1295600a45e1SMiao Xie 			unlock_page(page);
129609cbfeafSKirill A. Shutemov 			put_page(page);
1297600a45e1SMiao Xie 			goto again;
1298600a45e1SMiao Xie 		}
1299600a45e1SMiao Xie 
13004cb5300bSChris Mason 		pages[i] = page;
13014cb5300bSChris Mason 		i_done++;
13024cb5300bSChris Mason 	}
13034cb5300bSChris Mason 	if (!i_done || ret)
13044cb5300bSChris Mason 		goto out;
13054cb5300bSChris Mason 
13061751e8a6SLinus Torvalds 	if (!(inode->i_sb->s_flags & SB_ACTIVE))
13074cb5300bSChris Mason 		goto out;
13084cb5300bSChris Mason 
13094cb5300bSChris Mason 	/*
13104cb5300bSChris Mason 	 * so now we have a nice long stream of locked
13114cb5300bSChris Mason 	 * and up to date pages, lets wait on them
13124cb5300bSChris Mason 	 */
13134cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
13144cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
13154cb5300bSChris Mason 
13164cb5300bSChris Mason 	page_start = page_offset(pages[0]);
131709cbfeafSKirill A. Shutemov 	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
13184cb5300bSChris Mason 
13194cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1320ff13db41SDavid Sterba 			 page_start, page_end - 1, &cached_state);
13214cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
13224cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
13239e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1324ae0f1625SDavid Sterba 			  &cached_state);
13254cb5300bSChris Mason 
13261f12bd06SLiu Bo 	if (i_done != page_cnt) {
13279e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
13289e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
13299e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
1330bc42bda2SQu Wenruo 		btrfs_delalloc_release_space(inode, data_reserved,
133109cbfeafSKirill A. Shutemov 				start_index << PAGE_SHIFT,
133243b18595SQu Wenruo 				(page_cnt - i_done) << PAGE_SHIFT, true);
13334cb5300bSChris Mason 	}
13344cb5300bSChris Mason 
13354cb5300bSChris Mason 
13369e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1337018ed4f7SDavid Sterba 			  &cached_state);
13384cb5300bSChris Mason 
13394cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1340e43bbe5eSDavid Sterba 			     page_start, page_end - 1, &cached_state);
13414cb5300bSChris Mason 
13424cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
13434cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
13444cb5300bSChris Mason 		ClearPageChecked(pages[i]);
13454cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
13464cb5300bSChris Mason 		set_page_dirty(pages[i]);
13474cb5300bSChris Mason 		unlock_page(pages[i]);
134809cbfeafSKirill A. Shutemov 		put_page(pages[i]);
13494cb5300bSChris Mason 	}
135043b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
135143b18595SQu Wenruo 				       false);
1352364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
13534cb5300bSChris Mason 	return i_done;
13544cb5300bSChris Mason out:
13554cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
13564cb5300bSChris Mason 		unlock_page(pages[i]);
135709cbfeafSKirill A. Shutemov 		put_page(pages[i]);
13584cb5300bSChris Mason 	}
1359bc42bda2SQu Wenruo 	btrfs_delalloc_release_space(inode, data_reserved,
136009cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
136143b18595SQu Wenruo 			page_cnt << PAGE_SHIFT, true);
136243b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
136343b18595SQu Wenruo 				       true);
1364364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
13654cb5300bSChris Mason 	return ret;
13664cb5300bSChris Mason 
13674cb5300bSChris Mason }
13684cb5300bSChris Mason 
13694cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
13704cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
13714cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
13724cb5300bSChris Mason {
13730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
13744cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
13754cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
13764cb5300bSChris Mason 	unsigned long last_index;
1377151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1378940100a4SChris Mason 	u64 last_len = 0;
1379940100a4SChris Mason 	u64 skip = 0;
1380940100a4SChris Mason 	u64 defrag_end = 0;
13814cb5300bSChris Mason 	u64 newer_off = range->start;
1382f46b5a66SChristoph Hellwig 	unsigned long i;
1383008873eaSLi Zefan 	unsigned long ra_index = 0;
1384f46b5a66SChristoph Hellwig 	int ret;
13854cb5300bSChris Mason 	int defrag_count = 0;
13861a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1387aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
138809cbfeafSKirill A. Shutemov 	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1389c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
1390ee22184bSByongho Lee 	u64 new_align = ~((u64)SZ_128K - 1);
13914cb5300bSChris Mason 	struct page **pages = NULL;
13921e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
13934cb5300bSChris Mason 
13940abd5b17SLiu Bo 	if (isize == 0)
13950abd5b17SLiu Bo 		return 0;
13960abd5b17SLiu Bo 
13970abd5b17SLiu Bo 	if (range->start >= isize)
13980abd5b17SLiu Bo 		return -EINVAL;
13991a419d85SLi Zefan 
14001e2ef46dSDavid Sterba 	if (do_compress) {
14011a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
14021a419d85SLi Zefan 			return -EINVAL;
14031a419d85SLi Zefan 		if (range->compress_type)
14041a419d85SLi Zefan 			compress_type = range->compress_type;
14051a419d85SLi Zefan 	}
1406f46b5a66SChristoph Hellwig 
14070abd5b17SLiu Bo 	if (extent_thresh == 0)
1408ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1409f46b5a66SChristoph Hellwig 
14104cb5300bSChris Mason 	/*
14110a52d108SDavid Sterba 	 * If we were not given a file, allocate a readahead context. As
14120a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
14130a52d108SDavid Sterba 	 * we don't error out.
14144cb5300bSChris Mason 	 */
14154cb5300bSChris Mason 	if (!file) {
141663e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
14170a52d108SDavid Sterba 		if (ra)
14184cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
14194cb5300bSChris Mason 	} else {
14204cb5300bSChris Mason 		ra = &file->f_ra;
14214cb5300bSChris Mason 	}
14224cb5300bSChris Mason 
142363e727ecSDavid Sterba 	pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
14244cb5300bSChris Mason 	if (!pages) {
14254cb5300bSChris Mason 		ret = -ENOMEM;
14264cb5300bSChris Mason 		goto out_ra;
14274cb5300bSChris Mason 	}
14284cb5300bSChris Mason 
14294cb5300bSChris Mason 	/* find the last page to defrag */
14301e701a32SChris Mason 	if (range->start + range->len > range->start) {
1431151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
143209cbfeafSKirill A. Shutemov 			 range->start + range->len - 1) >> PAGE_SHIFT;
14331e701a32SChris Mason 	} else {
143409cbfeafSKirill A. Shutemov 		last_index = (isize - 1) >> PAGE_SHIFT;
14351e701a32SChris Mason 	}
14361e701a32SChris Mason 
14374cb5300bSChris Mason 	if (newer_than) {
14384cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
1439ee22184bSByongho Lee 				       &newer_off, SZ_64K);
14404cb5300bSChris Mason 		if (!ret) {
14414cb5300bSChris Mason 			range->start = newer_off;
14424cb5300bSChris Mason 			/*
14434cb5300bSChris Mason 			 * we always align our defrag to help keep
14444cb5300bSChris Mason 			 * the extents in the file evenly spaced
14454cb5300bSChris Mason 			 */
144609cbfeafSKirill A. Shutemov 			i = (newer_off & new_align) >> PAGE_SHIFT;
14474cb5300bSChris Mason 		} else
14484cb5300bSChris Mason 			goto out_ra;
14494cb5300bSChris Mason 	} else {
145009cbfeafSKirill A. Shutemov 		i = range->start >> PAGE_SHIFT;
14514cb5300bSChris Mason 	}
14524cb5300bSChris Mason 	if (!max_to_defrag)
1453070034bdSchandan 		max_to_defrag = last_index - i + 1;
14544cb5300bSChris Mason 
14552a0f7f57SLi Zefan 	/*
14562a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
14572a0f7f57SLi Zefan 	 * written sequentially.
14582a0f7f57SLi Zefan 	 */
14592a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
14602a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
14612a0f7f57SLi Zefan 
1462f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
146309cbfeafSKirill A. Shutemov 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
14644cb5300bSChris Mason 		/*
14654cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
14664cb5300bSChris Mason 		 * the FS
14674cb5300bSChris Mason 		 */
14681751e8a6SLinus Torvalds 		if (!(inode->i_sb->s_flags & SB_ACTIVE))
14694cb5300bSChris Mason 			break;
14704cb5300bSChris Mason 
14710b246afaSJeff Mahoney 		if (btrfs_defrag_cancelled(fs_info)) {
14720b246afaSJeff Mahoney 			btrfs_debug(fs_info, "defrag_file cancelled");
1473210549ebSDavid Sterba 			ret = -EAGAIN;
1474210549ebSDavid Sterba 			break;
1475210549ebSDavid Sterba 		}
1476210549ebSDavid Sterba 
147709cbfeafSKirill A. Shutemov 		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
14786c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
14791e2ef46dSDavid Sterba 					 &defrag_end, do_compress)){
1480940100a4SChris Mason 			unsigned long next;
1481940100a4SChris Mason 			/*
1482940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1483940100a4SChris Mason 			 * bump our counter by the suggested amount
1484940100a4SChris Mason 			 */
148509cbfeafSKirill A. Shutemov 			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1486940100a4SChris Mason 			i = max(i + 1, next);
1487940100a4SChris Mason 			continue;
1488940100a4SChris Mason 		}
1489008873eaSLi Zefan 
1490008873eaSLi Zefan 		if (!newer_than) {
149109cbfeafSKirill A. Shutemov 			cluster = (PAGE_ALIGN(defrag_end) >>
149209cbfeafSKirill A. Shutemov 				   PAGE_SHIFT) - i;
1493008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1494008873eaSLi Zefan 		} else {
1495008873eaSLi Zefan 			cluster = max_cluster;
1496008873eaSLi Zefan 		}
1497008873eaSLi Zefan 
1498008873eaSLi Zefan 		if (i + cluster > ra_index) {
1499008873eaSLi Zefan 			ra_index = max(i, ra_index);
15000a52d108SDavid Sterba 			if (ra)
1501d3c0bab5SDavid Sterba 				page_cache_sync_readahead(inode->i_mapping, ra,
1502d3c0bab5SDavid Sterba 						file, ra_index, cluster);
1503e4826a5bSchandan 			ra_index += cluster;
1504008873eaSLi Zefan 		}
15054cb5300bSChris Mason 
15065955102cSAl Viro 		inode_lock(inode);
15071e2ef46dSDavid Sterba 		if (do_compress)
1508eec63c65SDavid Sterba 			BTRFS_I(inode)->defrag_compress = compress_type;
1509008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1510ecb8bea8SLiu Bo 		if (ret < 0) {
15115955102cSAl Viro 			inode_unlock(inode);
15124cb5300bSChris Mason 			goto out_ra;
1513ecb8bea8SLiu Bo 		}
15144cb5300bSChris Mason 
15154cb5300bSChris Mason 		defrag_count += ret;
1516d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
15175955102cSAl Viro 		inode_unlock(inode);
15184cb5300bSChris Mason 
15194cb5300bSChris Mason 		if (newer_than) {
15204cb5300bSChris Mason 			if (newer_off == (u64)-1)
15214cb5300bSChris Mason 				break;
15224cb5300bSChris Mason 
1523e1f041e1SLiu Bo 			if (ret > 0)
1524e1f041e1SLiu Bo 				i += ret;
1525e1f041e1SLiu Bo 
15264cb5300bSChris Mason 			newer_off = max(newer_off + 1,
152709cbfeafSKirill A. Shutemov 					(u64)i << PAGE_SHIFT);
15284cb5300bSChris Mason 
1529ee22184bSByongho Lee 			ret = find_new_extents(root, inode, newer_than,
1530ee22184bSByongho Lee 					       &newer_off, SZ_64K);
15314cb5300bSChris Mason 			if (!ret) {
15324cb5300bSChris Mason 				range->start = newer_off;
153309cbfeafSKirill A. Shutemov 				i = (newer_off & new_align) >> PAGE_SHIFT;
15344cb5300bSChris Mason 			} else {
15354cb5300bSChris Mason 				break;
1536940100a4SChris Mason 			}
15374cb5300bSChris Mason 		} else {
1538008873eaSLi Zefan 			if (ret > 0) {
1539cbcc8326SLi Zefan 				i += ret;
154009cbfeafSKirill A. Shutemov 				last_len += ret << PAGE_SHIFT;
1541008873eaSLi Zefan 			} else {
1542940100a4SChris Mason 				i++;
1543008873eaSLi Zefan 				last_len = 0;
1544008873eaSLi Zefan 			}
1545f46b5a66SChristoph Hellwig 		}
15464cb5300bSChris Mason 	}
1547f46b5a66SChristoph Hellwig 
1548dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
15491e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1550dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1551dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1552dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1553dec8ef90SFilipe Manana 	}
15541e701a32SChris Mason 
15551a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
15560b246afaSJeff Mahoney 		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
15575c1aab1dSNick Terrell 	} else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
15585c1aab1dSNick Terrell 		btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
15591a419d85SLi Zefan 	}
15601a419d85SLi Zefan 
156160ccf82fSDiego Calleja 	ret = defrag_count;
1562940100a4SChris Mason 
15634cb5300bSChris Mason out_ra:
15641e2ef46dSDavid Sterba 	if (do_compress) {
15655955102cSAl Viro 		inode_lock(inode);
1566eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
15675955102cSAl Viro 		inode_unlock(inode);
1568633085c7SFilipe David Borba Manana 	}
15694cb5300bSChris Mason 	if (!file)
15704cb5300bSChris Mason 		kfree(ra);
15714cb5300bSChris Mason 	kfree(pages);
1572940100a4SChris Mason 	return ret;
1573f46b5a66SChristoph Hellwig }
1574f46b5a66SChristoph Hellwig 
1575198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
157676dda93cSYan, Zheng 					void __user *arg)
1577f46b5a66SChristoph Hellwig {
15780b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
15790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1580f46b5a66SChristoph Hellwig 	u64 new_size;
1581f46b5a66SChristoph Hellwig 	u64 old_size;
1582f46b5a66SChristoph Hellwig 	u64 devid = 1;
15830b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1584f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1585f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1586f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1587f46b5a66SChristoph Hellwig 	char *sizestr;
15889a40f122SGui Hecheng 	char *retptr;
1589f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1590f46b5a66SChristoph Hellwig 	int ret = 0;
1591f46b5a66SChristoph Hellwig 	int mod = 0;
1592f46b5a66SChristoph Hellwig 
1593e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1594e441d54dSChris Mason 		return -EPERM;
1595e441d54dSChris Mason 
1596198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1597198605a8SMiao Xie 	if (ret)
1598198605a8SMiao Xie 		return ret;
1599198605a8SMiao Xie 
1600171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
160197547676SMiao Xie 		mnt_drop_write_file(file);
1602e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1603c9e9f97bSIlya Dryomov 	}
1604c9e9f97bSIlya Dryomov 
1605dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1606c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1607c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1608c9e9f97bSIlya Dryomov 		goto out;
1609c9e9f97bSIlya Dryomov 	}
16105516e595SMark Fasheh 
16115516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1612f46b5a66SChristoph Hellwig 
1613f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1614f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1615f46b5a66SChristoph Hellwig 	if (devstr) {
1616f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1617f46b5a66SChristoph Hellwig 		*devstr = '\0';
1618f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
161958dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
162058dfae63SZhangZhen 		if (ret)
162158dfae63SZhangZhen 			goto out_free;
1622dfd79829SMiao Xie 		if (!devid) {
1623dfd79829SMiao Xie 			ret = -EINVAL;
1624dfd79829SMiao Xie 			goto out_free;
1625dfd79829SMiao Xie 		}
16260b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1627f46b5a66SChristoph Hellwig 	}
1628dba60f3fSMiao Xie 
16290b246afaSJeff Mahoney 	device = btrfs_find_device(fs_info, devid, NULL, NULL);
1630f46b5a66SChristoph Hellwig 	if (!device) {
16310b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1632c1c9ff7cSGeert Uytterhoeven 			   devid);
1633dfd79829SMiao Xie 		ret = -ENODEV;
1634c9e9f97bSIlya Dryomov 		goto out_free;
1635f46b5a66SChristoph Hellwig 	}
1636dba60f3fSMiao Xie 
1637ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
16380b246afaSJeff Mahoney 		btrfs_info(fs_info,
1639efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1640c1c9ff7cSGeert Uytterhoeven 		       devid);
1641dfd79829SMiao Xie 		ret = -EPERM;
16424e42ae1bSLiu Bo 		goto out_free;
16434e42ae1bSLiu Bo 	}
16444e42ae1bSLiu Bo 
1645f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1646f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1647f46b5a66SChristoph Hellwig 	else {
1648f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1649f46b5a66SChristoph Hellwig 			mod = -1;
1650f46b5a66SChristoph Hellwig 			sizestr++;
1651f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1652f46b5a66SChristoph Hellwig 			mod = 1;
1653f46b5a66SChristoph Hellwig 			sizestr++;
1654f46b5a66SChristoph Hellwig 		}
16559a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
16569a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1657f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1658c9e9f97bSIlya Dryomov 			goto out_free;
1659f46b5a66SChristoph Hellwig 		}
1660f46b5a66SChristoph Hellwig 	}
1661f46b5a66SChristoph Hellwig 
1662401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1663dfd79829SMiao Xie 		ret = -EPERM;
166463a212abSStefan Behrens 		goto out_free;
166563a212abSStefan Behrens 	}
166663a212abSStefan Behrens 
16677cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1668f46b5a66SChristoph Hellwig 
1669f46b5a66SChristoph Hellwig 	if (mod < 0) {
1670f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1671f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1672c9e9f97bSIlya Dryomov 			goto out_free;
1673f46b5a66SChristoph Hellwig 		}
1674f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1675f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1676eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1677902c68a4SGui Hecheng 			ret = -ERANGE;
1678eb8052e0SWenliang Fan 			goto out_free;
1679eb8052e0SWenliang Fan 		}
1680f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1681f46b5a66SChristoph Hellwig 	}
1682f46b5a66SChristoph Hellwig 
1683ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1684f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1685c9e9f97bSIlya Dryomov 		goto out_free;
1686f46b5a66SChristoph Hellwig 	}
1687f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1688f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1689c9e9f97bSIlya Dryomov 		goto out_free;
1690f46b5a66SChristoph Hellwig 	}
1691f46b5a66SChristoph Hellwig 
169247f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1693f46b5a66SChristoph Hellwig 
16940b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1695c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1696f46b5a66SChristoph Hellwig 
1697f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1698a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
169998d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
170098d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1701c9e9f97bSIlya Dryomov 			goto out_free;
170298d5dc13STsutomu Itoh 		}
1703f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
17043a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1705ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1706f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
17070253f40eSjeff.liu 	} /* equal, nothing need to do */
1708f46b5a66SChristoph Hellwig 
1709c9e9f97bSIlya Dryomov out_free:
1710f46b5a66SChristoph Hellwig 	kfree(vol_args);
1711c9e9f97bSIlya Dryomov out:
1712171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
171318f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1714f46b5a66SChristoph Hellwig 	return ret;
1715f46b5a66SChristoph Hellwig }
1716f46b5a66SChristoph Hellwig 
171772fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
171852f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
17196f72c7e2SArne Jansen 				u64 *transid, bool readonly,
17208696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1721f46b5a66SChristoph Hellwig {
1722f46b5a66SChristoph Hellwig 	int namelen;
17233de4586cSChris Mason 	int ret = 0;
1724f46b5a66SChristoph Hellwig 
1725325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1726325c50e3SJeff Mahoney 		return -ENOTDIR;
1727325c50e3SJeff Mahoney 
1728a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1729a874a63eSLiu Bo 	if (ret)
1730a874a63eSLiu Bo 		goto out;
1731a874a63eSLiu Bo 
173272fd032eSSage Weil 	namelen = strlen(name);
173372fd032eSSage Weil 	if (strchr(name, '/')) {
1734f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1735a874a63eSLiu Bo 		goto out_drop_write;
1736f46b5a66SChristoph Hellwig 	}
1737f46b5a66SChristoph Hellwig 
173816780cabSChris Mason 	if (name[0] == '.' &&
173916780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
174016780cabSChris Mason 		ret = -EEXIST;
1741a874a63eSLiu Bo 		goto out_drop_write;
174216780cabSChris Mason 	}
174316780cabSChris Mason 
17443de4586cSChris Mason 	if (subvol) {
174572fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
17466f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1747cb8e7090SChristoph Hellwig 	} else {
17482903ff01SAl Viro 		struct fd src = fdget(fd);
17493de4586cSChris Mason 		struct inode *src_inode;
17502903ff01SAl Viro 		if (!src.file) {
17513de4586cSChris Mason 			ret = -EINVAL;
1752a874a63eSLiu Bo 			goto out_drop_write;
17533de4586cSChris Mason 		}
17543de4586cSChris Mason 
1755496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1756496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1757c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1758efe120a0SFrank Holton 				   "Snapshot src from another FS");
175923ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1760d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1761d0242061SDavid Sterba 			/*
1762d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1763d0242061SDavid Sterba 			 * are limited to own subvolumes only
1764d0242061SDavid Sterba 			 */
1765d0242061SDavid Sterba 			ret = -EPERM;
1766ecd18815SAl Viro 		} else {
176772fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
176872fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
17696f72c7e2SArne Jansen 					     transid, readonly, inherit);
1770ecd18815SAl Viro 		}
17712903ff01SAl Viro 		fdput(src);
1772cb8e7090SChristoph Hellwig 	}
1773a874a63eSLiu Bo out_drop_write:
1774a874a63eSLiu Bo 	mnt_drop_write_file(file);
1775f46b5a66SChristoph Hellwig out:
177672fd032eSSage Weil 	return ret;
177772fd032eSSage Weil }
177872fd032eSSage Weil 
177972fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1780fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
178172fd032eSSage Weil {
1782fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
178372fd032eSSage Weil 	int ret;
178472fd032eSSage Weil 
1785325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1786325c50e3SJeff Mahoney 		return -ENOTDIR;
1787325c50e3SJeff Mahoney 
1788fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1789fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1790fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1791fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1792fa0d2b9bSLi Zefan 
1793fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1794b83cc969SLi Zefan 					      vol_args->fd, subvol,
17956f72c7e2SArne Jansen 					      NULL, false, NULL);
1796fa0d2b9bSLi Zefan 
1797fa0d2b9bSLi Zefan 	kfree(vol_args);
1798fa0d2b9bSLi Zefan 	return ret;
1799fa0d2b9bSLi Zefan }
1800fa0d2b9bSLi Zefan 
1801fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1802fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1803fa0d2b9bSLi Zefan {
1804fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1805fa0d2b9bSLi Zefan 	int ret;
1806fdfb1e4fSLi Zefan 	u64 transid = 0;
1807fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1808b83cc969SLi Zefan 	bool readonly = false;
18096f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
181072fd032eSSage Weil 
1811325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1812325c50e3SJeff Mahoney 		return -ENOTDIR;
1813325c50e3SJeff Mahoney 
1814fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1815fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1816fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1817fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1818fdfb1e4fSLi Zefan 
1819b83cc969SLi Zefan 	if (vol_args->flags &
18206f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
18216f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1822b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1823c47ca32dSDan Carpenter 		goto free_args;
1824fdfb1e4fSLi Zefan 	}
1825fdfb1e4fSLi Zefan 
1826fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1827fdfb1e4fSLi Zefan 		ptr = &transid;
1828b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1829b83cc969SLi Zefan 		readonly = true;
18306f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
183109cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
18326f72c7e2SArne Jansen 			ret = -EINVAL;
1833c47ca32dSDan Carpenter 			goto free_args;
18346f72c7e2SArne Jansen 		}
18356f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
18366f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
18376f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1838c47ca32dSDan Carpenter 			goto free_args;
18396f72c7e2SArne Jansen 		}
18406f72c7e2SArne Jansen 	}
184175eaa0e2SSage Weil 
1842fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
18436f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
18448696c533SMiao Xie 					      readonly, inherit);
1845c47ca32dSDan Carpenter 	if (ret)
1846c47ca32dSDan Carpenter 		goto free_inherit;
184775eaa0e2SSage Weil 
1848c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1849fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1850c47ca32dSDan Carpenter 					transid),
1851c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
185275eaa0e2SSage Weil 		ret = -EFAULT;
1853c47ca32dSDan Carpenter 
1854c47ca32dSDan Carpenter free_inherit:
18556f72c7e2SArne Jansen 	kfree(inherit);
1856c47ca32dSDan Carpenter free_args:
1857c47ca32dSDan Carpenter 	kfree(vol_args);
1858f46b5a66SChristoph Hellwig 	return ret;
1859f46b5a66SChristoph Hellwig }
1860f46b5a66SChristoph Hellwig 
18610caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
18620caa102dSLi Zefan 						void __user *arg)
18630caa102dSLi Zefan {
1864496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18660caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
18670caa102dSLi Zefan 	int ret = 0;
18680caa102dSLi Zefan 	u64 flags = 0;
18690caa102dSLi Zefan 
18704a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
18710caa102dSLi Zefan 		return -EINVAL;
18720caa102dSLi Zefan 
18730b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
18740caa102dSLi Zefan 	if (btrfs_root_readonly(root))
18750caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
18760b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
18770caa102dSLi Zefan 
18780caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
18790caa102dSLi Zefan 		ret = -EFAULT;
18800caa102dSLi Zefan 
18810caa102dSLi Zefan 	return ret;
18820caa102dSLi Zefan }
18830caa102dSLi Zefan 
18840caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
18850caa102dSLi Zefan 					      void __user *arg)
18860caa102dSLi Zefan {
1887496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18890caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
18900caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
18910caa102dSLi Zefan 	u64 root_flags;
18920caa102dSLi Zefan 	u64 flags;
18930caa102dSLi Zefan 	int ret = 0;
18940caa102dSLi Zefan 
1895bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1896bd60ea0fSDavid Sterba 		return -EPERM;
1897bd60ea0fSDavid Sterba 
1898b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1899b9ca0664SLiu Bo 	if (ret)
1900b9ca0664SLiu Bo 		goto out;
19010caa102dSLi Zefan 
19024a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1903b9ca0664SLiu Bo 		ret = -EINVAL;
1904b9ca0664SLiu Bo 		goto out_drop_write;
1905b9ca0664SLiu Bo 	}
19060caa102dSLi Zefan 
1907b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1908b9ca0664SLiu Bo 		ret = -EFAULT;
1909b9ca0664SLiu Bo 		goto out_drop_write;
1910b9ca0664SLiu Bo 	}
19110caa102dSLi Zefan 
1912b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1913b9ca0664SLiu Bo 		ret = -EINVAL;
1914b9ca0664SLiu Bo 		goto out_drop_write;
1915b9ca0664SLiu Bo 	}
19160caa102dSLi Zefan 
1917b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1918b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1919b9ca0664SLiu Bo 		goto out_drop_write;
1920b9ca0664SLiu Bo 	}
19210caa102dSLi Zefan 
19220b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
19230caa102dSLi Zefan 
19240caa102dSLi Zefan 	/* nothing to do */
19250caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1926b9ca0664SLiu Bo 		goto out_drop_sem;
19270caa102dSLi Zefan 
19280caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
19292c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
19300caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
19310caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
19322c686537SDavid Sterba 	} else {
19332c686537SDavid Sterba 		/*
19342c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
19352c686537SDavid Sterba 		 * send
19362c686537SDavid Sterba 		 */
19372c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
19382c686537SDavid Sterba 		if (root->send_in_progress == 0) {
19390caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
19400caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
19412c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19422c686537SDavid Sterba 		} else {
19432c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19440b246afaSJeff Mahoney 			btrfs_warn(fs_info,
19452c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
19462c686537SDavid Sterba 				   root->root_key.objectid);
19472c686537SDavid Sterba 			ret = -EPERM;
19482c686537SDavid Sterba 			goto out_drop_sem;
19492c686537SDavid Sterba 		}
19502c686537SDavid Sterba 	}
19510caa102dSLi Zefan 
19520caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
19530caa102dSLi Zefan 	if (IS_ERR(trans)) {
19540caa102dSLi Zefan 		ret = PTR_ERR(trans);
19550caa102dSLi Zefan 		goto out_reset;
19560caa102dSLi Zefan 	}
19570caa102dSLi Zefan 
19580b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
19590caa102dSLi Zefan 				&root->root_key, &root->root_item);
19609417ebc8SNikolay Borisov 	if (ret < 0) {
19619417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
19629417ebc8SNikolay Borisov 		goto out_reset;
19639417ebc8SNikolay Borisov 	}
19640caa102dSLi Zefan 
19659417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
19669417ebc8SNikolay Borisov 
19670caa102dSLi Zefan out_reset:
19680caa102dSLi Zefan 	if (ret)
19690caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1970b9ca0664SLiu Bo out_drop_sem:
19710b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
1972b9ca0664SLiu Bo out_drop_write:
1973b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1974b9ca0664SLiu Bo out:
19750caa102dSLi Zefan 	return ret;
19760caa102dSLi Zefan }
19770caa102dSLi Zefan 
1978ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1979ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1980ac8e9819SChris Mason {
1981abc6e134SChris Mason 	struct btrfs_key test;
1982abc6e134SChris Mason 	int ret;
1983abc6e134SChris Mason 
1984abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1985abc6e134SChris Mason 	test.type = sk->min_type;
1986abc6e134SChris Mason 	test.offset = sk->min_offset;
1987abc6e134SChris Mason 
1988abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1989abc6e134SChris Mason 	if (ret < 0)
1990ac8e9819SChris Mason 		return 0;
1991abc6e134SChris Mason 
1992abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1993abc6e134SChris Mason 	test.type = sk->max_type;
1994abc6e134SChris Mason 	test.offset = sk->max_offset;
1995abc6e134SChris Mason 
1996abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1997abc6e134SChris Mason 	if (ret > 0)
1998ac8e9819SChris Mason 		return 0;
1999ac8e9819SChris Mason 	return 1;
2000ac8e9819SChris Mason }
2001ac8e9819SChris Mason 
2002df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
2003ac8e9819SChris Mason 			       struct btrfs_key *key,
2004ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
20059b6e817dSGerhard Heift 			       size_t *buf_size,
2006ba346b35SGerhard Heift 			       char __user *ubuf,
2007ac8e9819SChris Mason 			       unsigned long *sk_offset,
2008ac8e9819SChris Mason 			       int *num_found)
2009ac8e9819SChris Mason {
2010ac8e9819SChris Mason 	u64 found_transid;
2011ac8e9819SChris Mason 	struct extent_buffer *leaf;
2012ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
2013dd81d459SNaohiro Aota 	struct btrfs_key test;
2014ac8e9819SChris Mason 	unsigned long item_off;
2015ac8e9819SChris Mason 	unsigned long item_len;
2016ac8e9819SChris Mason 	int nritems;
2017ac8e9819SChris Mason 	int i;
2018ac8e9819SChris Mason 	int slot;
2019ac8e9819SChris Mason 	int ret = 0;
2020ac8e9819SChris Mason 
2021ac8e9819SChris Mason 	leaf = path->nodes[0];
2022ac8e9819SChris Mason 	slot = path->slots[0];
2023ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
2024ac8e9819SChris Mason 
2025ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
2026ac8e9819SChris Mason 		i = nritems;
2027ac8e9819SChris Mason 		goto advance_key;
2028ac8e9819SChris Mason 	}
2029ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
2030ac8e9819SChris Mason 
2031ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
2032ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
2033ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
2034ac8e9819SChris Mason 
203503b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
203603b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
203703b71c6cSGabriel de Perthuis 			continue;
203803b71c6cSGabriel de Perthuis 
20399b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
20408f5f6178SGerhard Heift 			if (*num_found) {
2041ac8e9819SChris Mason 				ret = 1;
20428f5f6178SGerhard Heift 				goto out;
20438f5f6178SGerhard Heift 			}
20448f5f6178SGerhard Heift 
20458f5f6178SGerhard Heift 			/*
20468f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
20478f5f6178SGerhard Heift 			 * handle -EOVERFLOW
20488f5f6178SGerhard Heift 			 */
20498f5f6178SGerhard Heift 
20509b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
2051ac8e9819SChris Mason 			item_len = 0;
20528f5f6178SGerhard Heift 			ret = -EOVERFLOW;
20538f5f6178SGerhard Heift 		}
2054ac8e9819SChris Mason 
20559b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2056ac8e9819SChris Mason 			ret = 1;
205725c9bc2eSGerhard Heift 			goto out;
2058ac8e9819SChris Mason 		}
2059ac8e9819SChris Mason 
2060ac8e9819SChris Mason 		sh.objectid = key->objectid;
2061ac8e9819SChris Mason 		sh.offset = key->offset;
2062ac8e9819SChris Mason 		sh.type = key->type;
2063ac8e9819SChris Mason 		sh.len = item_len;
2064ac8e9819SChris Mason 		sh.transid = found_transid;
2065ac8e9819SChris Mason 
2066ac8e9819SChris Mason 		/* copy search result header */
2067ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2068ba346b35SGerhard Heift 			ret = -EFAULT;
2069ba346b35SGerhard Heift 			goto out;
2070ba346b35SGerhard Heift 		}
2071ba346b35SGerhard Heift 
2072ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2073ac8e9819SChris Mason 
2074ac8e9819SChris Mason 		if (item_len) {
2075ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2076ac8e9819SChris Mason 			/* copy the item */
2077ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
2078ba346b35SGerhard Heift 						       item_off, item_len)) {
2079ba346b35SGerhard Heift 				ret = -EFAULT;
2080ba346b35SGerhard Heift 				goto out;
2081ba346b35SGerhard Heift 			}
2082ba346b35SGerhard Heift 
2083ac8e9819SChris Mason 			*sk_offset += item_len;
2084ac8e9819SChris Mason 		}
2085e2156867SHugo Mills 		(*num_found)++;
2086ac8e9819SChris Mason 
20878f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
20888f5f6178SGerhard Heift 			goto out;
20898f5f6178SGerhard Heift 
209025c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
209125c9bc2eSGerhard Heift 			ret = 1;
209225c9bc2eSGerhard Heift 			goto out;
209325c9bc2eSGerhard Heift 		}
2094ac8e9819SChris Mason 	}
2095ac8e9819SChris Mason advance_key:
2096ac8e9819SChris Mason 	ret = 0;
2097dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2098dd81d459SNaohiro Aota 	test.type = sk->max_type;
2099dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2100dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2101dd81d459SNaohiro Aota 		ret = 1;
2102dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2103abc6e134SChris Mason 		key->offset++;
2104dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2105abc6e134SChris Mason 		key->offset = 0;
2106abc6e134SChris Mason 		key->type++;
2107dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2108abc6e134SChris Mason 		key->offset = 0;
2109abc6e134SChris Mason 		key->type = 0;
2110abc6e134SChris Mason 		key->objectid++;
2111abc6e134SChris Mason 	} else
2112abc6e134SChris Mason 		ret = 1;
211325c9bc2eSGerhard Heift out:
2114ba346b35SGerhard Heift 	/*
2115ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2116ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2117ba346b35SGerhard Heift 	 *     * all items were found
2118ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2119ba346b35SGerhard Heift 	 *     leaf
2120ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2121ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2122ba346b35SGerhard Heift 	 */
2123ac8e9819SChris Mason 	return ret;
2124ac8e9819SChris Mason }
2125ac8e9819SChris Mason 
2126ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
212712544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
21289b6e817dSGerhard Heift 				 size_t *buf_size,
2129ba346b35SGerhard Heift 				 char __user *ubuf)
2130ac8e9819SChris Mason {
21310b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2132ac8e9819SChris Mason 	struct btrfs_root *root;
2133ac8e9819SChris Mason 	struct btrfs_key key;
2134ac8e9819SChris Mason 	struct btrfs_path *path;
2135ac8e9819SChris Mason 	int ret;
2136ac8e9819SChris Mason 	int num_found = 0;
2137ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2138ac8e9819SChris Mason 
21399b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
21409b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
214112544442SGerhard Heift 		return -EOVERFLOW;
21429b6e817dSGerhard Heift 	}
214312544442SGerhard Heift 
2144ac8e9819SChris Mason 	path = btrfs_alloc_path();
2145ac8e9819SChris Mason 	if (!path)
2146ac8e9819SChris Mason 		return -ENOMEM;
2147ac8e9819SChris Mason 
2148ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2149ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2150ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2151ac8e9819SChris Mason 	} else {
2152ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2153ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2154ac8e9819SChris Mason 		key.offset = (u64)-1;
2155ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2156ac8e9819SChris Mason 		if (IS_ERR(root)) {
2157ac8e9819SChris Mason 			btrfs_free_path(path);
2158ad1e3d56SMisono Tomohiro 			return PTR_ERR(root);
2159ac8e9819SChris Mason 		}
2160ac8e9819SChris Mason 	}
2161ac8e9819SChris Mason 
2162ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2163ac8e9819SChris Mason 	key.type = sk->min_type;
2164ac8e9819SChris Mason 	key.offset = sk->min_offset;
2165ac8e9819SChris Mason 
2166ac8e9819SChris Mason 	while (1) {
21676174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2168ac8e9819SChris Mason 		if (ret != 0) {
2169ac8e9819SChris Mason 			if (ret > 0)
2170ac8e9819SChris Mason 				ret = 0;
2171ac8e9819SChris Mason 			goto err;
2172ac8e9819SChris Mason 		}
2173df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2174ac8e9819SChris Mason 				 &sk_offset, &num_found);
2175b3b4aa74SDavid Sterba 		btrfs_release_path(path);
217625c9bc2eSGerhard Heift 		if (ret)
2177ac8e9819SChris Mason 			break;
2178ac8e9819SChris Mason 
2179ac8e9819SChris Mason 	}
21808f5f6178SGerhard Heift 	if (ret > 0)
2181ac8e9819SChris Mason 		ret = 0;
2182ac8e9819SChris Mason err:
2183ac8e9819SChris Mason 	sk->nr_items = num_found;
2184ac8e9819SChris Mason 	btrfs_free_path(path);
2185ac8e9819SChris Mason 	return ret;
2186ac8e9819SChris Mason }
2187ac8e9819SChris Mason 
2188ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2189ac8e9819SChris Mason 					   void __user *argp)
2190ac8e9819SChris Mason {
2191ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2192ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2193ac8e9819SChris Mason 	struct inode *inode;
2194ac8e9819SChris Mason 	int ret;
21959b6e817dSGerhard Heift 	size_t buf_size;
2196ac8e9819SChris Mason 
2197ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2198ac8e9819SChris Mason 		return -EPERM;
2199ac8e9819SChris Mason 
2200ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2201ac8e9819SChris Mason 
2202ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2203ba346b35SGerhard Heift 		return -EFAULT;
2204ba346b35SGerhard Heift 
2205ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2206ac8e9819SChris Mason 
2207496ad9aaSAl Viro 	inode = file_inode(file);
2208ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
22098f5f6178SGerhard Heift 
22108f5f6178SGerhard Heift 	/*
22118f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
22128f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
22138f5f6178SGerhard Heift 	 */
22148f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
22158f5f6178SGerhard Heift 		ret = 0;
22168f5f6178SGerhard Heift 
2217ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2218ac8e9819SChris Mason 		ret = -EFAULT;
2219ac8e9819SChris Mason 	return ret;
2220ac8e9819SChris Mason }
2221ac8e9819SChris Mason 
2222cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2223cc68a8a5SGerhard Heift 					       void __user *argp)
2224cc68a8a5SGerhard Heift {
2225cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2226cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2227cc68a8a5SGerhard Heift 	struct inode *inode;
2228cc68a8a5SGerhard Heift 	int ret;
2229cc68a8a5SGerhard Heift 	size_t buf_size;
2230ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2231cc68a8a5SGerhard Heift 
2232cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2233cc68a8a5SGerhard Heift 		return -EPERM;
2234cc68a8a5SGerhard Heift 
2235cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2236cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2237cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2238cc68a8a5SGerhard Heift 		return -EFAULT;
2239cc68a8a5SGerhard Heift 
2240cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2241cc68a8a5SGerhard Heift 
2242cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2243cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2244cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2245cc68a8a5SGerhard Heift 
2246cc68a8a5SGerhard Heift 	inode = file_inode(file);
2247cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2248718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2249cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2250cc68a8a5SGerhard Heift 		ret = -EFAULT;
2251cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2252cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2253cc68a8a5SGerhard Heift 		ret = -EFAULT;
2254cc68a8a5SGerhard Heift 
225576dda93cSYan, Zheng 	return ret;
225676dda93cSYan, Zheng }
225776dda93cSYan, Zheng 
225898d377a0STARUISI Hiroaki /*
2259ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2260ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
226198d377a0STARUISI Hiroaki  */
226298d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
226398d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
226498d377a0STARUISI Hiroaki {
226598d377a0STARUISI Hiroaki 	struct btrfs_root *root;
226698d377a0STARUISI Hiroaki 	struct btrfs_key key;
2267ac8e9819SChris Mason 	char *ptr;
226898d377a0STARUISI Hiroaki 	int ret = -1;
226998d377a0STARUISI Hiroaki 	int slot;
227098d377a0STARUISI Hiroaki 	int len;
227198d377a0STARUISI Hiroaki 	int total_len = 0;
227298d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
227398d377a0STARUISI Hiroaki 	struct extent_buffer *l;
227498d377a0STARUISI Hiroaki 	struct btrfs_path *path;
227598d377a0STARUISI Hiroaki 
227698d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
227798d377a0STARUISI Hiroaki 		name[0]='\0';
227898d377a0STARUISI Hiroaki 		return 0;
227998d377a0STARUISI Hiroaki 	}
228098d377a0STARUISI Hiroaki 
228198d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
228298d377a0STARUISI Hiroaki 	if (!path)
228398d377a0STARUISI Hiroaki 		return -ENOMEM;
228498d377a0STARUISI Hiroaki 
2285c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
228698d377a0STARUISI Hiroaki 
228798d377a0STARUISI Hiroaki 	key.objectid = tree_id;
228898d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
228998d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
229098d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
229198d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2292ad1e3d56SMisono Tomohiro 		ret = PTR_ERR(root);
22938ad6fcabSChris Mason 		goto out;
229498d377a0STARUISI Hiroaki 	}
229598d377a0STARUISI Hiroaki 
229698d377a0STARUISI Hiroaki 	key.objectid = dirid;
229798d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
22988ad6fcabSChris Mason 	key.offset = (u64)-1;
229998d377a0STARUISI Hiroaki 
230098d377a0STARUISI Hiroaki 	while (1) {
230198d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
230298d377a0STARUISI Hiroaki 		if (ret < 0)
230398d377a0STARUISI Hiroaki 			goto out;
230418674c6cSFilipe David Borba Manana 		else if (ret > 0) {
230518674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
230618674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
230718674c6cSFilipe David Borba Manana 			if (ret < 0)
230818674c6cSFilipe David Borba Manana 				goto out;
230918674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2310ac8e9819SChris Mason 				ret = -ENOENT;
231198d377a0STARUISI Hiroaki 				goto out;
2312ac8e9819SChris Mason 			}
231318674c6cSFilipe David Borba Manana 		}
231418674c6cSFilipe David Borba Manana 
231518674c6cSFilipe David Borba Manana 		l = path->nodes[0];
231618674c6cSFilipe David Borba Manana 		slot = path->slots[0];
231718674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
231898d377a0STARUISI Hiroaki 
231998d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
232098d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
232198d377a0STARUISI Hiroaki 		ptr -= len + 1;
232298d377a0STARUISI Hiroaki 		total_len += len + 1;
2323a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2324a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
232598d377a0STARUISI Hiroaki 			goto out;
2326a696cf35SFilipe David Borba Manana 		}
232798d377a0STARUISI Hiroaki 
232898d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
232998d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
233098d377a0STARUISI Hiroaki 
233198d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
233298d377a0STARUISI Hiroaki 			break;
233398d377a0STARUISI Hiroaki 
2334b3b4aa74SDavid Sterba 		btrfs_release_path(path);
233598d377a0STARUISI Hiroaki 		key.objectid = key.offset;
23368ad6fcabSChris Mason 		key.offset = (u64)-1;
233798d377a0STARUISI Hiroaki 		dirid = key.objectid;
233898d377a0STARUISI Hiroaki 	}
233977906a50SLi Zefan 	memmove(name, ptr, total_len);
234098d377a0STARUISI Hiroaki 	name[total_len] = '\0';
234198d377a0STARUISI Hiroaki 	ret = 0;
234298d377a0STARUISI Hiroaki out:
234398d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2344ac8e9819SChris Mason 	return ret;
2345ac8e9819SChris Mason }
2346ac8e9819SChris Mason 
2347ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2348ac8e9819SChris Mason 					   void __user *argp)
2349ac8e9819SChris Mason {
2350ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2351ac8e9819SChris Mason 	 struct inode *inode;
235201b810b8SDavid Sterba 	int ret = 0;
2353ac8e9819SChris Mason 
23542354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
23552354d08fSJulia Lawall 	if (IS_ERR(args))
23562354d08fSJulia Lawall 		return PTR_ERR(args);
2357c2b96929SDan Carpenter 
2358496ad9aaSAl Viro 	inode = file_inode(file);
2359ac8e9819SChris Mason 
236001b810b8SDavid Sterba 	/*
236101b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
236201b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
236301b810b8SDavid Sterba 	 */
23641b53ac4dSChris Mason 	if (args->treeid == 0)
23651b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
23661b53ac4dSChris Mason 
236701b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
236801b810b8SDavid Sterba 		args->name[0] = 0;
236901b810b8SDavid Sterba 		goto out;
237001b810b8SDavid Sterba 	}
237101b810b8SDavid Sterba 
237201b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
237301b810b8SDavid Sterba 		ret = -EPERM;
237401b810b8SDavid Sterba 		goto out;
237501b810b8SDavid Sterba 	}
237601b810b8SDavid Sterba 
2377ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2378ac8e9819SChris Mason 					args->treeid, args->objectid,
2379ac8e9819SChris Mason 					args->name);
2380ac8e9819SChris Mason 
238101b810b8SDavid Sterba out:
2382ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2383ac8e9819SChris Mason 		ret = -EFAULT;
2384ac8e9819SChris Mason 
2385ac8e9819SChris Mason 	kfree(args);
238698d377a0STARUISI Hiroaki 	return ret;
238798d377a0STARUISI Hiroaki }
238898d377a0STARUISI Hiroaki 
238976dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
239076dda93cSYan, Zheng 					     void __user *arg)
239176dda93cSYan, Zheng {
239254563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
23930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
239476dda93cSYan, Zheng 	struct dentry *dentry;
23952b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
239676dda93cSYan, Zheng 	struct inode *inode;
239776dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
239876dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
239976dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
240076dda93cSYan, Zheng 	int namelen;
240176dda93cSYan, Zheng 	int err = 0;
240276dda93cSYan, Zheng 
2403325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2404325c50e3SJeff Mahoney 		return -ENOTDIR;
2405325c50e3SJeff Mahoney 
240676dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
240776dda93cSYan, Zheng 	if (IS_ERR(vol_args))
240876dda93cSYan, Zheng 		return PTR_ERR(vol_args);
240976dda93cSYan, Zheng 
241076dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
241176dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
241276dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
241376dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
241476dda93cSYan, Zheng 		err = -EINVAL;
241576dda93cSYan, Zheng 		goto out;
241676dda93cSYan, Zheng 	}
241776dda93cSYan, Zheng 
2418a561be71SAl Viro 	err = mnt_want_write_file(file);
241976dda93cSYan, Zheng 	if (err)
242076dda93cSYan, Zheng 		goto out;
242176dda93cSYan, Zheng 
2422521e0546SDavid Sterba 
242300235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
242400235411SAl Viro 	if (err == -EINTR)
242500235411SAl Viro 		goto out_drop_write;
242676dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
242776dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
242876dda93cSYan, Zheng 		err = PTR_ERR(dentry);
242976dda93cSYan, Zheng 		goto out_unlock_dir;
243076dda93cSYan, Zheng 	}
243176dda93cSYan, Zheng 
24322b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
243376dda93cSYan, Zheng 		err = -ENOENT;
243476dda93cSYan, Zheng 		goto out_dput;
243576dda93cSYan, Zheng 	}
243676dda93cSYan, Zheng 
24372b0143b5SDavid Howells 	inode = d_inode(dentry);
24384260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
24394260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
24404260f7c7SSage Weil 		/*
24414260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
24424260f7c7SSage Weil 		 * option, when the user has write+exec access to the
24434260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
24444260f7c7SSage Weil 		 * allowed.
24454260f7c7SSage Weil 		 *
24464260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
24474260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
24484260f7c7SSage Weil 		 * otherwise be able to delete.
24494260f7c7SSage Weil 		 *
24504260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
24514260f7c7SSage Weil 		 * rmdir(2).
24524260f7c7SSage Weil 		 */
24534260f7c7SSage Weil 		err = -EPERM;
24540b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
24554260f7c7SSage Weil 			goto out_dput;
24564260f7c7SSage Weil 
24574260f7c7SSage Weil 		/*
24584260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
24594260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
24604260f7c7SSage Weil 		 * must be called on the dentry referencing the root
24614260f7c7SSage Weil 		 * of the subvol, not a random directory contained
24624260f7c7SSage Weil 		 * within it.
24634260f7c7SSage Weil 		 */
24644260f7c7SSage Weil 		err = -EINVAL;
24654260f7c7SSage Weil 		if (root == dest)
24664260f7c7SSage Weil 			goto out_dput;
24674260f7c7SSage Weil 
24684260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
24694260f7c7SSage Weil 		if (err)
24704260f7c7SSage Weil 			goto out_dput;
24715c39da5bSMiao Xie 	}
24724260f7c7SSage Weil 
24735c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
24744260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
24754260f7c7SSage Weil 	if (err)
24764260f7c7SSage Weil 		goto out_dput;
24774260f7c7SSage Weil 
24784a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
247976dda93cSYan, Zheng 		err = -EINVAL;
248076dda93cSYan, Zheng 		goto out_dput;
248176dda93cSYan, Zheng 	}
248276dda93cSYan, Zheng 
24835955102cSAl Viro 	inode_lock(inode);
2484f60a2364SMisono Tomohiro 	err = btrfs_delete_subvolume(dir, dentry);
24855955102cSAl Viro 	inode_unlock(inode);
2486f60a2364SMisono Tomohiro 	if (!err)
248776dda93cSYan, Zheng 		d_delete(dentry);
2488fa6ac876SLiu Bo 
248976dda93cSYan, Zheng out_dput:
249076dda93cSYan, Zheng 	dput(dentry);
249176dda93cSYan, Zheng out_unlock_dir:
24925955102cSAl Viro 	inode_unlock(dir);
249300235411SAl Viro out_drop_write:
24942a79f17eSAl Viro 	mnt_drop_write_file(file);
249576dda93cSYan, Zheng out:
249676dda93cSYan, Zheng 	kfree(vol_args);
249776dda93cSYan, Zheng 	return err;
249876dda93cSYan, Zheng }
249976dda93cSYan, Zheng 
25001e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2501f46b5a66SChristoph Hellwig {
2502496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2503f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
25041e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2505c146afadSYan Zheng 	int ret;
2506c146afadSYan Zheng 
250725122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
250825122d15SIlya Dryomov 	if (ret)
250925122d15SIlya Dryomov 		return ret;
2510b83cc969SLi Zefan 
251125122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
251225122d15SIlya Dryomov 		ret = -EROFS;
251325122d15SIlya Dryomov 		goto out;
25145ac00addSStefan Behrens 	}
2515f46b5a66SChristoph Hellwig 
2516f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2517f46b5a66SChristoph Hellwig 	case S_IFDIR:
2518e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2519e441d54dSChris Mason 			ret = -EPERM;
2520e441d54dSChris Mason 			goto out;
2521e441d54dSChris Mason 		}
2522de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
2523f46b5a66SChristoph Hellwig 		break;
2524f46b5a66SChristoph Hellwig 	case S_IFREG:
2525e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2526e441d54dSChris Mason 			ret = -EINVAL;
2527e441d54dSChris Mason 			goto out;
2528e441d54dSChris Mason 		}
25291e701a32SChris Mason 
25301e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
25311e701a32SChris Mason 		if (!range) {
25321e701a32SChris Mason 			ret = -ENOMEM;
25331e701a32SChris Mason 			goto out;
25341e701a32SChris Mason 		}
25351e701a32SChris Mason 
25361e701a32SChris Mason 		if (argp) {
25371e701a32SChris Mason 			if (copy_from_user(range, argp,
25381e701a32SChris Mason 					   sizeof(*range))) {
25391e701a32SChris Mason 				ret = -EFAULT;
25401e701a32SChris Mason 				kfree(range);
2541683be16eSDan Carpenter 				goto out;
25421e701a32SChris Mason 			}
25431e701a32SChris Mason 			/* compression requires us to start the IO */
25441e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
25451e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
25461e701a32SChris Mason 				range->extent_thresh = (u32)-1;
25471e701a32SChris Mason 			}
25481e701a32SChris Mason 		} else {
25491e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
25501e701a32SChris Mason 			range->len = (u64)-1;
25511e701a32SChris Mason 		}
2552496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
25537c829b72SAnand Jain 					range, BTRFS_OLDEST_GENERATION, 0);
25544cb5300bSChris Mason 		if (ret > 0)
25554cb5300bSChris Mason 			ret = 0;
25561e701a32SChris Mason 		kfree(range);
2557f46b5a66SChristoph Hellwig 		break;
25588929ecfaSYan, Zheng 	default:
25598929ecfaSYan, Zheng 		ret = -EINVAL;
2560f46b5a66SChristoph Hellwig 	}
2561e441d54dSChris Mason out:
256225122d15SIlya Dryomov 	mnt_drop_write_file(file);
2563e441d54dSChris Mason 	return ret;
2564f46b5a66SChristoph Hellwig }
2565f46b5a66SChristoph Hellwig 
25662ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2567f46b5a66SChristoph Hellwig {
2568f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2569f46b5a66SChristoph Hellwig 	int ret;
2570f46b5a66SChristoph Hellwig 
2571e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2572e441d54dSChris Mason 		return -EPERM;
2573e441d54dSChris Mason 
2574171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2575e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2576c9e9f97bSIlya Dryomov 
2577dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2578c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2579c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2580c9e9f97bSIlya Dryomov 		goto out;
2581c9e9f97bSIlya Dryomov 	}
2582f46b5a66SChristoph Hellwig 
25835516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
25842ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
2585f46b5a66SChristoph Hellwig 
258643d20761SAnand Jain 	if (!ret)
25870b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
258843d20761SAnand Jain 
2589f46b5a66SChristoph Hellwig 	kfree(vol_args);
2590c9e9f97bSIlya Dryomov out:
2591171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2592f46b5a66SChristoph Hellwig 	return ret;
2593f46b5a66SChristoph Hellwig }
2594f46b5a66SChristoph Hellwig 
25956b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
2596f46b5a66SChristoph Hellwig {
25970b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
25980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
25996b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
2600f46b5a66SChristoph Hellwig 	int ret;
2601f46b5a66SChristoph Hellwig 
2602e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2603e441d54dSChris Mason 		return -EPERM;
2604e441d54dSChris Mason 
2605da24927bSMiao Xie 	ret = mnt_want_write_file(file);
2606da24927bSMiao Xie 	if (ret)
2607da24927bSMiao Xie 		return ret;
2608c146afadSYan Zheng 
2609dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2610c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2611c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2612c47ca32dSDan Carpenter 		goto err_drop;
2613c9e9f97bSIlya Dryomov 	}
2614f46b5a66SChristoph Hellwig 
26156b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
2616fd4e994bSOmar Sandoval 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
2617fd4e994bSOmar Sandoval 		ret = -EOPNOTSUPP;
2618fd4e994bSOmar Sandoval 		goto out;
2619fd4e994bSOmar Sandoval 	}
2620f46b5a66SChristoph Hellwig 
2621171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2622183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2623183860f6SAnand Jain 		goto out;
2624183860f6SAnand Jain 	}
2625183860f6SAnand Jain 
2626735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
26272ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
26286b526ed7SAnand Jain 	} else {
26296b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
26302ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
26316b526ed7SAnand Jain 	}
2632171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2633183860f6SAnand Jain 
26346b526ed7SAnand Jain 	if (!ret) {
2635735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
26360b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
26376b526ed7SAnand Jain 					vol_args->devid);
26386b526ed7SAnand Jain 		else
26390b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
26406b526ed7SAnand Jain 					vol_args->name);
26416b526ed7SAnand Jain 	}
2642183860f6SAnand Jain out:
2643183860f6SAnand Jain 	kfree(vol_args);
2644c47ca32dSDan Carpenter err_drop:
26454ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
2646f46b5a66SChristoph Hellwig 	return ret;
2647f46b5a66SChristoph Hellwig }
2648f46b5a66SChristoph Hellwig 
2649f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2650f46b5a66SChristoph Hellwig {
26510b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
26520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2653f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2654f46b5a66SChristoph Hellwig 	int ret;
2655f46b5a66SChristoph Hellwig 
2656f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
2657f46b5a66SChristoph Hellwig 		return -EPERM;
2658f46b5a66SChristoph Hellwig 
2659f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
2660f46b5a66SChristoph Hellwig 	if (ret)
2661f46b5a66SChristoph Hellwig 		return ret;
2662f46b5a66SChristoph Hellwig 
2663171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2664f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
266558d7bbf8SDavid Sterba 		goto out_drop_write;
266658d7bbf8SDavid Sterba 	}
266758d7bbf8SDavid Sterba 
266858d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
266958d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
267058d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
2671f46b5a66SChristoph Hellwig 		goto out;
2672f46b5a66SChristoph Hellwig 	}
2673f46b5a66SChristoph Hellwig 
267458d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
26752ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
2676f46b5a66SChristoph Hellwig 
2677f46b5a66SChristoph Hellwig 	if (!ret)
26780b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
2679f46b5a66SChristoph Hellwig 	kfree(vol_args);
268058d7bbf8SDavid Sterba out:
2681171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
268258d7bbf8SDavid Sterba out_drop_write:
2683f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
268458d7bbf8SDavid Sterba 
2685f46b5a66SChristoph Hellwig 	return ret;
2686f46b5a66SChristoph Hellwig }
2687f46b5a66SChristoph Hellwig 
26882ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
26892ff7e61eSJeff Mahoney 				void __user *arg)
2690475f6387SJan Schmidt {
2691027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
2692475f6387SJan Schmidt 	struct btrfs_device *device;
26930b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2694027ed2f0SLi Zefan 	int ret = 0;
2695475f6387SJan Schmidt 
2696027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2697027ed2f0SLi Zefan 	if (!fi_args)
2698027ed2f0SLi Zefan 		return -ENOMEM;
2699027ed2f0SLi Zefan 
2700d03262c7SDavid Sterba 	rcu_read_lock();
2701027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
2702475f6387SJan Schmidt 
2703d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2704027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
2705027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
2706475f6387SJan Schmidt 	}
2707d03262c7SDavid Sterba 	rcu_read_unlock();
2708475f6387SJan Schmidt 
2709d03262c7SDavid Sterba 	memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
2710bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
2711bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
2712bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
271380a773fbSDavid Sterba 
2714027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2715027ed2f0SLi Zefan 		ret = -EFAULT;
2716475f6387SJan Schmidt 
2717027ed2f0SLi Zefan 	kfree(fi_args);
2718027ed2f0SLi Zefan 	return ret;
2719475f6387SJan Schmidt }
2720475f6387SJan Schmidt 
27212ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
27222ff7e61eSJeff Mahoney 				 void __user *arg)
2723475f6387SJan Schmidt {
2724475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
2725475f6387SJan Schmidt 	struct btrfs_device *dev;
2726475f6387SJan Schmidt 	int ret = 0;
2727475f6387SJan Schmidt 	char *s_uuid = NULL;
2728475f6387SJan Schmidt 
2729475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
2730475f6387SJan Schmidt 	if (IS_ERR(di_args))
2731475f6387SJan Schmidt 		return PTR_ERR(di_args);
2732475f6387SJan Schmidt 
2733dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
2734475f6387SJan Schmidt 		s_uuid = di_args->uuid;
2735475f6387SJan Schmidt 
2736c5593ca3SDavid Sterba 	rcu_read_lock();
27370b246afaSJeff Mahoney 	dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
2738475f6387SJan Schmidt 
2739475f6387SJan Schmidt 	if (!dev) {
2740475f6387SJan Schmidt 		ret = -ENODEV;
2741475f6387SJan Schmidt 		goto out;
2742475f6387SJan Schmidt 	}
2743475f6387SJan Schmidt 
2744475f6387SJan Schmidt 	di_args->devid = dev->devid;
27457cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
27467cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2747475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2748a27202fbSJim Meyering 	if (dev->name) {
2749606686eeSJosef Bacik 		struct rcu_string *name;
2750606686eeSJosef Bacik 
2751606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
27526670d4c2SXiongfeng Wang 		strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
2753a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
2754a27202fbSJim Meyering 	} else {
275599ba55adSStefan Behrens 		di_args->path[0] = '\0';
2756a27202fbSJim Meyering 	}
2757475f6387SJan Schmidt 
2758475f6387SJan Schmidt out:
2759c5593ca3SDavid Sterba 	rcu_read_unlock();
2760475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2761475f6387SJan Schmidt 		ret = -EFAULT;
2762475f6387SJan Schmidt 
2763475f6387SJan Schmidt 	kfree(di_args);
2764475f6387SJan Schmidt 	return ret;
2765475f6387SJan Schmidt }
2766475f6387SJan Schmidt 
2767f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2768416161dbSMark Fasheh {
2769416161dbSMark Fasheh 	struct page *page;
2770416161dbSMark Fasheh 
2771416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
2772416161dbSMark Fasheh 	if (!page)
277331314002SFilipe Manana 		return ERR_PTR(-ENOMEM);
2774416161dbSMark Fasheh 
2775416161dbSMark Fasheh 	if (!PageUptodate(page)) {
277631314002SFilipe Manana 		int ret;
277731314002SFilipe Manana 
277831314002SFilipe Manana 		ret = btrfs_readpage(NULL, page);
277931314002SFilipe Manana 		if (ret)
278031314002SFilipe Manana 			return ERR_PTR(ret);
2781416161dbSMark Fasheh 		lock_page(page);
2782416161dbSMark Fasheh 		if (!PageUptodate(page)) {
2783416161dbSMark Fasheh 			unlock_page(page);
278409cbfeafSKirill A. Shutemov 			put_page(page);
278531314002SFilipe Manana 			return ERR_PTR(-EIO);
2786416161dbSMark Fasheh 		}
278731314002SFilipe Manana 		if (page->mapping != inode->i_mapping) {
2788416161dbSMark Fasheh 			unlock_page(page);
278909cbfeafSKirill A. Shutemov 			put_page(page);
279031314002SFilipe Manana 			return ERR_PTR(-EAGAIN);
2791416161dbSMark Fasheh 		}
2792416161dbSMark Fasheh 	}
2793416161dbSMark Fasheh 
2794416161dbSMark Fasheh 	return page;
2795416161dbSMark Fasheh }
2796416161dbSMark Fasheh 
2797f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
2798f4414602SMark Fasheh 			       int num_pages, u64 off)
2799f4414602SMark Fasheh {
2800f4414602SMark Fasheh 	int i;
280109cbfeafSKirill A. Shutemov 	pgoff_t index = off >> PAGE_SHIFT;
2802f4414602SMark Fasheh 
2803f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
280431314002SFilipe Manana again:
2805f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
280631314002SFilipe Manana 		if (IS_ERR(pages[i])) {
280731314002SFilipe Manana 			int err = PTR_ERR(pages[i]);
280831314002SFilipe Manana 
280931314002SFilipe Manana 			if (err == -EAGAIN)
281031314002SFilipe Manana 				goto again;
281131314002SFilipe Manana 			pages[i] = NULL;
281231314002SFilipe Manana 			return err;
281331314002SFilipe Manana 		}
2814f4414602SMark Fasheh 	}
2815f4414602SMark Fasheh 	return 0;
2816f4414602SMark Fasheh }
2817f4414602SMark Fasheh 
2818e0bd70c6SFilipe Manana static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2819e0bd70c6SFilipe Manana 			     bool retry_range_locking)
282077fe20dcSMark Fasheh {
2821e0bd70c6SFilipe Manana 	/*
2822e0bd70c6SFilipe Manana 	 * Do any pending delalloc/csum calculations on inode, one way or
2823e0bd70c6SFilipe Manana 	 * another, and lock file content.
2824e0bd70c6SFilipe Manana 	 * The locking order is:
2825e0bd70c6SFilipe Manana 	 *
2826e0bd70c6SFilipe Manana 	 *   1) pages
2827e0bd70c6SFilipe Manana 	 *   2) range in the inode's io tree
2828e0bd70c6SFilipe Manana 	 */
282977fe20dcSMark Fasheh 	while (1) {
283077fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
283177fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
283277fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
283377fe20dcSMark Fasheh 							    off + len - 1);
2834ff5df9b8SFilipe Manana 		if ((!ordered ||
2835ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
2836ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
283777fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2838ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2839ff5df9b8SFilipe Manana 			if (ordered)
2840ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
284177fe20dcSMark Fasheh 			break;
2842ff5df9b8SFilipe Manana 		}
284377fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
284477fe20dcSMark Fasheh 		if (ordered)
284577fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
2846e0bd70c6SFilipe Manana 		if (!retry_range_locking)
2847e0bd70c6SFilipe Manana 			return -EAGAIN;
284877fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
284977fe20dcSMark Fasheh 	}
2850e0bd70c6SFilipe Manana 	return 0;
285177fe20dcSMark Fasheh }
285277fe20dcSMark Fasheh 
2853f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2854416161dbSMark Fasheh {
28555955102cSAl Viro 	inode_unlock(inode1);
28565955102cSAl Viro 	inode_unlock(inode2);
2857416161dbSMark Fasheh }
2858416161dbSMark Fasheh 
2859f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2860f4414602SMark Fasheh {
2861f4414602SMark Fasheh 	if (inode1 < inode2)
2862f4414602SMark Fasheh 		swap(inode1, inode2);
2863f4414602SMark Fasheh 
28645955102cSAl Viro 	inode_lock_nested(inode1, I_MUTEX_PARENT);
28655955102cSAl Viro 	inode_lock_nested(inode2, I_MUTEX_CHILD);
2866f4414602SMark Fasheh }
2867f4414602SMark Fasheh 
2868f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2869f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
2870f4414602SMark Fasheh {
2871f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2872f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2873f4414602SMark Fasheh }
2874f4414602SMark Fasheh 
2875e0bd70c6SFilipe Manana static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2876e0bd70c6SFilipe Manana 				    struct inode *inode2, u64 loff2, u64 len,
2877e0bd70c6SFilipe Manana 				    bool retry_range_locking)
2878416161dbSMark Fasheh {
2879e0bd70c6SFilipe Manana 	int ret;
2880e0bd70c6SFilipe Manana 
2881416161dbSMark Fasheh 	if (inode1 < inode2) {
2882416161dbSMark Fasheh 		swap(inode1, inode2);
2883416161dbSMark Fasheh 		swap(loff1, loff2);
2884416161dbSMark Fasheh 	}
2885e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2886e0bd70c6SFilipe Manana 	if (ret)
2887e0bd70c6SFilipe Manana 		return ret;
2888e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2889e0bd70c6SFilipe Manana 	if (ret)
2890e0bd70c6SFilipe Manana 		unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2891e0bd70c6SFilipe Manana 			      loff1 + len - 1);
2892e0bd70c6SFilipe Manana 	return ret;
2893416161dbSMark Fasheh }
2894f4414602SMark Fasheh 
2895f4414602SMark Fasheh struct cmp_pages {
2896f4414602SMark Fasheh 	int		num_pages;
2897f4414602SMark Fasheh 	struct page	**src_pages;
2898f4414602SMark Fasheh 	struct page	**dst_pages;
2899f4414602SMark Fasheh };
2900f4414602SMark Fasheh 
2901f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2902f4414602SMark Fasheh {
2903f4414602SMark Fasheh 	int i;
2904f4414602SMark Fasheh 	struct page *pg;
2905f4414602SMark Fasheh 
2906f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
2907f4414602SMark Fasheh 		pg = cmp->src_pages[i];
2908e0bd70c6SFilipe Manana 		if (pg) {
2909e0bd70c6SFilipe Manana 			unlock_page(pg);
291009cbfeafSKirill A. Shutemov 			put_page(pg);
2911e0bd70c6SFilipe Manana 		}
2912f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
2913e0bd70c6SFilipe Manana 		if (pg) {
2914e0bd70c6SFilipe Manana 			unlock_page(pg);
291509cbfeafSKirill A. Shutemov 			put_page(pg);
2916f4414602SMark Fasheh 		}
2917e0bd70c6SFilipe Manana 	}
2918f4414602SMark Fasheh }
2919f4414602SMark Fasheh 
2920f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2921f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
2922f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
2923f4414602SMark Fasheh {
2924f4414602SMark Fasheh 	int ret;
292509cbfeafSKirill A. Shutemov 	int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
2926f4414602SMark Fasheh 
2927f4414602SMark Fasheh 	cmp->num_pages = num_pages;
2928f4414602SMark Fasheh 
292967b07bd4STimofey Titovets 	ret = gather_extent_pages(src, cmp->src_pages, num_pages, loff);
2930f4414602SMark Fasheh 	if (ret)
2931f4414602SMark Fasheh 		goto out;
2932f4414602SMark Fasheh 
293367b07bd4STimofey Titovets 	ret = gather_extent_pages(dst, cmp->dst_pages, num_pages, dst_loff);
2934f4414602SMark Fasheh 
2935f4414602SMark Fasheh out:
2936f4414602SMark Fasheh 	if (ret)
2937f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
293878ad4ce0SNaohiro Aota 	return ret;
2939416161dbSMark Fasheh }
2940416161dbSMark Fasheh 
29411a287cfeSDavid Sterba static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
2942416161dbSMark Fasheh {
2943416161dbSMark Fasheh 	int ret = 0;
2944f4414602SMark Fasheh 	int i;
2945416161dbSMark Fasheh 	struct page *src_page, *dst_page;
294609cbfeafSKirill A. Shutemov 	unsigned int cmp_len = PAGE_SIZE;
2947416161dbSMark Fasheh 	void *addr, *dst_addr;
2948416161dbSMark Fasheh 
2949f4414602SMark Fasheh 	i = 0;
2950416161dbSMark Fasheh 	while (len) {
295109cbfeafSKirill A. Shutemov 		if (len < PAGE_SIZE)
2952416161dbSMark Fasheh 			cmp_len = len;
2953416161dbSMark Fasheh 
2954f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
2955f4414602SMark Fasheh 
2956f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
2957f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
2958e0bd70c6SFilipe Manana 		ASSERT(PageLocked(src_page));
2959e0bd70c6SFilipe Manana 		ASSERT(PageLocked(dst_page));
2960f4414602SMark Fasheh 
2961416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
2962416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
2963416161dbSMark Fasheh 
2964416161dbSMark Fasheh 		flush_dcache_page(src_page);
2965416161dbSMark Fasheh 		flush_dcache_page(dst_page);
2966416161dbSMark Fasheh 
2967416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
29682b3909f8SDarrick J. Wong 			ret = -EBADE;
2969416161dbSMark Fasheh 
2970416161dbSMark Fasheh 		kunmap_atomic(addr);
2971416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
2972416161dbSMark Fasheh 
2973416161dbSMark Fasheh 		if (ret)
2974416161dbSMark Fasheh 			break;
2975416161dbSMark Fasheh 
2976416161dbSMark Fasheh 		len -= cmp_len;
2977f4414602SMark Fasheh 		i++;
2978416161dbSMark Fasheh 	}
2979416161dbSMark Fasheh 
2980416161dbSMark Fasheh 	return ret;
2981416161dbSMark Fasheh }
2982416161dbSMark Fasheh 
2983e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
2984e1d227a4SMark Fasheh 				     u64 olen)
2985416161dbSMark Fasheh {
2986e1d227a4SMark Fasheh 	u64 len = *plen;
2987416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2988416161dbSMark Fasheh 
2989e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
2990416161dbSMark Fasheh 		return -EINVAL;
2991e1d227a4SMark Fasheh 
2992e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
2993e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
2994e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
2995e1d227a4SMark Fasheh 
2996416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
2997416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2998416161dbSMark Fasheh 		return -EINVAL;
2999416161dbSMark Fasheh 
3000416161dbSMark Fasheh 	return 0;
3001416161dbSMark Fasheh }
3002416161dbSMark Fasheh 
30033973909dSTimofey Titovets static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 olen,
300467b07bd4STimofey Titovets 				   struct inode *dst, u64 dst_loff,
300567b07bd4STimofey Titovets 				   struct cmp_pages *cmp)
3006416161dbSMark Fasheh {
3007416161dbSMark Fasheh 	int ret;
3008e1d227a4SMark Fasheh 	u64 len = olen;
3009fc4badd9SOmar Sandoval 	bool same_inode = (src == dst);
30100efa9f48SMark Fasheh 	u64 same_lock_start = 0;
30110efa9f48SMark Fasheh 	u64 same_lock_len = 0;
3012416161dbSMark Fasheh 
30130efa9f48SMark Fasheh 	ret = extent_same_check_offsets(src, loff, &len, olen);
30140efa9f48SMark Fasheh 	if (ret)
30153973909dSTimofey Titovets 		return ret;
3016fc4badd9SOmar Sandoval 
3017fc4badd9SOmar Sandoval 	ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3018f4dfe687SFilipe Manana 	if (ret)
30193973909dSTimofey Titovets 		return ret;
30200efa9f48SMark Fasheh 
3021fc4badd9SOmar Sandoval 	if (same_inode) {
30220efa9f48SMark Fasheh 		/*
30230efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
30240efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
30250efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
30260efa9f48SMark Fasheh 		 *
30270efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
30280efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
30290efa9f48SMark Fasheh 		 * reject the request.
30300efa9f48SMark Fasheh 		 *
30310efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
30320efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
30330efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
30340efa9f48SMark Fasheh 		 * i_size.
30350efa9f48SMark Fasheh 		 */
30363973909dSTimofey Titovets 		if (len != olen)
30373973909dSTimofey Titovets 			return -EINVAL;
30380efa9f48SMark Fasheh 
30390efa9f48SMark Fasheh 		/* Check for overlapping ranges */
30403973909dSTimofey Titovets 		if (dst_loff + len > loff && dst_loff < loff + len)
30413973909dSTimofey Titovets 			return -EINVAL;
30420efa9f48SMark Fasheh 
30430efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
30440efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
30450efa9f48SMark Fasheh 	}
3046416161dbSMark Fasheh 
3047e0bd70c6SFilipe Manana again:
304867b07bd4STimofey Titovets 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, cmp);
3049f4414602SMark Fasheh 	if (ret)
30503973909dSTimofey Titovets 		return ret;
3051f4414602SMark Fasheh 
30520efa9f48SMark Fasheh 	if (same_inode)
3053e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, same_lock_start, same_lock_len,
3054e0bd70c6SFilipe Manana 					false);
30550efa9f48SMark Fasheh 	else
3056e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3057e0bd70c6SFilipe Manana 					       false);
3058e0bd70c6SFilipe Manana 	/*
3059e0bd70c6SFilipe Manana 	 * If one of the inodes has dirty pages in the respective range or
3060e0bd70c6SFilipe Manana 	 * ordered extents, we need to flush dellaloc and wait for all ordered
3061e0bd70c6SFilipe Manana 	 * extents in the range. We must unlock the pages and the ranges in the
3062e0bd70c6SFilipe Manana 	 * io trees to avoid deadlocks when flushing delalloc (requires locking
3063e0bd70c6SFilipe Manana 	 * pages) and when waiting for ordered extents to complete (they require
3064e0bd70c6SFilipe Manana 	 * range locking).
3065e0bd70c6SFilipe Manana 	 */
3066e0bd70c6SFilipe Manana 	if (ret == -EAGAIN) {
3067e0bd70c6SFilipe Manana 		/*
3068e0bd70c6SFilipe Manana 		 * Ranges in the io trees already unlocked. Now unlock all
3069e0bd70c6SFilipe Manana 		 * pages before waiting for all IO to complete.
3070e0bd70c6SFilipe Manana 		 */
307167b07bd4STimofey Titovets 		btrfs_cmp_data_free(cmp);
3072e0bd70c6SFilipe Manana 		if (same_inode) {
3073e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, same_lock_start,
3074e0bd70c6SFilipe Manana 						 same_lock_len);
3075e0bd70c6SFilipe Manana 		} else {
3076e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, loff, len);
3077e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(dst, dst_loff, len);
3078e0bd70c6SFilipe Manana 		}
3079e0bd70c6SFilipe Manana 		goto again;
3080e0bd70c6SFilipe Manana 	}
3081e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3082e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3083e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
308467b07bd4STimofey Titovets 		btrfs_cmp_data_free(cmp);
3085e0bd70c6SFilipe Manana 		return ret;
3086e0bd70c6SFilipe Manana 	}
3087f4414602SMark Fasheh 
3088207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
308967b07bd4STimofey Titovets 	ret = btrfs_cmp_data(olen, cmp);
3090416161dbSMark Fasheh 	if (ret == 0)
30911c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3092416161dbSMark Fasheh 
30930efa9f48SMark Fasheh 	if (same_inode)
30940efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
30950efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
30960efa9f48SMark Fasheh 	else
3097f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3098f4414602SMark Fasheh 
309967b07bd4STimofey Titovets 	btrfs_cmp_data_free(cmp);
31003973909dSTimofey Titovets 
31013973909dSTimofey Titovets 	return ret;
31023973909dSTimofey Titovets }
31033973909dSTimofey Titovets 
3104b6728768STimofey Titovets #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3105b6728768STimofey Titovets 
31063973909dSTimofey Titovets static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
31073973909dSTimofey Titovets 			     struct inode *dst, u64 dst_loff)
31083973909dSTimofey Titovets {
31093973909dSTimofey Titovets 	int ret;
311067b07bd4STimofey Titovets 	struct cmp_pages cmp;
311167b07bd4STimofey Titovets 	int num_pages = PAGE_ALIGN(BTRFS_MAX_DEDUPE_LEN) >> PAGE_SHIFT;
31123973909dSTimofey Titovets 	bool same_inode = (src == dst);
3113b6728768STimofey Titovets 	u64 i, tail_len, chunk_count;
31143973909dSTimofey Titovets 
31153973909dSTimofey Titovets 	if (olen == 0)
31163973909dSTimofey Titovets 		return 0;
31173973909dSTimofey Titovets 
31183973909dSTimofey Titovets 	if (same_inode)
31193973909dSTimofey Titovets 		inode_lock(src);
31203973909dSTimofey Titovets 	else
31213973909dSTimofey Titovets 		btrfs_double_inode_lock(src, dst);
31223973909dSTimofey Titovets 
31233973909dSTimofey Titovets 	/* don't make the dst file partly checksummed */
31243973909dSTimofey Titovets 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
31253973909dSTimofey Titovets 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
31263973909dSTimofey Titovets 		ret = -EINVAL;
31273973909dSTimofey Titovets 		goto out_unlock;
31283973909dSTimofey Titovets 	}
31293973909dSTimofey Titovets 
3130b6728768STimofey Titovets 	tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3131b6728768STimofey Titovets 	chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
313267b07bd4STimofey Titovets 	if (chunk_count == 0)
313367b07bd4STimofey Titovets 		num_pages = PAGE_ALIGN(tail_len) >> PAGE_SHIFT;
313467b07bd4STimofey Titovets 
313567b07bd4STimofey Titovets 	/*
313667b07bd4STimofey Titovets 	 * If deduping ranges in the same inode, locking rules make it
313767b07bd4STimofey Titovets 	 * mandatory to always lock pages in ascending order to avoid deadlocks
313867b07bd4STimofey Titovets 	 * with concurrent tasks (such as starting writeback/delalloc).
313967b07bd4STimofey Titovets 	 */
314067b07bd4STimofey Titovets 	if (same_inode && dst_loff < loff)
314167b07bd4STimofey Titovets 		swap(loff, dst_loff);
314267b07bd4STimofey Titovets 
314367b07bd4STimofey Titovets 	/*
314467b07bd4STimofey Titovets 	 * We must gather up all the pages before we initiate our extent
314567b07bd4STimofey Titovets 	 * locking. We use an array for the page pointers. Size of the array is
314667b07bd4STimofey Titovets 	 * bounded by len, which is in turn bounded by BTRFS_MAX_DEDUPE_LEN.
314767b07bd4STimofey Titovets 	 */
3148bf5091c8SDavid Sterba 	cmp.src_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3149bf5091c8SDavid Sterba 				       GFP_KERNEL | __GFP_ZERO);
3150bf5091c8SDavid Sterba 	cmp.dst_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3151bf5091c8SDavid Sterba 				       GFP_KERNEL | __GFP_ZERO);
315267b07bd4STimofey Titovets 	if (!cmp.src_pages || !cmp.dst_pages) {
3153bf5091c8SDavid Sterba 		ret = -ENOMEM;
3154bf5091c8SDavid Sterba 		goto out_free;
315567b07bd4STimofey Titovets 	}
3156b6728768STimofey Titovets 
3157b6728768STimofey Titovets 	for (i = 0; i < chunk_count; i++) {
3158b6728768STimofey Titovets 		ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
315967b07bd4STimofey Titovets 					      dst, dst_loff, &cmp);
3160b6728768STimofey Titovets 		if (ret)
3161b6728768STimofey Titovets 			goto out_unlock;
3162b6728768STimofey Titovets 
3163b6728768STimofey Titovets 		loff += BTRFS_MAX_DEDUPE_LEN;
3164b6728768STimofey Titovets 		dst_loff += BTRFS_MAX_DEDUPE_LEN;
3165b6728768STimofey Titovets 	}
3166b6728768STimofey Titovets 
3167b6728768STimofey Titovets 	if (tail_len > 0)
316867b07bd4STimofey Titovets 		ret = btrfs_extent_same_range(src, loff, tail_len, dst,
316967b07bd4STimofey Titovets 					      dst_loff, &cmp);
31703973909dSTimofey Titovets 
3171416161dbSMark Fasheh out_unlock:
31720efa9f48SMark Fasheh 	if (same_inode)
31735955102cSAl Viro 		inode_unlock(src);
31740efa9f48SMark Fasheh 	else
3175f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3176416161dbSMark Fasheh 
3177bf5091c8SDavid Sterba out_free:
3178bf5091c8SDavid Sterba 	kvfree(cmp.src_pages);
3179bf5091c8SDavid Sterba 	kvfree(cmp.dst_pages);
318067b07bd4STimofey Titovets 
3181416161dbSMark Fasheh 	return ret;
3182416161dbSMark Fasheh }
3183416161dbSMark Fasheh 
31842b3909f8SDarrick J. Wong ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
31852b3909f8SDarrick J. Wong 				struct file *dst_file, u64 dst_loff)
3186416161dbSMark Fasheh {
31872b3909f8SDarrick J. Wong 	struct inode *src = file_inode(src_file);
31882b3909f8SDarrick J. Wong 	struct inode *dst = file_inode(dst_file);
3189416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
31902b3909f8SDarrick J. Wong 	ssize_t res;
3191416161dbSMark Fasheh 
319209cbfeafSKirill A. Shutemov 	if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3193416161dbSMark Fasheh 		/*
3194416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3195416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3196416161dbSMark Fasheh 		 * this situation without an update.
3197416161dbSMark Fasheh 		 */
31982b3909f8SDarrick J. Wong 		return -EINVAL;
3199416161dbSMark Fasheh 	}
3200416161dbSMark Fasheh 
32012b3909f8SDarrick J. Wong 	res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
32022b3909f8SDarrick J. Wong 	if (res)
32032b3909f8SDarrick J. Wong 		return res;
32042b3909f8SDarrick J. Wong 	return olen;
3205416161dbSMark Fasheh }
3206416161dbSMark Fasheh 
3207f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3208f82a9901SFilipe Manana 				     struct inode *inode,
3209f82a9901SFilipe Manana 				     u64 endoff,
3210f82a9901SFilipe Manana 				     const u64 destoff,
32111c919a5eSMark Fasheh 				     const u64 olen,
32121c919a5eSMark Fasheh 				     int no_time_update)
3213f82a9901SFilipe Manana {
3214f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3215f82a9901SFilipe Manana 	int ret;
3216f82a9901SFilipe Manana 
3217f82a9901SFilipe Manana 	inode_inc_iversion(inode);
32181c919a5eSMark Fasheh 	if (!no_time_update)
3219c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3220f82a9901SFilipe Manana 	/*
3221f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3222f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3223f82a9901SFilipe Manana 	 */
3224f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3225f82a9901SFilipe Manana 		endoff = destoff + olen;
3226f82a9901SFilipe Manana 	if (endoff > inode->i_size)
32276ef06d27SNikolay Borisov 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3228f82a9901SFilipe Manana 
3229f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3230f82a9901SFilipe Manana 	if (ret) {
323166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32323a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3233f82a9901SFilipe Manana 		goto out;
3234f82a9901SFilipe Manana 	}
32353a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
3236f82a9901SFilipe Manana out:
3237f82a9901SFilipe Manana 	return ret;
3238f82a9901SFilipe Manana }
3239f82a9901SFilipe Manana 
3240a2f392e4SNikolay Borisov static void clone_update_extent_map(struct btrfs_inode *inode,
32417ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
32427ffbb598SFilipe Manana 				    const struct btrfs_path *path,
32437ffbb598SFilipe Manana 				    const u64 hole_offset,
32447ffbb598SFilipe Manana 				    const u64 hole_len)
32457ffbb598SFilipe Manana {
3246a2f392e4SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
32477ffbb598SFilipe Manana 	struct extent_map *em;
32487ffbb598SFilipe Manana 	int ret;
32497ffbb598SFilipe Manana 
32507ffbb598SFilipe Manana 	em = alloc_extent_map();
32517ffbb598SFilipe Manana 	if (!em) {
3252a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
32537ffbb598SFilipe Manana 		return;
32547ffbb598SFilipe Manana 	}
32557ffbb598SFilipe Manana 
325614f59796SFilipe Manana 	if (path) {
325714f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
325814f59796SFilipe Manana 
325914f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
326014f59796SFilipe Manana 				    struct btrfs_file_extent_item);
3261a2f392e4SNikolay Borisov 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
32627ffbb598SFilipe Manana 		em->generation = -1;
32637ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
32647ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
32657ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3266a2f392e4SNikolay Borisov 					&inode->runtime_flags);
32677ffbb598SFilipe Manana 	} else {
32687ffbb598SFilipe Manana 		em->start = hole_offset;
32697ffbb598SFilipe Manana 		em->len = hole_len;
32707ffbb598SFilipe Manana 		em->ram_bytes = em->len;
32717ffbb598SFilipe Manana 		em->orig_start = hole_offset;
32727ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
32737ffbb598SFilipe Manana 		em->block_len = 0;
32747ffbb598SFilipe Manana 		em->orig_block_len = 0;
32757ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
32767ffbb598SFilipe Manana 		em->generation = trans->transid;
32777ffbb598SFilipe Manana 	}
32787ffbb598SFilipe Manana 
32797ffbb598SFilipe Manana 	while (1) {
32807ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
32817ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
32827ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
32837ffbb598SFilipe Manana 		if (ret != -EEXIST) {
32847ffbb598SFilipe Manana 			free_extent_map(em);
32857ffbb598SFilipe Manana 			break;
32867ffbb598SFilipe Manana 		}
3287a2f392e4SNikolay Borisov 		btrfs_drop_extent_cache(inode, em->start,
32887ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
32897ffbb598SFilipe Manana 	}
32907ffbb598SFilipe Manana 
3291ee39b432SDavid Sterba 	if (ret)
3292a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
32937ffbb598SFilipe Manana }
32947ffbb598SFilipe Manana 
32958039d87dSFilipe Manana /*
32968039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
32978039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
32988039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
32998039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
33008039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
33018039d87dSFilipe Manana  *
33028039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
33038039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
33048039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
33058039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
33068039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
33078039d87dSFilipe Manana  * i_mutex, which we are holding here).
33088039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
33098039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
33108039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
33118039d87dSFilipe Manana  *
33128039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
33138039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
33148039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
33158039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
33168039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
33178039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
33188039d87dSFilipe Manana  * the former.
33198039d87dSFilipe Manana  */
33204a0ab9d7SDavid Sterba static int clone_copy_inline_extent(struct inode *dst,
33218039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
33228039d87dSFilipe Manana 				    struct btrfs_path *path,
33238039d87dSFilipe Manana 				    struct btrfs_key *new_key,
33248039d87dSFilipe Manana 				    const u64 drop_start,
33258039d87dSFilipe Manana 				    const u64 datal,
33268039d87dSFilipe Manana 				    const u64 skip,
33278039d87dSFilipe Manana 				    const u64 size,
33288039d87dSFilipe Manana 				    char *inline_data)
33298039d87dSFilipe Manana {
33300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
33318039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
33328039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
33330b246afaSJeff Mahoney 				      fs_info->sectorsize);
33348039d87dSFilipe Manana 	int ret;
33358039d87dSFilipe Manana 	struct btrfs_key key;
33368039d87dSFilipe Manana 
33378039d87dSFilipe Manana 	if (new_key->offset > 0)
33388039d87dSFilipe Manana 		return -EOPNOTSUPP;
33398039d87dSFilipe Manana 
33404a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(dst));
33418039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
33428039d87dSFilipe Manana 	key.offset = 0;
33438039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
33448039d87dSFilipe Manana 	if (ret < 0) {
33458039d87dSFilipe Manana 		return ret;
33468039d87dSFilipe Manana 	} else if (ret > 0) {
33478039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
33488039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
33498039d87dSFilipe Manana 			if (ret < 0)
33508039d87dSFilipe Manana 				return ret;
33518039d87dSFilipe Manana 			else if (ret > 0)
33528039d87dSFilipe Manana 				goto copy_inline_extent;
33538039d87dSFilipe Manana 		}
33548039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
33554a0cc7caSNikolay Borisov 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
33568039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
33578039d87dSFilipe Manana 			ASSERT(key.offset > 0);
33588039d87dSFilipe Manana 			return -EOPNOTSUPP;
33598039d87dSFilipe Manana 		}
33608039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
33618039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
33628039d87dSFilipe Manana 		u64 ext_len;
33638039d87dSFilipe Manana 
33648039d87dSFilipe Manana 		/*
33658039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
33668039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
33678039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
33688039d87dSFilipe Manana 		 */
33698039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
33708039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
33718039d87dSFilipe Manana 		/*
33728039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
33738039d87dSFilipe Manana 		 * following it.
33748039d87dSFilipe Manana 		 */
33758039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
33768039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
33778039d87dSFilipe Manana 			goto copy_inline_extent;
33788039d87dSFilipe Manana 
33798039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
33808039d87dSFilipe Manana 		if (ext_len > aligned_end)
33818039d87dSFilipe Manana 			return -EOPNOTSUPP;
33828039d87dSFilipe Manana 
33838039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
33848039d87dSFilipe Manana 		if (ret < 0) {
33858039d87dSFilipe Manana 			return ret;
33868039d87dSFilipe Manana 		} else if (ret == 0) {
33878039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
33888039d87dSFilipe Manana 					      path->slots[0]);
33894a0cc7caSNikolay Borisov 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
33908039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
33918039d87dSFilipe Manana 				return -EOPNOTSUPP;
33928039d87dSFilipe Manana 		}
33938039d87dSFilipe Manana 	}
33948039d87dSFilipe Manana 
33958039d87dSFilipe Manana copy_inline_extent:
33968039d87dSFilipe Manana 	/*
33978039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
33988039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
33998039d87dSFilipe Manana 	 */
34008039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
34018039d87dSFilipe Manana 		/*
34028039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
34038039d87dSFilipe Manana 		 * This would require copying the data from the source inline
34048039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
34058039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
34068039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
34078039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
34088039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
34098039d87dSFilipe Manana 		 * inline extent).
34108039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
34118039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
34128039d87dSFilipe Manana 		 */
34138039d87dSFilipe Manana 		return -EOPNOTSUPP;
34148039d87dSFilipe Manana 	}
34158039d87dSFilipe Manana 
34168039d87dSFilipe Manana 	btrfs_release_path(path);
34178039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
34188039d87dSFilipe Manana 	if (ret)
34198039d87dSFilipe Manana 		return ret;
34208039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
34218039d87dSFilipe Manana 	if (ret)
34228039d87dSFilipe Manana 		return ret;
34238039d87dSFilipe Manana 
34248039d87dSFilipe Manana 	if (skip) {
34258039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
34268039d87dSFilipe Manana 
34278039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
34288039d87dSFilipe Manana 	}
34298039d87dSFilipe Manana 
34308039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
34318039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
34328039d87dSFilipe Manana 						  path->slots[0]),
34338039d87dSFilipe Manana 			    size);
34348039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
34358039d87dSFilipe Manana 
34368039d87dSFilipe Manana 	return 0;
34378039d87dSFilipe Manana }
34388039d87dSFilipe Manana 
343932b7c687SMark Fasheh /**
344032b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
344132b7c687SMark Fasheh  *
344232b7c687SMark Fasheh  * @src: Inode to clone from
344332b7c687SMark Fasheh  * @inode: Inode to clone to
344432b7c687SMark Fasheh  * @off: Offset within source to start clone from
344532b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
34461c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
344732b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
34481c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
344932b7c687SMark Fasheh  */
345032b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3451f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
34521c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3453f46b5a66SChristoph Hellwig {
34540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3455f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
345632b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3457f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
345832b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
345932b7c687SMark Fasheh 	char *buf = NULL;
3460ae01a0abSYan Zheng 	struct btrfs_key key;
3461f46b5a66SChristoph Hellwig 	u32 nritems;
3462f46b5a66SChristoph Hellwig 	int slot;
3463ae01a0abSYan Zheng 	int ret;
3464f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3465f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3466ae01a0abSYan Zheng 
3467ae01a0abSYan Zheng 	ret = -ENOMEM;
3468752ade68SMichal Hocko 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3469ae01a0abSYan Zheng 	if (!buf)
347032b7c687SMark Fasheh 		return ret;
3471ae01a0abSYan Zheng 
3472ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3473ae01a0abSYan Zheng 	if (!path) {
347415351955SDavid Sterba 		kvfree(buf);
347532b7c687SMark Fasheh 		return ret;
3476ae01a0abSYan Zheng 	}
347732b7c687SMark Fasheh 
3478e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3479c5c9cd4dSSage Weil 	/* clone data */
34804a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(src));
3481ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
34822c463823SFilipe Manana 	key.offset = off;
3483f46b5a66SChristoph Hellwig 
3484f46b5a66SChristoph Hellwig 	while (1) {
3485de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3486df858e76SFilipe Manana 
3487f46b5a66SChristoph Hellwig 		/*
3488f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3489f46b5a66SChristoph Hellwig 		 * tree.
3490f46b5a66SChristoph Hellwig 		 */
3491e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3492362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3493362a20c5SDavid Sterba 				0, 0);
3494f46b5a66SChristoph Hellwig 		if (ret < 0)
3495f46b5a66SChristoph Hellwig 			goto out;
34962c463823SFilipe Manana 		/*
34972c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
34982c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
34992c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
35002c463823SFilipe Manana 		 */
35012c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
35022c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
35032c463823SFilipe Manana 					      path->slots[0] - 1);
35042c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
35052c463823SFilipe Manana 				path->slots[0]--;
35062c463823SFilipe Manana 		}
3507f46b5a66SChristoph Hellwig 
3508ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3509e4355f34SFilipe David Borba Manana process_slot:
3510ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3511362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3512f46b5a66SChristoph Hellwig 			if (ret < 0)
3513f46b5a66SChristoph Hellwig 				goto out;
3514f46b5a66SChristoph Hellwig 			if (ret > 0)
3515f46b5a66SChristoph Hellwig 				break;
3516ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3517f46b5a66SChristoph Hellwig 		}
3518f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3519f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3520f46b5a66SChristoph Hellwig 
3521ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3522962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
35234a0cc7caSNikolay Borisov 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3524f46b5a66SChristoph Hellwig 			break;
3525f46b5a66SChristoph Hellwig 
3526962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3527c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3528c5c9cd4dSSage Weil 			int type;
352931840ae1SZheng Yan 			u32 size;
353031840ae1SZheng Yan 			struct btrfs_key new_key;
3531c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3532c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3533c5c9cd4dSSage Weil 			u8 comp;
3534f82a9901SFilipe Manana 			u64 drop_start;
353531840ae1SZheng Yan 
3536c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3537c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3538c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3539c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3540c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3541c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3542d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3543d397712bSChris Mason 								      extent);
3544d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3545d397712bSChris Mason 								 extent);
3546c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3547d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3548d397712bSChris Mason 								    extent);
3549c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3550c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3551c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3552c5c9cd4dSSage Weil 								    extent);
3553c5c9cd4dSSage Weil 			}
355431840ae1SZheng Yan 
35552c463823SFilipe Manana 			/*
35562c463823SFilipe Manana 			 * The first search might have left us at an extent
35572c463823SFilipe Manana 			 * item that ends before our target range's start, can
35582c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
35592c463823SFilipe Manana 			 */
35602c463823SFilipe Manana 			if (key.offset + datal <= off) {
3561e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3562e4355f34SFilipe David Borba Manana 				goto process_slot;
35632c463823SFilipe Manana 			} else if (key.offset >= off + len) {
35642c463823SFilipe Manana 				break;
3565e4355f34SFilipe David Borba Manana 			}
3566df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3567e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3568e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3569e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3570e4355f34SFilipe David Borba Manana 					   size);
3571e4355f34SFilipe David Borba Manana 
3572e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3573e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3574c5c9cd4dSSage Weil 
357531840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
35764a0cc7caSNikolay Borisov 			new_key.objectid = btrfs_ino(BTRFS_I(inode));
35774d728ec7SLi Zefan 			if (off <= key.offset)
3578c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
35794d728ec7SLi Zefan 			else
35804d728ec7SLi Zefan 				new_key.offset = destoff;
3581c5c9cd4dSSage Weil 
3582b6f3409bSSage Weil 			/*
3583f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3584f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3585f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3586f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3587f82a9901SFilipe Manana 			 * partially overlaps it).
3588f82a9901SFilipe Manana 			 */
3589f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3590f82a9901SFilipe Manana 				drop_start = last_dest_end;
3591f82a9901SFilipe Manana 			else
3592f82a9901SFilipe Manana 				drop_start = new_key.offset;
3593f82a9901SFilipe Manana 
3594f82a9901SFilipe Manana 			/*
3595b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3596b6f3409bSSage Weil 			 * 1 - add new extent
3597b6f3409bSSage Weil 			 * 1 - inode update
3598b6f3409bSSage Weil 			 */
3599b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3600a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3601a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3602a22285a6SYan, Zheng 				goto out;
3603a22285a6SYan, Zheng 			}
3604a22285a6SYan, Zheng 
3605c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3606c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3607d72c0842SLi Zefan 				/*
3608d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3609d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3610d72c0842SLi Zefan 				 */
3611d72c0842SLi Zefan 
361293915584SAntonio Ospite 				/* subtract range b */
3613d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3614d72c0842SLi Zefan 					datal = off + len - key.offset;
3615d72c0842SLi Zefan 
361693915584SAntonio Ospite 				/* subtract range a */
3617a22285a6SYan, Zheng 				if (off > key.offset) {
3618a22285a6SYan, Zheng 					datao += off - key.offset;
3619a22285a6SYan, Zheng 					datal -= off - key.offset;
3620a22285a6SYan, Zheng 				}
3621a22285a6SYan, Zheng 
36225dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3623f82a9901SFilipe Manana 							 drop_start,
3624a22285a6SYan, Zheng 							 new_key.offset + datal,
36252671485dSJosef Bacik 							 1);
362679787eaaSJeff Mahoney 				if (ret) {
36273f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
362800fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
362966642832SJeff Mahoney 									ret);
36303a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
363179787eaaSJeff Mahoney 					goto out;
363279787eaaSJeff Mahoney 				}
3633a22285a6SYan, Zheng 
363431840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
363531840ae1SZheng Yan 							      &new_key, size);
363679787eaaSJeff Mahoney 				if (ret) {
363766642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
36383a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
363979787eaaSJeff Mahoney 					goto out;
364079787eaaSJeff Mahoney 				}
364131840ae1SZheng Yan 
364231840ae1SZheng Yan 				leaf = path->nodes[0];
364331840ae1SZheng Yan 				slot = path->slots[0];
364431840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
364531840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
364631840ae1SZheng Yan 					    size);
3647ae01a0abSYan Zheng 
3648f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3649f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3650c5c9cd4dSSage Weil 
3651c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3652c5c9cd4dSSage Weil 				if (!disko)
3653c5c9cd4dSSage Weil 					datao = 0;
3654c5c9cd4dSSage Weil 
3655c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3656c5c9cd4dSSage Weil 							     datao);
3657c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3658c5c9cd4dSSage Weil 								datal);
3659fcebe456SJosef Bacik 
3660c5c9cd4dSSage Weil 				if (disko) {
3661c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
36622ff7e61eSJeff Mahoney 					ret = btrfs_inc_extent_ref(trans,
366384f7d8e6SJosef Bacik 							root,
36645d4f98a2SYan Zheng 							disko, diskl, 0,
3665f46b5a66SChristoph Hellwig 							root->root_key.objectid,
36664a0cc7caSNikolay Borisov 							btrfs_ino(BTRFS_I(inode)),
3667b06c4bf5SFilipe Manana 							new_key.offset - datao);
366879787eaaSJeff Mahoney 					if (ret) {
366979787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
367079787eaaSJeff Mahoney 									ret);
36713a45bb20SJeff Mahoney 						btrfs_end_transaction(trans);
367279787eaaSJeff Mahoney 						goto out;
367379787eaaSJeff Mahoney 
367479787eaaSJeff Mahoney 					}
3675f46b5a66SChristoph Hellwig 				}
3676c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3677c5c9cd4dSSage Weil 				u64 skip = 0;
3678c5c9cd4dSSage Weil 				u64 trim = 0;
3679ed958762SFilipe Manana 
3680c5c9cd4dSSage Weil 				if (off > key.offset) {
3681c5c9cd4dSSage Weil 					skip = off - key.offset;
3682c5c9cd4dSSage Weil 					new_key.offset += skip;
368331840ae1SZheng Yan 				}
3684d397712bSChris Mason 
3685c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3686c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3687d397712bSChris Mason 
3688c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3689c5c9cd4dSSage Weil 					ret = -EINVAL;
36903a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
3691c5c9cd4dSSage Weil 					goto out;
369231840ae1SZheng Yan 				}
3693c5c9cd4dSSage Weil 				size -= skip + trim;
3694c5c9cd4dSSage Weil 				datal -= skip + trim;
3695a22285a6SYan, Zheng 
36964a0ab9d7SDavid Sterba 				ret = clone_copy_inline_extent(inode,
36978039d87dSFilipe Manana 							       trans, path,
36988039d87dSFilipe Manana 							       &new_key,
3699f82a9901SFilipe Manana 							       drop_start,
37008039d87dSFilipe Manana 							       datal,
37018039d87dSFilipe Manana 							       skip, size, buf);
370279787eaaSJeff Mahoney 				if (ret) {
37033f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
37043a29bc09SChris Mason 						btrfs_abort_transaction(trans,
370579787eaaSJeff Mahoney 									ret);
37063a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
370779787eaaSJeff Mahoney 					goto out;
370879787eaaSJeff Mahoney 				}
3709c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3710c5c9cd4dSSage Weil 				slot = path->slots[0];
3711c5c9cd4dSSage Weil 			}
3712c5c9cd4dSSage Weil 
37137ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
37147ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
3715a2f392e4SNikolay Borisov 				clone_update_extent_map(BTRFS_I(inode), trans,
371614f59796SFilipe Manana 						NULL, drop_start,
37177ffbb598SFilipe Manana 						new_key.offset - drop_start);
37187ffbb598SFilipe Manana 
3719a2f392e4SNikolay Borisov 			clone_update_extent_map(BTRFS_I(inode), trans,
3720a2f392e4SNikolay Borisov 					path, 0, 0);
37217ffbb598SFilipe Manana 
3722c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3723b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3724c5c9cd4dSSage Weil 
372562e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
37260b246afaSJeff Mahoney 					      fs_info->sectorsize);
3727f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3728f82a9901SFilipe Manana 							last_dest_end,
37291c919a5eSMark Fasheh 							destoff, olen,
37301c919a5eSMark Fasheh 							no_time_update);
3731f82a9901SFilipe Manana 			if (ret)
373279787eaaSJeff Mahoney 				goto out;
37332c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
37342c463823SFilipe Manana 				break;
3735a22285a6SYan, Zheng 		}
3736b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3737df858e76SFilipe Manana 		key.offset = next_key_min_offset;
373869ae5e44SWang Xiaoguang 
373969ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
374069ae5e44SWang Xiaoguang 			ret = -EINTR;
374169ae5e44SWang Xiaoguang 			goto out;
374269ae5e44SWang Xiaoguang 		}
3743ae01a0abSYan Zheng 	}
3744f46b5a66SChristoph Hellwig 	ret = 0;
374532b7c687SMark Fasheh 
3746f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3747f82a9901SFilipe Manana 		/*
3748f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3749f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3750f82a9901SFilipe Manana 		 */
3751b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3752f82a9901SFilipe Manana 
3753f82a9901SFilipe Manana 		/*
3754f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3755f82a9901SFilipe Manana 		 * 1 - inode update
3756f82a9901SFilipe Manana 		 */
3757f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3758f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3759f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3760f82a9901SFilipe Manana 			goto out;
3761f82a9901SFilipe Manana 		}
3762f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3763f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3764f82a9901SFilipe Manana 		if (ret) {
3765f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
376666642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
37673a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
3768f82a9901SFilipe Manana 			goto out;
3769f82a9901SFilipe Manana 		}
3770a2f392e4SNikolay Borisov 		clone_update_extent_map(BTRFS_I(inode), trans, NULL,
3771a2f392e4SNikolay Borisov 				last_dest_end,
377214f59796SFilipe Manana 				destoff + len - last_dest_end);
3773f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
37741c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3775f82a9901SFilipe Manana 	}
3776f82a9901SFilipe Manana 
3777f46b5a66SChristoph Hellwig out:
377832b7c687SMark Fasheh 	btrfs_free_path(path);
377915351955SDavid Sterba 	kvfree(buf);
378032b7c687SMark Fasheh 	return ret;
378132b7c687SMark Fasheh }
378232b7c687SMark Fasheh 
37833db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
378432b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
378532b7c687SMark Fasheh {
378654563d41SAl Viro 	struct inode *inode = file_inode(file);
37873db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
37880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
378932b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
379032b7c687SMark Fasheh 	int ret;
379132b7c687SMark Fasheh 	u64 len = olen;
37920b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
37933db11b2eSZach Brown 	int same_inode = src == inode;
379432b7c687SMark Fasheh 
379532b7c687SMark Fasheh 	/*
379632b7c687SMark Fasheh 	 * TODO:
379732b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
379832b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
379932b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
380032b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
380100fdf13aSLiu Bo 	 *
380200fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
380300fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
380432b7c687SMark Fasheh 	 */
380532b7c687SMark Fasheh 
380632b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
380732b7c687SMark Fasheh 		return -EROFS;
380832b7c687SMark Fasheh 
38093db11b2eSZach Brown 	if (file_src->f_path.mnt != file->f_path.mnt ||
38103db11b2eSZach Brown 	    src->i_sb != inode->i_sb)
38113db11b2eSZach Brown 		return -EXDEV;
381232b7c687SMark Fasheh 
381332b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
38143db11b2eSZach Brown 		return -EISDIR;
381532b7c687SMark Fasheh 
381632b7c687SMark Fasheh 	if (!same_inode) {
3817293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
381832b7c687SMark Fasheh 	} else {
38195955102cSAl Viro 		inode_lock(src);
382032b7c687SMark Fasheh 	}
382132b7c687SMark Fasheh 
3822b5c40d59SOmar Sandoval 	/* don't make the dst file partly checksummed */
3823b5c40d59SOmar Sandoval 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3824b5c40d59SOmar Sandoval 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
3825b5c40d59SOmar Sandoval 		ret = -EINVAL;
3826b5c40d59SOmar Sandoval 		goto out_unlock;
3827b5c40d59SOmar Sandoval 	}
3828b5c40d59SOmar Sandoval 
382932b7c687SMark Fasheh 	/* determine range to clone */
383032b7c687SMark Fasheh 	ret = -EINVAL;
383132b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
383232b7c687SMark Fasheh 		goto out_unlock;
383332b7c687SMark Fasheh 	if (len == 0)
383432b7c687SMark Fasheh 		olen = len = src->i_size - off;
383532b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
383632b7c687SMark Fasheh 	if (off + len == src->i_size)
383732b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
383832b7c687SMark Fasheh 
3839ccccf3d6SFilipe Manana 	if (len == 0) {
3840ccccf3d6SFilipe Manana 		ret = 0;
3841ccccf3d6SFilipe Manana 		goto out_unlock;
3842ccccf3d6SFilipe Manana 	}
3843ccccf3d6SFilipe Manana 
384432b7c687SMark Fasheh 	/* verify the end result is block aligned */
384532b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
384632b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
384732b7c687SMark Fasheh 		goto out_unlock;
384832b7c687SMark Fasheh 
384932b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
385032b7c687SMark Fasheh 	if (same_inode) {
385132b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
385232b7c687SMark Fasheh 			goto out_unlock;
385332b7c687SMark Fasheh 	}
385432b7c687SMark Fasheh 
385532b7c687SMark Fasheh 	if (destoff > inode->i_size) {
385632b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
385732b7c687SMark Fasheh 		if (ret)
385832b7c687SMark Fasheh 			goto out_unlock;
385932b7c687SMark Fasheh 	}
386032b7c687SMark Fasheh 
3861c125b8bfSFilipe Manana 	/*
3862c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
3863c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
3864c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
3865c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
3866c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
3867c125b8bfSFilipe Manana 	 */
3868c125b8bfSFilipe Manana 	if (same_inode) {
3869c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3870c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
387132b7c687SMark Fasheh 
3872e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, lock_start, lock_len, true);
3873c125b8bfSFilipe Manana 	} else {
3874e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
3875e0bd70c6SFilipe Manana 					       true);
3876e0bd70c6SFilipe Manana 	}
3877e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3878e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3879e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3880e0bd70c6SFilipe Manana 		goto out_unlock;
3881c125b8bfSFilipe Manana 	}
388232b7c687SMark Fasheh 
38831c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
388432b7c687SMark Fasheh 
3885c125b8bfSFilipe Manana 	if (same_inode) {
3886c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3887c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
3888c125b8bfSFilipe Manana 
3889c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3890c125b8bfSFilipe Manana 	} else {
3891293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
3892c125b8bfSFilipe Manana 	}
3893c125b8bfSFilipe Manana 	/*
3894c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3895c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3896c125b8bfSFilipe Manana 	 */
389765bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
389809cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
389909cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
3900f46b5a66SChristoph Hellwig out_unlock:
3901293a8489SMark Fasheh 	if (!same_inode)
3902293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
3903293a8489SMark Fasheh 	else
39045955102cSAl Viro 		inode_unlock(src);
39053db11b2eSZach Brown 	return ret;
39063db11b2eSZach Brown }
39073db11b2eSZach Brown 
390804b38d60SChristoph Hellwig int btrfs_clone_file_range(struct file *src_file, loff_t off,
390904b38d60SChristoph Hellwig 		struct file *dst_file, loff_t destoff, u64 len)
39103db11b2eSZach Brown {
391104b38d60SChristoph Hellwig 	return btrfs_clone_files(dst_file, src_file, off, len, destoff);
3912c5c9cd4dSSage Weil }
3913c5c9cd4dSSage Weil 
39146ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
39156ef5ed0dSJosef Bacik {
3916496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
39170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39186ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
39196ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
39206ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
39216ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
39226ef5ed0dSJosef Bacik 	struct btrfs_path *path;
39236ef5ed0dSJosef Bacik 	struct btrfs_key location;
39246ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
39256ef5ed0dSJosef Bacik 	u64 objectid = 0;
39266ef5ed0dSJosef Bacik 	u64 dir_id;
39273c04ce01SMiao Xie 	int ret;
39286ef5ed0dSJosef Bacik 
39296ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
39306ef5ed0dSJosef Bacik 		return -EPERM;
39316ef5ed0dSJosef Bacik 
39323c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
39333c04ce01SMiao Xie 	if (ret)
39343c04ce01SMiao Xie 		return ret;
39353c04ce01SMiao Xie 
39363c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
39373c04ce01SMiao Xie 		ret = -EFAULT;
39383c04ce01SMiao Xie 		goto out;
39393c04ce01SMiao Xie 	}
39406ef5ed0dSJosef Bacik 
39416ef5ed0dSJosef Bacik 	if (!objectid)
39421cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
39436ef5ed0dSJosef Bacik 
39446ef5ed0dSJosef Bacik 	location.objectid = objectid;
39456ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
39466ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
39476ef5ed0dSJosef Bacik 
39480b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
39493c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
39503c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
39513c04ce01SMiao Xie 		goto out;
39523c04ce01SMiao Xie 	}
39536d6d2829Ssatoru takeuchi 	if (!is_fstree(new_root->objectid)) {
39546d6d2829Ssatoru takeuchi 		ret = -ENOENT;
39556d6d2829Ssatoru takeuchi 		goto out;
39566d6d2829Ssatoru takeuchi 	}
39576ef5ed0dSJosef Bacik 
39586ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
39593c04ce01SMiao Xie 	if (!path) {
39603c04ce01SMiao Xie 		ret = -ENOMEM;
39613c04ce01SMiao Xie 		goto out;
39623c04ce01SMiao Xie 	}
39636ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
39646ef5ed0dSJosef Bacik 
39656ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
396698d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
39676ef5ed0dSJosef Bacik 		btrfs_free_path(path);
39683c04ce01SMiao Xie 		ret = PTR_ERR(trans);
39693c04ce01SMiao Xie 		goto out;
39706ef5ed0dSJosef Bacik 	}
39716ef5ed0dSJosef Bacik 
39720b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
39730b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
39746ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
3975cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
39766ef5ed0dSJosef Bacik 		btrfs_free_path(path);
39773a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
39780b246afaSJeff Mahoney 		btrfs_err(fs_info,
39795d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
39803c04ce01SMiao Xie 		ret = -ENOENT;
39813c04ce01SMiao Xie 		goto out;
39826ef5ed0dSJosef Bacik 	}
39836ef5ed0dSJosef Bacik 
39846ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
39856ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
39866ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
39876ef5ed0dSJosef Bacik 	btrfs_free_path(path);
39886ef5ed0dSJosef Bacik 
39890b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
39903a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
39913c04ce01SMiao Xie out:
39923c04ce01SMiao Xie 	mnt_drop_write_file(file);
39933c04ce01SMiao Xie 	return ret;
39946ef5ed0dSJosef Bacik }
39956ef5ed0dSJosef Bacik 
3996c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
3997bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
3998bf5fc093SJosef Bacik {
3999bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4000bf5fc093SJosef Bacik 
4001bf5fc093SJosef Bacik 	space->total_bytes = 0;
4002bf5fc093SJosef Bacik 	space->used_bytes = 0;
4003bf5fc093SJosef Bacik 	space->flags = 0;
4004bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4005bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4006bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4007bf5fc093SJosef Bacik 		space->used_bytes +=
4008bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4009bf5fc093SJosef Bacik 	}
4010bf5fc093SJosef Bacik }
4011bf5fc093SJosef Bacik 
40122ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
40132ff7e61eSJeff Mahoney 				   void __user *arg)
40141406e432SJosef Bacik {
40151406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
40161406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
40171406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
40187fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
401913f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
40201406e432SJosef Bacik 	struct btrfs_space_info *info;
4021315d8e98SColin Ian King 	static const u64 types[] = {
4022315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
4023bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
4024bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
4025315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4026315d8e98SColin Ian King 	};
4027bf5fc093SJosef Bacik 	int num_types = 4;
40287fde62bfSChris Mason 	int alloc_size;
40291406e432SJosef Bacik 	int ret = 0;
403051788b1bSDan Rosenberg 	u64 slot_count = 0;
4031bf5fc093SJosef Bacik 	int i, c;
40321406e432SJosef Bacik 
40331406e432SJosef Bacik 	if (copy_from_user(&space_args,
40341406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
40351406e432SJosef Bacik 			   sizeof(space_args)))
40361406e432SJosef Bacik 		return -EFAULT;
40371406e432SJosef Bacik 
4038bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4039bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4040bf5fc093SJosef Bacik 
4041bf5fc093SJosef Bacik 		info = NULL;
40427fde62bfSChris Mason 		rcu_read_lock();
40430b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4044bf5fc093SJosef Bacik 					list) {
4045bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4046bf5fc093SJosef Bacik 				info = tmp;
4047bf5fc093SJosef Bacik 				break;
4048bf5fc093SJosef Bacik 			}
4049bf5fc093SJosef Bacik 		}
40507fde62bfSChris Mason 		rcu_read_unlock();
40511406e432SJosef Bacik 
4052bf5fc093SJosef Bacik 		if (!info)
4053bf5fc093SJosef Bacik 			continue;
4054bf5fc093SJosef Bacik 
4055bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4056bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4057bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4058bf5fc093SJosef Bacik 				slot_count++;
4059bf5fc093SJosef Bacik 		}
4060bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4061bf5fc093SJosef Bacik 	}
4062bf5fc093SJosef Bacik 
406336523e95SDavid Sterba 	/*
406436523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
406536523e95SDavid Sterba 	 */
406636523e95SDavid Sterba 	slot_count++;
406736523e95SDavid Sterba 
40687fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
40697fde62bfSChris Mason 	if (space_args.space_slots == 0) {
40707fde62bfSChris Mason 		space_args.total_spaces = slot_count;
40717fde62bfSChris Mason 		goto out;
40727fde62bfSChris Mason 	}
4073bf5fc093SJosef Bacik 
407451788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4075bf5fc093SJosef Bacik 
40767fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4077bf5fc093SJosef Bacik 
40787fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
40797fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
40807fde62bfSChris Mason 	 */
408109cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
40827fde62bfSChris Mason 		return -ENOMEM;
40837fde62bfSChris Mason 
40847fde62bfSChris Mason 	space_args.total_spaces = 0;
40858d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
40867fde62bfSChris Mason 	if (!dest)
40877fde62bfSChris Mason 		return -ENOMEM;
40887fde62bfSChris Mason 	dest_orig = dest;
40897fde62bfSChris Mason 
40907fde62bfSChris Mason 	/* now we have a buffer to copy into */
4091bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4092bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4093bf5fc093SJosef Bacik 
409451788b1bSDan Rosenberg 		if (!slot_count)
409551788b1bSDan Rosenberg 			break;
409651788b1bSDan Rosenberg 
4097bf5fc093SJosef Bacik 		info = NULL;
40981406e432SJosef Bacik 		rcu_read_lock();
40990b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4100bf5fc093SJosef Bacik 					list) {
4101bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4102bf5fc093SJosef Bacik 				info = tmp;
41037fde62bfSChris Mason 				break;
4104bf5fc093SJosef Bacik 			}
4105bf5fc093SJosef Bacik 		}
4106bf5fc093SJosef Bacik 		rcu_read_unlock();
41077fde62bfSChris Mason 
4108bf5fc093SJosef Bacik 		if (!info)
4109bf5fc093SJosef Bacik 			continue;
4110bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4111bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4112bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
4113c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
4114c065f5b1SSu Yue 						     &space);
41157fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
41161406e432SJosef Bacik 				dest++;
41171406e432SJosef Bacik 				space_args.total_spaces++;
411851788b1bSDan Rosenberg 				slot_count--;
41191406e432SJosef Bacik 			}
412051788b1bSDan Rosenberg 			if (!slot_count)
412151788b1bSDan Rosenberg 				break;
4122bf5fc093SJosef Bacik 		}
4123bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4124bf5fc093SJosef Bacik 	}
41251406e432SJosef Bacik 
412636523e95SDavid Sterba 	/*
412736523e95SDavid Sterba 	 * Add global block reserve
412836523e95SDavid Sterba 	 */
412936523e95SDavid Sterba 	if (slot_count) {
41300b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
413136523e95SDavid Sterba 
413236523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
413336523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
413436523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
413536523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
413636523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
413736523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
413836523e95SDavid Sterba 		space_args.total_spaces++;
413936523e95SDavid Sterba 	}
414036523e95SDavid Sterba 
41412eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
41427fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
41437fde62bfSChris Mason 
41447fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
41457fde62bfSChris Mason 		ret = -EFAULT;
41467fde62bfSChris Mason 
41477fde62bfSChris Mason 	kfree(dest_orig);
41487fde62bfSChris Mason out:
41497fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
41501406e432SJosef Bacik 		ret = -EFAULT;
41511406e432SJosef Bacik 
41521406e432SJosef Bacik 	return ret;
41531406e432SJosef Bacik }
41541406e432SJosef Bacik 
41559a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
41569a8c28beSMiao Xie 					    void __user *argp)
415746204592SSage Weil {
415846204592SSage Weil 	struct btrfs_trans_handle *trans;
415946204592SSage Weil 	u64 transid;
4160db5b493aSTsutomu Itoh 	int ret;
416146204592SSage Weil 
4162d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4163ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4164ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
416598d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4166ff7c1d33SMiao Xie 
4167ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4168ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4169ff7c1d33SMiao Xie 		goto out;
4170ff7c1d33SMiao Xie 	}
417146204592SSage Weil 	transid = trans->transid;
41723a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction_async(trans, 0);
41738b2b2d3cSTsutomu Itoh 	if (ret) {
41743a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
4175db5b493aSTsutomu Itoh 		return ret;
41768b2b2d3cSTsutomu Itoh 	}
4177ff7c1d33SMiao Xie out:
417846204592SSage Weil 	if (argp)
417946204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
418046204592SSage Weil 			return -EFAULT;
418146204592SSage Weil 	return 0;
418246204592SSage Weil }
418346204592SSage Weil 
41842ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
41859a8c28beSMiao Xie 					   void __user *argp)
418646204592SSage Weil {
418746204592SSage Weil 	u64 transid;
418846204592SSage Weil 
418946204592SSage Weil 	if (argp) {
419046204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
419146204592SSage Weil 			return -EFAULT;
419246204592SSage Weil 	} else {
419346204592SSage Weil 		transid = 0;  /* current trans */
419446204592SSage Weil 	}
41952ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
419646204592SSage Weil }
419746204592SSage Weil 
4198b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4199475f6387SJan Schmidt {
42000b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4201475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4202b8e95489SMiao Xie 	int ret;
4203475f6387SJan Schmidt 
4204475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4205475f6387SJan Schmidt 		return -EPERM;
4206475f6387SJan Schmidt 
4207475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4208475f6387SJan Schmidt 	if (IS_ERR(sa))
4209475f6387SJan Schmidt 		return PTR_ERR(sa);
4210475f6387SJan Schmidt 
4211b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4212b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4213b8e95489SMiao Xie 		if (ret)
4214b8e95489SMiao Xie 			goto out;
4215b8e95489SMiao Xie 	}
4216b8e95489SMiao Xie 
42170b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
421863a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
421963a212abSStefan Behrens 			      0);
4220475f6387SJan Schmidt 
4221475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4222475f6387SJan Schmidt 		ret = -EFAULT;
4223475f6387SJan Schmidt 
4224b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4225b8e95489SMiao Xie 		mnt_drop_write_file(file);
4226b8e95489SMiao Xie out:
4227475f6387SJan Schmidt 	kfree(sa);
4228475f6387SJan Schmidt 	return ret;
4229475f6387SJan Schmidt }
4230475f6387SJan Schmidt 
42312ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4232475f6387SJan Schmidt {
4233475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4234475f6387SJan Schmidt 		return -EPERM;
4235475f6387SJan Schmidt 
42362ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4237475f6387SJan Schmidt }
4238475f6387SJan Schmidt 
42392ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4240475f6387SJan Schmidt 				       void __user *arg)
4241475f6387SJan Schmidt {
4242475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4243475f6387SJan Schmidt 	int ret;
4244475f6387SJan Schmidt 
4245475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4246475f6387SJan Schmidt 		return -EPERM;
4247475f6387SJan Schmidt 
4248475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4249475f6387SJan Schmidt 	if (IS_ERR(sa))
4250475f6387SJan Schmidt 		return PTR_ERR(sa);
4251475f6387SJan Schmidt 
42522ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4253475f6387SJan Schmidt 
4254475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4255475f6387SJan Schmidt 		ret = -EFAULT;
4256475f6387SJan Schmidt 
4257475f6387SJan Schmidt 	kfree(sa);
4258475f6387SJan Schmidt 	return ret;
4259475f6387SJan Schmidt }
4260475f6387SJan Schmidt 
42612ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4262b27f7c0cSDavid Sterba 				      void __user *arg)
4263c11d2c23SStefan Behrens {
4264c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4265c11d2c23SStefan Behrens 	int ret;
4266c11d2c23SStefan Behrens 
4267c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4268c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4269c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4270c11d2c23SStefan Behrens 
4271b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4272b27f7c0cSDavid Sterba 		kfree(sa);
4273b27f7c0cSDavid Sterba 		return -EPERM;
4274b27f7c0cSDavid Sterba 	}
4275b27f7c0cSDavid Sterba 
42762ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4277c11d2c23SStefan Behrens 
4278c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4279c11d2c23SStefan Behrens 		ret = -EFAULT;
4280c11d2c23SStefan Behrens 
4281c11d2c23SStefan Behrens 	kfree(sa);
4282c11d2c23SStefan Behrens 	return ret;
4283c11d2c23SStefan Behrens }
4284c11d2c23SStefan Behrens 
42852ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
42862ff7e61eSJeff Mahoney 				    void __user *arg)
42873f6bcfbdSStefan Behrens {
42883f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
42893f6bcfbdSStefan Behrens 	int ret;
42903f6bcfbdSStefan Behrens 
42913f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
42923f6bcfbdSStefan Behrens 		return -EPERM;
42933f6bcfbdSStefan Behrens 
42943f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
42953f6bcfbdSStefan Behrens 	if (IS_ERR(p))
42963f6bcfbdSStefan Behrens 		return PTR_ERR(p);
42973f6bcfbdSStefan Behrens 
42983f6bcfbdSStefan Behrens 	switch (p->cmd) {
42993f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4300bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
4301adfa97cbSIlya Dryomov 			ret = -EROFS;
4302adfa97cbSIlya Dryomov 			goto out;
4303adfa97cbSIlya Dryomov 		}
4304171938e5SDavid Sterba 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4305e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
43063f6bcfbdSStefan Behrens 		} else {
43072ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4308171938e5SDavid Sterba 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
43093f6bcfbdSStefan Behrens 		}
43103f6bcfbdSStefan Behrens 		break;
43113f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
43120b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
43133f6bcfbdSStefan Behrens 		ret = 0;
43143f6bcfbdSStefan Behrens 		break;
43153f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
431617d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
431797282031SAnand Jain 		ret = 0;
43183f6bcfbdSStefan Behrens 		break;
43193f6bcfbdSStefan Behrens 	default:
43203f6bcfbdSStefan Behrens 		ret = -EINVAL;
43213f6bcfbdSStefan Behrens 		break;
43223f6bcfbdSStefan Behrens 	}
43233f6bcfbdSStefan Behrens 
43243f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
43253f6bcfbdSStefan Behrens 		ret = -EFAULT;
4326adfa97cbSIlya Dryomov out:
43273f6bcfbdSStefan Behrens 	kfree(p);
43283f6bcfbdSStefan Behrens 	return ret;
43293f6bcfbdSStefan Behrens }
43303f6bcfbdSStefan Behrens 
4331d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4332d7728c96SJan Schmidt {
4333d7728c96SJan Schmidt 	int ret = 0;
4334d7728c96SJan Schmidt 	int i;
4335740c3d22SChris Mason 	u64 rel_ptr;
4336d7728c96SJan Schmidt 	int size;
4337806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4338d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4339d7728c96SJan Schmidt 	struct btrfs_path *path;
4340d7728c96SJan Schmidt 
434182b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4342d7728c96SJan Schmidt 		return -EPERM;
4343d7728c96SJan Schmidt 
4344d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4345d7728c96SJan Schmidt 	if (!path) {
4346d7728c96SJan Schmidt 		ret = -ENOMEM;
4347d7728c96SJan Schmidt 		goto out;
4348d7728c96SJan Schmidt 	}
4349d7728c96SJan Schmidt 
4350d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4351d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4352d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4353d7728c96SJan Schmidt 		ipa = NULL;
4354d7728c96SJan Schmidt 		goto out;
4355d7728c96SJan Schmidt 	}
4356d7728c96SJan Schmidt 
4357d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4358d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4359d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4360d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4361d7728c96SJan Schmidt 		ipath = NULL;
4362d7728c96SJan Schmidt 		goto out;
4363d7728c96SJan Schmidt 	}
4364d7728c96SJan Schmidt 
4365d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4366d7728c96SJan Schmidt 	if (ret < 0)
4367d7728c96SJan Schmidt 		goto out;
4368d7728c96SJan Schmidt 
4369d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4370745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4371745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4372740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4373d7728c96SJan Schmidt 	}
4374d7728c96SJan Schmidt 
4375718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4376718dc5faSOmar Sandoval 			   ipath->fspath, size);
4377d7728c96SJan Schmidt 	if (ret) {
4378d7728c96SJan Schmidt 		ret = -EFAULT;
4379d7728c96SJan Schmidt 		goto out;
4380d7728c96SJan Schmidt 	}
4381d7728c96SJan Schmidt 
4382d7728c96SJan Schmidt out:
4383d7728c96SJan Schmidt 	btrfs_free_path(path);
4384d7728c96SJan Schmidt 	free_ipath(ipath);
4385d7728c96SJan Schmidt 	kfree(ipa);
4386d7728c96SJan Schmidt 
4387d7728c96SJan Schmidt 	return ret;
4388d7728c96SJan Schmidt }
4389d7728c96SJan Schmidt 
4390d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4391d7728c96SJan Schmidt {
4392d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4393d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4394d7728c96SJan Schmidt 
4395d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4396d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4397d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4398d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4399d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4400d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4401d7728c96SJan Schmidt 	} else {
4402d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4403d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4404d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4405d7728c96SJan Schmidt 	}
4406d7728c96SJan Schmidt 
4407d7728c96SJan Schmidt 	return 0;
4408d7728c96SJan Schmidt }
4409d7728c96SJan Schmidt 
44102ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4411d24a67b2SZygo Blaxell 					void __user *arg, int version)
4412d7728c96SJan Schmidt {
4413d7728c96SJan Schmidt 	int ret = 0;
4414d7728c96SJan Schmidt 	int size;
4415d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4416d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4417d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4418d24a67b2SZygo Blaxell 	bool ignore_offset;
4419d7728c96SJan Schmidt 
4420d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4421d7728c96SJan Schmidt 		return -EPERM;
4422d7728c96SJan Schmidt 
4423d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
44247b9ea627SShailendra Verma 	if (IS_ERR(loi))
44257b9ea627SShailendra Verma 		return PTR_ERR(loi);
4426d7728c96SJan Schmidt 
4427d24a67b2SZygo Blaxell 	if (version == 1) {
4428d24a67b2SZygo Blaxell 		ignore_offset = false;
4429b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
4430d24a67b2SZygo Blaxell 	} else {
4431d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
4432d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4433d24a67b2SZygo Blaxell 			ret = -EINVAL;
4434d24a67b2SZygo Blaxell 			goto out_loi;
4435d24a67b2SZygo Blaxell 		}
4436d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
4437d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4438d24a67b2SZygo Blaxell 			ret = -EINVAL;
4439d24a67b2SZygo Blaxell 			goto out_loi;
4440d24a67b2SZygo Blaxell 		}
4441d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4442b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
4443d24a67b2SZygo Blaxell 	}
4444d24a67b2SZygo Blaxell 
4445d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4446d7728c96SJan Schmidt 	if (!path) {
4447d7728c96SJan Schmidt 		ret = -ENOMEM;
4448d7728c96SJan Schmidt 		goto out;
4449d7728c96SJan Schmidt 	}
4450d7728c96SJan Schmidt 
4451d7728c96SJan Schmidt 	inodes = init_data_container(size);
4452d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4453d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4454d7728c96SJan Schmidt 		inodes = NULL;
4455d7728c96SJan Schmidt 		goto out;
4456d7728c96SJan Schmidt 	}
4457d7728c96SJan Schmidt 
44582ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4459d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
4460df031f07SLiu Bo 	if (ret == -EINVAL)
4461d7728c96SJan Schmidt 		ret = -ENOENT;
4462d7728c96SJan Schmidt 	if (ret < 0)
4463d7728c96SJan Schmidt 		goto out;
4464d7728c96SJan Schmidt 
4465718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4466718dc5faSOmar Sandoval 			   size);
4467d7728c96SJan Schmidt 	if (ret)
4468d7728c96SJan Schmidt 		ret = -EFAULT;
4469d7728c96SJan Schmidt 
4470d7728c96SJan Schmidt out:
4471d7728c96SJan Schmidt 	btrfs_free_path(path);
4472f54de068SDavid Sterba 	kvfree(inodes);
4473d24a67b2SZygo Blaxell out_loi:
4474d7728c96SJan Schmidt 	kfree(loi);
4475d7728c96SJan Schmidt 
4476d7728c96SJan Schmidt 	return ret;
4477d7728c96SJan Schmidt }
4478d7728c96SJan Schmidt 
4479008ef096SDavid Sterba void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4480c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4481c9e9f97bSIlya Dryomov {
4482c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4483c9e9f97bSIlya Dryomov 
4484c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4485c9e9f97bSIlya Dryomov 
44863009a62fSDavid Sterba 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4487837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4488837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4489837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4490a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4491a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4492837d5b6eSIlya Dryomov 
4493c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4494c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4495c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
449619a39dceSIlya Dryomov 
449719a39dceSIlya Dryomov 	spin_lock(&fs_info->balance_lock);
449819a39dceSIlya Dryomov 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
449919a39dceSIlya Dryomov 	spin_unlock(&fs_info->balance_lock);
4500c9e9f97bSIlya Dryomov }
4501c9e9f97bSIlya Dryomov 
45029ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4503c9e9f97bSIlya Dryomov {
4504496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4505c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4506c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4507c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4508ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4509c9e9f97bSIlya Dryomov 	int ret;
4510c9e9f97bSIlya Dryomov 
4511c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4512c9e9f97bSIlya Dryomov 		return -EPERM;
4513c9e9f97bSIlya Dryomov 
4514e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
45159ba1f6e4SLiu Bo 	if (ret)
45169ba1f6e4SLiu Bo 		return ret;
45179ba1f6e4SLiu Bo 
4518ed0fb78fSIlya Dryomov again:
4519171938e5SDavid Sterba 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4520c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4521ed0fb78fSIlya Dryomov 		need_unlock = true;
4522ed0fb78fSIlya Dryomov 		goto locked;
4523ed0fb78fSIlya Dryomov 	}
4524ed0fb78fSIlya Dryomov 
4525ed0fb78fSIlya Dryomov 	/*
452601327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4527ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4528ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4529ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4530ed0fb78fSIlya Dryomov 	 */
4531ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4532ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4533ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
45343009a62fSDavid Sterba 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4535ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4536dccdb07bSDavid Sterba 			/*
4537dccdb07bSDavid Sterba 			 * Lock released to allow other waiters to continue,
4538dccdb07bSDavid Sterba 			 * we'll reexamine the status again.
4539dccdb07bSDavid Sterba 			 */
4540ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4541ed0fb78fSIlya Dryomov 
4542ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
45433009a62fSDavid Sterba 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4544ed0fb78fSIlya Dryomov 				/* this is (3) */
4545ed0fb78fSIlya Dryomov 				need_unlock = false;
4546ed0fb78fSIlya Dryomov 				goto locked;
4547ed0fb78fSIlya Dryomov 			}
4548ed0fb78fSIlya Dryomov 
4549ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4550ed0fb78fSIlya Dryomov 			goto again;
4551ed0fb78fSIlya Dryomov 		} else {
4552ed0fb78fSIlya Dryomov 			/* this is (2) */
4553ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4554ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4555ed0fb78fSIlya Dryomov 			goto out;
4556ed0fb78fSIlya Dryomov 		}
4557ed0fb78fSIlya Dryomov 	} else {
4558ed0fb78fSIlya Dryomov 		/* this is (1) */
4559ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4560e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4561ed0fb78fSIlya Dryomov 		goto out;
4562ed0fb78fSIlya Dryomov 	}
4563ed0fb78fSIlya Dryomov 
4564ed0fb78fSIlya Dryomov locked:
4565171938e5SDavid Sterba 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4566c9e9f97bSIlya Dryomov 
4567c9e9f97bSIlya Dryomov 	if (arg) {
4568c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4569c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4570c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4571ed0fb78fSIlya Dryomov 			goto out_unlock;
4572c9e9f97bSIlya Dryomov 		}
4573de322263SIlya Dryomov 
4574de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4575de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4576de322263SIlya Dryomov 				ret = -ENOTCONN;
4577de322263SIlya Dryomov 				goto out_bargs;
4578de322263SIlya Dryomov 			}
4579de322263SIlya Dryomov 
4580de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4581de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4582de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4583de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4584de322263SIlya Dryomov 
4585de322263SIlya Dryomov 			goto do_balance;
4586de322263SIlya Dryomov 		}
4587c9e9f97bSIlya Dryomov 	} else {
4588c9e9f97bSIlya Dryomov 		bargs = NULL;
4589c9e9f97bSIlya Dryomov 	}
4590c9e9f97bSIlya Dryomov 
4591ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4592837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4593837d5b6eSIlya Dryomov 		goto out_bargs;
4594837d5b6eSIlya Dryomov 	}
4595837d5b6eSIlya Dryomov 
45968d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4597c9e9f97bSIlya Dryomov 	if (!bctl) {
4598c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4599c9e9f97bSIlya Dryomov 		goto out_bargs;
4600c9e9f97bSIlya Dryomov 	}
4601c9e9f97bSIlya Dryomov 
4602c9e9f97bSIlya Dryomov 	if (arg) {
4603c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4604c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4605c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4606c9e9f97bSIlya Dryomov 
4607c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4608f43ffb60SIlya Dryomov 	} else {
4609f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4610f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4611c9e9f97bSIlya Dryomov 	}
4612c9e9f97bSIlya Dryomov 
46138eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
46148eb93459SDavid Sterba 		ret = -EINVAL;
46150f89abf5SChristian Engelmayer 		goto out_bctl;
46168eb93459SDavid Sterba 	}
46178eb93459SDavid Sterba 
4618de322263SIlya Dryomov do_balance:
4619c9e9f97bSIlya Dryomov 	/*
4620149196a2SDavid Sterba 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
4621149196a2SDavid Sterba 	 * btrfs_balance.  bctl is freed in reset_balance_state, or, if
4622149196a2SDavid Sterba 	 * restriper was paused all the way until unmount, in free_fs_info.
4623149196a2SDavid Sterba 	 * The flag should be cleared after reset_balance_state.
4624c9e9f97bSIlya Dryomov 	 */
4625ed0fb78fSIlya Dryomov 	need_unlock = false;
4626ed0fb78fSIlya Dryomov 
46276fcf6e2bSDavid Sterba 	ret = btrfs_balance(fs_info, bctl, bargs);
46280f89abf5SChristian Engelmayer 	bctl = NULL;
4629ed0fb78fSIlya Dryomov 
4630c9e9f97bSIlya Dryomov 	if (arg) {
4631c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4632c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4633c9e9f97bSIlya Dryomov 	}
4634c9e9f97bSIlya Dryomov 
46350f89abf5SChristian Engelmayer out_bctl:
46360f89abf5SChristian Engelmayer 	kfree(bctl);
4637c9e9f97bSIlya Dryomov out_bargs:
4638c9e9f97bSIlya Dryomov 	kfree(bargs);
4639ed0fb78fSIlya Dryomov out_unlock:
4640c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4641ed0fb78fSIlya Dryomov 	if (need_unlock)
4642171938e5SDavid Sterba 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4643ed0fb78fSIlya Dryomov out:
4644e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4645c9e9f97bSIlya Dryomov 	return ret;
4646c9e9f97bSIlya Dryomov }
4647c9e9f97bSIlya Dryomov 
46482ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4649837d5b6eSIlya Dryomov {
4650837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4651837d5b6eSIlya Dryomov 		return -EPERM;
4652837d5b6eSIlya Dryomov 
4653837d5b6eSIlya Dryomov 	switch (cmd) {
4654837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
46550b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4656a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
46570b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4658837d5b6eSIlya Dryomov 	}
4659837d5b6eSIlya Dryomov 
4660837d5b6eSIlya Dryomov 	return -EINVAL;
4661837d5b6eSIlya Dryomov }
4662837d5b6eSIlya Dryomov 
46632ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
466419a39dceSIlya Dryomov 					 void __user *arg)
466519a39dceSIlya Dryomov {
466619a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
466719a39dceSIlya Dryomov 	int ret = 0;
466819a39dceSIlya Dryomov 
466919a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
467019a39dceSIlya Dryomov 		return -EPERM;
467119a39dceSIlya Dryomov 
467219a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
467319a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
467419a39dceSIlya Dryomov 		ret = -ENOTCONN;
467519a39dceSIlya Dryomov 		goto out;
467619a39dceSIlya Dryomov 	}
467719a39dceSIlya Dryomov 
46788d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
467919a39dceSIlya Dryomov 	if (!bargs) {
468019a39dceSIlya Dryomov 		ret = -ENOMEM;
468119a39dceSIlya Dryomov 		goto out;
468219a39dceSIlya Dryomov 	}
468319a39dceSIlya Dryomov 
4684008ef096SDavid Sterba 	btrfs_update_ioctl_balance_args(fs_info, bargs);
468519a39dceSIlya Dryomov 
468619a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
468719a39dceSIlya Dryomov 		ret = -EFAULT;
468819a39dceSIlya Dryomov 
468919a39dceSIlya Dryomov 	kfree(bargs);
469019a39dceSIlya Dryomov out:
469119a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
469219a39dceSIlya Dryomov 	return ret;
469319a39dceSIlya Dryomov }
469419a39dceSIlya Dryomov 
4695905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
46965d13a37bSArne Jansen {
46970b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
46980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46995d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
47005d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
47015d13a37bSArne Jansen 	int ret;
47025d13a37bSArne Jansen 	int err;
47035d13a37bSArne Jansen 
47045d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
47055d13a37bSArne Jansen 		return -EPERM;
47065d13a37bSArne Jansen 
4707905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4708905b0ddaSMiao Xie 	if (ret)
4709905b0ddaSMiao Xie 		return ret;
47105d13a37bSArne Jansen 
47115d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4712905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4713905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4714905b0ddaSMiao Xie 		goto drop_write;
4715905b0ddaSMiao Xie 	}
47165d13a37bSArne Jansen 
47170b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
47180b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 2);
47195d13a37bSArne Jansen 	if (IS_ERR(trans)) {
47205d13a37bSArne Jansen 		ret = PTR_ERR(trans);
47215d13a37bSArne Jansen 		goto out;
47225d13a37bSArne Jansen 	}
47235d13a37bSArne Jansen 
47245d13a37bSArne Jansen 	switch (sa->cmd) {
47255d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
47260b246afaSJeff Mahoney 		ret = btrfs_quota_enable(trans, fs_info);
47275d13a37bSArne Jansen 		break;
47285d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
47290b246afaSJeff Mahoney 		ret = btrfs_quota_disable(trans, fs_info);
47305d13a37bSArne Jansen 		break;
47315d13a37bSArne Jansen 	default:
47325d13a37bSArne Jansen 		ret = -EINVAL;
47335d13a37bSArne Jansen 		break;
47345d13a37bSArne Jansen 	}
47355d13a37bSArne Jansen 
47363a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
47375d13a37bSArne Jansen 	if (err && !ret)
47385d13a37bSArne Jansen 		ret = err;
47395d13a37bSArne Jansen out:
47405d13a37bSArne Jansen 	kfree(sa);
47410b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4742905b0ddaSMiao Xie drop_write:
4743905b0ddaSMiao Xie 	mnt_drop_write_file(file);
47445d13a37bSArne Jansen 	return ret;
47455d13a37bSArne Jansen }
47465d13a37bSArne Jansen 
4747905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
47485d13a37bSArne Jansen {
47490b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47510b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
47525d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
47535d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
47545d13a37bSArne Jansen 	int ret;
47555d13a37bSArne Jansen 	int err;
47565d13a37bSArne Jansen 
47575d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
47585d13a37bSArne Jansen 		return -EPERM;
47595d13a37bSArne Jansen 
4760905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4761905b0ddaSMiao Xie 	if (ret)
4762905b0ddaSMiao Xie 		return ret;
47635d13a37bSArne Jansen 
47645d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4765905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4766905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4767905b0ddaSMiao Xie 		goto drop_write;
4768905b0ddaSMiao Xie 	}
47695d13a37bSArne Jansen 
47705d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
47715d13a37bSArne Jansen 	if (IS_ERR(trans)) {
47725d13a37bSArne Jansen 		ret = PTR_ERR(trans);
47735d13a37bSArne Jansen 		goto out;
47745d13a37bSArne Jansen 	}
47755d13a37bSArne Jansen 
47765d13a37bSArne Jansen 	if (sa->assign) {
47770b246afaSJeff Mahoney 		ret = btrfs_add_qgroup_relation(trans, fs_info,
47785d13a37bSArne Jansen 						sa->src, sa->dst);
47795d13a37bSArne Jansen 	} else {
47800b246afaSJeff Mahoney 		ret = btrfs_del_qgroup_relation(trans, fs_info,
47815d13a37bSArne Jansen 						sa->src, sa->dst);
47825d13a37bSArne Jansen 	}
47835d13a37bSArne Jansen 
4784e082f563SQu Wenruo 	/* update qgroup status and info */
47850b246afaSJeff Mahoney 	err = btrfs_run_qgroups(trans, fs_info);
4786e082f563SQu Wenruo 	if (err < 0)
47870b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4788ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
47893a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
47905d13a37bSArne Jansen 	if (err && !ret)
47915d13a37bSArne Jansen 		ret = err;
47925d13a37bSArne Jansen 
47935d13a37bSArne Jansen out:
47945d13a37bSArne Jansen 	kfree(sa);
4795905b0ddaSMiao Xie drop_write:
4796905b0ddaSMiao Xie 	mnt_drop_write_file(file);
47975d13a37bSArne Jansen 	return ret;
47985d13a37bSArne Jansen }
47995d13a37bSArne Jansen 
4800905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
48015d13a37bSArne Jansen {
48020b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48040b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
48055d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
48065d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48075d13a37bSArne Jansen 	int ret;
48085d13a37bSArne Jansen 	int err;
48095d13a37bSArne Jansen 
48105d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48115d13a37bSArne Jansen 		return -EPERM;
48125d13a37bSArne Jansen 
4813905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4814905b0ddaSMiao Xie 	if (ret)
4815905b0ddaSMiao Xie 		return ret;
48165d13a37bSArne Jansen 
48175d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4818905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4819905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4820905b0ddaSMiao Xie 		goto drop_write;
4821905b0ddaSMiao Xie 	}
48225d13a37bSArne Jansen 
4823d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4824d86e56cfSMiao Xie 		ret = -EINVAL;
4825d86e56cfSMiao Xie 		goto out;
4826d86e56cfSMiao Xie 	}
4827d86e56cfSMiao Xie 
48285d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
48295d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48305d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48315d13a37bSArne Jansen 		goto out;
48325d13a37bSArne Jansen 	}
48335d13a37bSArne Jansen 
48345d13a37bSArne Jansen 	if (sa->create) {
48350b246afaSJeff Mahoney 		ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
48365d13a37bSArne Jansen 	} else {
48370b246afaSJeff Mahoney 		ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
48385d13a37bSArne Jansen 	}
48395d13a37bSArne Jansen 
48403a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
48415d13a37bSArne Jansen 	if (err && !ret)
48425d13a37bSArne Jansen 		ret = err;
48435d13a37bSArne Jansen 
48445d13a37bSArne Jansen out:
48455d13a37bSArne Jansen 	kfree(sa);
4846905b0ddaSMiao Xie drop_write:
4847905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48485d13a37bSArne Jansen 	return ret;
48495d13a37bSArne Jansen }
48505d13a37bSArne Jansen 
4851905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
48525d13a37bSArne Jansen {
48530b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48550b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
48565d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
48575d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48585d13a37bSArne Jansen 	int ret;
48595d13a37bSArne Jansen 	int err;
48605d13a37bSArne Jansen 	u64 qgroupid;
48615d13a37bSArne Jansen 
48625d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48635d13a37bSArne Jansen 		return -EPERM;
48645d13a37bSArne Jansen 
4865905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4866905b0ddaSMiao Xie 	if (ret)
4867905b0ddaSMiao Xie 		return ret;
48685d13a37bSArne Jansen 
48695d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4870905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4871905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4872905b0ddaSMiao Xie 		goto drop_write;
4873905b0ddaSMiao Xie 	}
48745d13a37bSArne Jansen 
48755d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
48765d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48775d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48785d13a37bSArne Jansen 		goto out;
48795d13a37bSArne Jansen 	}
48805d13a37bSArne Jansen 
48815d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
48825d13a37bSArne Jansen 	if (!qgroupid) {
48835d13a37bSArne Jansen 		/* take the current subvol as qgroup */
48845d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
48855d13a37bSArne Jansen 	}
48865d13a37bSArne Jansen 
48870b246afaSJeff Mahoney 	ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
48885d13a37bSArne Jansen 
48893a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
48905d13a37bSArne Jansen 	if (err && !ret)
48915d13a37bSArne Jansen 		ret = err;
48925d13a37bSArne Jansen 
48935d13a37bSArne Jansen out:
48945d13a37bSArne Jansen 	kfree(sa);
4895905b0ddaSMiao Xie drop_write:
4896905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48975d13a37bSArne Jansen 	return ret;
48985d13a37bSArne Jansen }
48995d13a37bSArne Jansen 
49002f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
49012f232036SJan Schmidt {
49020b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49042f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
49052f232036SJan Schmidt 	int ret;
49062f232036SJan Schmidt 
49072f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
49082f232036SJan Schmidt 		return -EPERM;
49092f232036SJan Schmidt 
49102f232036SJan Schmidt 	ret = mnt_want_write_file(file);
49112f232036SJan Schmidt 	if (ret)
49122f232036SJan Schmidt 		return ret;
49132f232036SJan Schmidt 
49142f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
49152f232036SJan Schmidt 	if (IS_ERR(qsa)) {
49162f232036SJan Schmidt 		ret = PTR_ERR(qsa);
49172f232036SJan Schmidt 		goto drop_write;
49182f232036SJan Schmidt 	}
49192f232036SJan Schmidt 
49202f232036SJan Schmidt 	if (qsa->flags) {
49212f232036SJan Schmidt 		ret = -EINVAL;
49222f232036SJan Schmidt 		goto out;
49232f232036SJan Schmidt 	}
49242f232036SJan Schmidt 
49250b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
49262f232036SJan Schmidt 
49272f232036SJan Schmidt out:
49282f232036SJan Schmidt 	kfree(qsa);
49292f232036SJan Schmidt drop_write:
49302f232036SJan Schmidt 	mnt_drop_write_file(file);
49312f232036SJan Schmidt 	return ret;
49322f232036SJan Schmidt }
49332f232036SJan Schmidt 
49342f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
49352f232036SJan Schmidt {
49360b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49370b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49382f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
49392f232036SJan Schmidt 	int ret = 0;
49402f232036SJan Schmidt 
49412f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
49422f232036SJan Schmidt 		return -EPERM;
49432f232036SJan Schmidt 
49448d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
49452f232036SJan Schmidt 	if (!qsa)
49462f232036SJan Schmidt 		return -ENOMEM;
49472f232036SJan Schmidt 
49480b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
49492f232036SJan Schmidt 		qsa->flags = 1;
49500b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
49512f232036SJan Schmidt 	}
49522f232036SJan Schmidt 
49532f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
49542f232036SJan Schmidt 		ret = -EFAULT;
49552f232036SJan Schmidt 
49562f232036SJan Schmidt 	kfree(qsa);
49572f232036SJan Schmidt 	return ret;
49582f232036SJan Schmidt }
49592f232036SJan Schmidt 
496057254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
496157254b6eSJan Schmidt {
49620b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
496457254b6eSJan Schmidt 
496557254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
496657254b6eSJan Schmidt 		return -EPERM;
496757254b6eSJan Schmidt 
49680b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
496957254b6eSJan Schmidt }
497057254b6eSJan Schmidt 
4971abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
4972abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
49738ea05e3aSAlexander Block {
4974496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
49750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49768ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
49778ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
49788ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
4979c2050a45SDeepa Dinamani 	struct timespec ct = current_time(inode);
49808ea05e3aSAlexander Block 	int ret = 0;
4981dd5f9615SStefan Behrens 	int received_uuid_changed;
49828ea05e3aSAlexander Block 
4983bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
4984bd60ea0fSDavid Sterba 		return -EPERM;
4985bd60ea0fSDavid Sterba 
49868ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
49878ea05e3aSAlexander Block 	if (ret < 0)
49888ea05e3aSAlexander Block 		return ret;
49898ea05e3aSAlexander Block 
49900b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
49918ea05e3aSAlexander Block 
49924a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
49938ea05e3aSAlexander Block 		ret = -EINVAL;
49948ea05e3aSAlexander Block 		goto out;
49958ea05e3aSAlexander Block 	}
49968ea05e3aSAlexander Block 
49978ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
49988ea05e3aSAlexander Block 		ret = -EROFS;
49998ea05e3aSAlexander Block 		goto out;
50008ea05e3aSAlexander Block 	}
50018ea05e3aSAlexander Block 
5002dd5f9615SStefan Behrens 	/*
5003dd5f9615SStefan Behrens 	 * 1 - root item
5004dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5005dd5f9615SStefan Behrens 	 */
5006dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
50078ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
50088ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
50098ea05e3aSAlexander Block 		trans = NULL;
50108ea05e3aSAlexander Block 		goto out;
50118ea05e3aSAlexander Block 	}
50128ea05e3aSAlexander Block 
50138ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
50148ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
50158ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
50168ea05e3aSAlexander Block 
5017dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5018dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5019dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5020d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
5021d87ff758SNikolay Borisov 		ret = btrfs_uuid_tree_rem(trans, fs_info,
5022d87ff758SNikolay Borisov 					  root_item->received_uuid,
5023dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5024dd5f9615SStefan Behrens 					  root->root_key.objectid);
5025d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
5026d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
5027d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
5028d87ff758SNikolay Borisov 		        goto out;
5029d87ff758SNikolay Borisov 		}
5030d87ff758SNikolay Borisov 	}
50318ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
50328ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
50338ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
50343cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
50353cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
50363cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
50373cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
50388ea05e3aSAlexander Block 
50390b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
50408ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
50418ea05e3aSAlexander Block 	if (ret < 0) {
50423a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
50438ea05e3aSAlexander Block 		goto out;
5044dd5f9615SStefan Behrens 	}
5045dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
50460b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_add(trans, fs_info, sa->uuid,
5047dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5048dd5f9615SStefan Behrens 					  root->root_key.objectid);
5049dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
505066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
5051efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
5052dd5f9615SStefan Behrens 			goto out;
5053dd5f9615SStefan Behrens 		}
5054dd5f9615SStefan Behrens 	}
50553a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5056abccd00fSHugo Mills out:
50570b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5058abccd00fSHugo Mills 	mnt_drop_write_file(file);
5059abccd00fSHugo Mills 	return ret;
5060abccd00fSHugo Mills }
5061abccd00fSHugo Mills 
5062abccd00fSHugo Mills #ifdef CONFIG_64BIT
5063abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5064abccd00fSHugo Mills 						void __user *arg)
5065abccd00fSHugo Mills {
5066abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5067abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5068abccd00fSHugo Mills 	int ret = 0;
5069abccd00fSHugo Mills 
5070abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
50717b9ea627SShailendra Verma 	if (IS_ERR(args32))
50727b9ea627SShailendra Verma 		return PTR_ERR(args32);
5073abccd00fSHugo Mills 
50748d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
507584dbeb87SDan Carpenter 	if (!args64) {
507684dbeb87SDan Carpenter 		ret = -ENOMEM;
5077abccd00fSHugo Mills 		goto out;
5078abccd00fSHugo Mills 	}
5079abccd00fSHugo Mills 
5080abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5081abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5082abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5083abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5084abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5085abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5086abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5087abccd00fSHugo Mills 	args64->flags = args32->flags;
5088abccd00fSHugo Mills 
5089abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5090abccd00fSHugo Mills 	if (ret)
5091abccd00fSHugo Mills 		goto out;
5092abccd00fSHugo Mills 
5093abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5094abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5095abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5096abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5097abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5098abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5099abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5100abccd00fSHugo Mills 	args32->flags = args64->flags;
5101abccd00fSHugo Mills 
5102abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5103abccd00fSHugo Mills 	if (ret)
5104abccd00fSHugo Mills 		ret = -EFAULT;
5105abccd00fSHugo Mills 
5106abccd00fSHugo Mills out:
5107abccd00fSHugo Mills 	kfree(args32);
5108abccd00fSHugo Mills 	kfree(args64);
5109abccd00fSHugo Mills 	return ret;
5110abccd00fSHugo Mills }
5111abccd00fSHugo Mills #endif
5112abccd00fSHugo Mills 
5113abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5114abccd00fSHugo Mills 					    void __user *arg)
5115abccd00fSHugo Mills {
5116abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5117abccd00fSHugo Mills 	int ret = 0;
5118abccd00fSHugo Mills 
5119abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
51207b9ea627SShailendra Verma 	if (IS_ERR(sa))
51217b9ea627SShailendra Verma 		return PTR_ERR(sa);
5122abccd00fSHugo Mills 
5123abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5124abccd00fSHugo Mills 
5125abccd00fSHugo Mills 	if (ret)
5126abccd00fSHugo Mills 		goto out;
5127abccd00fSHugo Mills 
51288ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
51298ea05e3aSAlexander Block 	if (ret)
51308ea05e3aSAlexander Block 		ret = -EFAULT;
51318ea05e3aSAlexander Block 
51328ea05e3aSAlexander Block out:
51338ea05e3aSAlexander Block 	kfree(sa);
51348ea05e3aSAlexander Block 	return ret;
51358ea05e3aSAlexander Block }
51368ea05e3aSAlexander Block 
5137867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5138867ab667Sjeff.liu {
51390b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51400b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5141a1b83ac5SAnand Jain 	size_t len;
5142867ab667Sjeff.liu 	int ret;
5143a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5144a1b83ac5SAnand Jain 
51450b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
51460b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
51470b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
5148a1b83ac5SAnand Jain 
5149a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5150867ab667Sjeff.liu 
5151867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
51520b246afaSJeff Mahoney 		btrfs_warn(fs_info,
51530b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
51540b246afaSJeff Mahoney 			   --len);
5155867ab667Sjeff.liu 	}
5156867ab667Sjeff.liu 
5157867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5158867ab667Sjeff.liu 
5159867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5160867ab667Sjeff.liu }
5161867ab667Sjeff.liu 
5162a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5163a8bfd4abSjeff.liu {
51640b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51660b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
51670b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
5168a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5169a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5170a8bfd4abSjeff.liu 	int ret;
5171a8bfd4abSjeff.liu 
5172a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5173a8bfd4abSjeff.liu 		return -EPERM;
5174a8bfd4abSjeff.liu 
5175a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5176a8bfd4abSjeff.liu 		return -EFAULT;
5177a8bfd4abSjeff.liu 
5178a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
51790b246afaSJeff Mahoney 		btrfs_err(fs_info,
51805d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5181a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5182a8bfd4abSjeff.liu 		return -EINVAL;
5183a8bfd4abSjeff.liu 	}
5184a8bfd4abSjeff.liu 
5185a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5186a8bfd4abSjeff.liu 	if (ret)
5187a8bfd4abSjeff.liu 		return ret;
5188a8bfd4abSjeff.liu 
5189a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5190a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5191a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5192a8bfd4abSjeff.liu 		goto out_unlock;
5193a8bfd4abSjeff.liu 	}
5194a8bfd4abSjeff.liu 
51950b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5196a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
51970b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
51983a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5199a8bfd4abSjeff.liu 
5200a8bfd4abSjeff.liu out_unlock:
5201a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5202a8bfd4abSjeff.liu 	return ret;
5203a8bfd4abSjeff.liu }
5204a8bfd4abSjeff.liu 
52052eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
52062eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
52072eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
52082eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
52092eaa055fSJeff Mahoney 
5210d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
52112eaa055fSJeff Mahoney {
52124d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
52132eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
52142eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
52152eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
52162eaa055fSJeff Mahoney 	};
52172eaa055fSJeff Mahoney 
52182eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
52192eaa055fSJeff Mahoney 		return -EFAULT;
52202eaa055fSJeff Mahoney 
52212eaa055fSJeff Mahoney 	return 0;
52222eaa055fSJeff Mahoney }
52232eaa055fSJeff Mahoney 
52242eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
52252eaa055fSJeff Mahoney {
52260b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52270b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52280b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
52292eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
52302eaa055fSJeff Mahoney 
52312eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
52322eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
52332eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
52342eaa055fSJeff Mahoney 
52352eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
52362eaa055fSJeff Mahoney 		return -EFAULT;
52372eaa055fSJeff Mahoney 
52382eaa055fSJeff Mahoney 	return 0;
52392eaa055fSJeff Mahoney }
52402eaa055fSJeff Mahoney 
52412ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
52423b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
52432eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
52442eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
52452eaa055fSJeff Mahoney {
52463b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
52473b02a68aSJeff Mahoney 	char *names;
52482eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
52492eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
52502eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
52512eaa055fSJeff Mahoney 
52522eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
52532eaa055fSJeff Mahoney 	if (unsupported) {
52543b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
52553b02a68aSJeff Mahoney 		if (names) {
52560b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52573b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
52583b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
52593b02a68aSJeff Mahoney 			kfree(names);
52603b02a68aSJeff Mahoney 		} else
52610b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52622eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
52632eaa055fSJeff Mahoney 				   type, unsupported);
52642eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
52652eaa055fSJeff Mahoney 	}
52662eaa055fSJeff Mahoney 
52672eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
52682eaa055fSJeff Mahoney 	if (disallowed) {
52693b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
52703b02a68aSJeff Mahoney 		if (names) {
52710b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52723b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
52733b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
52743b02a68aSJeff Mahoney 			kfree(names);
52753b02a68aSJeff Mahoney 		} else
52760b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52772eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
52782eaa055fSJeff Mahoney 				   type, disallowed);
52792eaa055fSJeff Mahoney 		return -EPERM;
52802eaa055fSJeff Mahoney 	}
52812eaa055fSJeff Mahoney 
52822eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
52832eaa055fSJeff Mahoney 	if (disallowed) {
52843b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
52853b02a68aSJeff Mahoney 		if (names) {
52860b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52873b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
52883b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
52893b02a68aSJeff Mahoney 			kfree(names);
52903b02a68aSJeff Mahoney 		} else
52910b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52922eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
52932eaa055fSJeff Mahoney 				   type, disallowed);
52942eaa055fSJeff Mahoney 		return -EPERM;
52952eaa055fSJeff Mahoney 	}
52962eaa055fSJeff Mahoney 
52972eaa055fSJeff Mahoney 	return 0;
52982eaa055fSJeff Mahoney }
52992eaa055fSJeff Mahoney 
53002ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
53012ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
53022eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
53032eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
53042eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
53052eaa055fSJeff Mahoney 
53062eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
53072eaa055fSJeff Mahoney {
53080b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53100b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
53110b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
53122eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
53132eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
53142eaa055fSJeff Mahoney 	u64 newflags;
53152eaa055fSJeff Mahoney 	int ret;
53162eaa055fSJeff Mahoney 
53172eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
53182eaa055fSJeff Mahoney 		return -EPERM;
53192eaa055fSJeff Mahoney 
53202eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
53212eaa055fSJeff Mahoney 		return -EFAULT;
53222eaa055fSJeff Mahoney 
53232eaa055fSJeff Mahoney 	/* Nothing to do */
53242eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
53252eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
53262eaa055fSJeff Mahoney 		return 0;
53272eaa055fSJeff Mahoney 
53282ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
53292eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
53302eaa055fSJeff Mahoney 	if (ret)
53312eaa055fSJeff Mahoney 		return ret;
53322eaa055fSJeff Mahoney 
53332ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
53342eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
53352eaa055fSJeff Mahoney 	if (ret)
53362eaa055fSJeff Mahoney 		return ret;
53372eaa055fSJeff Mahoney 
53382ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
53392eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
53402eaa055fSJeff Mahoney 	if (ret)
53412eaa055fSJeff Mahoney 		return ret;
53422eaa055fSJeff Mahoney 
53437ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
53447ab19625SDavid Sterba 	if (ret)
53457ab19625SDavid Sterba 		return ret;
53467ab19625SDavid Sterba 
53478051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
53487ab19625SDavid Sterba 	if (IS_ERR(trans)) {
53497ab19625SDavid Sterba 		ret = PTR_ERR(trans);
53507ab19625SDavid Sterba 		goto out_drop_write;
53517ab19625SDavid Sterba 	}
53522eaa055fSJeff Mahoney 
53530b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
53542eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
53552eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
53562eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
53572eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
53582eaa055fSJeff Mahoney 
53592eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
53602eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
53612eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
53622eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
53632eaa055fSJeff Mahoney 
53642eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
53652eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
53662eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
53672eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
53680b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
53692eaa055fSJeff Mahoney 
53703a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
53717ab19625SDavid Sterba out_drop_write:
53727ab19625SDavid Sterba 	mnt_drop_write_file(file);
53737ab19625SDavid Sterba 
53747ab19625SDavid Sterba 	return ret;
53752eaa055fSJeff Mahoney }
53762eaa055fSJeff Mahoney 
53772351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
53782351f431SJosef Bacik {
53792351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
53802351f431SJosef Bacik 	int ret;
53812351f431SJosef Bacik 
53822351f431SJosef Bacik 	if (compat) {
53832351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
53842351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
53852351f431SJosef Bacik 
53862351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
53872351f431SJosef Bacik 		if (ret)
53882351f431SJosef Bacik 			return -EFAULT;
53892351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
53902351f431SJosef Bacik 		if (!arg)
53912351f431SJosef Bacik 			return -ENOMEM;
53922351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
53932351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
53942351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
53952351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
53962351f431SJosef Bacik 		arg->flags = args32.flags;
53972351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
53982351f431SJosef Bacik 		       sizeof(args32.reserved));
53992351f431SJosef Bacik #else
54002351f431SJosef Bacik 		return -ENOTTY;
54012351f431SJosef Bacik #endif
54022351f431SJosef Bacik 	} else {
54032351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
54042351f431SJosef Bacik 		if (IS_ERR(arg))
54052351f431SJosef Bacik 			return PTR_ERR(arg);
54062351f431SJosef Bacik 	}
54072351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
54082351f431SJosef Bacik 	kfree(arg);
54092351f431SJosef Bacik 	return ret;
54102351f431SJosef Bacik }
54112351f431SJosef Bacik 
5412f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5413f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5414f46b5a66SChristoph Hellwig {
54150b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
54160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
54170b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
54184bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5419f46b5a66SChristoph Hellwig 
5420f46b5a66SChristoph Hellwig 	switch (cmd) {
54216cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
54226cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
54236cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
54246cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
54256cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
54266cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5427f7039b1dSLi Dongyang 	case FITRIM:
5428f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5429f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5430fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5431fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5432fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
54333de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5434fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
54356f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
54366f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
543776dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
543876dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
54390caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
54400caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
54410caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
54420caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
54436ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
54446ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5445f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
54461e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
54471e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
54481e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5449f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5450198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5451f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
54522ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5453f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5454da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
54556b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
54566b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5457475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
54582ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5459475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
54602ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5461f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
54629ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5463ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5464ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5465cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5466cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5467ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5468ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5469d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5470d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5471d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5472d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5473d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
5474d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
54751406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
54762ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
54779b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
54789b199859SFilipe David Borba Manana 		int ret;
54799b199859SFilipe David Borba Manana 
548082b3e53bSNikolay Borisov 		ret = btrfs_start_delalloc_roots(fs_info, -1);
54819b199859SFilipe David Borba Manana 		if (ret)
54829b199859SFilipe David Borba Manana 			return ret;
54830b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
54842fad4e83SDavid Sterba 		/*
54852fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
548601327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
54872fad4e83SDavid Sterba 		 * processing uncleaned subvols.
54882fad4e83SDavid Sterba 		 */
54890b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
54909b199859SFilipe David Borba Manana 		return ret;
54919b199859SFilipe David Borba Manana 	}
549246204592SSage Weil 	case BTRFS_IOC_START_SYNC:
54939a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
549446204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
54952ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5496475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5497b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5498475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
54992ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5500475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
55012ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5502c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
55039ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5504837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
55052ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
550619a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
55072ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
55088ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
55098ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5510abccd00fSHugo Mills #ifdef CONFIG_64BIT
5511abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5512abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5513abccd00fSHugo Mills #endif
551431db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
55152351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
55162351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
55172351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
55182351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
55192351f431SJosef Bacik #endif
5520c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
55212ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
55225d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5523905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
55245d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5525905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
55265d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5527905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
55285d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5529905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
55302f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
55312f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
55322f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
55332f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
553457254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
553557254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
55363f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
55372ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5538867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5539867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5540a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5541a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
55422eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5543d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
55442eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
55452eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
55462eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
55472eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5548e4202ac9SDavid Sterba 	case FS_IOC_FSGETXATTR:
5549e4202ac9SDavid Sterba 		return btrfs_ioctl_fsgetxattr(file, argp);
5550025f2121SDavid Sterba 	case FS_IOC_FSSETXATTR:
5551025f2121SDavid Sterba 		return btrfs_ioctl_fssetxattr(file, argp);
5552f46b5a66SChristoph Hellwig 	}
5553f46b5a66SChristoph Hellwig 
5554f46b5a66SChristoph Hellwig 	return -ENOTTY;
5555f46b5a66SChristoph Hellwig }
55564c63c245SLuke Dashjr 
55574c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
55584c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
55594c63c245SLuke Dashjr {
55602a362249SJeff Mahoney 	/*
55612a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
55622a362249SJeff Mahoney 	 * handling is necessary.
55632a362249SJeff Mahoney 	 */
55644c63c245SLuke Dashjr 	switch (cmd) {
55654c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
55664c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
55674c63c245SLuke Dashjr 		break;
55684c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
55694c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
55704c63c245SLuke Dashjr 		break;
55714c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
55724c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
55734c63c245SLuke Dashjr 		break;
55744c63c245SLuke Dashjr 	}
55754c63c245SLuke Dashjr 
55764c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
55774c63c245SLuke Dashjr }
55784c63c245SLuke Dashjr #endif
5579