xref: /openbmc/linux/fs/btrfs/ioctl.c (revision 1905a0f7)
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 /*
1086cbff00fSChristoph Hellwig  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
1096cbff00fSChristoph Hellwig  */
1106cbff00fSChristoph Hellwig static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
1116cbff00fSChristoph Hellwig {
1126cbff00fSChristoph Hellwig 	unsigned int iflags = 0;
1136cbff00fSChristoph Hellwig 
1146cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_SYNC)
1156cbff00fSChristoph Hellwig 		iflags |= FS_SYNC_FL;
1166cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_IMMUTABLE)
1176cbff00fSChristoph Hellwig 		iflags |= FS_IMMUTABLE_FL;
1186cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_APPEND)
1196cbff00fSChristoph Hellwig 		iflags |= FS_APPEND_FL;
1206cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NODUMP)
1216cbff00fSChristoph Hellwig 		iflags |= FS_NODUMP_FL;
1226cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NOATIME)
1236cbff00fSChristoph Hellwig 		iflags |= FS_NOATIME_FL;
1246cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_DIRSYNC)
1256cbff00fSChristoph Hellwig 		iflags |= FS_DIRSYNC_FL;
126d0092bddSLi Zefan 	if (flags & BTRFS_INODE_NODATACOW)
127d0092bddSLi Zefan 		iflags |= FS_NOCOW_FL;
128d0092bddSLi Zefan 
12913f48dc9SSatoru Takeuchi 	if (flags & BTRFS_INODE_NOCOMPRESS)
130d0092bddSLi Zefan 		iflags |= FS_NOCOMP_FL;
13113f48dc9SSatoru Takeuchi 	else if (flags & BTRFS_INODE_COMPRESS)
13213f48dc9SSatoru Takeuchi 		iflags |= FS_COMPR_FL;
1336cbff00fSChristoph Hellwig 
1346cbff00fSChristoph Hellwig 	return iflags;
1356cbff00fSChristoph Hellwig }
1366cbff00fSChristoph Hellwig 
1376cbff00fSChristoph Hellwig /*
1386cbff00fSChristoph Hellwig  * Update inode->i_flags based on the btrfs internal flags.
1396cbff00fSChristoph Hellwig  */
1407b6a221eSDavid Sterba void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
1416cbff00fSChristoph Hellwig {
1426cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
1433cc79392SFilipe Manana 	unsigned int new_fl = 0;
1446cbff00fSChristoph Hellwig 
1456cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_SYNC)
1463cc79392SFilipe Manana 		new_fl |= S_SYNC;
1476cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_IMMUTABLE)
1483cc79392SFilipe Manana 		new_fl |= S_IMMUTABLE;
1496cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_APPEND)
1503cc79392SFilipe Manana 		new_fl |= S_APPEND;
1516cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_NOATIME)
1523cc79392SFilipe Manana 		new_fl |= S_NOATIME;
1536cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_DIRSYNC)
1543cc79392SFilipe Manana 		new_fl |= S_DIRSYNC;
1553cc79392SFilipe Manana 
1563cc79392SFilipe Manana 	set_mask_bits(&inode->i_flags,
1573cc79392SFilipe Manana 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
1583cc79392SFilipe Manana 		      new_fl);
1596cbff00fSChristoph Hellwig }
1606cbff00fSChristoph Hellwig 
1616cbff00fSChristoph Hellwig static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
1626cbff00fSChristoph Hellwig {
163496ad9aaSAl Viro 	struct btrfs_inode *ip = BTRFS_I(file_inode(file));
1646cbff00fSChristoph Hellwig 	unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
1656cbff00fSChristoph Hellwig 
1666cbff00fSChristoph Hellwig 	if (copy_to_user(arg, &flags, sizeof(flags)))
1676cbff00fSChristoph Hellwig 		return -EFAULT;
1686cbff00fSChristoph Hellwig 	return 0;
1696cbff00fSChristoph Hellwig }
1706cbff00fSChristoph Hellwig 
17175e7cb7fSLiu Bo static int check_flags(unsigned int flags)
17275e7cb7fSLiu Bo {
17375e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
17475e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
17575e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
176e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
177e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
17875e7cb7fSLiu Bo 		return -EOPNOTSUPP;
17975e7cb7fSLiu Bo 
18075e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
18175e7cb7fSLiu Bo 		return -EINVAL;
18275e7cb7fSLiu Bo 
18375e7cb7fSLiu Bo 	return 0;
18475e7cb7fSLiu Bo }
18575e7cb7fSLiu Bo 
1866cbff00fSChristoph Hellwig static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
1876cbff00fSChristoph Hellwig {
188496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
1890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1906cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
1916cbff00fSChristoph Hellwig 	struct btrfs_root *root = ip->root;
1926cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
1936cbff00fSChristoph Hellwig 	unsigned int flags, oldflags;
1946cbff00fSChristoph Hellwig 	int ret;
195f062abf0SLi Zefan 	u64 ip_oldflags;
196f062abf0SLi Zefan 	unsigned int i_oldflags;
1977e97b8daSDavid Sterba 	umode_t mode;
1986cbff00fSChristoph Hellwig 
199bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
200bd60ea0fSDavid Sterba 		return -EPERM;
201bd60ea0fSDavid Sterba 
202b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
203b83cc969SLi Zefan 		return -EROFS;
204b83cc969SLi Zefan 
2056cbff00fSChristoph Hellwig 	if (copy_from_user(&flags, arg, sizeof(flags)))
2066cbff00fSChristoph Hellwig 		return -EFAULT;
2076cbff00fSChristoph Hellwig 
20875e7cb7fSLiu Bo 	ret = check_flags(flags);
20975e7cb7fSLiu Bo 	if (ret)
21075e7cb7fSLiu Bo 		return ret;
2116cbff00fSChristoph Hellwig 
212e7848683SJan Kara 	ret = mnt_want_write_file(file);
213e7848683SJan Kara 	if (ret)
214e7848683SJan Kara 		return ret;
215e7848683SJan Kara 
2165955102cSAl Viro 	inode_lock(inode);
2176cbff00fSChristoph Hellwig 
218f062abf0SLi Zefan 	ip_oldflags = ip->flags;
219f062abf0SLi Zefan 	i_oldflags = inode->i_flags;
2207e97b8daSDavid Sterba 	mode = inode->i_mode;
221f062abf0SLi Zefan 
2221905a0f7SDavid Sterba 	flags = btrfs_mask_fsflags_for_type(inode, flags);
2236cbff00fSChristoph Hellwig 	oldflags = btrfs_flags_to_ioctl(ip->flags);
2246cbff00fSChristoph Hellwig 	if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
2256cbff00fSChristoph Hellwig 		if (!capable(CAP_LINUX_IMMUTABLE)) {
2266cbff00fSChristoph Hellwig 			ret = -EPERM;
2276cbff00fSChristoph Hellwig 			goto out_unlock;
2286cbff00fSChristoph Hellwig 		}
2296cbff00fSChristoph Hellwig 	}
2306cbff00fSChristoph Hellwig 
2316cbff00fSChristoph Hellwig 	if (flags & FS_SYNC_FL)
2326cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_SYNC;
2336cbff00fSChristoph Hellwig 	else
2346cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_SYNC;
2356cbff00fSChristoph Hellwig 	if (flags & FS_IMMUTABLE_FL)
2366cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_IMMUTABLE;
2376cbff00fSChristoph Hellwig 	else
2386cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_IMMUTABLE;
2396cbff00fSChristoph Hellwig 	if (flags & FS_APPEND_FL)
2406cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_APPEND;
2416cbff00fSChristoph Hellwig 	else
2426cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_APPEND;
2436cbff00fSChristoph Hellwig 	if (flags & FS_NODUMP_FL)
2446cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NODUMP;
2456cbff00fSChristoph Hellwig 	else
2466cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NODUMP;
2476cbff00fSChristoph Hellwig 	if (flags & FS_NOATIME_FL)
2486cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NOATIME;
2496cbff00fSChristoph Hellwig 	else
2506cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NOATIME;
2516cbff00fSChristoph Hellwig 	if (flags & FS_DIRSYNC_FL)
2526cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_DIRSYNC;
2536cbff00fSChristoph Hellwig 	else
2546cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_DIRSYNC;
2557e97b8daSDavid Sterba 	if (flags & FS_NOCOW_FL) {
2567e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2577e97b8daSDavid Sterba 			/*
2587e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2597e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2607e97b8daSDavid Sterba 			 * status of the file and will not set it.
2617e97b8daSDavid Sterba 			 */
2627e97b8daSDavid Sterba 			if (inode->i_size == 0)
2637e97b8daSDavid Sterba 				ip->flags |= BTRFS_INODE_NODATACOW
2647e97b8daSDavid Sterba 					   | BTRFS_INODE_NODATASUM;
2657e97b8daSDavid Sterba 		} else {
266e1e8fb6aSLi Zefan 			ip->flags |= BTRFS_INODE_NODATACOW;
2677e97b8daSDavid Sterba 		}
2687e97b8daSDavid Sterba 	} else {
2697e97b8daSDavid Sterba 		/*
27001327610SNicholas D Steeves 		 * Revert back under same assumptions as above
2717e97b8daSDavid Sterba 		 */
2727e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2737e97b8daSDavid Sterba 			if (inode->i_size == 0)
2747e97b8daSDavid Sterba 				ip->flags &= ~(BTRFS_INODE_NODATACOW
2757e97b8daSDavid Sterba 				             | BTRFS_INODE_NODATASUM);
2767e97b8daSDavid Sterba 		} else {
277e1e8fb6aSLi Zefan 			ip->flags &= ~BTRFS_INODE_NODATACOW;
2787e97b8daSDavid Sterba 		}
2797e97b8daSDavid Sterba 	}
2806cbff00fSChristoph Hellwig 
28175e7cb7fSLiu Bo 	/*
28275e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
28375e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
28475e7cb7fSLiu Bo 	 * things smaller.
28575e7cb7fSLiu Bo 	 */
28675e7cb7fSLiu Bo 	if (flags & FS_NOCOMP_FL) {
28775e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_COMPRESS;
28875e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_NOCOMPRESS;
28963541927SFilipe David Borba Manana 
29063541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
29163541927SFilipe David Borba Manana 		if (ret && ret != -ENODATA)
29263541927SFilipe David Borba Manana 			goto out_drop;
29375e7cb7fSLiu Bo 	} else if (flags & FS_COMPR_FL) {
29463541927SFilipe David Borba Manana 		const char *comp;
29563541927SFilipe David Borba Manana 
29675e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_COMPRESS;
29775e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
29863541927SFilipe David Borba Manana 
29993370509SDavid Sterba 		comp = btrfs_compress_type2str(fs_info->compress_type);
30093370509SDavid Sterba 		if (!comp || comp[0] == 0)
30193370509SDavid Sterba 			comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
30293370509SDavid Sterba 
30363541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression",
30463541927SFilipe David Borba Manana 				     comp, strlen(comp), 0);
30563541927SFilipe David Borba Manana 		if (ret)
30663541927SFilipe David Borba Manana 			goto out_drop;
30763541927SFilipe David Borba Manana 
308ebcb904dSLi Zefan 	} else {
30978a017a2SFilipe Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
31078a017a2SFilipe Manana 		if (ret && ret != -ENODATA)
31178a017a2SFilipe Manana 			goto out_drop;
312ebcb904dSLi Zefan 		ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
31375e7cb7fSLiu Bo 	}
3146cbff00fSChristoph Hellwig 
3154da6f1a3SLi Zefan 	trans = btrfs_start_transaction(root, 1);
316f062abf0SLi Zefan 	if (IS_ERR(trans)) {
317f062abf0SLi Zefan 		ret = PTR_ERR(trans);
318f062abf0SLi Zefan 		goto out_drop;
319f062abf0SLi Zefan 	}
3206cbff00fSChristoph Hellwig 
3217b6a221eSDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
3220c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
323c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3246cbff00fSChristoph Hellwig 	ret = btrfs_update_inode(trans, root, inode);
3256cbff00fSChristoph Hellwig 
3263a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
327f062abf0SLi Zefan  out_drop:
328f062abf0SLi Zefan 	if (ret) {
329f062abf0SLi Zefan 		ip->flags = ip_oldflags;
330f062abf0SLi Zefan 		inode->i_flags = i_oldflags;
331f062abf0SLi Zefan 	}
3326cbff00fSChristoph Hellwig 
3336cbff00fSChristoph Hellwig  out_unlock:
3345955102cSAl Viro 	inode_unlock(inode);
335e7848683SJan Kara 	mnt_drop_write_file(file);
3362d4e6f6aSliubo 	return ret;
3376cbff00fSChristoph Hellwig }
3386cbff00fSChristoph Hellwig 
3396cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
3406cbff00fSChristoph Hellwig {
341496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3426cbff00fSChristoph Hellwig 
3436cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
3446cbff00fSChristoph Hellwig }
345f46b5a66SChristoph Hellwig 
346f7039b1dSLi Dongyang static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
347f7039b1dSLi Dongyang {
3480b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
3490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
350f7039b1dSLi Dongyang 	struct btrfs_device *device;
351f7039b1dSLi Dongyang 	struct request_queue *q;
352f7039b1dSLi Dongyang 	struct fstrim_range range;
353f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
354f7039b1dSLi Dongyang 	u64 num_devices = 0;
355815745cfSAl Viro 	u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
356f7039b1dSLi Dongyang 	int ret;
357f7039b1dSLi Dongyang 
358f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
359f7039b1dSLi Dongyang 		return -EPERM;
360f7039b1dSLi Dongyang 
3611f78160cSXiao Guangrong 	rcu_read_lock();
3621f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
3631f78160cSXiao Guangrong 				dev_list) {
364f7039b1dSLi Dongyang 		if (!device->bdev)
365f7039b1dSLi Dongyang 			continue;
366f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
367f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
368f7039b1dSLi Dongyang 			num_devices++;
36950d0446eSSeraphime Kirkovski 			minlen = min_t(u64, q->limits.discard_granularity,
370f7039b1dSLi Dongyang 				     minlen);
371f7039b1dSLi Dongyang 		}
372f7039b1dSLi Dongyang 	}
3731f78160cSXiao Guangrong 	rcu_read_unlock();
374f4c697e6SLukas Czerner 
375f7039b1dSLi Dongyang 	if (!num_devices)
376f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
377f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
378f7039b1dSLi Dongyang 		return -EFAULT;
379e515c18bSLukas Czerner 	if (range.start > total_bytes ||
380e515c18bSLukas Czerner 	    range.len < fs_info->sb->s_blocksize)
381f4c697e6SLukas Czerner 		return -EINVAL;
382f7039b1dSLi Dongyang 
383f4c697e6SLukas Czerner 	range.len = min(range.len, total_bytes - range.start);
384f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
3852ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
386f7039b1dSLi Dongyang 	if (ret < 0)
387f7039b1dSLi Dongyang 		return ret;
388f7039b1dSLi Dongyang 
389f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
390f7039b1dSLi Dongyang 		return -EFAULT;
391f7039b1dSLi Dongyang 
392f7039b1dSLi Dongyang 	return 0;
393f7039b1dSLi Dongyang }
394f7039b1dSLi Dongyang 
395dd5f9615SStefan Behrens int btrfs_is_empty_uuid(u8 *uuid)
396dd5f9615SStefan Behrens {
39746e0f66aSChris Mason 	int i;
39846e0f66aSChris Mason 
39946e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
40046e0f66aSChris Mason 		if (uuid[i])
40146e0f66aSChris Mason 			return 0;
40246e0f66aSChris Mason 	}
40346e0f66aSChris Mason 	return 1;
404dd5f9615SStefan Behrens }
405dd5f9615SStefan Behrens 
406d5c12070SMiao Xie static noinline int create_subvol(struct inode *dir,
407cb8e7090SChristoph Hellwig 				  struct dentry *dentry,
40852f75f4fSDavid Sterba 				  const char *name, int namelen,
4096f72c7e2SArne Jansen 				  u64 *async_transid,
4108696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
411f46b5a66SChristoph Hellwig {
4120b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
413f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
414f46b5a66SChristoph Hellwig 	struct btrfs_key key;
41549a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
416f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
417f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
418d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
41976dda93cSYan, Zheng 	struct btrfs_root *new_root;
420d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
421c2050a45SDeepa Dinamani 	struct timespec cur_time = current_time(dir);
4225662344bSTsutomu Itoh 	struct inode *inode;
423f46b5a66SChristoph Hellwig 	int ret;
424f46b5a66SChristoph Hellwig 	int err;
425f46b5a66SChristoph Hellwig 	u64 objectid;
426f46b5a66SChristoph Hellwig 	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
4273de4586cSChris Mason 	u64 index = 0;
428d5c12070SMiao Xie 	u64 qgroup_reserved;
4298ea05e3aSAlexander Block 	uuid_le new_uuid;
430f46b5a66SChristoph Hellwig 
43149a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
43249a3c4d9SDavid Sterba 	if (!root_item)
43349a3c4d9SDavid Sterba 		return -ENOMEM;
43449a3c4d9SDavid Sterba 
4350b246afaSJeff Mahoney 	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
4362fbe8c8aSAl Viro 	if (ret)
43749a3c4d9SDavid Sterba 		goto fail_free;
4386a912213SJosef Bacik 
439e09fe2d2SQu Wenruo 	/*
440e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
44101327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
442e09fe2d2SQu Wenruo 	 */
44349a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
44449a3c4d9SDavid Sterba 		ret = -ENOSPC;
44549a3c4d9SDavid Sterba 		goto fail_free;
44649a3c4d9SDavid Sterba 	}
447e09fe2d2SQu Wenruo 
448d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4499ed74f2dSJosef Bacik 	/*
450d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
451d5c12070SMiao Xie 	 * of create_snapshot().
4529ed74f2dSJosef Bacik 	 */
453d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
454dd5f9615SStefan Behrens 					       8, &qgroup_reserved, false);
455d5c12070SMiao Xie 	if (ret)
45649a3c4d9SDavid Sterba 		goto fail_free;
457f46b5a66SChristoph Hellwig 
458d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
459d5c12070SMiao Xie 	if (IS_ERR(trans)) {
460d5c12070SMiao Xie 		ret = PTR_ERR(trans);
4617775c818SDavid Sterba 		btrfs_subvolume_release_metadata(fs_info, &block_rsv);
46249a3c4d9SDavid Sterba 		goto fail_free;
463d5c12070SMiao Xie 	}
464d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
465d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
466f46b5a66SChristoph Hellwig 
4670b246afaSJeff Mahoney 	ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
4686f72c7e2SArne Jansen 	if (ret)
4696f72c7e2SArne Jansen 		goto fail;
4706f72c7e2SArne Jansen 
4714d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
4728e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
4738e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
4748e8a1e31SJosef Bacik 		goto fail;
4758e8a1e31SJosef Bacik 	}
476f46b5a66SChristoph Hellwig 
477b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
478f46b5a66SChristoph Hellwig 	btrfs_set_header_bytenr(leaf, leaf->start);
479f46b5a66SChristoph Hellwig 	btrfs_set_header_generation(leaf, trans->transid);
4805d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
481f46b5a66SChristoph Hellwig 	btrfs_set_header_owner(leaf, objectid);
482f46b5a66SChristoph Hellwig 
4830b246afaSJeff Mahoney 	write_extent_buffer_fsid(leaf, fs_info->fsid);
4840b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
485f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
486f46b5a66SChristoph Hellwig 
48749a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
4883cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
4893cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
4903cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
491da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
4920b246afaSJeff Mahoney 				     fs_info->nodesize);
4933cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
494f46b5a66SChristoph Hellwig 
49549a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
49649a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
4973cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
49808fe4db1SLi Zefan 
49949a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
50049a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
50149a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
50249a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
50349a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
50449a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
505f46b5a66SChristoph Hellwig 
50649a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
50749a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
5088ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
50949a3c4d9SDavid Sterba 	memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
51049a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
51149a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
51249a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
51349a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
51449a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
515f46b5a66SChristoph Hellwig 
516925baeddSChris Mason 	btrfs_tree_unlock(leaf);
517f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
518f46b5a66SChristoph Hellwig 	leaf = NULL;
519f46b5a66SChristoph Hellwig 
52049a3c4d9SDavid Sterba 	btrfs_set_root_dirid(root_item, new_dirid);
521f46b5a66SChristoph Hellwig 
522f46b5a66SChristoph Hellwig 	key.objectid = objectid;
5235d4f98a2SYan Zheng 	key.offset = 0;
524962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
5250b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
52649a3c4d9SDavid Sterba 				root_item);
527f46b5a66SChristoph Hellwig 	if (ret)
528f46b5a66SChristoph Hellwig 		goto fail;
529f46b5a66SChristoph Hellwig 
53076dda93cSYan, Zheng 	key.offset = (u64)-1;
5310b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &key);
53279787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
53379787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
53466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
53579787eaaSJeff Mahoney 		goto fail;
53679787eaaSJeff Mahoney 	}
53776dda93cSYan, Zheng 
53876dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
53976dda93cSYan, Zheng 
54063541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
541ce598979SMark Fasheh 	if (ret) {
542ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
54366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
544ce598979SMark Fasheh 		goto fail;
545ce598979SMark Fasheh 	}
546ce598979SMark Fasheh 
547f32e48e9SChandan Rajendra 	mutex_lock(&new_root->objectid_mutex);
548f32e48e9SChandan Rajendra 	new_root->highest_objectid = new_dirid;
549f32e48e9SChandan Rajendra 	mutex_unlock(&new_root->objectid_mutex);
550f32e48e9SChandan Rajendra 
551f46b5a66SChristoph Hellwig 	/*
552f46b5a66SChristoph Hellwig 	 * insert the directory item
553f46b5a66SChristoph Hellwig 	 */
554877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
55579787eaaSJeff Mahoney 	if (ret) {
55666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
55779787eaaSJeff Mahoney 		goto fail;
55879787eaaSJeff Mahoney 	}
5593de4586cSChris Mason 
5603de4586cSChris Mason 	ret = btrfs_insert_dir_item(trans, root,
5618e7611cfSNikolay Borisov 				    name, namelen, BTRFS_I(dir), &key,
5623de4586cSChris Mason 				    BTRFS_FT_DIR, index);
56379787eaaSJeff Mahoney 	if (ret) {
56466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
565f46b5a66SChristoph Hellwig 		goto fail;
56679787eaaSJeff Mahoney 	}
5670660b5afSChris Mason 
5686ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
56952c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
57052c26179SYan Zheng 	BUG_ON(ret);
57152c26179SYan Zheng 
5720b246afaSJeff Mahoney 	ret = btrfs_add_root_ref(trans, fs_info,
5734df27c4dSYan, Zheng 				 objectid, root->root_key.objectid,
5744a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
5750660b5afSChris Mason 	BUG_ON(ret);
5760660b5afSChris Mason 
5770b246afaSJeff Mahoney 	ret = btrfs_uuid_tree_add(trans, fs_info, root_item->uuid,
5786bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
579dd5f9615SStefan Behrens 	if (ret)
58066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
581dd5f9615SStefan Behrens 
582f46b5a66SChristoph Hellwig fail:
58349a3c4d9SDavid Sterba 	kfree(root_item);
584d5c12070SMiao Xie 	trans->block_rsv = NULL;
585d5c12070SMiao Xie 	trans->bytes_reserved = 0;
5867775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
587de6e8200SLiu Bo 
58872fd032eSSage Weil 	if (async_transid) {
58972fd032eSSage Weil 		*async_transid = trans->transid;
5903a45bb20SJeff Mahoney 		err = btrfs_commit_transaction_async(trans, 1);
59100d71c9cSMiao Xie 		if (err)
5923a45bb20SJeff Mahoney 			err = btrfs_commit_transaction(trans);
59372fd032eSSage Weil 	} else {
5943a45bb20SJeff Mahoney 		err = btrfs_commit_transaction(trans);
59572fd032eSSage Weil 	}
596f46b5a66SChristoph Hellwig 	if (err && !ret)
597f46b5a66SChristoph Hellwig 		ret = err;
5981a65e24bSChris Mason 
5995662344bSTsutomu Itoh 	if (!ret) {
6005662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
601de6e8200SLiu Bo 		if (IS_ERR(inode))
602de6e8200SLiu Bo 			return PTR_ERR(inode);
6035662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
6045662344bSTsutomu Itoh 	}
605f46b5a66SChristoph Hellwig 	return ret;
60649a3c4d9SDavid Sterba 
60749a3c4d9SDavid Sterba fail_free:
60849a3c4d9SDavid Sterba 	kfree(root_item);
60949a3c4d9SDavid Sterba 	return ret;
610f46b5a66SChristoph Hellwig }
611f46b5a66SChristoph Hellwig 
612e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
61361d7e4cbSDavid Sterba 			   struct dentry *dentry,
614e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
615e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
616f46b5a66SChristoph Hellwig {
6170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6182e4bfab9SYan, Zheng 	struct inode *inode;
619f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
620f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
6212e4bfab9SYan, Zheng 	int ret;
622f46b5a66SChristoph Hellwig 
62327cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
624f46b5a66SChristoph Hellwig 		return -EINVAL;
625f46b5a66SChristoph Hellwig 
62623269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
627a1ee7362SDavid Sterba 	if (!pending_snapshot)
628a1ee7362SDavid Sterba 		return -ENOMEM;
629a1ee7362SDavid Sterba 
630b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
63123269bf5SDavid Sterba 			GFP_KERNEL);
6328546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
6338546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
634b0c0ea63SDavid Sterba 		ret = -ENOMEM;
635b0c0ea63SDavid Sterba 		goto free_pending;
636b0c0ea63SDavid Sterba 	}
637b0c0ea63SDavid Sterba 
638ea14b57fSDavid Sterba 	atomic_inc(&root->will_be_snapshotted);
6394e857c58SPeter Zijlstra 	smp_mb__after_atomic();
64045bac0f3SLiu Bo 	/* wait for no snapshot writes */
64145bac0f3SLiu Bo 	wait_event(root->subv_writers->wait,
64245bac0f3SLiu Bo 		   percpu_counter_sum(&root->subv_writers->counter) == 0);
6438257b2dcSMiao Xie 
64476f32e24SNikolay Borisov 	ret = btrfs_start_delalloc_inodes(root);
6456a03843dSMiao Xie 	if (ret)
646a1ee7362SDavid Sterba 		goto dec_and_free;
6476a03843dSMiao Xie 
6486374e57aSChris Mason 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
6496a03843dSMiao Xie 
65066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
65166d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
652d5c12070SMiao Xie 	/*
653d5c12070SMiao Xie 	 * 1 - parent dir inode
654d5c12070SMiao Xie 	 * 2 - dir entries
655d5c12070SMiao Xie 	 * 1 - root item
656d5c12070SMiao Xie 	 * 2 - root ref/backref
657d5c12070SMiao Xie 	 * 1 - root of snapshot
658dd5f9615SStefan Behrens 	 * 1 - UUID item
659d5c12070SMiao Xie 	 */
660d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
661dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
662ee3441b4SJeff Mahoney 					&pending_snapshot->qgroup_reserved,
663ee3441b4SJeff Mahoney 					false);
664d5c12070SMiao Xie 	if (ret)
665a1ee7362SDavid Sterba 		goto dec_and_free;
666d5c12070SMiao Xie 
667a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
668a22285a6SYan, Zheng 	pending_snapshot->root = root;
669b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
670e9662f70SMiao Xie 	pending_snapshot->dir = dir;
6718696c533SMiao Xie 	pending_snapshot->inherit = inherit;
672a22285a6SYan, Zheng 
673d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
674a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
675a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
676a22285a6SYan, Zheng 		goto fail;
677a22285a6SYan, Zheng 	}
678a22285a6SYan, Zheng 
6790b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
680a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
681a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
6820b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
68372fd032eSSage Weil 	if (async_transid) {
68472fd032eSSage Weil 		*async_transid = trans->transid;
6853a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction_async(trans, 1);
68600d71c9cSMiao Xie 		if (ret)
6873a45bb20SJeff Mahoney 			ret = btrfs_commit_transaction(trans);
68872fd032eSSage Weil 	} else {
6893a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
69072fd032eSSage Weil 	}
691aec8030aSMiao Xie 	if (ret)
692c37b2b62SJosef Bacik 		goto fail;
693a22285a6SYan, Zheng 
694a22285a6SYan, Zheng 	ret = pending_snapshot->error;
695f46b5a66SChristoph Hellwig 	if (ret)
6962e4bfab9SYan, Zheng 		goto fail;
697f46b5a66SChristoph Hellwig 
698d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
699d3797308SChris Mason 	if (ret)
700d3797308SChris Mason 		goto fail;
701d3797308SChris Mason 
7022b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
7032e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
7042e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
7052e4bfab9SYan, Zheng 		goto fail;
7062e4bfab9SYan, Zheng 	}
7075662344bSTsutomu Itoh 
7082e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
7092e4bfab9SYan, Zheng 	ret = 0;
7102e4bfab9SYan, Zheng fail:
7117775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
712a1ee7362SDavid Sterba dec_and_free:
713ea14b57fSDavid Sterba 	if (atomic_dec_and_test(&root->will_be_snapshotted))
7144625956aSPeter Zijlstra 		wake_up_var(&root->will_be_snapshotted);
715b0c0ea63SDavid Sterba free_pending:
716b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
7178546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
718a1ee7362SDavid Sterba 	kfree(pending_snapshot);
719a1ee7362SDavid Sterba 
720f46b5a66SChristoph Hellwig 	return ret;
721f46b5a66SChristoph Hellwig }
722f46b5a66SChristoph Hellwig 
7234260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
7244260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
7254260f7c7SSage Weil  *  whether the type of victim is right.
7264260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
7274260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
7284260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
7294260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
7304260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
7314260f7c7SSage Weil  *	a. be owner of dir, or
7324260f7c7SSage Weil  *	b. be owner of victim, or
7334260f7c7SSage Weil  *	c. have CAP_FOWNER capability
73401327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
7354260f7c7SSage Weil  *     links pointing to it.
7364260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
7374260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
7384260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
7394260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
7404260f7c7SSage Weil  *     nfs_async_unlink().
7414260f7c7SSage Weil  */
7424260f7c7SSage Weil 
7434260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
7444260f7c7SSage Weil {
7454260f7c7SSage Weil 	int error;
7464260f7c7SSage Weil 
7472b0143b5SDavid Howells 	if (d_really_is_negative(victim))
7484260f7c7SSage Weil 		return -ENOENT;
7494260f7c7SSage Weil 
7502b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
7514fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
7524260f7c7SSage Weil 
7534260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
7544260f7c7SSage Weil 	if (error)
7554260f7c7SSage Weil 		return error;
7564260f7c7SSage Weil 	if (IS_APPEND(dir))
7574260f7c7SSage Weil 		return -EPERM;
7582b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
7592b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
7604260f7c7SSage Weil 		return -EPERM;
7614260f7c7SSage Weil 	if (isdir) {
762e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
7634260f7c7SSage Weil 			return -ENOTDIR;
7644260f7c7SSage Weil 		if (IS_ROOT(victim))
7654260f7c7SSage Weil 			return -EBUSY;
766e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
7674260f7c7SSage Weil 		return -EISDIR;
7684260f7c7SSage Weil 	if (IS_DEADDIR(dir))
7694260f7c7SSage Weil 		return -ENOENT;
7704260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
7714260f7c7SSage Weil 		return -EBUSY;
7724260f7c7SSage Weil 	return 0;
7734260f7c7SSage Weil }
7744260f7c7SSage Weil 
775cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
776cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
777cb8e7090SChristoph Hellwig {
7782b0143b5SDavid Howells 	if (d_really_is_positive(child))
779cb8e7090SChristoph Hellwig 		return -EEXIST;
780cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
781cb8e7090SChristoph Hellwig 		return -ENOENT;
782cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
783cb8e7090SChristoph Hellwig }
784cb8e7090SChristoph Hellwig 
785cb8e7090SChristoph Hellwig /*
786cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
787cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
788cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
789cb8e7090SChristoph Hellwig  */
79092872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
79152f75f4fSDavid Sterba 				   const char *name, int namelen,
79272fd032eSSage Weil 				   struct btrfs_root *snap_src,
7936f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
7948696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
795cb8e7090SChristoph Hellwig {
7962b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
7970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
798cb8e7090SChristoph Hellwig 	struct dentry *dentry;
799cb8e7090SChristoph Hellwig 	int error;
800cb8e7090SChristoph Hellwig 
80100235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
80200235411SAl Viro 	if (error == -EINTR)
80300235411SAl Viro 		return error;
804cb8e7090SChristoph Hellwig 
805cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
806cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
807cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
808cb8e7090SChristoph Hellwig 		goto out_unlock;
809cb8e7090SChristoph Hellwig 
81076dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
811cb8e7090SChristoph Hellwig 	if (error)
812a874a63eSLiu Bo 		goto out_dput;
813cb8e7090SChristoph Hellwig 
8149c52057cSChris Mason 	/*
8159c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
8169c52057cSChris Mason 	 * check for them now when we can safely fail
8179c52057cSChris Mason 	 */
8189c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
8199c52057cSChris Mason 					       dir->i_ino, name,
8209c52057cSChris Mason 					       namelen);
8219c52057cSChris Mason 	if (error)
8229c52057cSChris Mason 		goto out_dput;
8239c52057cSChris Mason 
8240b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
82576dda93cSYan, Zheng 
82676dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
82776dda93cSYan, Zheng 		goto out_up_read;
82876dda93cSYan, Zheng 
8293de4586cSChris Mason 	if (snap_src) {
83061d7e4cbSDavid Sterba 		error = create_snapshot(snap_src, dir, dentry,
8316f72c7e2SArne Jansen 					async_transid, readonly, inherit);
8323de4586cSChris Mason 	} else {
833d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
834d5c12070SMiao Xie 				      async_transid, inherit);
8353de4586cSChris Mason 	}
83676dda93cSYan, Zheng 	if (!error)
83776dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
83876dda93cSYan, Zheng out_up_read:
8390b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
840cb8e7090SChristoph Hellwig out_dput:
841cb8e7090SChristoph Hellwig 	dput(dentry);
842cb8e7090SChristoph Hellwig out_unlock:
8435955102cSAl Viro 	inode_unlock(dir);
844cb8e7090SChristoph Hellwig 	return error;
845cb8e7090SChristoph Hellwig }
846cb8e7090SChristoph Hellwig 
8474cb5300bSChris Mason /*
8484cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
8494cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
8504cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
8514cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
8524cb5300bSChris Mason  * part of the file
8534cb5300bSChris Mason  */
854aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
8554cb5300bSChris Mason {
8564cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8574cb5300bSChris Mason 	struct extent_map *em = NULL;
8584cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8594cb5300bSChris Mason 	u64 end;
8604cb5300bSChris Mason 
8614cb5300bSChris Mason 	read_lock(&em_tree->lock);
86209cbfeafSKirill A. Shutemov 	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
8634cb5300bSChris Mason 	read_unlock(&em_tree->lock);
8644cb5300bSChris Mason 
8654cb5300bSChris Mason 	if (em) {
8664cb5300bSChris Mason 		end = extent_map_end(em);
8674cb5300bSChris Mason 		free_extent_map(em);
8684cb5300bSChris Mason 		if (end - offset > thresh)
8694cb5300bSChris Mason 			return 0;
8704cb5300bSChris Mason 	}
8714cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
8724cb5300bSChris Mason 	thresh /= 2;
8734cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
8744cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
8754cb5300bSChris Mason 	if (end >= thresh)
8764cb5300bSChris Mason 		return 0;
8774cb5300bSChris Mason 	return 1;
8784cb5300bSChris Mason }
8794cb5300bSChris Mason 
8804cb5300bSChris Mason /*
8814cb5300bSChris Mason  * helper function to walk through a file and find extents
8824cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
8834cb5300bSChris Mason  *
8844cb5300bSChris Mason  * This is used by the defragging code to find new and small
8854cb5300bSChris Mason  * extents
8864cb5300bSChris Mason  */
8874cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
8884cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
889aab110abSDavid Sterba 			    u64 *off, u32 thresh)
8904cb5300bSChris Mason {
8914cb5300bSChris Mason 	struct btrfs_path *path;
8924cb5300bSChris Mason 	struct btrfs_key min_key;
8934cb5300bSChris Mason 	struct extent_buffer *leaf;
8944cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
8954cb5300bSChris Mason 	int type;
8964cb5300bSChris Mason 	int ret;
8974a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
8984cb5300bSChris Mason 
8994cb5300bSChris Mason 	path = btrfs_alloc_path();
9004cb5300bSChris Mason 	if (!path)
9014cb5300bSChris Mason 		return -ENOMEM;
9024cb5300bSChris Mason 
903a4689d2bSDavid Sterba 	min_key.objectid = ino;
9044cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
9054cb5300bSChris Mason 	min_key.offset = *off;
9064cb5300bSChris Mason 
9074cb5300bSChris Mason 	while (1) {
9086174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
9094cb5300bSChris Mason 		if (ret != 0)
9104cb5300bSChris Mason 			goto none;
911f094c9bdSFilipe Manana process_slot:
912a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
9134cb5300bSChris Mason 			goto none;
9144cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
9154cb5300bSChris Mason 			goto none;
9164cb5300bSChris Mason 
9174cb5300bSChris Mason 		leaf = path->nodes[0];
9184cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
9194cb5300bSChris Mason 					struct btrfs_file_extent_item);
9204cb5300bSChris Mason 
9214cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
9224cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
9234cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
9244cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
9254cb5300bSChris Mason 			*off = min_key.offset;
9264cb5300bSChris Mason 			btrfs_free_path(path);
9274cb5300bSChris Mason 			return 0;
9284cb5300bSChris Mason 		}
9294cb5300bSChris Mason 
930f094c9bdSFilipe Manana 		path->slots[0]++;
931f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
932f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
933f094c9bdSFilipe Manana 			goto process_slot;
934f094c9bdSFilipe Manana 		}
935f094c9bdSFilipe Manana 
9364cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
9374cb5300bSChris Mason 			goto none;
9384cb5300bSChris Mason 
9394cb5300bSChris Mason 		min_key.offset++;
9404cb5300bSChris Mason 		btrfs_release_path(path);
9414cb5300bSChris Mason 	}
9424cb5300bSChris Mason none:
9434cb5300bSChris Mason 	btrfs_free_path(path);
9444cb5300bSChris Mason 	return -ENOENT;
9454cb5300bSChris Mason }
9464cb5300bSChris Mason 
9476c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
94817ce6ef8SLiu Bo {
94917ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
950940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9516c282eb4SLi Zefan 	struct extent_map *em;
95209cbfeafSKirill A. Shutemov 	u64 len = PAGE_SIZE;
953940100a4SChris Mason 
954940100a4SChris Mason 	/*
955940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
956940100a4SChris Mason 	 * the full extent lock
957940100a4SChris Mason 	 */
958940100a4SChris Mason 	read_lock(&em_tree->lock);
959940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
960940100a4SChris Mason 	read_unlock(&em_tree->lock);
961940100a4SChris Mason 
962940100a4SChris Mason 	if (!em) {
963308d9800SFilipe Manana 		struct extent_state *cached = NULL;
964308d9800SFilipe Manana 		u64 end = start + len - 1;
965308d9800SFilipe Manana 
966940100a4SChris Mason 		/* get the big lock and read metadata off disk */
967ff13db41SDavid Sterba 		lock_extent_bits(io_tree, start, end, &cached);
968fc4f21b1SNikolay Borisov 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
969e43bbe5eSDavid Sterba 		unlock_extent_cached(io_tree, start, end, &cached);
970940100a4SChris Mason 
9716cf8bfbfSDan Carpenter 		if (IS_ERR(em))
9726c282eb4SLi Zefan 			return NULL;
973940100a4SChris Mason 	}
974940100a4SChris Mason 
9756c282eb4SLi Zefan 	return em;
9766c282eb4SLi Zefan }
9776c282eb4SLi Zefan 
9786c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
9796c282eb4SLi Zefan {
9806c282eb4SLi Zefan 	struct extent_map *next;
9816c282eb4SLi Zefan 	bool ret = true;
9826c282eb4SLi Zefan 
9836c282eb4SLi Zefan 	/* this is the last extent */
9846c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
9856c282eb4SLi Zefan 		return false;
9866c282eb4SLi Zefan 
9876c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
988e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
989e9512d72SChris Mason 		ret = false;
990e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
991ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
9926c282eb4SLi Zefan 		ret = false;
9936c282eb4SLi Zefan 
9946c282eb4SLi Zefan 	free_extent_map(next);
9956c282eb4SLi Zefan 	return ret;
9966c282eb4SLi Zefan }
9976c282eb4SLi Zefan 
998aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
999a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
1000a43a2111SAndrew Mahone 			       int compress)
10016c282eb4SLi Zefan {
10026c282eb4SLi Zefan 	struct extent_map *em;
10036c282eb4SLi Zefan 	int ret = 1;
10046c282eb4SLi Zefan 	bool next_mergeable = true;
10054a3560c4SLiu Bo 	bool prev_mergeable = true;
10066c282eb4SLi Zefan 
10076c282eb4SLi Zefan 	/*
10086c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
10096c282eb4SLi Zefan 	 * defragging it
10106c282eb4SLi Zefan 	 */
10116c282eb4SLi Zefan 	if (start < *defrag_end)
10126c282eb4SLi Zefan 		return 1;
10136c282eb4SLi Zefan 
10146c282eb4SLi Zefan 	*skip = 0;
10156c282eb4SLi Zefan 
10166c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
10176c282eb4SLi Zefan 	if (!em)
10186c282eb4SLi Zefan 		return 0;
10196c282eb4SLi Zefan 
1020940100a4SChris Mason 	/* this will cover holes, and inline extents */
102117ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1022940100a4SChris Mason 		ret = 0;
102317ce6ef8SLiu Bo 		goto out;
102417ce6ef8SLiu Bo 	}
102517ce6ef8SLiu Bo 
10264a3560c4SLiu Bo 	if (!*defrag_end)
10274a3560c4SLiu Bo 		prev_mergeable = false;
10284a3560c4SLiu Bo 
10296c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1030940100a4SChris Mason 	/*
10316c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
10326c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1033940100a4SChris Mason 	 */
1034a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
10354a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1036940100a4SChris Mason 		ret = 0;
103717ce6ef8SLiu Bo out:
1038940100a4SChris Mason 	/*
1039940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1040940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1041940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1042940100a4SChris Mason 	 *
1043940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1044940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1045940100a4SChris Mason 	 */
1046940100a4SChris Mason 	if (ret) {
1047940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1048940100a4SChris Mason 	} else {
1049940100a4SChris Mason 		*last_len = 0;
1050940100a4SChris Mason 		*skip = extent_map_end(em);
1051940100a4SChris Mason 		*defrag_end = 0;
1052940100a4SChris Mason 	}
1053940100a4SChris Mason 
1054940100a4SChris Mason 	free_extent_map(em);
1055940100a4SChris Mason 	return ret;
1056940100a4SChris Mason }
1057940100a4SChris Mason 
10584cb5300bSChris Mason /*
10594cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
10604cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
10614cb5300bSChris Mason  * to COW and defrag.
10624cb5300bSChris Mason  *
10634cb5300bSChris Mason  * It also makes sure the delalloc code has enough
10644cb5300bSChris Mason  * dirty data to avoid making new small extents as part
10654cb5300bSChris Mason  * of the defrag
10664cb5300bSChris Mason  *
10674cb5300bSChris Mason  * It's a good idea to start RA on this range
10684cb5300bSChris Mason  * before calling this.
10694cb5300bSChris Mason  */
10704cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
10714cb5300bSChris Mason 				    struct page **pages,
10724cb5300bSChris Mason 				    unsigned long start_index,
1073c41570c9SJustin Maggard 				    unsigned long num_pages)
1074f46b5a66SChristoph Hellwig {
10754cb5300bSChris Mason 	unsigned long file_end;
10764cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1077f46b5a66SChristoph Hellwig 	u64 page_start;
1078f46b5a66SChristoph Hellwig 	u64 page_end;
10791f12bd06SLiu Bo 	u64 page_cnt;
10804cb5300bSChris Mason 	int ret;
10814cb5300bSChris Mason 	int i;
10824cb5300bSChris Mason 	int i_done;
10834cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
10844cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1085600a45e1SMiao Xie 	struct extent_io_tree *tree;
1086364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
10873b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
10884cb5300bSChris Mason 
108909cbfeafSKirill A. Shutemov 	file_end = (isize - 1) >> PAGE_SHIFT;
10901f12bd06SLiu Bo 	if (!isize || start_index > file_end)
10911f12bd06SLiu Bo 		return 0;
10921f12bd06SLiu Bo 
10931f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
10944cb5300bSChris Mason 
1095364ecf36SQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
109609cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
109709cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
10984cb5300bSChris Mason 	if (ret)
10994cb5300bSChris Mason 		return ret;
11004cb5300bSChris Mason 	i_done = 0;
1101600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
11024cb5300bSChris Mason 
11034cb5300bSChris Mason 	/* step one, lock all the pages */
11041f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
11054cb5300bSChris Mason 		struct page *page;
1106600a45e1SMiao Xie again:
1107a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
11083b16a4e3SJosef Bacik 					   start_index + i, mask);
11094cb5300bSChris Mason 		if (!page)
11104cb5300bSChris Mason 			break;
11114cb5300bSChris Mason 
1112600a45e1SMiao Xie 		page_start = page_offset(page);
111309cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
1114600a45e1SMiao Xie 		while (1) {
1115308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1116ff13db41SDavid Sterba 					 &cached_state);
1117600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1118600a45e1SMiao Xie 							      page_start);
1119308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1120e43bbe5eSDavid Sterba 					     &cached_state);
1121600a45e1SMiao Xie 			if (!ordered)
1122600a45e1SMiao Xie 				break;
1123600a45e1SMiao Xie 
1124600a45e1SMiao Xie 			unlock_page(page);
1125600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1126600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1127600a45e1SMiao Xie 			lock_page(page);
11281f12bd06SLiu Bo 			/*
11291f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
11301f12bd06SLiu Bo 			 * it was released or not.
11311f12bd06SLiu Bo 			 */
11321f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
11331f12bd06SLiu Bo 				unlock_page(page);
113409cbfeafSKirill A. Shutemov 				put_page(page);
11351f12bd06SLiu Bo 				goto again;
11361f12bd06SLiu Bo 			}
1137600a45e1SMiao Xie 		}
1138600a45e1SMiao Xie 
11394cb5300bSChris Mason 		if (!PageUptodate(page)) {
11404cb5300bSChris Mason 			btrfs_readpage(NULL, page);
11414cb5300bSChris Mason 			lock_page(page);
11424cb5300bSChris Mason 			if (!PageUptodate(page)) {
11434cb5300bSChris Mason 				unlock_page(page);
114409cbfeafSKirill A. Shutemov 				put_page(page);
11454cb5300bSChris Mason 				ret = -EIO;
11464cb5300bSChris Mason 				break;
11474cb5300bSChris Mason 			}
11484cb5300bSChris Mason 		}
1149600a45e1SMiao Xie 
1150600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1151600a45e1SMiao Xie 			unlock_page(page);
115209cbfeafSKirill A. Shutemov 			put_page(page);
1153600a45e1SMiao Xie 			goto again;
1154600a45e1SMiao Xie 		}
1155600a45e1SMiao Xie 
11564cb5300bSChris Mason 		pages[i] = page;
11574cb5300bSChris Mason 		i_done++;
11584cb5300bSChris Mason 	}
11594cb5300bSChris Mason 	if (!i_done || ret)
11604cb5300bSChris Mason 		goto out;
11614cb5300bSChris Mason 
11621751e8a6SLinus Torvalds 	if (!(inode->i_sb->s_flags & SB_ACTIVE))
11634cb5300bSChris Mason 		goto out;
11644cb5300bSChris Mason 
11654cb5300bSChris Mason 	/*
11664cb5300bSChris Mason 	 * so now we have a nice long stream of locked
11674cb5300bSChris Mason 	 * and up to date pages, lets wait on them
11684cb5300bSChris Mason 	 */
11694cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
11704cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
11714cb5300bSChris Mason 
11724cb5300bSChris Mason 	page_start = page_offset(pages[0]);
117309cbfeafSKirill A. Shutemov 	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
11744cb5300bSChris Mason 
11754cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1176ff13db41SDavid Sterba 			 page_start, page_end - 1, &cached_state);
11774cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
11784cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
11799e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1180ae0f1625SDavid Sterba 			  &cached_state);
11814cb5300bSChris Mason 
11821f12bd06SLiu Bo 	if (i_done != page_cnt) {
11839e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
11849e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
11859e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
1186bc42bda2SQu Wenruo 		btrfs_delalloc_release_space(inode, data_reserved,
118709cbfeafSKirill A. Shutemov 				start_index << PAGE_SHIFT,
118843b18595SQu Wenruo 				(page_cnt - i_done) << PAGE_SHIFT, true);
11894cb5300bSChris Mason 	}
11904cb5300bSChris Mason 
11914cb5300bSChris Mason 
11929e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1193018ed4f7SDavid Sterba 			  &cached_state);
11944cb5300bSChris Mason 
11954cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1196e43bbe5eSDavid Sterba 			     page_start, page_end - 1, &cached_state);
11974cb5300bSChris Mason 
11984cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
11994cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
12004cb5300bSChris Mason 		ClearPageChecked(pages[i]);
12014cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
12024cb5300bSChris Mason 		set_page_dirty(pages[i]);
12034cb5300bSChris Mason 		unlock_page(pages[i]);
120409cbfeafSKirill A. Shutemov 		put_page(pages[i]);
12054cb5300bSChris Mason 	}
120643b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
120743b18595SQu Wenruo 				       false);
1208364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
12094cb5300bSChris Mason 	return i_done;
12104cb5300bSChris Mason out:
12114cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12124cb5300bSChris Mason 		unlock_page(pages[i]);
121309cbfeafSKirill A. Shutemov 		put_page(pages[i]);
12144cb5300bSChris Mason 	}
1215bc42bda2SQu Wenruo 	btrfs_delalloc_release_space(inode, data_reserved,
121609cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
121743b18595SQu Wenruo 			page_cnt << PAGE_SHIFT, true);
121843b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
121943b18595SQu Wenruo 				       true);
1220364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
12214cb5300bSChris Mason 	return ret;
12224cb5300bSChris Mason 
12234cb5300bSChris Mason }
12244cb5300bSChris Mason 
12254cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
12264cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
12274cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
12284cb5300bSChris Mason {
12290b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
12304cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
12314cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
12324cb5300bSChris Mason 	unsigned long last_index;
1233151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1234940100a4SChris Mason 	u64 last_len = 0;
1235940100a4SChris Mason 	u64 skip = 0;
1236940100a4SChris Mason 	u64 defrag_end = 0;
12374cb5300bSChris Mason 	u64 newer_off = range->start;
1238f46b5a66SChristoph Hellwig 	unsigned long i;
1239008873eaSLi Zefan 	unsigned long ra_index = 0;
1240f46b5a66SChristoph Hellwig 	int ret;
12414cb5300bSChris Mason 	int defrag_count = 0;
12421a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1243aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
124409cbfeafSKirill A. Shutemov 	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1245c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
1246ee22184bSByongho Lee 	u64 new_align = ~((u64)SZ_128K - 1);
12474cb5300bSChris Mason 	struct page **pages = NULL;
12481e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
12494cb5300bSChris Mason 
12500abd5b17SLiu Bo 	if (isize == 0)
12510abd5b17SLiu Bo 		return 0;
12520abd5b17SLiu Bo 
12530abd5b17SLiu Bo 	if (range->start >= isize)
12540abd5b17SLiu Bo 		return -EINVAL;
12551a419d85SLi Zefan 
12561e2ef46dSDavid Sterba 	if (do_compress) {
12571a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
12581a419d85SLi Zefan 			return -EINVAL;
12591a419d85SLi Zefan 		if (range->compress_type)
12601a419d85SLi Zefan 			compress_type = range->compress_type;
12611a419d85SLi Zefan 	}
1262f46b5a66SChristoph Hellwig 
12630abd5b17SLiu Bo 	if (extent_thresh == 0)
1264ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1265f46b5a66SChristoph Hellwig 
12664cb5300bSChris Mason 	/*
12670a52d108SDavid Sterba 	 * If we were not given a file, allocate a readahead context. As
12680a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
12690a52d108SDavid Sterba 	 * we don't error out.
12704cb5300bSChris Mason 	 */
12714cb5300bSChris Mason 	if (!file) {
127263e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
12730a52d108SDavid Sterba 		if (ra)
12744cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
12754cb5300bSChris Mason 	} else {
12764cb5300bSChris Mason 		ra = &file->f_ra;
12774cb5300bSChris Mason 	}
12784cb5300bSChris Mason 
127963e727ecSDavid Sterba 	pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
12804cb5300bSChris Mason 	if (!pages) {
12814cb5300bSChris Mason 		ret = -ENOMEM;
12824cb5300bSChris Mason 		goto out_ra;
12834cb5300bSChris Mason 	}
12844cb5300bSChris Mason 
12854cb5300bSChris Mason 	/* find the last page to defrag */
12861e701a32SChris Mason 	if (range->start + range->len > range->start) {
1287151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
128809cbfeafSKirill A. Shutemov 			 range->start + range->len - 1) >> PAGE_SHIFT;
12891e701a32SChris Mason 	} else {
129009cbfeafSKirill A. Shutemov 		last_index = (isize - 1) >> PAGE_SHIFT;
12911e701a32SChris Mason 	}
12921e701a32SChris Mason 
12934cb5300bSChris Mason 	if (newer_than) {
12944cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
1295ee22184bSByongho Lee 				       &newer_off, SZ_64K);
12964cb5300bSChris Mason 		if (!ret) {
12974cb5300bSChris Mason 			range->start = newer_off;
12984cb5300bSChris Mason 			/*
12994cb5300bSChris Mason 			 * we always align our defrag to help keep
13004cb5300bSChris Mason 			 * the extents in the file evenly spaced
13014cb5300bSChris Mason 			 */
130209cbfeafSKirill A. Shutemov 			i = (newer_off & new_align) >> PAGE_SHIFT;
13034cb5300bSChris Mason 		} else
13044cb5300bSChris Mason 			goto out_ra;
13054cb5300bSChris Mason 	} else {
130609cbfeafSKirill A. Shutemov 		i = range->start >> PAGE_SHIFT;
13074cb5300bSChris Mason 	}
13084cb5300bSChris Mason 	if (!max_to_defrag)
1309070034bdSchandan 		max_to_defrag = last_index - i + 1;
13104cb5300bSChris Mason 
13112a0f7f57SLi Zefan 	/*
13122a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
13132a0f7f57SLi Zefan 	 * written sequentially.
13142a0f7f57SLi Zefan 	 */
13152a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
13162a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
13172a0f7f57SLi Zefan 
1318f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
131909cbfeafSKirill A. Shutemov 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
13204cb5300bSChris Mason 		/*
13214cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
13224cb5300bSChris Mason 		 * the FS
13234cb5300bSChris Mason 		 */
13241751e8a6SLinus Torvalds 		if (!(inode->i_sb->s_flags & SB_ACTIVE))
13254cb5300bSChris Mason 			break;
13264cb5300bSChris Mason 
13270b246afaSJeff Mahoney 		if (btrfs_defrag_cancelled(fs_info)) {
13280b246afaSJeff Mahoney 			btrfs_debug(fs_info, "defrag_file cancelled");
1329210549ebSDavid Sterba 			ret = -EAGAIN;
1330210549ebSDavid Sterba 			break;
1331210549ebSDavid Sterba 		}
1332210549ebSDavid Sterba 
133309cbfeafSKirill A. Shutemov 		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
13346c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
13351e2ef46dSDavid Sterba 					 &defrag_end, do_compress)){
1336940100a4SChris Mason 			unsigned long next;
1337940100a4SChris Mason 			/*
1338940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1339940100a4SChris Mason 			 * bump our counter by the suggested amount
1340940100a4SChris Mason 			 */
134109cbfeafSKirill A. Shutemov 			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1342940100a4SChris Mason 			i = max(i + 1, next);
1343940100a4SChris Mason 			continue;
1344940100a4SChris Mason 		}
1345008873eaSLi Zefan 
1346008873eaSLi Zefan 		if (!newer_than) {
134709cbfeafSKirill A. Shutemov 			cluster = (PAGE_ALIGN(defrag_end) >>
134809cbfeafSKirill A. Shutemov 				   PAGE_SHIFT) - i;
1349008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1350008873eaSLi Zefan 		} else {
1351008873eaSLi Zefan 			cluster = max_cluster;
1352008873eaSLi Zefan 		}
1353008873eaSLi Zefan 
1354008873eaSLi Zefan 		if (i + cluster > ra_index) {
1355008873eaSLi Zefan 			ra_index = max(i, ra_index);
13560a52d108SDavid Sterba 			if (ra)
1357d3c0bab5SDavid Sterba 				page_cache_sync_readahead(inode->i_mapping, ra,
1358d3c0bab5SDavid Sterba 						file, ra_index, cluster);
1359e4826a5bSchandan 			ra_index += cluster;
1360008873eaSLi Zefan 		}
13614cb5300bSChris Mason 
13625955102cSAl Viro 		inode_lock(inode);
13631e2ef46dSDavid Sterba 		if (do_compress)
1364eec63c65SDavid Sterba 			BTRFS_I(inode)->defrag_compress = compress_type;
1365008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1366ecb8bea8SLiu Bo 		if (ret < 0) {
13675955102cSAl Viro 			inode_unlock(inode);
13684cb5300bSChris Mason 			goto out_ra;
1369ecb8bea8SLiu Bo 		}
13704cb5300bSChris Mason 
13714cb5300bSChris Mason 		defrag_count += ret;
1372d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
13735955102cSAl Viro 		inode_unlock(inode);
13744cb5300bSChris Mason 
13754cb5300bSChris Mason 		if (newer_than) {
13764cb5300bSChris Mason 			if (newer_off == (u64)-1)
13774cb5300bSChris Mason 				break;
13784cb5300bSChris Mason 
1379e1f041e1SLiu Bo 			if (ret > 0)
1380e1f041e1SLiu Bo 				i += ret;
1381e1f041e1SLiu Bo 
13824cb5300bSChris Mason 			newer_off = max(newer_off + 1,
138309cbfeafSKirill A. Shutemov 					(u64)i << PAGE_SHIFT);
13844cb5300bSChris Mason 
1385ee22184bSByongho Lee 			ret = find_new_extents(root, inode, newer_than,
1386ee22184bSByongho Lee 					       &newer_off, SZ_64K);
13874cb5300bSChris Mason 			if (!ret) {
13884cb5300bSChris Mason 				range->start = newer_off;
138909cbfeafSKirill A. Shutemov 				i = (newer_off & new_align) >> PAGE_SHIFT;
13904cb5300bSChris Mason 			} else {
13914cb5300bSChris Mason 				break;
1392940100a4SChris Mason 			}
13934cb5300bSChris Mason 		} else {
1394008873eaSLi Zefan 			if (ret > 0) {
1395cbcc8326SLi Zefan 				i += ret;
139609cbfeafSKirill A. Shutemov 				last_len += ret << PAGE_SHIFT;
1397008873eaSLi Zefan 			} else {
1398940100a4SChris Mason 				i++;
1399008873eaSLi Zefan 				last_len = 0;
1400008873eaSLi Zefan 			}
1401f46b5a66SChristoph Hellwig 		}
14024cb5300bSChris Mason 	}
1403f46b5a66SChristoph Hellwig 
1404dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
14051e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1406dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1407dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1408dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1409dec8ef90SFilipe Manana 	}
14101e701a32SChris Mason 
14111a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
14120b246afaSJeff Mahoney 		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
14135c1aab1dSNick Terrell 	} else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
14145c1aab1dSNick Terrell 		btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
14151a419d85SLi Zefan 	}
14161a419d85SLi Zefan 
141760ccf82fSDiego Calleja 	ret = defrag_count;
1418940100a4SChris Mason 
14194cb5300bSChris Mason out_ra:
14201e2ef46dSDavid Sterba 	if (do_compress) {
14215955102cSAl Viro 		inode_lock(inode);
1422eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
14235955102cSAl Viro 		inode_unlock(inode);
1424633085c7SFilipe David Borba Manana 	}
14254cb5300bSChris Mason 	if (!file)
14264cb5300bSChris Mason 		kfree(ra);
14274cb5300bSChris Mason 	kfree(pages);
1428940100a4SChris Mason 	return ret;
1429f46b5a66SChristoph Hellwig }
1430f46b5a66SChristoph Hellwig 
1431198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
143276dda93cSYan, Zheng 					void __user *arg)
1433f46b5a66SChristoph Hellwig {
14340b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
14350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1436f46b5a66SChristoph Hellwig 	u64 new_size;
1437f46b5a66SChristoph Hellwig 	u64 old_size;
1438f46b5a66SChristoph Hellwig 	u64 devid = 1;
14390b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1440f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1441f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1442f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1443f46b5a66SChristoph Hellwig 	char *sizestr;
14449a40f122SGui Hecheng 	char *retptr;
1445f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1446f46b5a66SChristoph Hellwig 	int ret = 0;
1447f46b5a66SChristoph Hellwig 	int mod = 0;
1448f46b5a66SChristoph Hellwig 
1449e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1450e441d54dSChris Mason 		return -EPERM;
1451e441d54dSChris Mason 
1452198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1453198605a8SMiao Xie 	if (ret)
1454198605a8SMiao Xie 		return ret;
1455198605a8SMiao Xie 
1456171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
145797547676SMiao Xie 		mnt_drop_write_file(file);
1458e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1459c9e9f97bSIlya Dryomov 	}
1460c9e9f97bSIlya Dryomov 
1461dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1462c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1463c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1464c9e9f97bSIlya Dryomov 		goto out;
1465c9e9f97bSIlya Dryomov 	}
14665516e595SMark Fasheh 
14675516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1468f46b5a66SChristoph Hellwig 
1469f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1470f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1471f46b5a66SChristoph Hellwig 	if (devstr) {
1472f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1473f46b5a66SChristoph Hellwig 		*devstr = '\0';
1474f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
147558dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
147658dfae63SZhangZhen 		if (ret)
147758dfae63SZhangZhen 			goto out_free;
1478dfd79829SMiao Xie 		if (!devid) {
1479dfd79829SMiao Xie 			ret = -EINVAL;
1480dfd79829SMiao Xie 			goto out_free;
1481dfd79829SMiao Xie 		}
14820b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1483f46b5a66SChristoph Hellwig 	}
1484dba60f3fSMiao Xie 
14850b246afaSJeff Mahoney 	device = btrfs_find_device(fs_info, devid, NULL, NULL);
1486f46b5a66SChristoph Hellwig 	if (!device) {
14870b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1488c1c9ff7cSGeert Uytterhoeven 			   devid);
1489dfd79829SMiao Xie 		ret = -ENODEV;
1490c9e9f97bSIlya Dryomov 		goto out_free;
1491f46b5a66SChristoph Hellwig 	}
1492dba60f3fSMiao Xie 
1493ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
14940b246afaSJeff Mahoney 		btrfs_info(fs_info,
1495efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1496c1c9ff7cSGeert Uytterhoeven 		       devid);
1497dfd79829SMiao Xie 		ret = -EPERM;
14984e42ae1bSLiu Bo 		goto out_free;
14994e42ae1bSLiu Bo 	}
15004e42ae1bSLiu Bo 
1501f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1502f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1503f46b5a66SChristoph Hellwig 	else {
1504f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1505f46b5a66SChristoph Hellwig 			mod = -1;
1506f46b5a66SChristoph Hellwig 			sizestr++;
1507f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1508f46b5a66SChristoph Hellwig 			mod = 1;
1509f46b5a66SChristoph Hellwig 			sizestr++;
1510f46b5a66SChristoph Hellwig 		}
15119a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
15129a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1513f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1514c9e9f97bSIlya Dryomov 			goto out_free;
1515f46b5a66SChristoph Hellwig 		}
1516f46b5a66SChristoph Hellwig 	}
1517f46b5a66SChristoph Hellwig 
1518401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1519dfd79829SMiao Xie 		ret = -EPERM;
152063a212abSStefan Behrens 		goto out_free;
152163a212abSStefan Behrens 	}
152263a212abSStefan Behrens 
15237cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1524f46b5a66SChristoph Hellwig 
1525f46b5a66SChristoph Hellwig 	if (mod < 0) {
1526f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1527f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1528c9e9f97bSIlya Dryomov 			goto out_free;
1529f46b5a66SChristoph Hellwig 		}
1530f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1531f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1532eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1533902c68a4SGui Hecheng 			ret = -ERANGE;
1534eb8052e0SWenliang Fan 			goto out_free;
1535eb8052e0SWenliang Fan 		}
1536f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1537f46b5a66SChristoph Hellwig 	}
1538f46b5a66SChristoph Hellwig 
1539ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1540f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1541c9e9f97bSIlya Dryomov 		goto out_free;
1542f46b5a66SChristoph Hellwig 	}
1543f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1544f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1545c9e9f97bSIlya Dryomov 		goto out_free;
1546f46b5a66SChristoph Hellwig 	}
1547f46b5a66SChristoph Hellwig 
154847f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1549f46b5a66SChristoph Hellwig 
15500b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1551c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1552f46b5a66SChristoph Hellwig 
1553f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1554a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
155598d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
155698d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1557c9e9f97bSIlya Dryomov 			goto out_free;
155898d5dc13STsutomu Itoh 		}
1559f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
15603a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1561ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1562f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
15630253f40eSjeff.liu 	} /* equal, nothing need to do */
1564f46b5a66SChristoph Hellwig 
1565c9e9f97bSIlya Dryomov out_free:
1566f46b5a66SChristoph Hellwig 	kfree(vol_args);
1567c9e9f97bSIlya Dryomov out:
1568171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
156918f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1570f46b5a66SChristoph Hellwig 	return ret;
1571f46b5a66SChristoph Hellwig }
1572f46b5a66SChristoph Hellwig 
157372fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
157452f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
15756f72c7e2SArne Jansen 				u64 *transid, bool readonly,
15768696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1577f46b5a66SChristoph Hellwig {
1578f46b5a66SChristoph Hellwig 	int namelen;
15793de4586cSChris Mason 	int ret = 0;
1580f46b5a66SChristoph Hellwig 
1581325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1582325c50e3SJeff Mahoney 		return -ENOTDIR;
1583325c50e3SJeff Mahoney 
1584a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1585a874a63eSLiu Bo 	if (ret)
1586a874a63eSLiu Bo 		goto out;
1587a874a63eSLiu Bo 
158872fd032eSSage Weil 	namelen = strlen(name);
158972fd032eSSage Weil 	if (strchr(name, '/')) {
1590f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1591a874a63eSLiu Bo 		goto out_drop_write;
1592f46b5a66SChristoph Hellwig 	}
1593f46b5a66SChristoph Hellwig 
159416780cabSChris Mason 	if (name[0] == '.' &&
159516780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
159616780cabSChris Mason 		ret = -EEXIST;
1597a874a63eSLiu Bo 		goto out_drop_write;
159816780cabSChris Mason 	}
159916780cabSChris Mason 
16003de4586cSChris Mason 	if (subvol) {
160172fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
16026f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1603cb8e7090SChristoph Hellwig 	} else {
16042903ff01SAl Viro 		struct fd src = fdget(fd);
16053de4586cSChris Mason 		struct inode *src_inode;
16062903ff01SAl Viro 		if (!src.file) {
16073de4586cSChris Mason 			ret = -EINVAL;
1608a874a63eSLiu Bo 			goto out_drop_write;
16093de4586cSChris Mason 		}
16103de4586cSChris Mason 
1611496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1612496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1613c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1614efe120a0SFrank Holton 				   "Snapshot src from another FS");
161523ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1616d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1617d0242061SDavid Sterba 			/*
1618d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1619d0242061SDavid Sterba 			 * are limited to own subvolumes only
1620d0242061SDavid Sterba 			 */
1621d0242061SDavid Sterba 			ret = -EPERM;
1622ecd18815SAl Viro 		} else {
162372fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
162472fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
16256f72c7e2SArne Jansen 					     transid, readonly, inherit);
1626ecd18815SAl Viro 		}
16272903ff01SAl Viro 		fdput(src);
1628cb8e7090SChristoph Hellwig 	}
1629a874a63eSLiu Bo out_drop_write:
1630a874a63eSLiu Bo 	mnt_drop_write_file(file);
1631f46b5a66SChristoph Hellwig out:
163272fd032eSSage Weil 	return ret;
163372fd032eSSage Weil }
163472fd032eSSage Weil 
163572fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1636fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
163772fd032eSSage Weil {
1638fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
163972fd032eSSage Weil 	int ret;
164072fd032eSSage Weil 
1641325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1642325c50e3SJeff Mahoney 		return -ENOTDIR;
1643325c50e3SJeff Mahoney 
1644fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1645fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1646fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1647fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1648fa0d2b9bSLi Zefan 
1649fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1650b83cc969SLi Zefan 					      vol_args->fd, subvol,
16516f72c7e2SArne Jansen 					      NULL, false, NULL);
1652fa0d2b9bSLi Zefan 
1653fa0d2b9bSLi Zefan 	kfree(vol_args);
1654fa0d2b9bSLi Zefan 	return ret;
1655fa0d2b9bSLi Zefan }
1656fa0d2b9bSLi Zefan 
1657fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1658fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1659fa0d2b9bSLi Zefan {
1660fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1661fa0d2b9bSLi Zefan 	int ret;
1662fdfb1e4fSLi Zefan 	u64 transid = 0;
1663fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1664b83cc969SLi Zefan 	bool readonly = false;
16656f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
166672fd032eSSage Weil 
1667325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1668325c50e3SJeff Mahoney 		return -ENOTDIR;
1669325c50e3SJeff Mahoney 
1670fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1671fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1672fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1673fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1674fdfb1e4fSLi Zefan 
1675b83cc969SLi Zefan 	if (vol_args->flags &
16766f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
16776f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1678b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1679c47ca32dSDan Carpenter 		goto free_args;
1680fdfb1e4fSLi Zefan 	}
1681fdfb1e4fSLi Zefan 
1682fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1683fdfb1e4fSLi Zefan 		ptr = &transid;
1684b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1685b83cc969SLi Zefan 		readonly = true;
16866f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
168709cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
16886f72c7e2SArne Jansen 			ret = -EINVAL;
1689c47ca32dSDan Carpenter 			goto free_args;
16906f72c7e2SArne Jansen 		}
16916f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
16926f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
16936f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1694c47ca32dSDan Carpenter 			goto free_args;
16956f72c7e2SArne Jansen 		}
16966f72c7e2SArne Jansen 	}
169775eaa0e2SSage Weil 
1698fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
16996f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
17008696c533SMiao Xie 					      readonly, inherit);
1701c47ca32dSDan Carpenter 	if (ret)
1702c47ca32dSDan Carpenter 		goto free_inherit;
170375eaa0e2SSage Weil 
1704c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1705fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1706c47ca32dSDan Carpenter 					transid),
1707c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
170875eaa0e2SSage Weil 		ret = -EFAULT;
1709c47ca32dSDan Carpenter 
1710c47ca32dSDan Carpenter free_inherit:
17116f72c7e2SArne Jansen 	kfree(inherit);
1712c47ca32dSDan Carpenter free_args:
1713c47ca32dSDan Carpenter 	kfree(vol_args);
1714f46b5a66SChristoph Hellwig 	return ret;
1715f46b5a66SChristoph Hellwig }
1716f46b5a66SChristoph Hellwig 
17170caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
17180caa102dSLi Zefan 						void __user *arg)
17190caa102dSLi Zefan {
1720496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17210b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17220caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17230caa102dSLi Zefan 	int ret = 0;
17240caa102dSLi Zefan 	u64 flags = 0;
17250caa102dSLi Zefan 
17264a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
17270caa102dSLi Zefan 		return -EINVAL;
17280caa102dSLi Zefan 
17290b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
17300caa102dSLi Zefan 	if (btrfs_root_readonly(root))
17310caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
17320b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
17330caa102dSLi Zefan 
17340caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
17350caa102dSLi Zefan 		ret = -EFAULT;
17360caa102dSLi Zefan 
17370caa102dSLi Zefan 	return ret;
17380caa102dSLi Zefan }
17390caa102dSLi Zefan 
17400caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
17410caa102dSLi Zefan 					      void __user *arg)
17420caa102dSLi Zefan {
1743496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17440b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17450caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17460caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
17470caa102dSLi Zefan 	u64 root_flags;
17480caa102dSLi Zefan 	u64 flags;
17490caa102dSLi Zefan 	int ret = 0;
17500caa102dSLi Zefan 
1751bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1752bd60ea0fSDavid Sterba 		return -EPERM;
1753bd60ea0fSDavid Sterba 
1754b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1755b9ca0664SLiu Bo 	if (ret)
1756b9ca0664SLiu Bo 		goto out;
17570caa102dSLi Zefan 
17584a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1759b9ca0664SLiu Bo 		ret = -EINVAL;
1760b9ca0664SLiu Bo 		goto out_drop_write;
1761b9ca0664SLiu Bo 	}
17620caa102dSLi Zefan 
1763b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1764b9ca0664SLiu Bo 		ret = -EFAULT;
1765b9ca0664SLiu Bo 		goto out_drop_write;
1766b9ca0664SLiu Bo 	}
17670caa102dSLi Zefan 
1768b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1769b9ca0664SLiu Bo 		ret = -EINVAL;
1770b9ca0664SLiu Bo 		goto out_drop_write;
1771b9ca0664SLiu Bo 	}
17720caa102dSLi Zefan 
1773b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1774b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1775b9ca0664SLiu Bo 		goto out_drop_write;
1776b9ca0664SLiu Bo 	}
17770caa102dSLi Zefan 
17780b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
17790caa102dSLi Zefan 
17800caa102dSLi Zefan 	/* nothing to do */
17810caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1782b9ca0664SLiu Bo 		goto out_drop_sem;
17830caa102dSLi Zefan 
17840caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
17852c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
17860caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
17870caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
17882c686537SDavid Sterba 	} else {
17892c686537SDavid Sterba 		/*
17902c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
17912c686537SDavid Sterba 		 * send
17922c686537SDavid Sterba 		 */
17932c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
17942c686537SDavid Sterba 		if (root->send_in_progress == 0) {
17950caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
17960caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
17972c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
17982c686537SDavid Sterba 		} else {
17992c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18000b246afaSJeff Mahoney 			btrfs_warn(fs_info,
18012c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
18022c686537SDavid Sterba 				   root->root_key.objectid);
18032c686537SDavid Sterba 			ret = -EPERM;
18042c686537SDavid Sterba 			goto out_drop_sem;
18052c686537SDavid Sterba 		}
18062c686537SDavid Sterba 	}
18070caa102dSLi Zefan 
18080caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
18090caa102dSLi Zefan 	if (IS_ERR(trans)) {
18100caa102dSLi Zefan 		ret = PTR_ERR(trans);
18110caa102dSLi Zefan 		goto out_reset;
18120caa102dSLi Zefan 	}
18130caa102dSLi Zefan 
18140b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
18150caa102dSLi Zefan 				&root->root_key, &root->root_item);
18169417ebc8SNikolay Borisov 	if (ret < 0) {
18179417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
18189417ebc8SNikolay Borisov 		goto out_reset;
18199417ebc8SNikolay Borisov 	}
18200caa102dSLi Zefan 
18219417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
18229417ebc8SNikolay Borisov 
18230caa102dSLi Zefan out_reset:
18240caa102dSLi Zefan 	if (ret)
18250caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1826b9ca0664SLiu Bo out_drop_sem:
18270b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
1828b9ca0664SLiu Bo out_drop_write:
1829b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1830b9ca0664SLiu Bo out:
18310caa102dSLi Zefan 	return ret;
18320caa102dSLi Zefan }
18330caa102dSLi Zefan 
1834ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1835ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1836ac8e9819SChris Mason {
1837abc6e134SChris Mason 	struct btrfs_key test;
1838abc6e134SChris Mason 	int ret;
1839abc6e134SChris Mason 
1840abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1841abc6e134SChris Mason 	test.type = sk->min_type;
1842abc6e134SChris Mason 	test.offset = sk->min_offset;
1843abc6e134SChris Mason 
1844abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1845abc6e134SChris Mason 	if (ret < 0)
1846ac8e9819SChris Mason 		return 0;
1847abc6e134SChris Mason 
1848abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1849abc6e134SChris Mason 	test.type = sk->max_type;
1850abc6e134SChris Mason 	test.offset = sk->max_offset;
1851abc6e134SChris Mason 
1852abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1853abc6e134SChris Mason 	if (ret > 0)
1854ac8e9819SChris Mason 		return 0;
1855ac8e9819SChris Mason 	return 1;
1856ac8e9819SChris Mason }
1857ac8e9819SChris Mason 
1858df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
1859ac8e9819SChris Mason 			       struct btrfs_key *key,
1860ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
18619b6e817dSGerhard Heift 			       size_t *buf_size,
1862ba346b35SGerhard Heift 			       char __user *ubuf,
1863ac8e9819SChris Mason 			       unsigned long *sk_offset,
1864ac8e9819SChris Mason 			       int *num_found)
1865ac8e9819SChris Mason {
1866ac8e9819SChris Mason 	u64 found_transid;
1867ac8e9819SChris Mason 	struct extent_buffer *leaf;
1868ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
1869dd81d459SNaohiro Aota 	struct btrfs_key test;
1870ac8e9819SChris Mason 	unsigned long item_off;
1871ac8e9819SChris Mason 	unsigned long item_len;
1872ac8e9819SChris Mason 	int nritems;
1873ac8e9819SChris Mason 	int i;
1874ac8e9819SChris Mason 	int slot;
1875ac8e9819SChris Mason 	int ret = 0;
1876ac8e9819SChris Mason 
1877ac8e9819SChris Mason 	leaf = path->nodes[0];
1878ac8e9819SChris Mason 	slot = path->slots[0];
1879ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
1880ac8e9819SChris Mason 
1881ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
1882ac8e9819SChris Mason 		i = nritems;
1883ac8e9819SChris Mason 		goto advance_key;
1884ac8e9819SChris Mason 	}
1885ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
1886ac8e9819SChris Mason 
1887ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
1888ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
1889ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
1890ac8e9819SChris Mason 
189103b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
189203b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
189303b71c6cSGabriel de Perthuis 			continue;
189403b71c6cSGabriel de Perthuis 
18959b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
18968f5f6178SGerhard Heift 			if (*num_found) {
1897ac8e9819SChris Mason 				ret = 1;
18988f5f6178SGerhard Heift 				goto out;
18998f5f6178SGerhard Heift 			}
19008f5f6178SGerhard Heift 
19018f5f6178SGerhard Heift 			/*
19028f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
19038f5f6178SGerhard Heift 			 * handle -EOVERFLOW
19048f5f6178SGerhard Heift 			 */
19058f5f6178SGerhard Heift 
19069b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
1907ac8e9819SChris Mason 			item_len = 0;
19088f5f6178SGerhard Heift 			ret = -EOVERFLOW;
19098f5f6178SGerhard Heift 		}
1910ac8e9819SChris Mason 
19119b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
1912ac8e9819SChris Mason 			ret = 1;
191325c9bc2eSGerhard Heift 			goto out;
1914ac8e9819SChris Mason 		}
1915ac8e9819SChris Mason 
1916ac8e9819SChris Mason 		sh.objectid = key->objectid;
1917ac8e9819SChris Mason 		sh.offset = key->offset;
1918ac8e9819SChris Mason 		sh.type = key->type;
1919ac8e9819SChris Mason 		sh.len = item_len;
1920ac8e9819SChris Mason 		sh.transid = found_transid;
1921ac8e9819SChris Mason 
1922ac8e9819SChris Mason 		/* copy search result header */
1923ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
1924ba346b35SGerhard Heift 			ret = -EFAULT;
1925ba346b35SGerhard Heift 			goto out;
1926ba346b35SGerhard Heift 		}
1927ba346b35SGerhard Heift 
1928ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
1929ac8e9819SChris Mason 
1930ac8e9819SChris Mason 		if (item_len) {
1931ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
1932ac8e9819SChris Mason 			/* copy the item */
1933ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
1934ba346b35SGerhard Heift 						       item_off, item_len)) {
1935ba346b35SGerhard Heift 				ret = -EFAULT;
1936ba346b35SGerhard Heift 				goto out;
1937ba346b35SGerhard Heift 			}
1938ba346b35SGerhard Heift 
1939ac8e9819SChris Mason 			*sk_offset += item_len;
1940ac8e9819SChris Mason 		}
1941e2156867SHugo Mills 		(*num_found)++;
1942ac8e9819SChris Mason 
19438f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
19448f5f6178SGerhard Heift 			goto out;
19458f5f6178SGerhard Heift 
194625c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
194725c9bc2eSGerhard Heift 			ret = 1;
194825c9bc2eSGerhard Heift 			goto out;
194925c9bc2eSGerhard Heift 		}
1950ac8e9819SChris Mason 	}
1951ac8e9819SChris Mason advance_key:
1952ac8e9819SChris Mason 	ret = 0;
1953dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
1954dd81d459SNaohiro Aota 	test.type = sk->max_type;
1955dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
1956dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
1957dd81d459SNaohiro Aota 		ret = 1;
1958dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
1959abc6e134SChris Mason 		key->offset++;
1960dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
1961abc6e134SChris Mason 		key->offset = 0;
1962abc6e134SChris Mason 		key->type++;
1963dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
1964abc6e134SChris Mason 		key->offset = 0;
1965abc6e134SChris Mason 		key->type = 0;
1966abc6e134SChris Mason 		key->objectid++;
1967abc6e134SChris Mason 	} else
1968abc6e134SChris Mason 		ret = 1;
196925c9bc2eSGerhard Heift out:
1970ba346b35SGerhard Heift 	/*
1971ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
1972ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
1973ba346b35SGerhard Heift 	 *     * all items were found
1974ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
1975ba346b35SGerhard Heift 	 *     leaf
1976ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
1977ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
1978ba346b35SGerhard Heift 	 */
1979ac8e9819SChris Mason 	return ret;
1980ac8e9819SChris Mason }
1981ac8e9819SChris Mason 
1982ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
198312544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
19849b6e817dSGerhard Heift 				 size_t *buf_size,
1985ba346b35SGerhard Heift 				 char __user *ubuf)
1986ac8e9819SChris Mason {
19870b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
1988ac8e9819SChris Mason 	struct btrfs_root *root;
1989ac8e9819SChris Mason 	struct btrfs_key key;
1990ac8e9819SChris Mason 	struct btrfs_path *path;
1991ac8e9819SChris Mason 	int ret;
1992ac8e9819SChris Mason 	int num_found = 0;
1993ac8e9819SChris Mason 	unsigned long sk_offset = 0;
1994ac8e9819SChris Mason 
19959b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
19969b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
199712544442SGerhard Heift 		return -EOVERFLOW;
19989b6e817dSGerhard Heift 	}
199912544442SGerhard Heift 
2000ac8e9819SChris Mason 	path = btrfs_alloc_path();
2001ac8e9819SChris Mason 	if (!path)
2002ac8e9819SChris Mason 		return -ENOMEM;
2003ac8e9819SChris Mason 
2004ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2005ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2006ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2007ac8e9819SChris Mason 	} else {
2008ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2009ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2010ac8e9819SChris Mason 		key.offset = (u64)-1;
2011ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2012ac8e9819SChris Mason 		if (IS_ERR(root)) {
2013ac8e9819SChris Mason 			btrfs_free_path(path);
2014ac8e9819SChris Mason 			return -ENOENT;
2015ac8e9819SChris Mason 		}
2016ac8e9819SChris Mason 	}
2017ac8e9819SChris Mason 
2018ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2019ac8e9819SChris Mason 	key.type = sk->min_type;
2020ac8e9819SChris Mason 	key.offset = sk->min_offset;
2021ac8e9819SChris Mason 
2022ac8e9819SChris Mason 	while (1) {
20236174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2024ac8e9819SChris Mason 		if (ret != 0) {
2025ac8e9819SChris Mason 			if (ret > 0)
2026ac8e9819SChris Mason 				ret = 0;
2027ac8e9819SChris Mason 			goto err;
2028ac8e9819SChris Mason 		}
2029df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2030ac8e9819SChris Mason 				 &sk_offset, &num_found);
2031b3b4aa74SDavid Sterba 		btrfs_release_path(path);
203225c9bc2eSGerhard Heift 		if (ret)
2033ac8e9819SChris Mason 			break;
2034ac8e9819SChris Mason 
2035ac8e9819SChris Mason 	}
20368f5f6178SGerhard Heift 	if (ret > 0)
2037ac8e9819SChris Mason 		ret = 0;
2038ac8e9819SChris Mason err:
2039ac8e9819SChris Mason 	sk->nr_items = num_found;
2040ac8e9819SChris Mason 	btrfs_free_path(path);
2041ac8e9819SChris Mason 	return ret;
2042ac8e9819SChris Mason }
2043ac8e9819SChris Mason 
2044ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2045ac8e9819SChris Mason 					   void __user *argp)
2046ac8e9819SChris Mason {
2047ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2048ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2049ac8e9819SChris Mason 	struct inode *inode;
2050ac8e9819SChris Mason 	int ret;
20519b6e817dSGerhard Heift 	size_t buf_size;
2052ac8e9819SChris Mason 
2053ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2054ac8e9819SChris Mason 		return -EPERM;
2055ac8e9819SChris Mason 
2056ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2057ac8e9819SChris Mason 
2058ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2059ba346b35SGerhard Heift 		return -EFAULT;
2060ba346b35SGerhard Heift 
2061ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2062ac8e9819SChris Mason 
2063496ad9aaSAl Viro 	inode = file_inode(file);
2064ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
20658f5f6178SGerhard Heift 
20668f5f6178SGerhard Heift 	/*
20678f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
20688f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
20698f5f6178SGerhard Heift 	 */
20708f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
20718f5f6178SGerhard Heift 		ret = 0;
20728f5f6178SGerhard Heift 
2073ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2074ac8e9819SChris Mason 		ret = -EFAULT;
2075ac8e9819SChris Mason 	return ret;
2076ac8e9819SChris Mason }
2077ac8e9819SChris Mason 
2078cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2079cc68a8a5SGerhard Heift 					       void __user *argp)
2080cc68a8a5SGerhard Heift {
2081cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2082cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2083cc68a8a5SGerhard Heift 	struct inode *inode;
2084cc68a8a5SGerhard Heift 	int ret;
2085cc68a8a5SGerhard Heift 	size_t buf_size;
2086ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2087cc68a8a5SGerhard Heift 
2088cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2089cc68a8a5SGerhard Heift 		return -EPERM;
2090cc68a8a5SGerhard Heift 
2091cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2092cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2093cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2094cc68a8a5SGerhard Heift 		return -EFAULT;
2095cc68a8a5SGerhard Heift 
2096cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2097cc68a8a5SGerhard Heift 
2098cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2099cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2100cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2101cc68a8a5SGerhard Heift 
2102cc68a8a5SGerhard Heift 	inode = file_inode(file);
2103cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2104718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2105cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2106cc68a8a5SGerhard Heift 		ret = -EFAULT;
2107cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2108cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2109cc68a8a5SGerhard Heift 		ret = -EFAULT;
2110cc68a8a5SGerhard Heift 
211176dda93cSYan, Zheng 	return ret;
211276dda93cSYan, Zheng }
211376dda93cSYan, Zheng 
211498d377a0STARUISI Hiroaki /*
2115ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2116ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
211798d377a0STARUISI Hiroaki  */
211898d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
211998d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
212098d377a0STARUISI Hiroaki {
212198d377a0STARUISI Hiroaki 	struct btrfs_root *root;
212298d377a0STARUISI Hiroaki 	struct btrfs_key key;
2123ac8e9819SChris Mason 	char *ptr;
212498d377a0STARUISI Hiroaki 	int ret = -1;
212598d377a0STARUISI Hiroaki 	int slot;
212698d377a0STARUISI Hiroaki 	int len;
212798d377a0STARUISI Hiroaki 	int total_len = 0;
212898d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
212998d377a0STARUISI Hiroaki 	struct extent_buffer *l;
213098d377a0STARUISI Hiroaki 	struct btrfs_path *path;
213198d377a0STARUISI Hiroaki 
213298d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
213398d377a0STARUISI Hiroaki 		name[0]='\0';
213498d377a0STARUISI Hiroaki 		return 0;
213598d377a0STARUISI Hiroaki 	}
213698d377a0STARUISI Hiroaki 
213798d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
213898d377a0STARUISI Hiroaki 	if (!path)
213998d377a0STARUISI Hiroaki 		return -ENOMEM;
214098d377a0STARUISI Hiroaki 
2141c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
214298d377a0STARUISI Hiroaki 
214398d377a0STARUISI Hiroaki 	key.objectid = tree_id;
214498d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
214598d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
214698d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
214798d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2148f14d104dSDavid Sterba 		btrfs_err(info, "could not find root %llu", tree_id);
21498ad6fcabSChris Mason 		ret = -ENOENT;
21508ad6fcabSChris Mason 		goto out;
215198d377a0STARUISI Hiroaki 	}
215298d377a0STARUISI Hiroaki 
215398d377a0STARUISI Hiroaki 	key.objectid = dirid;
215498d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
21558ad6fcabSChris Mason 	key.offset = (u64)-1;
215698d377a0STARUISI Hiroaki 
215798d377a0STARUISI Hiroaki 	while (1) {
215898d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
215998d377a0STARUISI Hiroaki 		if (ret < 0)
216098d377a0STARUISI Hiroaki 			goto out;
216118674c6cSFilipe David Borba Manana 		else if (ret > 0) {
216218674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
216318674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
216418674c6cSFilipe David Borba Manana 			if (ret < 0)
216518674c6cSFilipe David Borba Manana 				goto out;
216618674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2167ac8e9819SChris Mason 				ret = -ENOENT;
216898d377a0STARUISI Hiroaki 				goto out;
2169ac8e9819SChris Mason 			}
217018674c6cSFilipe David Borba Manana 		}
217118674c6cSFilipe David Borba Manana 
217218674c6cSFilipe David Borba Manana 		l = path->nodes[0];
217318674c6cSFilipe David Borba Manana 		slot = path->slots[0];
217418674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
217598d377a0STARUISI Hiroaki 
217698d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
217798d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
217898d377a0STARUISI Hiroaki 		ptr -= len + 1;
217998d377a0STARUISI Hiroaki 		total_len += len + 1;
2180a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2181a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
218298d377a0STARUISI Hiroaki 			goto out;
2183a696cf35SFilipe David Borba Manana 		}
218498d377a0STARUISI Hiroaki 
218598d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
218698d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
218798d377a0STARUISI Hiroaki 
218898d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
218998d377a0STARUISI Hiroaki 			break;
219098d377a0STARUISI Hiroaki 
2191b3b4aa74SDavid Sterba 		btrfs_release_path(path);
219298d377a0STARUISI Hiroaki 		key.objectid = key.offset;
21938ad6fcabSChris Mason 		key.offset = (u64)-1;
219498d377a0STARUISI Hiroaki 		dirid = key.objectid;
219598d377a0STARUISI Hiroaki 	}
219677906a50SLi Zefan 	memmove(name, ptr, total_len);
219798d377a0STARUISI Hiroaki 	name[total_len] = '\0';
219898d377a0STARUISI Hiroaki 	ret = 0;
219998d377a0STARUISI Hiroaki out:
220098d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2201ac8e9819SChris Mason 	return ret;
2202ac8e9819SChris Mason }
2203ac8e9819SChris Mason 
2204ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2205ac8e9819SChris Mason 					   void __user *argp)
2206ac8e9819SChris Mason {
2207ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2208ac8e9819SChris Mason 	 struct inode *inode;
220901b810b8SDavid Sterba 	int ret = 0;
2210ac8e9819SChris Mason 
22112354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
22122354d08fSJulia Lawall 	if (IS_ERR(args))
22132354d08fSJulia Lawall 		return PTR_ERR(args);
2214c2b96929SDan Carpenter 
2215496ad9aaSAl Viro 	inode = file_inode(file);
2216ac8e9819SChris Mason 
221701b810b8SDavid Sterba 	/*
221801b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
221901b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
222001b810b8SDavid Sterba 	 */
22211b53ac4dSChris Mason 	if (args->treeid == 0)
22221b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
22231b53ac4dSChris Mason 
222401b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
222501b810b8SDavid Sterba 		args->name[0] = 0;
222601b810b8SDavid Sterba 		goto out;
222701b810b8SDavid Sterba 	}
222801b810b8SDavid Sterba 
222901b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
223001b810b8SDavid Sterba 		ret = -EPERM;
223101b810b8SDavid Sterba 		goto out;
223201b810b8SDavid Sterba 	}
223301b810b8SDavid Sterba 
2234ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2235ac8e9819SChris Mason 					args->treeid, args->objectid,
2236ac8e9819SChris Mason 					args->name);
2237ac8e9819SChris Mason 
223801b810b8SDavid Sterba out:
2239ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2240ac8e9819SChris Mason 		ret = -EFAULT;
2241ac8e9819SChris Mason 
2242ac8e9819SChris Mason 	kfree(args);
224398d377a0STARUISI Hiroaki 	return ret;
224498d377a0STARUISI Hiroaki }
224598d377a0STARUISI Hiroaki 
224676dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
224776dda93cSYan, Zheng 					     void __user *arg)
224876dda93cSYan, Zheng {
224954563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
22500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
225176dda93cSYan, Zheng 	struct dentry *dentry;
22522b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
225376dda93cSYan, Zheng 	struct inode *inode;
225476dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
225576dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
225676dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
225776dda93cSYan, Zheng 	int namelen;
225876dda93cSYan, Zheng 	int err = 0;
225976dda93cSYan, Zheng 
2260325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2261325c50e3SJeff Mahoney 		return -ENOTDIR;
2262325c50e3SJeff Mahoney 
226376dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
226476dda93cSYan, Zheng 	if (IS_ERR(vol_args))
226576dda93cSYan, Zheng 		return PTR_ERR(vol_args);
226676dda93cSYan, Zheng 
226776dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
226876dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
226976dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
227076dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
227176dda93cSYan, Zheng 		err = -EINVAL;
227276dda93cSYan, Zheng 		goto out;
227376dda93cSYan, Zheng 	}
227476dda93cSYan, Zheng 
2275a561be71SAl Viro 	err = mnt_want_write_file(file);
227676dda93cSYan, Zheng 	if (err)
227776dda93cSYan, Zheng 		goto out;
227876dda93cSYan, Zheng 
2279521e0546SDavid Sterba 
228000235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
228100235411SAl Viro 	if (err == -EINTR)
228200235411SAl Viro 		goto out_drop_write;
228376dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
228476dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
228576dda93cSYan, Zheng 		err = PTR_ERR(dentry);
228676dda93cSYan, Zheng 		goto out_unlock_dir;
228776dda93cSYan, Zheng 	}
228876dda93cSYan, Zheng 
22892b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
229076dda93cSYan, Zheng 		err = -ENOENT;
229176dda93cSYan, Zheng 		goto out_dput;
229276dda93cSYan, Zheng 	}
229376dda93cSYan, Zheng 
22942b0143b5SDavid Howells 	inode = d_inode(dentry);
22954260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
22964260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
22974260f7c7SSage Weil 		/*
22984260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
22994260f7c7SSage Weil 		 * option, when the user has write+exec access to the
23004260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
23014260f7c7SSage Weil 		 * allowed.
23024260f7c7SSage Weil 		 *
23034260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
23044260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
23054260f7c7SSage Weil 		 * otherwise be able to delete.
23064260f7c7SSage Weil 		 *
23074260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
23084260f7c7SSage Weil 		 * rmdir(2).
23094260f7c7SSage Weil 		 */
23104260f7c7SSage Weil 		err = -EPERM;
23110b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
23124260f7c7SSage Weil 			goto out_dput;
23134260f7c7SSage Weil 
23144260f7c7SSage Weil 		/*
23154260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
23164260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
23174260f7c7SSage Weil 		 * must be called on the dentry referencing the root
23184260f7c7SSage Weil 		 * of the subvol, not a random directory contained
23194260f7c7SSage Weil 		 * within it.
23204260f7c7SSage Weil 		 */
23214260f7c7SSage Weil 		err = -EINVAL;
23224260f7c7SSage Weil 		if (root == dest)
23234260f7c7SSage Weil 			goto out_dput;
23244260f7c7SSage Weil 
23254260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
23264260f7c7SSage Weil 		if (err)
23274260f7c7SSage Weil 			goto out_dput;
23285c39da5bSMiao Xie 	}
23294260f7c7SSage Weil 
23305c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
23314260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
23324260f7c7SSage Weil 	if (err)
23334260f7c7SSage Weil 		goto out_dput;
23344260f7c7SSage Weil 
23354a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
233676dda93cSYan, Zheng 		err = -EINVAL;
233776dda93cSYan, Zheng 		goto out_dput;
233876dda93cSYan, Zheng 	}
233976dda93cSYan, Zheng 
23405955102cSAl Viro 	inode_lock(inode);
2341f60a2364SMisono Tomohiro 	err = btrfs_delete_subvolume(dir, dentry);
23425955102cSAl Viro 	inode_unlock(inode);
2343f60a2364SMisono Tomohiro 	if (!err)
234476dda93cSYan, Zheng 		d_delete(dentry);
2345fa6ac876SLiu Bo 
234676dda93cSYan, Zheng out_dput:
234776dda93cSYan, Zheng 	dput(dentry);
234876dda93cSYan, Zheng out_unlock_dir:
23495955102cSAl Viro 	inode_unlock(dir);
235000235411SAl Viro out_drop_write:
23512a79f17eSAl Viro 	mnt_drop_write_file(file);
235276dda93cSYan, Zheng out:
235376dda93cSYan, Zheng 	kfree(vol_args);
235476dda93cSYan, Zheng 	return err;
235576dda93cSYan, Zheng }
235676dda93cSYan, Zheng 
23571e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2358f46b5a66SChristoph Hellwig {
2359496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2360f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
23611e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2362c146afadSYan Zheng 	int ret;
2363c146afadSYan Zheng 
236425122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
236525122d15SIlya Dryomov 	if (ret)
236625122d15SIlya Dryomov 		return ret;
2367b83cc969SLi Zefan 
236825122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
236925122d15SIlya Dryomov 		ret = -EROFS;
237025122d15SIlya Dryomov 		goto out;
23715ac00addSStefan Behrens 	}
2372f46b5a66SChristoph Hellwig 
2373f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2374f46b5a66SChristoph Hellwig 	case S_IFDIR:
2375e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2376e441d54dSChris Mason 			ret = -EPERM;
2377e441d54dSChris Mason 			goto out;
2378e441d54dSChris Mason 		}
2379de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
2380f46b5a66SChristoph Hellwig 		break;
2381f46b5a66SChristoph Hellwig 	case S_IFREG:
2382e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2383e441d54dSChris Mason 			ret = -EINVAL;
2384e441d54dSChris Mason 			goto out;
2385e441d54dSChris Mason 		}
23861e701a32SChris Mason 
23871e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
23881e701a32SChris Mason 		if (!range) {
23891e701a32SChris Mason 			ret = -ENOMEM;
23901e701a32SChris Mason 			goto out;
23911e701a32SChris Mason 		}
23921e701a32SChris Mason 
23931e701a32SChris Mason 		if (argp) {
23941e701a32SChris Mason 			if (copy_from_user(range, argp,
23951e701a32SChris Mason 					   sizeof(*range))) {
23961e701a32SChris Mason 				ret = -EFAULT;
23971e701a32SChris Mason 				kfree(range);
2398683be16eSDan Carpenter 				goto out;
23991e701a32SChris Mason 			}
24001e701a32SChris Mason 			/* compression requires us to start the IO */
24011e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
24021e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
24031e701a32SChris Mason 				range->extent_thresh = (u32)-1;
24041e701a32SChris Mason 			}
24051e701a32SChris Mason 		} else {
24061e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
24071e701a32SChris Mason 			range->len = (u64)-1;
24081e701a32SChris Mason 		}
2409496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
24107c829b72SAnand Jain 					range, BTRFS_OLDEST_GENERATION, 0);
24114cb5300bSChris Mason 		if (ret > 0)
24124cb5300bSChris Mason 			ret = 0;
24131e701a32SChris Mason 		kfree(range);
2414f46b5a66SChristoph Hellwig 		break;
24158929ecfaSYan, Zheng 	default:
24168929ecfaSYan, Zheng 		ret = -EINVAL;
2417f46b5a66SChristoph Hellwig 	}
2418e441d54dSChris Mason out:
241925122d15SIlya Dryomov 	mnt_drop_write_file(file);
2420e441d54dSChris Mason 	return ret;
2421f46b5a66SChristoph Hellwig }
2422f46b5a66SChristoph Hellwig 
24232ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2424f46b5a66SChristoph Hellwig {
2425f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2426f46b5a66SChristoph Hellwig 	int ret;
2427f46b5a66SChristoph Hellwig 
2428e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2429e441d54dSChris Mason 		return -EPERM;
2430e441d54dSChris Mason 
2431171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2432e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2433c9e9f97bSIlya Dryomov 
2434dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2435c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2436c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2437c9e9f97bSIlya Dryomov 		goto out;
2438c9e9f97bSIlya Dryomov 	}
2439f46b5a66SChristoph Hellwig 
24405516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
24412ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
2442f46b5a66SChristoph Hellwig 
244343d20761SAnand Jain 	if (!ret)
24440b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
244543d20761SAnand Jain 
2446f46b5a66SChristoph Hellwig 	kfree(vol_args);
2447c9e9f97bSIlya Dryomov out:
2448171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2449f46b5a66SChristoph Hellwig 	return ret;
2450f46b5a66SChristoph Hellwig }
2451f46b5a66SChristoph Hellwig 
24526b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
2453f46b5a66SChristoph Hellwig {
24540b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
24550b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
24566b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
2457f46b5a66SChristoph Hellwig 	int ret;
2458f46b5a66SChristoph Hellwig 
2459e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2460e441d54dSChris Mason 		return -EPERM;
2461e441d54dSChris Mason 
2462da24927bSMiao Xie 	ret = mnt_want_write_file(file);
2463da24927bSMiao Xie 	if (ret)
2464da24927bSMiao Xie 		return ret;
2465c146afadSYan Zheng 
2466dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2467c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2468c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2469c47ca32dSDan Carpenter 		goto err_drop;
2470c9e9f97bSIlya Dryomov 	}
2471f46b5a66SChristoph Hellwig 
24726b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
2473735654eaSDavid Sterba 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED)
2474735654eaSDavid Sterba 		return -EOPNOTSUPP;
2475f46b5a66SChristoph Hellwig 
2476171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2477183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2478183860f6SAnand Jain 		goto out;
2479183860f6SAnand Jain 	}
2480183860f6SAnand Jain 
2481735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
24822ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
24836b526ed7SAnand Jain 	} else {
24846b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
24852ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
24866b526ed7SAnand Jain 	}
2487171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2488183860f6SAnand Jain 
24896b526ed7SAnand Jain 	if (!ret) {
2490735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
24910b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
24926b526ed7SAnand Jain 					vol_args->devid);
24936b526ed7SAnand Jain 		else
24940b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
24956b526ed7SAnand Jain 					vol_args->name);
24966b526ed7SAnand Jain 	}
2497183860f6SAnand Jain out:
2498183860f6SAnand Jain 	kfree(vol_args);
2499c47ca32dSDan Carpenter err_drop:
25004ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
2501f46b5a66SChristoph Hellwig 	return ret;
2502f46b5a66SChristoph Hellwig }
2503f46b5a66SChristoph Hellwig 
2504f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2505f46b5a66SChristoph Hellwig {
25060b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
25070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2508f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2509f46b5a66SChristoph Hellwig 	int ret;
2510f46b5a66SChristoph Hellwig 
2511f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
2512f46b5a66SChristoph Hellwig 		return -EPERM;
2513f46b5a66SChristoph Hellwig 
2514f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
2515f46b5a66SChristoph Hellwig 	if (ret)
2516f46b5a66SChristoph Hellwig 		return ret;
2517f46b5a66SChristoph Hellwig 
2518171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2519f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
252058d7bbf8SDavid Sterba 		goto out_drop_write;
252158d7bbf8SDavid Sterba 	}
252258d7bbf8SDavid Sterba 
252358d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
252458d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
252558d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
2526f46b5a66SChristoph Hellwig 		goto out;
2527f46b5a66SChristoph Hellwig 	}
2528f46b5a66SChristoph Hellwig 
252958d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
25302ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
2531f46b5a66SChristoph Hellwig 
2532f46b5a66SChristoph Hellwig 	if (!ret)
25330b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
2534f46b5a66SChristoph Hellwig 	kfree(vol_args);
253558d7bbf8SDavid Sterba out:
2536171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
253758d7bbf8SDavid Sterba out_drop_write:
2538f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
253958d7bbf8SDavid Sterba 
2540f46b5a66SChristoph Hellwig 	return ret;
2541f46b5a66SChristoph Hellwig }
2542f46b5a66SChristoph Hellwig 
25432ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
25442ff7e61eSJeff Mahoney 				void __user *arg)
2545475f6387SJan Schmidt {
2546027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
2547475f6387SJan Schmidt 	struct btrfs_device *device;
25480b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2549027ed2f0SLi Zefan 	int ret = 0;
2550475f6387SJan Schmidt 
2551027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2552027ed2f0SLi Zefan 	if (!fi_args)
2553027ed2f0SLi Zefan 		return -ENOMEM;
2554027ed2f0SLi Zefan 
2555d03262c7SDavid Sterba 	rcu_read_lock();
2556027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
2557475f6387SJan Schmidt 
2558d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2559027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
2560027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
2561475f6387SJan Schmidt 	}
2562d03262c7SDavid Sterba 	rcu_read_unlock();
2563475f6387SJan Schmidt 
2564d03262c7SDavid Sterba 	memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
2565bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
2566bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
2567bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
256880a773fbSDavid Sterba 
2569027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2570027ed2f0SLi Zefan 		ret = -EFAULT;
2571475f6387SJan Schmidt 
2572027ed2f0SLi Zefan 	kfree(fi_args);
2573027ed2f0SLi Zefan 	return ret;
2574475f6387SJan Schmidt }
2575475f6387SJan Schmidt 
25762ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
25772ff7e61eSJeff Mahoney 				 void __user *arg)
2578475f6387SJan Schmidt {
2579475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
2580475f6387SJan Schmidt 	struct btrfs_device *dev;
2581475f6387SJan Schmidt 	int ret = 0;
2582475f6387SJan Schmidt 	char *s_uuid = NULL;
2583475f6387SJan Schmidt 
2584475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
2585475f6387SJan Schmidt 	if (IS_ERR(di_args))
2586475f6387SJan Schmidt 		return PTR_ERR(di_args);
2587475f6387SJan Schmidt 
2588dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
2589475f6387SJan Schmidt 		s_uuid = di_args->uuid;
2590475f6387SJan Schmidt 
2591c5593ca3SDavid Sterba 	rcu_read_lock();
25920b246afaSJeff Mahoney 	dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
2593475f6387SJan Schmidt 
2594475f6387SJan Schmidt 	if (!dev) {
2595475f6387SJan Schmidt 		ret = -ENODEV;
2596475f6387SJan Schmidt 		goto out;
2597475f6387SJan Schmidt 	}
2598475f6387SJan Schmidt 
2599475f6387SJan Schmidt 	di_args->devid = dev->devid;
26007cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
26017cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2602475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2603a27202fbSJim Meyering 	if (dev->name) {
2604606686eeSJosef Bacik 		struct rcu_string *name;
2605606686eeSJosef Bacik 
2606606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
26076670d4c2SXiongfeng Wang 		strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
2608a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
2609a27202fbSJim Meyering 	} else {
261099ba55adSStefan Behrens 		di_args->path[0] = '\0';
2611a27202fbSJim Meyering 	}
2612475f6387SJan Schmidt 
2613475f6387SJan Schmidt out:
2614c5593ca3SDavid Sterba 	rcu_read_unlock();
2615475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2616475f6387SJan Schmidt 		ret = -EFAULT;
2617475f6387SJan Schmidt 
2618475f6387SJan Schmidt 	kfree(di_args);
2619475f6387SJan Schmidt 	return ret;
2620475f6387SJan Schmidt }
2621475f6387SJan Schmidt 
2622f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2623416161dbSMark Fasheh {
2624416161dbSMark Fasheh 	struct page *page;
2625416161dbSMark Fasheh 
2626416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
2627416161dbSMark Fasheh 	if (!page)
262831314002SFilipe Manana 		return ERR_PTR(-ENOMEM);
2629416161dbSMark Fasheh 
2630416161dbSMark Fasheh 	if (!PageUptodate(page)) {
263131314002SFilipe Manana 		int ret;
263231314002SFilipe Manana 
263331314002SFilipe Manana 		ret = btrfs_readpage(NULL, page);
263431314002SFilipe Manana 		if (ret)
263531314002SFilipe Manana 			return ERR_PTR(ret);
2636416161dbSMark Fasheh 		lock_page(page);
2637416161dbSMark Fasheh 		if (!PageUptodate(page)) {
2638416161dbSMark Fasheh 			unlock_page(page);
263909cbfeafSKirill A. Shutemov 			put_page(page);
264031314002SFilipe Manana 			return ERR_PTR(-EIO);
2641416161dbSMark Fasheh 		}
264231314002SFilipe Manana 		if (page->mapping != inode->i_mapping) {
2643416161dbSMark Fasheh 			unlock_page(page);
264409cbfeafSKirill A. Shutemov 			put_page(page);
264531314002SFilipe Manana 			return ERR_PTR(-EAGAIN);
2646416161dbSMark Fasheh 		}
2647416161dbSMark Fasheh 	}
2648416161dbSMark Fasheh 
2649416161dbSMark Fasheh 	return page;
2650416161dbSMark Fasheh }
2651416161dbSMark Fasheh 
2652f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
2653f4414602SMark Fasheh 			       int num_pages, u64 off)
2654f4414602SMark Fasheh {
2655f4414602SMark Fasheh 	int i;
265609cbfeafSKirill A. Shutemov 	pgoff_t index = off >> PAGE_SHIFT;
2657f4414602SMark Fasheh 
2658f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
265931314002SFilipe Manana again:
2660f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
266131314002SFilipe Manana 		if (IS_ERR(pages[i])) {
266231314002SFilipe Manana 			int err = PTR_ERR(pages[i]);
266331314002SFilipe Manana 
266431314002SFilipe Manana 			if (err == -EAGAIN)
266531314002SFilipe Manana 				goto again;
266631314002SFilipe Manana 			pages[i] = NULL;
266731314002SFilipe Manana 			return err;
266831314002SFilipe Manana 		}
2669f4414602SMark Fasheh 	}
2670f4414602SMark Fasheh 	return 0;
2671f4414602SMark Fasheh }
2672f4414602SMark Fasheh 
2673e0bd70c6SFilipe Manana static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2674e0bd70c6SFilipe Manana 			     bool retry_range_locking)
267577fe20dcSMark Fasheh {
2676e0bd70c6SFilipe Manana 	/*
2677e0bd70c6SFilipe Manana 	 * Do any pending delalloc/csum calculations on inode, one way or
2678e0bd70c6SFilipe Manana 	 * another, and lock file content.
2679e0bd70c6SFilipe Manana 	 * The locking order is:
2680e0bd70c6SFilipe Manana 	 *
2681e0bd70c6SFilipe Manana 	 *   1) pages
2682e0bd70c6SFilipe Manana 	 *   2) range in the inode's io tree
2683e0bd70c6SFilipe Manana 	 */
268477fe20dcSMark Fasheh 	while (1) {
268577fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
268677fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
268777fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
268877fe20dcSMark Fasheh 							    off + len - 1);
2689ff5df9b8SFilipe Manana 		if ((!ordered ||
2690ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
2691ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
269277fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2693ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2694ff5df9b8SFilipe Manana 			if (ordered)
2695ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
269677fe20dcSMark Fasheh 			break;
2697ff5df9b8SFilipe Manana 		}
269877fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
269977fe20dcSMark Fasheh 		if (ordered)
270077fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
2701e0bd70c6SFilipe Manana 		if (!retry_range_locking)
2702e0bd70c6SFilipe Manana 			return -EAGAIN;
270377fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
270477fe20dcSMark Fasheh 	}
2705e0bd70c6SFilipe Manana 	return 0;
270677fe20dcSMark Fasheh }
270777fe20dcSMark Fasheh 
2708f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2709416161dbSMark Fasheh {
27105955102cSAl Viro 	inode_unlock(inode1);
27115955102cSAl Viro 	inode_unlock(inode2);
2712416161dbSMark Fasheh }
2713416161dbSMark Fasheh 
2714f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2715f4414602SMark Fasheh {
2716f4414602SMark Fasheh 	if (inode1 < inode2)
2717f4414602SMark Fasheh 		swap(inode1, inode2);
2718f4414602SMark Fasheh 
27195955102cSAl Viro 	inode_lock_nested(inode1, I_MUTEX_PARENT);
27205955102cSAl Viro 	inode_lock_nested(inode2, I_MUTEX_CHILD);
2721f4414602SMark Fasheh }
2722f4414602SMark Fasheh 
2723f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2724f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
2725f4414602SMark Fasheh {
2726f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2727f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2728f4414602SMark Fasheh }
2729f4414602SMark Fasheh 
2730e0bd70c6SFilipe Manana static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2731e0bd70c6SFilipe Manana 				    struct inode *inode2, u64 loff2, u64 len,
2732e0bd70c6SFilipe Manana 				    bool retry_range_locking)
2733416161dbSMark Fasheh {
2734e0bd70c6SFilipe Manana 	int ret;
2735e0bd70c6SFilipe Manana 
2736416161dbSMark Fasheh 	if (inode1 < inode2) {
2737416161dbSMark Fasheh 		swap(inode1, inode2);
2738416161dbSMark Fasheh 		swap(loff1, loff2);
2739416161dbSMark Fasheh 	}
2740e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2741e0bd70c6SFilipe Manana 	if (ret)
2742e0bd70c6SFilipe Manana 		return ret;
2743e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2744e0bd70c6SFilipe Manana 	if (ret)
2745e0bd70c6SFilipe Manana 		unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2746e0bd70c6SFilipe Manana 			      loff1 + len - 1);
2747e0bd70c6SFilipe Manana 	return ret;
2748416161dbSMark Fasheh }
2749f4414602SMark Fasheh 
2750f4414602SMark Fasheh struct cmp_pages {
2751f4414602SMark Fasheh 	int		num_pages;
2752f4414602SMark Fasheh 	struct page	**src_pages;
2753f4414602SMark Fasheh 	struct page	**dst_pages;
2754f4414602SMark Fasheh };
2755f4414602SMark Fasheh 
2756f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2757f4414602SMark Fasheh {
2758f4414602SMark Fasheh 	int i;
2759f4414602SMark Fasheh 	struct page *pg;
2760f4414602SMark Fasheh 
2761f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
2762f4414602SMark Fasheh 		pg = cmp->src_pages[i];
2763e0bd70c6SFilipe Manana 		if (pg) {
2764e0bd70c6SFilipe Manana 			unlock_page(pg);
276509cbfeafSKirill A. Shutemov 			put_page(pg);
2766e0bd70c6SFilipe Manana 		}
2767f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
2768e0bd70c6SFilipe Manana 		if (pg) {
2769e0bd70c6SFilipe Manana 			unlock_page(pg);
277009cbfeafSKirill A. Shutemov 			put_page(pg);
2771f4414602SMark Fasheh 		}
2772e0bd70c6SFilipe Manana 	}
2773f4414602SMark Fasheh 	kfree(cmp->src_pages);
2774f4414602SMark Fasheh 	kfree(cmp->dst_pages);
2775f4414602SMark Fasheh }
2776f4414602SMark Fasheh 
2777f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2778f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
2779f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
2780f4414602SMark Fasheh {
2781f4414602SMark Fasheh 	int ret;
278209cbfeafSKirill A. Shutemov 	int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
2783f4414602SMark Fasheh 	struct page **src_pgarr, **dst_pgarr;
2784f4414602SMark Fasheh 
2785f4414602SMark Fasheh 	/*
2786f4414602SMark Fasheh 	 * We must gather up all the pages before we initiate our
2787f4414602SMark Fasheh 	 * extent locking. We use an array for the page pointers. Size
2788f4414602SMark Fasheh 	 * of the array is bounded by len, which is in turn bounded by
2789f4414602SMark Fasheh 	 * BTRFS_MAX_DEDUPE_LEN.
2790f4414602SMark Fasheh 	 */
279166722f7cSDavid Sterba 	src_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
279266722f7cSDavid Sterba 	dst_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
2793f4414602SMark Fasheh 	if (!src_pgarr || !dst_pgarr) {
2794f4414602SMark Fasheh 		kfree(src_pgarr);
2795f4414602SMark Fasheh 		kfree(dst_pgarr);
2796f4414602SMark Fasheh 		return -ENOMEM;
2797f4414602SMark Fasheh 	}
2798f4414602SMark Fasheh 	cmp->num_pages = num_pages;
2799f4414602SMark Fasheh 	cmp->src_pages = src_pgarr;
2800f4414602SMark Fasheh 	cmp->dst_pages = dst_pgarr;
2801f4414602SMark Fasheh 
2802b1517622SFilipe Manana 	/*
2803b1517622SFilipe Manana 	 * If deduping ranges in the same inode, locking rules make it mandatory
2804b1517622SFilipe Manana 	 * to always lock pages in ascending order to avoid deadlocks with
2805b1517622SFilipe Manana 	 * concurrent tasks (such as starting writeback/delalloc).
2806b1517622SFilipe Manana 	 */
2807b1517622SFilipe Manana 	if (src == dst && dst_loff < loff) {
2808b1517622SFilipe Manana 		swap(src_pgarr, dst_pgarr);
2809b1517622SFilipe Manana 		swap(loff, dst_loff);
2810b1517622SFilipe Manana 	}
2811b1517622SFilipe Manana 
2812b1517622SFilipe Manana 	ret = gather_extent_pages(src, src_pgarr, cmp->num_pages, loff);
2813f4414602SMark Fasheh 	if (ret)
2814f4414602SMark Fasheh 		goto out;
2815f4414602SMark Fasheh 
2816b1517622SFilipe Manana 	ret = gather_extent_pages(dst, dst_pgarr, cmp->num_pages, dst_loff);
2817f4414602SMark Fasheh 
2818f4414602SMark Fasheh out:
2819f4414602SMark Fasheh 	if (ret)
2820f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
282178ad4ce0SNaohiro Aota 	return ret;
2822416161dbSMark Fasheh }
2823416161dbSMark Fasheh 
28241a287cfeSDavid Sterba static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
2825416161dbSMark Fasheh {
2826416161dbSMark Fasheh 	int ret = 0;
2827f4414602SMark Fasheh 	int i;
2828416161dbSMark Fasheh 	struct page *src_page, *dst_page;
282909cbfeafSKirill A. Shutemov 	unsigned int cmp_len = PAGE_SIZE;
2830416161dbSMark Fasheh 	void *addr, *dst_addr;
2831416161dbSMark Fasheh 
2832f4414602SMark Fasheh 	i = 0;
2833416161dbSMark Fasheh 	while (len) {
283409cbfeafSKirill A. Shutemov 		if (len < PAGE_SIZE)
2835416161dbSMark Fasheh 			cmp_len = len;
2836416161dbSMark Fasheh 
2837f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
2838f4414602SMark Fasheh 
2839f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
2840f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
2841e0bd70c6SFilipe Manana 		ASSERT(PageLocked(src_page));
2842e0bd70c6SFilipe Manana 		ASSERT(PageLocked(dst_page));
2843f4414602SMark Fasheh 
2844416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
2845416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
2846416161dbSMark Fasheh 
2847416161dbSMark Fasheh 		flush_dcache_page(src_page);
2848416161dbSMark Fasheh 		flush_dcache_page(dst_page);
2849416161dbSMark Fasheh 
2850416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
28512b3909f8SDarrick J. Wong 			ret = -EBADE;
2852416161dbSMark Fasheh 
2853416161dbSMark Fasheh 		kunmap_atomic(addr);
2854416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
2855416161dbSMark Fasheh 
2856416161dbSMark Fasheh 		if (ret)
2857416161dbSMark Fasheh 			break;
2858416161dbSMark Fasheh 
2859416161dbSMark Fasheh 		len -= cmp_len;
2860f4414602SMark Fasheh 		i++;
2861416161dbSMark Fasheh 	}
2862416161dbSMark Fasheh 
2863416161dbSMark Fasheh 	return ret;
2864416161dbSMark Fasheh }
2865416161dbSMark Fasheh 
2866e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
2867e1d227a4SMark Fasheh 				     u64 olen)
2868416161dbSMark Fasheh {
2869e1d227a4SMark Fasheh 	u64 len = *plen;
2870416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2871416161dbSMark Fasheh 
2872e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
2873416161dbSMark Fasheh 		return -EINVAL;
2874e1d227a4SMark Fasheh 
2875e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
2876e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
2877e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
2878e1d227a4SMark Fasheh 
2879416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
2880416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2881416161dbSMark Fasheh 		return -EINVAL;
2882416161dbSMark Fasheh 
2883416161dbSMark Fasheh 	return 0;
2884416161dbSMark Fasheh }
2885416161dbSMark Fasheh 
2886e1d227a4SMark Fasheh static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
2887416161dbSMark Fasheh 			     struct inode *dst, u64 dst_loff)
2888416161dbSMark Fasheh {
2889416161dbSMark Fasheh 	int ret;
2890e1d227a4SMark Fasheh 	u64 len = olen;
2891f4414602SMark Fasheh 	struct cmp_pages cmp;
2892fc4badd9SOmar Sandoval 	bool same_inode = (src == dst);
28930efa9f48SMark Fasheh 	u64 same_lock_start = 0;
28940efa9f48SMark Fasheh 	u64 same_lock_len = 0;
2895416161dbSMark Fasheh 
2896113e8283SFilipe Manana 	if (len == 0)
2897113e8283SFilipe Manana 		return 0;
2898113e8283SFilipe Manana 
2899fc4badd9SOmar Sandoval 	if (same_inode)
29005955102cSAl Viro 		inode_lock(src);
2901fc4badd9SOmar Sandoval 	else
2902fc4badd9SOmar Sandoval 		btrfs_double_inode_lock(src, dst);
29030efa9f48SMark Fasheh 
29040efa9f48SMark Fasheh 	ret = extent_same_check_offsets(src, loff, &len, olen);
29050efa9f48SMark Fasheh 	if (ret)
29060efa9f48SMark Fasheh 		goto out_unlock;
2907fc4badd9SOmar Sandoval 
2908fc4badd9SOmar Sandoval 	ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
2909f4dfe687SFilipe Manana 	if (ret)
2910f4dfe687SFilipe Manana 		goto out_unlock;
29110efa9f48SMark Fasheh 
2912fc4badd9SOmar Sandoval 	if (same_inode) {
29130efa9f48SMark Fasheh 		/*
29140efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
29150efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
29160efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
29170efa9f48SMark Fasheh 		 *
29180efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
29190efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
29200efa9f48SMark Fasheh 		 * reject the request.
29210efa9f48SMark Fasheh 		 *
29220efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
29230efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
29240efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
29250efa9f48SMark Fasheh 		 * i_size.
29260efa9f48SMark Fasheh 		 */
29270efa9f48SMark Fasheh 		if (len != olen) {
29280efa9f48SMark Fasheh 			ret = -EINVAL;
29290efa9f48SMark Fasheh 			goto out_unlock;
29300efa9f48SMark Fasheh 		}
29310efa9f48SMark Fasheh 
29320efa9f48SMark Fasheh 		/* Check for overlapping ranges */
29330efa9f48SMark Fasheh 		if (dst_loff + len > loff && dst_loff < loff + len) {
29340efa9f48SMark Fasheh 			ret = -EINVAL;
29350efa9f48SMark Fasheh 			goto out_unlock;
29360efa9f48SMark Fasheh 		}
29370efa9f48SMark Fasheh 
29380efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
29390efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
29400efa9f48SMark Fasheh 	}
2941416161dbSMark Fasheh 
2942416161dbSMark Fasheh 	/* don't make the dst file partly checksummed */
2943416161dbSMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2944416161dbSMark Fasheh 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
2945416161dbSMark Fasheh 		ret = -EINVAL;
2946416161dbSMark Fasheh 		goto out_unlock;
2947416161dbSMark Fasheh 	}
2948416161dbSMark Fasheh 
2949e0bd70c6SFilipe Manana again:
2950f4414602SMark Fasheh 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
2951f4414602SMark Fasheh 	if (ret)
2952f4414602SMark Fasheh 		goto out_unlock;
2953f4414602SMark Fasheh 
29540efa9f48SMark Fasheh 	if (same_inode)
2955e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, same_lock_start, same_lock_len,
2956e0bd70c6SFilipe Manana 					false);
29570efa9f48SMark Fasheh 	else
2958e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
2959e0bd70c6SFilipe Manana 					       false);
2960e0bd70c6SFilipe Manana 	/*
2961e0bd70c6SFilipe Manana 	 * If one of the inodes has dirty pages in the respective range or
2962e0bd70c6SFilipe Manana 	 * ordered extents, we need to flush dellaloc and wait for all ordered
2963e0bd70c6SFilipe Manana 	 * extents in the range. We must unlock the pages and the ranges in the
2964e0bd70c6SFilipe Manana 	 * io trees to avoid deadlocks when flushing delalloc (requires locking
2965e0bd70c6SFilipe Manana 	 * pages) and when waiting for ordered extents to complete (they require
2966e0bd70c6SFilipe Manana 	 * range locking).
2967e0bd70c6SFilipe Manana 	 */
2968e0bd70c6SFilipe Manana 	if (ret == -EAGAIN) {
2969e0bd70c6SFilipe Manana 		/*
2970e0bd70c6SFilipe Manana 		 * Ranges in the io trees already unlocked. Now unlock all
2971e0bd70c6SFilipe Manana 		 * pages before waiting for all IO to complete.
2972e0bd70c6SFilipe Manana 		 */
2973e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
2974e0bd70c6SFilipe Manana 		if (same_inode) {
2975e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, same_lock_start,
2976e0bd70c6SFilipe Manana 						 same_lock_len);
2977e0bd70c6SFilipe Manana 		} else {
2978e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, loff, len);
2979e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(dst, dst_loff, len);
2980e0bd70c6SFilipe Manana 		}
2981e0bd70c6SFilipe Manana 		goto again;
2982e0bd70c6SFilipe Manana 	}
2983e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
2984e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
2985e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
2986e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
2987e0bd70c6SFilipe Manana 		return ret;
2988e0bd70c6SFilipe Manana 	}
2989f4414602SMark Fasheh 
2990207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
29911a287cfeSDavid Sterba 	ret = btrfs_cmp_data(olen, &cmp);
2992416161dbSMark Fasheh 	if (ret == 0)
29931c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
2994416161dbSMark Fasheh 
29950efa9f48SMark Fasheh 	if (same_inode)
29960efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
29970efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
29980efa9f48SMark Fasheh 	else
2999f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3000f4414602SMark Fasheh 
3001f4414602SMark Fasheh 	btrfs_cmp_data_free(&cmp);
3002416161dbSMark Fasheh out_unlock:
30030efa9f48SMark Fasheh 	if (same_inode)
30045955102cSAl Viro 		inode_unlock(src);
30050efa9f48SMark Fasheh 	else
3006f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3007416161dbSMark Fasheh 
3008416161dbSMark Fasheh 	return ret;
3009416161dbSMark Fasheh }
3010416161dbSMark Fasheh 
3011ee22184bSByongho Lee #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3012416161dbSMark Fasheh 
30132b3909f8SDarrick J. Wong ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
30142b3909f8SDarrick J. Wong 				struct file *dst_file, u64 dst_loff)
3015416161dbSMark Fasheh {
30162b3909f8SDarrick J. Wong 	struct inode *src = file_inode(src_file);
30172b3909f8SDarrick J. Wong 	struct inode *dst = file_inode(dst_file);
3018416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
30192b3909f8SDarrick J. Wong 	ssize_t res;
3020416161dbSMark Fasheh 
30212b3909f8SDarrick J. Wong 	if (olen > BTRFS_MAX_DEDUPE_LEN)
30222b3909f8SDarrick J. Wong 		olen = BTRFS_MAX_DEDUPE_LEN;
3023416161dbSMark Fasheh 
302409cbfeafSKirill A. Shutemov 	if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3025416161dbSMark Fasheh 		/*
3026416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3027416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3028416161dbSMark Fasheh 		 * this situation without an update.
3029416161dbSMark Fasheh 		 */
30302b3909f8SDarrick J. Wong 		return -EINVAL;
3031416161dbSMark Fasheh 	}
3032416161dbSMark Fasheh 
30332b3909f8SDarrick J. Wong 	res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
30342b3909f8SDarrick J. Wong 	if (res)
30352b3909f8SDarrick J. Wong 		return res;
30362b3909f8SDarrick J. Wong 	return olen;
3037416161dbSMark Fasheh }
3038416161dbSMark Fasheh 
3039f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3040f82a9901SFilipe Manana 				     struct inode *inode,
3041f82a9901SFilipe Manana 				     u64 endoff,
3042f82a9901SFilipe Manana 				     const u64 destoff,
30431c919a5eSMark Fasheh 				     const u64 olen,
30441c919a5eSMark Fasheh 				     int no_time_update)
3045f82a9901SFilipe Manana {
3046f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3047f82a9901SFilipe Manana 	int ret;
3048f82a9901SFilipe Manana 
3049f82a9901SFilipe Manana 	inode_inc_iversion(inode);
30501c919a5eSMark Fasheh 	if (!no_time_update)
3051c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3052f82a9901SFilipe Manana 	/*
3053f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3054f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3055f82a9901SFilipe Manana 	 */
3056f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3057f82a9901SFilipe Manana 		endoff = destoff + olen;
3058f82a9901SFilipe Manana 	if (endoff > inode->i_size)
30596ef06d27SNikolay Borisov 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3060f82a9901SFilipe Manana 
3061f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3062f82a9901SFilipe Manana 	if (ret) {
306366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
30643a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3065f82a9901SFilipe Manana 		goto out;
3066f82a9901SFilipe Manana 	}
30673a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
3068f82a9901SFilipe Manana out:
3069f82a9901SFilipe Manana 	return ret;
3070f82a9901SFilipe Manana }
3071f82a9901SFilipe Manana 
3072a2f392e4SNikolay Borisov static void clone_update_extent_map(struct btrfs_inode *inode,
30737ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
30747ffbb598SFilipe Manana 				    const struct btrfs_path *path,
30757ffbb598SFilipe Manana 				    const u64 hole_offset,
30767ffbb598SFilipe Manana 				    const u64 hole_len)
30777ffbb598SFilipe Manana {
3078a2f392e4SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
30797ffbb598SFilipe Manana 	struct extent_map *em;
30807ffbb598SFilipe Manana 	int ret;
30817ffbb598SFilipe Manana 
30827ffbb598SFilipe Manana 	em = alloc_extent_map();
30837ffbb598SFilipe Manana 	if (!em) {
3084a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
30857ffbb598SFilipe Manana 		return;
30867ffbb598SFilipe Manana 	}
30877ffbb598SFilipe Manana 
308814f59796SFilipe Manana 	if (path) {
308914f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
309014f59796SFilipe Manana 
309114f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
309214f59796SFilipe Manana 				    struct btrfs_file_extent_item);
3093a2f392e4SNikolay Borisov 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
30947ffbb598SFilipe Manana 		em->generation = -1;
30957ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
30967ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
30977ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3098a2f392e4SNikolay Borisov 					&inode->runtime_flags);
30997ffbb598SFilipe Manana 	} else {
31007ffbb598SFilipe Manana 		em->start = hole_offset;
31017ffbb598SFilipe Manana 		em->len = hole_len;
31027ffbb598SFilipe Manana 		em->ram_bytes = em->len;
31037ffbb598SFilipe Manana 		em->orig_start = hole_offset;
31047ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
31057ffbb598SFilipe Manana 		em->block_len = 0;
31067ffbb598SFilipe Manana 		em->orig_block_len = 0;
31077ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
31087ffbb598SFilipe Manana 		em->generation = trans->transid;
31097ffbb598SFilipe Manana 	}
31107ffbb598SFilipe Manana 
31117ffbb598SFilipe Manana 	while (1) {
31127ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
31137ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
31147ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
31157ffbb598SFilipe Manana 		if (ret != -EEXIST) {
31167ffbb598SFilipe Manana 			free_extent_map(em);
31177ffbb598SFilipe Manana 			break;
31187ffbb598SFilipe Manana 		}
3119a2f392e4SNikolay Borisov 		btrfs_drop_extent_cache(inode, em->start,
31207ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
31217ffbb598SFilipe Manana 	}
31227ffbb598SFilipe Manana 
3123ee39b432SDavid Sterba 	if (ret)
3124a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
31257ffbb598SFilipe Manana }
31267ffbb598SFilipe Manana 
31278039d87dSFilipe Manana /*
31288039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
31298039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
31308039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
31318039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
31328039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
31338039d87dSFilipe Manana  *
31348039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
31358039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
31368039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
31378039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
31388039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
31398039d87dSFilipe Manana  * i_mutex, which we are holding here).
31408039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
31418039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
31428039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
31438039d87dSFilipe Manana  *
31448039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
31458039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
31468039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
31478039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
31488039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
31498039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
31508039d87dSFilipe Manana  * the former.
31518039d87dSFilipe Manana  */
31524a0ab9d7SDavid Sterba static int clone_copy_inline_extent(struct inode *dst,
31538039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
31548039d87dSFilipe Manana 				    struct btrfs_path *path,
31558039d87dSFilipe Manana 				    struct btrfs_key *new_key,
31568039d87dSFilipe Manana 				    const u64 drop_start,
31578039d87dSFilipe Manana 				    const u64 datal,
31588039d87dSFilipe Manana 				    const u64 skip,
31598039d87dSFilipe Manana 				    const u64 size,
31608039d87dSFilipe Manana 				    char *inline_data)
31618039d87dSFilipe Manana {
31620b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
31638039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
31648039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
31650b246afaSJeff Mahoney 				      fs_info->sectorsize);
31668039d87dSFilipe Manana 	int ret;
31678039d87dSFilipe Manana 	struct btrfs_key key;
31688039d87dSFilipe Manana 
31698039d87dSFilipe Manana 	if (new_key->offset > 0)
31708039d87dSFilipe Manana 		return -EOPNOTSUPP;
31718039d87dSFilipe Manana 
31724a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(dst));
31738039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
31748039d87dSFilipe Manana 	key.offset = 0;
31758039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
31768039d87dSFilipe Manana 	if (ret < 0) {
31778039d87dSFilipe Manana 		return ret;
31788039d87dSFilipe Manana 	} else if (ret > 0) {
31798039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
31808039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
31818039d87dSFilipe Manana 			if (ret < 0)
31828039d87dSFilipe Manana 				return ret;
31838039d87dSFilipe Manana 			else if (ret > 0)
31848039d87dSFilipe Manana 				goto copy_inline_extent;
31858039d87dSFilipe Manana 		}
31868039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
31874a0cc7caSNikolay Borisov 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
31888039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
31898039d87dSFilipe Manana 			ASSERT(key.offset > 0);
31908039d87dSFilipe Manana 			return -EOPNOTSUPP;
31918039d87dSFilipe Manana 		}
31928039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
31938039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
31948039d87dSFilipe Manana 		u64 ext_len;
31958039d87dSFilipe Manana 
31968039d87dSFilipe Manana 		/*
31978039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
31988039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
31998039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
32008039d87dSFilipe Manana 		 */
32018039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
32028039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
32038039d87dSFilipe Manana 		/*
32048039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
32058039d87dSFilipe Manana 		 * following it.
32068039d87dSFilipe Manana 		 */
32078039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
32088039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
32098039d87dSFilipe Manana 			goto copy_inline_extent;
32108039d87dSFilipe Manana 
32118039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
32128039d87dSFilipe Manana 		if (ext_len > aligned_end)
32138039d87dSFilipe Manana 			return -EOPNOTSUPP;
32148039d87dSFilipe Manana 
32158039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
32168039d87dSFilipe Manana 		if (ret < 0) {
32178039d87dSFilipe Manana 			return ret;
32188039d87dSFilipe Manana 		} else if (ret == 0) {
32198039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
32208039d87dSFilipe Manana 					      path->slots[0]);
32214a0cc7caSNikolay Borisov 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
32228039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
32238039d87dSFilipe Manana 				return -EOPNOTSUPP;
32248039d87dSFilipe Manana 		}
32258039d87dSFilipe Manana 	}
32268039d87dSFilipe Manana 
32278039d87dSFilipe Manana copy_inline_extent:
32288039d87dSFilipe Manana 	/*
32298039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
32308039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
32318039d87dSFilipe Manana 	 */
32328039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
32338039d87dSFilipe Manana 		/*
32348039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
32358039d87dSFilipe Manana 		 * This would require copying the data from the source inline
32368039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
32378039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
32388039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
32398039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
32408039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
32418039d87dSFilipe Manana 		 * inline extent).
32428039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
32438039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
32448039d87dSFilipe Manana 		 */
32458039d87dSFilipe Manana 		return -EOPNOTSUPP;
32468039d87dSFilipe Manana 	}
32478039d87dSFilipe Manana 
32488039d87dSFilipe Manana 	btrfs_release_path(path);
32498039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
32508039d87dSFilipe Manana 	if (ret)
32518039d87dSFilipe Manana 		return ret;
32528039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
32538039d87dSFilipe Manana 	if (ret)
32548039d87dSFilipe Manana 		return ret;
32558039d87dSFilipe Manana 
32568039d87dSFilipe Manana 	if (skip) {
32578039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
32588039d87dSFilipe Manana 
32598039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
32608039d87dSFilipe Manana 	}
32618039d87dSFilipe Manana 
32628039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
32638039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
32648039d87dSFilipe Manana 						  path->slots[0]),
32658039d87dSFilipe Manana 			    size);
32668039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
32678039d87dSFilipe Manana 
32688039d87dSFilipe Manana 	return 0;
32698039d87dSFilipe Manana }
32708039d87dSFilipe Manana 
327132b7c687SMark Fasheh /**
327232b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
327332b7c687SMark Fasheh  *
327432b7c687SMark Fasheh  * @src: Inode to clone from
327532b7c687SMark Fasheh  * @inode: Inode to clone to
327632b7c687SMark Fasheh  * @off: Offset within source to start clone from
327732b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
32781c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
327932b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
32801c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
328132b7c687SMark Fasheh  */
328232b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3283f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
32841c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3285f46b5a66SChristoph Hellwig {
32860b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3287f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
328832b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3289f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
329032b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
329132b7c687SMark Fasheh 	char *buf = NULL;
3292ae01a0abSYan Zheng 	struct btrfs_key key;
3293f46b5a66SChristoph Hellwig 	u32 nritems;
3294f46b5a66SChristoph Hellwig 	int slot;
3295ae01a0abSYan Zheng 	int ret;
3296f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3297f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3298ae01a0abSYan Zheng 
3299ae01a0abSYan Zheng 	ret = -ENOMEM;
3300752ade68SMichal Hocko 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3301ae01a0abSYan Zheng 	if (!buf)
330232b7c687SMark Fasheh 		return ret;
3303ae01a0abSYan Zheng 
3304ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3305ae01a0abSYan Zheng 	if (!path) {
330615351955SDavid Sterba 		kvfree(buf);
330732b7c687SMark Fasheh 		return ret;
3308ae01a0abSYan Zheng 	}
330932b7c687SMark Fasheh 
3310e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3311c5c9cd4dSSage Weil 	/* clone data */
33124a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(src));
3313ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
33142c463823SFilipe Manana 	key.offset = off;
3315f46b5a66SChristoph Hellwig 
3316f46b5a66SChristoph Hellwig 	while (1) {
3317de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3318df858e76SFilipe Manana 
3319f46b5a66SChristoph Hellwig 		/*
3320f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3321f46b5a66SChristoph Hellwig 		 * tree.
3322f46b5a66SChristoph Hellwig 		 */
3323e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3324362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3325362a20c5SDavid Sterba 				0, 0);
3326f46b5a66SChristoph Hellwig 		if (ret < 0)
3327f46b5a66SChristoph Hellwig 			goto out;
33282c463823SFilipe Manana 		/*
33292c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
33302c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
33312c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
33322c463823SFilipe Manana 		 */
33332c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
33342c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
33352c463823SFilipe Manana 					      path->slots[0] - 1);
33362c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
33372c463823SFilipe Manana 				path->slots[0]--;
33382c463823SFilipe Manana 		}
3339f46b5a66SChristoph Hellwig 
3340ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3341e4355f34SFilipe David Borba Manana process_slot:
3342ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3343362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3344f46b5a66SChristoph Hellwig 			if (ret < 0)
3345f46b5a66SChristoph Hellwig 				goto out;
3346f46b5a66SChristoph Hellwig 			if (ret > 0)
3347f46b5a66SChristoph Hellwig 				break;
3348ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3349f46b5a66SChristoph Hellwig 		}
3350f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3351f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3352f46b5a66SChristoph Hellwig 
3353ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3354962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
33554a0cc7caSNikolay Borisov 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3356f46b5a66SChristoph Hellwig 			break;
3357f46b5a66SChristoph Hellwig 
3358962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3359c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3360c5c9cd4dSSage Weil 			int type;
336131840ae1SZheng Yan 			u32 size;
336231840ae1SZheng Yan 			struct btrfs_key new_key;
3363c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3364c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3365c5c9cd4dSSage Weil 			u8 comp;
3366f82a9901SFilipe Manana 			u64 drop_start;
336731840ae1SZheng Yan 
3368c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3369c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3370c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3371c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3372c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3373c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3374d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3375d397712bSChris Mason 								      extent);
3376d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3377d397712bSChris Mason 								 extent);
3378c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3379d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3380d397712bSChris Mason 								    extent);
3381c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3382c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3383c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3384c5c9cd4dSSage Weil 								    extent);
3385c5c9cd4dSSage Weil 			}
338631840ae1SZheng Yan 
33872c463823SFilipe Manana 			/*
33882c463823SFilipe Manana 			 * The first search might have left us at an extent
33892c463823SFilipe Manana 			 * item that ends before our target range's start, can
33902c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
33912c463823SFilipe Manana 			 */
33922c463823SFilipe Manana 			if (key.offset + datal <= off) {
3393e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3394e4355f34SFilipe David Borba Manana 				goto process_slot;
33952c463823SFilipe Manana 			} else if (key.offset >= off + len) {
33962c463823SFilipe Manana 				break;
3397e4355f34SFilipe David Borba Manana 			}
3398df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3399e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3400e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3401e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3402e4355f34SFilipe David Borba Manana 					   size);
3403e4355f34SFilipe David Borba Manana 
3404e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3405e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3406c5c9cd4dSSage Weil 
340731840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
34084a0cc7caSNikolay Borisov 			new_key.objectid = btrfs_ino(BTRFS_I(inode));
34094d728ec7SLi Zefan 			if (off <= key.offset)
3410c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
34114d728ec7SLi Zefan 			else
34124d728ec7SLi Zefan 				new_key.offset = destoff;
3413c5c9cd4dSSage Weil 
3414b6f3409bSSage Weil 			/*
3415f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3416f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3417f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3418f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3419f82a9901SFilipe Manana 			 * partially overlaps it).
3420f82a9901SFilipe Manana 			 */
3421f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3422f82a9901SFilipe Manana 				drop_start = last_dest_end;
3423f82a9901SFilipe Manana 			else
3424f82a9901SFilipe Manana 				drop_start = new_key.offset;
3425f82a9901SFilipe Manana 
3426f82a9901SFilipe Manana 			/*
3427b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3428b6f3409bSSage Weil 			 * 1 - add new extent
3429b6f3409bSSage Weil 			 * 1 - inode update
3430b6f3409bSSage Weil 			 */
3431b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3432a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3433a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3434a22285a6SYan, Zheng 				goto out;
3435a22285a6SYan, Zheng 			}
3436a22285a6SYan, Zheng 
3437c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3438c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3439d72c0842SLi Zefan 				/*
3440d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3441d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3442d72c0842SLi Zefan 				 */
3443d72c0842SLi Zefan 
344493915584SAntonio Ospite 				/* subtract range b */
3445d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3446d72c0842SLi Zefan 					datal = off + len - key.offset;
3447d72c0842SLi Zefan 
344893915584SAntonio Ospite 				/* subtract range a */
3449a22285a6SYan, Zheng 				if (off > key.offset) {
3450a22285a6SYan, Zheng 					datao += off - key.offset;
3451a22285a6SYan, Zheng 					datal -= off - key.offset;
3452a22285a6SYan, Zheng 				}
3453a22285a6SYan, Zheng 
34545dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3455f82a9901SFilipe Manana 							 drop_start,
3456a22285a6SYan, Zheng 							 new_key.offset + datal,
34572671485dSJosef Bacik 							 1);
345879787eaaSJeff Mahoney 				if (ret) {
34593f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
346000fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
346166642832SJeff Mahoney 									ret);
34623a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
346379787eaaSJeff Mahoney 					goto out;
346479787eaaSJeff Mahoney 				}
3465a22285a6SYan, Zheng 
346631840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
346731840ae1SZheng Yan 							      &new_key, size);
346879787eaaSJeff Mahoney 				if (ret) {
346966642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
34703a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
347179787eaaSJeff Mahoney 					goto out;
347279787eaaSJeff Mahoney 				}
347331840ae1SZheng Yan 
347431840ae1SZheng Yan 				leaf = path->nodes[0];
347531840ae1SZheng Yan 				slot = path->slots[0];
347631840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
347731840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
347831840ae1SZheng Yan 					    size);
3479ae01a0abSYan Zheng 
3480f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3481f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3482c5c9cd4dSSage Weil 
3483c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3484c5c9cd4dSSage Weil 				if (!disko)
3485c5c9cd4dSSage Weil 					datao = 0;
3486c5c9cd4dSSage Weil 
3487c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3488c5c9cd4dSSage Weil 							     datao);
3489c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3490c5c9cd4dSSage Weil 								datal);
3491fcebe456SJosef Bacik 
3492c5c9cd4dSSage Weil 				if (disko) {
3493c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
34942ff7e61eSJeff Mahoney 					ret = btrfs_inc_extent_ref(trans,
349584f7d8e6SJosef Bacik 							root,
34965d4f98a2SYan Zheng 							disko, diskl, 0,
3497f46b5a66SChristoph Hellwig 							root->root_key.objectid,
34984a0cc7caSNikolay Borisov 							btrfs_ino(BTRFS_I(inode)),
3499b06c4bf5SFilipe Manana 							new_key.offset - datao);
350079787eaaSJeff Mahoney 					if (ret) {
350179787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
350279787eaaSJeff Mahoney 									ret);
35033a45bb20SJeff Mahoney 						btrfs_end_transaction(trans);
350479787eaaSJeff Mahoney 						goto out;
350579787eaaSJeff Mahoney 
350679787eaaSJeff Mahoney 					}
3507f46b5a66SChristoph Hellwig 				}
3508c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3509c5c9cd4dSSage Weil 				u64 skip = 0;
3510c5c9cd4dSSage Weil 				u64 trim = 0;
3511ed958762SFilipe Manana 
3512c5c9cd4dSSage Weil 				if (off > key.offset) {
3513c5c9cd4dSSage Weil 					skip = off - key.offset;
3514c5c9cd4dSSage Weil 					new_key.offset += skip;
351531840ae1SZheng Yan 				}
3516d397712bSChris Mason 
3517c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3518c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3519d397712bSChris Mason 
3520c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3521c5c9cd4dSSage Weil 					ret = -EINVAL;
35223a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
3523c5c9cd4dSSage Weil 					goto out;
352431840ae1SZheng Yan 				}
3525c5c9cd4dSSage Weil 				size -= skip + trim;
3526c5c9cd4dSSage Weil 				datal -= skip + trim;
3527a22285a6SYan, Zheng 
35284a0ab9d7SDavid Sterba 				ret = clone_copy_inline_extent(inode,
35298039d87dSFilipe Manana 							       trans, path,
35308039d87dSFilipe Manana 							       &new_key,
3531f82a9901SFilipe Manana 							       drop_start,
35328039d87dSFilipe Manana 							       datal,
35338039d87dSFilipe Manana 							       skip, size, buf);
353479787eaaSJeff Mahoney 				if (ret) {
35353f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
35363a29bc09SChris Mason 						btrfs_abort_transaction(trans,
353779787eaaSJeff Mahoney 									ret);
35383a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
353979787eaaSJeff Mahoney 					goto out;
354079787eaaSJeff Mahoney 				}
3541c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3542c5c9cd4dSSage Weil 				slot = path->slots[0];
3543c5c9cd4dSSage Weil 			}
3544c5c9cd4dSSage Weil 
35457ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
35467ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
3547a2f392e4SNikolay Borisov 				clone_update_extent_map(BTRFS_I(inode), trans,
354814f59796SFilipe Manana 						NULL, drop_start,
35497ffbb598SFilipe Manana 						new_key.offset - drop_start);
35507ffbb598SFilipe Manana 
3551a2f392e4SNikolay Borisov 			clone_update_extent_map(BTRFS_I(inode), trans,
3552a2f392e4SNikolay Borisov 					path, 0, 0);
35537ffbb598SFilipe Manana 
3554c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3555b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3556c5c9cd4dSSage Weil 
355762e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
35580b246afaSJeff Mahoney 					      fs_info->sectorsize);
3559f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3560f82a9901SFilipe Manana 							last_dest_end,
35611c919a5eSMark Fasheh 							destoff, olen,
35621c919a5eSMark Fasheh 							no_time_update);
3563f82a9901SFilipe Manana 			if (ret)
356479787eaaSJeff Mahoney 				goto out;
35652c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
35662c463823SFilipe Manana 				break;
3567a22285a6SYan, Zheng 		}
3568b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3569df858e76SFilipe Manana 		key.offset = next_key_min_offset;
357069ae5e44SWang Xiaoguang 
357169ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
357269ae5e44SWang Xiaoguang 			ret = -EINTR;
357369ae5e44SWang Xiaoguang 			goto out;
357469ae5e44SWang Xiaoguang 		}
3575ae01a0abSYan Zheng 	}
3576f46b5a66SChristoph Hellwig 	ret = 0;
357732b7c687SMark Fasheh 
3578f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3579f82a9901SFilipe Manana 		/*
3580f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3581f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3582f82a9901SFilipe Manana 		 */
3583b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3584f82a9901SFilipe Manana 
3585f82a9901SFilipe Manana 		/*
3586f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3587f82a9901SFilipe Manana 		 * 1 - inode update
3588f82a9901SFilipe Manana 		 */
3589f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3590f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3591f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3592f82a9901SFilipe Manana 			goto out;
3593f82a9901SFilipe Manana 		}
3594f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3595f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3596f82a9901SFilipe Manana 		if (ret) {
3597f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
359866642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
35993a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
3600f82a9901SFilipe Manana 			goto out;
3601f82a9901SFilipe Manana 		}
3602a2f392e4SNikolay Borisov 		clone_update_extent_map(BTRFS_I(inode), trans, NULL,
3603a2f392e4SNikolay Borisov 				last_dest_end,
360414f59796SFilipe Manana 				destoff + len - last_dest_end);
3605f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
36061c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3607f82a9901SFilipe Manana 	}
3608f82a9901SFilipe Manana 
3609f46b5a66SChristoph Hellwig out:
361032b7c687SMark Fasheh 	btrfs_free_path(path);
361115351955SDavid Sterba 	kvfree(buf);
361232b7c687SMark Fasheh 	return ret;
361332b7c687SMark Fasheh }
361432b7c687SMark Fasheh 
36153db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
361632b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
361732b7c687SMark Fasheh {
361854563d41SAl Viro 	struct inode *inode = file_inode(file);
36193db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
36200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
362132b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
362232b7c687SMark Fasheh 	int ret;
362332b7c687SMark Fasheh 	u64 len = olen;
36240b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
36253db11b2eSZach Brown 	int same_inode = src == inode;
362632b7c687SMark Fasheh 
362732b7c687SMark Fasheh 	/*
362832b7c687SMark Fasheh 	 * TODO:
362932b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
363032b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
363132b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
363232b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
363300fdf13aSLiu Bo 	 *
363400fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
363500fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
363632b7c687SMark Fasheh 	 */
363732b7c687SMark Fasheh 
363832b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
363932b7c687SMark Fasheh 		return -EROFS;
364032b7c687SMark Fasheh 
36413db11b2eSZach Brown 	if (file_src->f_path.mnt != file->f_path.mnt ||
36423db11b2eSZach Brown 	    src->i_sb != inode->i_sb)
36433db11b2eSZach Brown 		return -EXDEV;
364432b7c687SMark Fasheh 
364532b7c687SMark Fasheh 	/* don't make the dst file partly checksummed */
364632b7c687SMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
364732b7c687SMark Fasheh 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
36483db11b2eSZach Brown 		return -EINVAL;
364932b7c687SMark Fasheh 
365032b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
36513db11b2eSZach Brown 		return -EISDIR;
365232b7c687SMark Fasheh 
365332b7c687SMark Fasheh 	if (!same_inode) {
3654293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
365532b7c687SMark Fasheh 	} else {
36565955102cSAl Viro 		inode_lock(src);
365732b7c687SMark Fasheh 	}
365832b7c687SMark Fasheh 
365932b7c687SMark Fasheh 	/* determine range to clone */
366032b7c687SMark Fasheh 	ret = -EINVAL;
366132b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
366232b7c687SMark Fasheh 		goto out_unlock;
366332b7c687SMark Fasheh 	if (len == 0)
366432b7c687SMark Fasheh 		olen = len = src->i_size - off;
366532b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
366632b7c687SMark Fasheh 	if (off + len == src->i_size)
366732b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
366832b7c687SMark Fasheh 
3669ccccf3d6SFilipe Manana 	if (len == 0) {
3670ccccf3d6SFilipe Manana 		ret = 0;
3671ccccf3d6SFilipe Manana 		goto out_unlock;
3672ccccf3d6SFilipe Manana 	}
3673ccccf3d6SFilipe Manana 
367432b7c687SMark Fasheh 	/* verify the end result is block aligned */
367532b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
367632b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
367732b7c687SMark Fasheh 		goto out_unlock;
367832b7c687SMark Fasheh 
367932b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
368032b7c687SMark Fasheh 	if (same_inode) {
368132b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
368232b7c687SMark Fasheh 			goto out_unlock;
368332b7c687SMark Fasheh 	}
368432b7c687SMark Fasheh 
368532b7c687SMark Fasheh 	if (destoff > inode->i_size) {
368632b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
368732b7c687SMark Fasheh 		if (ret)
368832b7c687SMark Fasheh 			goto out_unlock;
368932b7c687SMark Fasheh 	}
369032b7c687SMark Fasheh 
3691c125b8bfSFilipe Manana 	/*
3692c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
3693c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
3694c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
3695c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
3696c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
3697c125b8bfSFilipe Manana 	 */
3698c125b8bfSFilipe Manana 	if (same_inode) {
3699c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3700c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
370132b7c687SMark Fasheh 
3702e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, lock_start, lock_len, true);
3703c125b8bfSFilipe Manana 	} else {
3704e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
3705e0bd70c6SFilipe Manana 					       true);
3706e0bd70c6SFilipe Manana 	}
3707e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3708e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3709e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3710e0bd70c6SFilipe Manana 		goto out_unlock;
3711c125b8bfSFilipe Manana 	}
371232b7c687SMark Fasheh 
37131c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
371432b7c687SMark Fasheh 
3715c125b8bfSFilipe Manana 	if (same_inode) {
3716c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3717c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
3718c125b8bfSFilipe Manana 
3719c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3720c125b8bfSFilipe Manana 	} else {
3721293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
3722c125b8bfSFilipe Manana 	}
3723c125b8bfSFilipe Manana 	/*
3724c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3725c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3726c125b8bfSFilipe Manana 	 */
372765bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
372809cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
372909cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
3730f46b5a66SChristoph Hellwig out_unlock:
3731293a8489SMark Fasheh 	if (!same_inode)
3732293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
3733293a8489SMark Fasheh 	else
37345955102cSAl Viro 		inode_unlock(src);
37353db11b2eSZach Brown 	return ret;
37363db11b2eSZach Brown }
37373db11b2eSZach Brown 
373804b38d60SChristoph Hellwig int btrfs_clone_file_range(struct file *src_file, loff_t off,
373904b38d60SChristoph Hellwig 		struct file *dst_file, loff_t destoff, u64 len)
37403db11b2eSZach Brown {
374104b38d60SChristoph Hellwig 	return btrfs_clone_files(dst_file, src_file, off, len, destoff);
3742c5c9cd4dSSage Weil }
3743c5c9cd4dSSage Weil 
37446ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
37456ef5ed0dSJosef Bacik {
3746496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
37470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
37486ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
37496ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
37506ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
37516ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
37526ef5ed0dSJosef Bacik 	struct btrfs_path *path;
37536ef5ed0dSJosef Bacik 	struct btrfs_key location;
37546ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
37556ef5ed0dSJosef Bacik 	u64 objectid = 0;
37566ef5ed0dSJosef Bacik 	u64 dir_id;
37573c04ce01SMiao Xie 	int ret;
37586ef5ed0dSJosef Bacik 
37596ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
37606ef5ed0dSJosef Bacik 		return -EPERM;
37616ef5ed0dSJosef Bacik 
37623c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
37633c04ce01SMiao Xie 	if (ret)
37643c04ce01SMiao Xie 		return ret;
37653c04ce01SMiao Xie 
37663c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
37673c04ce01SMiao Xie 		ret = -EFAULT;
37683c04ce01SMiao Xie 		goto out;
37693c04ce01SMiao Xie 	}
37706ef5ed0dSJosef Bacik 
37716ef5ed0dSJosef Bacik 	if (!objectid)
37721cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
37736ef5ed0dSJosef Bacik 
37746ef5ed0dSJosef Bacik 	location.objectid = objectid;
37756ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
37766ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
37776ef5ed0dSJosef Bacik 
37780b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
37793c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
37803c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
37813c04ce01SMiao Xie 		goto out;
37823c04ce01SMiao Xie 	}
37836d6d2829Ssatoru takeuchi 	if (!is_fstree(new_root->objectid)) {
37846d6d2829Ssatoru takeuchi 		ret = -ENOENT;
37856d6d2829Ssatoru takeuchi 		goto out;
37866d6d2829Ssatoru takeuchi 	}
37876ef5ed0dSJosef Bacik 
37886ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
37893c04ce01SMiao Xie 	if (!path) {
37903c04ce01SMiao Xie 		ret = -ENOMEM;
37913c04ce01SMiao Xie 		goto out;
37923c04ce01SMiao Xie 	}
37936ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
37946ef5ed0dSJosef Bacik 
37956ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
379698d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
37976ef5ed0dSJosef Bacik 		btrfs_free_path(path);
37983c04ce01SMiao Xie 		ret = PTR_ERR(trans);
37993c04ce01SMiao Xie 		goto out;
38006ef5ed0dSJosef Bacik 	}
38016ef5ed0dSJosef Bacik 
38020b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
38030b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
38046ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
3805cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
38066ef5ed0dSJosef Bacik 		btrfs_free_path(path);
38073a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
38080b246afaSJeff Mahoney 		btrfs_err(fs_info,
38095d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
38103c04ce01SMiao Xie 		ret = -ENOENT;
38113c04ce01SMiao Xie 		goto out;
38126ef5ed0dSJosef Bacik 	}
38136ef5ed0dSJosef Bacik 
38146ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
38156ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
38166ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
38176ef5ed0dSJosef Bacik 	btrfs_free_path(path);
38186ef5ed0dSJosef Bacik 
38190b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
38203a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
38213c04ce01SMiao Xie out:
38223c04ce01SMiao Xie 	mnt_drop_write_file(file);
38233c04ce01SMiao Xie 	return ret;
38246ef5ed0dSJosef Bacik }
38256ef5ed0dSJosef Bacik 
3826c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
3827bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
3828bf5fc093SJosef Bacik {
3829bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
3830bf5fc093SJosef Bacik 
3831bf5fc093SJosef Bacik 	space->total_bytes = 0;
3832bf5fc093SJosef Bacik 	space->used_bytes = 0;
3833bf5fc093SJosef Bacik 	space->flags = 0;
3834bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
3835bf5fc093SJosef Bacik 		space->flags = block_group->flags;
3836bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
3837bf5fc093SJosef Bacik 		space->used_bytes +=
3838bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
3839bf5fc093SJosef Bacik 	}
3840bf5fc093SJosef Bacik }
3841bf5fc093SJosef Bacik 
38422ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
38432ff7e61eSJeff Mahoney 				   void __user *arg)
38441406e432SJosef Bacik {
38451406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
38461406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
38471406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
38487fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
384913f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
38501406e432SJosef Bacik 	struct btrfs_space_info *info;
3851315d8e98SColin Ian King 	static const u64 types[] = {
3852315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
3853bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
3854bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
3855315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3856315d8e98SColin Ian King 	};
3857bf5fc093SJosef Bacik 	int num_types = 4;
38587fde62bfSChris Mason 	int alloc_size;
38591406e432SJosef Bacik 	int ret = 0;
386051788b1bSDan Rosenberg 	u64 slot_count = 0;
3861bf5fc093SJosef Bacik 	int i, c;
38621406e432SJosef Bacik 
38631406e432SJosef Bacik 	if (copy_from_user(&space_args,
38641406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
38651406e432SJosef Bacik 			   sizeof(space_args)))
38661406e432SJosef Bacik 		return -EFAULT;
38671406e432SJosef Bacik 
3868bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
3869bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
3870bf5fc093SJosef Bacik 
3871bf5fc093SJosef Bacik 		info = NULL;
38727fde62bfSChris Mason 		rcu_read_lock();
38730b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
3874bf5fc093SJosef Bacik 					list) {
3875bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
3876bf5fc093SJosef Bacik 				info = tmp;
3877bf5fc093SJosef Bacik 				break;
3878bf5fc093SJosef Bacik 			}
3879bf5fc093SJosef Bacik 		}
38807fde62bfSChris Mason 		rcu_read_unlock();
38811406e432SJosef Bacik 
3882bf5fc093SJosef Bacik 		if (!info)
3883bf5fc093SJosef Bacik 			continue;
3884bf5fc093SJosef Bacik 
3885bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
3886bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3887bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
3888bf5fc093SJosef Bacik 				slot_count++;
3889bf5fc093SJosef Bacik 		}
3890bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
3891bf5fc093SJosef Bacik 	}
3892bf5fc093SJosef Bacik 
389336523e95SDavid Sterba 	/*
389436523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
389536523e95SDavid Sterba 	 */
389636523e95SDavid Sterba 	slot_count++;
389736523e95SDavid Sterba 
38987fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
38997fde62bfSChris Mason 	if (space_args.space_slots == 0) {
39007fde62bfSChris Mason 		space_args.total_spaces = slot_count;
39017fde62bfSChris Mason 		goto out;
39027fde62bfSChris Mason 	}
3903bf5fc093SJosef Bacik 
390451788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
3905bf5fc093SJosef Bacik 
39067fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
3907bf5fc093SJosef Bacik 
39087fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
39097fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
39107fde62bfSChris Mason 	 */
391109cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
39127fde62bfSChris Mason 		return -ENOMEM;
39137fde62bfSChris Mason 
39147fde62bfSChris Mason 	space_args.total_spaces = 0;
39158d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
39167fde62bfSChris Mason 	if (!dest)
39177fde62bfSChris Mason 		return -ENOMEM;
39187fde62bfSChris Mason 	dest_orig = dest;
39197fde62bfSChris Mason 
39207fde62bfSChris Mason 	/* now we have a buffer to copy into */
3921bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
3922bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
3923bf5fc093SJosef Bacik 
392451788b1bSDan Rosenberg 		if (!slot_count)
392551788b1bSDan Rosenberg 			break;
392651788b1bSDan Rosenberg 
3927bf5fc093SJosef Bacik 		info = NULL;
39281406e432SJosef Bacik 		rcu_read_lock();
39290b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
3930bf5fc093SJosef Bacik 					list) {
3931bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
3932bf5fc093SJosef Bacik 				info = tmp;
39337fde62bfSChris Mason 				break;
3934bf5fc093SJosef Bacik 			}
3935bf5fc093SJosef Bacik 		}
3936bf5fc093SJosef Bacik 		rcu_read_unlock();
39377fde62bfSChris Mason 
3938bf5fc093SJosef Bacik 		if (!info)
3939bf5fc093SJosef Bacik 			continue;
3940bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
3941bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3942bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
3943c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
3944c065f5b1SSu Yue 						     &space);
39457fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
39461406e432SJosef Bacik 				dest++;
39471406e432SJosef Bacik 				space_args.total_spaces++;
394851788b1bSDan Rosenberg 				slot_count--;
39491406e432SJosef Bacik 			}
395051788b1bSDan Rosenberg 			if (!slot_count)
395151788b1bSDan Rosenberg 				break;
3952bf5fc093SJosef Bacik 		}
3953bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
3954bf5fc093SJosef Bacik 	}
39551406e432SJosef Bacik 
395636523e95SDavid Sterba 	/*
395736523e95SDavid Sterba 	 * Add global block reserve
395836523e95SDavid Sterba 	 */
395936523e95SDavid Sterba 	if (slot_count) {
39600b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
396136523e95SDavid Sterba 
396236523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
396336523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
396436523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
396536523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
396636523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
396736523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
396836523e95SDavid Sterba 		space_args.total_spaces++;
396936523e95SDavid Sterba 	}
397036523e95SDavid Sterba 
39712eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
39727fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
39737fde62bfSChris Mason 
39747fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
39757fde62bfSChris Mason 		ret = -EFAULT;
39767fde62bfSChris Mason 
39777fde62bfSChris Mason 	kfree(dest_orig);
39787fde62bfSChris Mason out:
39797fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
39801406e432SJosef Bacik 		ret = -EFAULT;
39811406e432SJosef Bacik 
39821406e432SJosef Bacik 	return ret;
39831406e432SJosef Bacik }
39841406e432SJosef Bacik 
39859a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
39869a8c28beSMiao Xie 					    void __user *argp)
398746204592SSage Weil {
398846204592SSage Weil 	struct btrfs_trans_handle *trans;
398946204592SSage Weil 	u64 transid;
3990db5b493aSTsutomu Itoh 	int ret;
399146204592SSage Weil 
3992d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
3993ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
3994ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
399598d5dc13STsutomu Itoh 			return PTR_ERR(trans);
3996ff7c1d33SMiao Xie 
3997ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
3998ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
3999ff7c1d33SMiao Xie 		goto out;
4000ff7c1d33SMiao Xie 	}
400146204592SSage Weil 	transid = trans->transid;
40023a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction_async(trans, 0);
40038b2b2d3cSTsutomu Itoh 	if (ret) {
40043a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
4005db5b493aSTsutomu Itoh 		return ret;
40068b2b2d3cSTsutomu Itoh 	}
4007ff7c1d33SMiao Xie out:
400846204592SSage Weil 	if (argp)
400946204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
401046204592SSage Weil 			return -EFAULT;
401146204592SSage Weil 	return 0;
401246204592SSage Weil }
401346204592SSage Weil 
40142ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
40159a8c28beSMiao Xie 					   void __user *argp)
401646204592SSage Weil {
401746204592SSage Weil 	u64 transid;
401846204592SSage Weil 
401946204592SSage Weil 	if (argp) {
402046204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
402146204592SSage Weil 			return -EFAULT;
402246204592SSage Weil 	} else {
402346204592SSage Weil 		transid = 0;  /* current trans */
402446204592SSage Weil 	}
40252ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
402646204592SSage Weil }
402746204592SSage Weil 
4028b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4029475f6387SJan Schmidt {
40300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4031475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4032b8e95489SMiao Xie 	int ret;
4033475f6387SJan Schmidt 
4034475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4035475f6387SJan Schmidt 		return -EPERM;
4036475f6387SJan Schmidt 
4037475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4038475f6387SJan Schmidt 	if (IS_ERR(sa))
4039475f6387SJan Schmidt 		return PTR_ERR(sa);
4040475f6387SJan Schmidt 
4041b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4042b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4043b8e95489SMiao Xie 		if (ret)
4044b8e95489SMiao Xie 			goto out;
4045b8e95489SMiao Xie 	}
4046b8e95489SMiao Xie 
40470b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
404863a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
404963a212abSStefan Behrens 			      0);
4050475f6387SJan Schmidt 
4051475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4052475f6387SJan Schmidt 		ret = -EFAULT;
4053475f6387SJan Schmidt 
4054b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4055b8e95489SMiao Xie 		mnt_drop_write_file(file);
4056b8e95489SMiao Xie out:
4057475f6387SJan Schmidt 	kfree(sa);
4058475f6387SJan Schmidt 	return ret;
4059475f6387SJan Schmidt }
4060475f6387SJan Schmidt 
40612ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4062475f6387SJan Schmidt {
4063475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4064475f6387SJan Schmidt 		return -EPERM;
4065475f6387SJan Schmidt 
40662ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4067475f6387SJan Schmidt }
4068475f6387SJan Schmidt 
40692ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4070475f6387SJan Schmidt 				       void __user *arg)
4071475f6387SJan Schmidt {
4072475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4073475f6387SJan Schmidt 	int ret;
4074475f6387SJan Schmidt 
4075475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4076475f6387SJan Schmidt 		return -EPERM;
4077475f6387SJan Schmidt 
4078475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4079475f6387SJan Schmidt 	if (IS_ERR(sa))
4080475f6387SJan Schmidt 		return PTR_ERR(sa);
4081475f6387SJan Schmidt 
40822ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4083475f6387SJan Schmidt 
4084475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4085475f6387SJan Schmidt 		ret = -EFAULT;
4086475f6387SJan Schmidt 
4087475f6387SJan Schmidt 	kfree(sa);
4088475f6387SJan Schmidt 	return ret;
4089475f6387SJan Schmidt }
4090475f6387SJan Schmidt 
40912ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4092b27f7c0cSDavid Sterba 				      void __user *arg)
4093c11d2c23SStefan Behrens {
4094c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4095c11d2c23SStefan Behrens 	int ret;
4096c11d2c23SStefan Behrens 
4097c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4098c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4099c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4100c11d2c23SStefan Behrens 
4101b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4102b27f7c0cSDavid Sterba 		kfree(sa);
4103b27f7c0cSDavid Sterba 		return -EPERM;
4104b27f7c0cSDavid Sterba 	}
4105b27f7c0cSDavid Sterba 
41062ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4107c11d2c23SStefan Behrens 
4108c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4109c11d2c23SStefan Behrens 		ret = -EFAULT;
4110c11d2c23SStefan Behrens 
4111c11d2c23SStefan Behrens 	kfree(sa);
4112c11d2c23SStefan Behrens 	return ret;
4113c11d2c23SStefan Behrens }
4114c11d2c23SStefan Behrens 
41152ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
41162ff7e61eSJeff Mahoney 				    void __user *arg)
41173f6bcfbdSStefan Behrens {
41183f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
41193f6bcfbdSStefan Behrens 	int ret;
41203f6bcfbdSStefan Behrens 
41213f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
41223f6bcfbdSStefan Behrens 		return -EPERM;
41233f6bcfbdSStefan Behrens 
41243f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
41253f6bcfbdSStefan Behrens 	if (IS_ERR(p))
41263f6bcfbdSStefan Behrens 		return PTR_ERR(p);
41273f6bcfbdSStefan Behrens 
41283f6bcfbdSStefan Behrens 	switch (p->cmd) {
41293f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4130bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
4131adfa97cbSIlya Dryomov 			ret = -EROFS;
4132adfa97cbSIlya Dryomov 			goto out;
4133adfa97cbSIlya Dryomov 		}
4134171938e5SDavid Sterba 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4135e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
41363f6bcfbdSStefan Behrens 		} else {
41372ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4138171938e5SDavid Sterba 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
41393f6bcfbdSStefan Behrens 		}
41403f6bcfbdSStefan Behrens 		break;
41413f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
41420b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
41433f6bcfbdSStefan Behrens 		ret = 0;
41443f6bcfbdSStefan Behrens 		break;
41453f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
414617d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
414797282031SAnand Jain 		ret = 0;
41483f6bcfbdSStefan Behrens 		break;
41493f6bcfbdSStefan Behrens 	default:
41503f6bcfbdSStefan Behrens 		ret = -EINVAL;
41513f6bcfbdSStefan Behrens 		break;
41523f6bcfbdSStefan Behrens 	}
41533f6bcfbdSStefan Behrens 
41543f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
41553f6bcfbdSStefan Behrens 		ret = -EFAULT;
4156adfa97cbSIlya Dryomov out:
41573f6bcfbdSStefan Behrens 	kfree(p);
41583f6bcfbdSStefan Behrens 	return ret;
41593f6bcfbdSStefan Behrens }
41603f6bcfbdSStefan Behrens 
4161d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4162d7728c96SJan Schmidt {
4163d7728c96SJan Schmidt 	int ret = 0;
4164d7728c96SJan Schmidt 	int i;
4165740c3d22SChris Mason 	u64 rel_ptr;
4166d7728c96SJan Schmidt 	int size;
4167806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4168d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4169d7728c96SJan Schmidt 	struct btrfs_path *path;
4170d7728c96SJan Schmidt 
417182b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4172d7728c96SJan Schmidt 		return -EPERM;
4173d7728c96SJan Schmidt 
4174d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4175d7728c96SJan Schmidt 	if (!path) {
4176d7728c96SJan Schmidt 		ret = -ENOMEM;
4177d7728c96SJan Schmidt 		goto out;
4178d7728c96SJan Schmidt 	}
4179d7728c96SJan Schmidt 
4180d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4181d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4182d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4183d7728c96SJan Schmidt 		ipa = NULL;
4184d7728c96SJan Schmidt 		goto out;
4185d7728c96SJan Schmidt 	}
4186d7728c96SJan Schmidt 
4187d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4188d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4189d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4190d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4191d7728c96SJan Schmidt 		ipath = NULL;
4192d7728c96SJan Schmidt 		goto out;
4193d7728c96SJan Schmidt 	}
4194d7728c96SJan Schmidt 
4195d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4196d7728c96SJan Schmidt 	if (ret < 0)
4197d7728c96SJan Schmidt 		goto out;
4198d7728c96SJan Schmidt 
4199d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4200745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4201745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4202740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4203d7728c96SJan Schmidt 	}
4204d7728c96SJan Schmidt 
4205718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4206718dc5faSOmar Sandoval 			   ipath->fspath, size);
4207d7728c96SJan Schmidt 	if (ret) {
4208d7728c96SJan Schmidt 		ret = -EFAULT;
4209d7728c96SJan Schmidt 		goto out;
4210d7728c96SJan Schmidt 	}
4211d7728c96SJan Schmidt 
4212d7728c96SJan Schmidt out:
4213d7728c96SJan Schmidt 	btrfs_free_path(path);
4214d7728c96SJan Schmidt 	free_ipath(ipath);
4215d7728c96SJan Schmidt 	kfree(ipa);
4216d7728c96SJan Schmidt 
4217d7728c96SJan Schmidt 	return ret;
4218d7728c96SJan Schmidt }
4219d7728c96SJan Schmidt 
4220d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4221d7728c96SJan Schmidt {
4222d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4223d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4224d7728c96SJan Schmidt 
4225d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4226d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4227d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4228d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4229d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4230d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4231d7728c96SJan Schmidt 	} else {
4232d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4233d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4234d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4235d7728c96SJan Schmidt 	}
4236d7728c96SJan Schmidt 
4237d7728c96SJan Schmidt 	return 0;
4238d7728c96SJan Schmidt }
4239d7728c96SJan Schmidt 
42402ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4241d24a67b2SZygo Blaxell 					void __user *arg, int version)
4242d7728c96SJan Schmidt {
4243d7728c96SJan Schmidt 	int ret = 0;
4244d7728c96SJan Schmidt 	int size;
4245d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4246d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4247d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4248d24a67b2SZygo Blaxell 	bool ignore_offset;
4249d7728c96SJan Schmidt 
4250d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4251d7728c96SJan Schmidt 		return -EPERM;
4252d7728c96SJan Schmidt 
4253d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
42547b9ea627SShailendra Verma 	if (IS_ERR(loi))
42557b9ea627SShailendra Verma 		return PTR_ERR(loi);
4256d7728c96SJan Schmidt 
4257d24a67b2SZygo Blaxell 	if (version == 1) {
4258d24a67b2SZygo Blaxell 		ignore_offset = false;
4259b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
4260d24a67b2SZygo Blaxell 	} else {
4261d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
4262d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4263d24a67b2SZygo Blaxell 			ret = -EINVAL;
4264d24a67b2SZygo Blaxell 			goto out_loi;
4265d24a67b2SZygo Blaxell 		}
4266d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
4267d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4268d24a67b2SZygo Blaxell 			ret = -EINVAL;
4269d24a67b2SZygo Blaxell 			goto out_loi;
4270d24a67b2SZygo Blaxell 		}
4271d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4272b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
4273d24a67b2SZygo Blaxell 	}
4274d24a67b2SZygo Blaxell 
4275d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4276d7728c96SJan Schmidt 	if (!path) {
4277d7728c96SJan Schmidt 		ret = -ENOMEM;
4278d7728c96SJan Schmidt 		goto out;
4279d7728c96SJan Schmidt 	}
4280d7728c96SJan Schmidt 
4281d7728c96SJan Schmidt 	inodes = init_data_container(size);
4282d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4283d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4284d7728c96SJan Schmidt 		inodes = NULL;
4285d7728c96SJan Schmidt 		goto out;
4286d7728c96SJan Schmidt 	}
4287d7728c96SJan Schmidt 
42882ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4289d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
4290df031f07SLiu Bo 	if (ret == -EINVAL)
4291d7728c96SJan Schmidt 		ret = -ENOENT;
4292d7728c96SJan Schmidt 	if (ret < 0)
4293d7728c96SJan Schmidt 		goto out;
4294d7728c96SJan Schmidt 
4295718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4296718dc5faSOmar Sandoval 			   size);
4297d7728c96SJan Schmidt 	if (ret)
4298d7728c96SJan Schmidt 		ret = -EFAULT;
4299d7728c96SJan Schmidt 
4300d7728c96SJan Schmidt out:
4301d7728c96SJan Schmidt 	btrfs_free_path(path);
4302f54de068SDavid Sterba 	kvfree(inodes);
4303d24a67b2SZygo Blaxell out_loi:
4304d7728c96SJan Schmidt 	kfree(loi);
4305d7728c96SJan Schmidt 
4306d7728c96SJan Schmidt 	return ret;
4307d7728c96SJan Schmidt }
4308d7728c96SJan Schmidt 
4309008ef096SDavid Sterba void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4310c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4311c9e9f97bSIlya Dryomov {
4312c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4313c9e9f97bSIlya Dryomov 
4314c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4315c9e9f97bSIlya Dryomov 
43163009a62fSDavid Sterba 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4317837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4318837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4319837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4320a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4321a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4322837d5b6eSIlya Dryomov 
4323c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4324c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4325c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
432619a39dceSIlya Dryomov 
432719a39dceSIlya Dryomov 	spin_lock(&fs_info->balance_lock);
432819a39dceSIlya Dryomov 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
432919a39dceSIlya Dryomov 	spin_unlock(&fs_info->balance_lock);
4330c9e9f97bSIlya Dryomov }
4331c9e9f97bSIlya Dryomov 
43329ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4333c9e9f97bSIlya Dryomov {
4334496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4335c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4336c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4337c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4338ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4339c9e9f97bSIlya Dryomov 	int ret;
4340c9e9f97bSIlya Dryomov 
4341c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4342c9e9f97bSIlya Dryomov 		return -EPERM;
4343c9e9f97bSIlya Dryomov 
4344e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
43459ba1f6e4SLiu Bo 	if (ret)
43469ba1f6e4SLiu Bo 		return ret;
43479ba1f6e4SLiu Bo 
4348ed0fb78fSIlya Dryomov again:
4349171938e5SDavid Sterba 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4350c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4351ed0fb78fSIlya Dryomov 		need_unlock = true;
4352ed0fb78fSIlya Dryomov 		goto locked;
4353ed0fb78fSIlya Dryomov 	}
4354ed0fb78fSIlya Dryomov 
4355ed0fb78fSIlya Dryomov 	/*
435601327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4357ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4358ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4359ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4360ed0fb78fSIlya Dryomov 	 */
4361ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4362ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4363ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
43643009a62fSDavid Sterba 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4365ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4366dccdb07bSDavid Sterba 			/*
4367dccdb07bSDavid Sterba 			 * Lock released to allow other waiters to continue,
4368dccdb07bSDavid Sterba 			 * we'll reexamine the status again.
4369dccdb07bSDavid Sterba 			 */
4370ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4371ed0fb78fSIlya Dryomov 
4372ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
43733009a62fSDavid Sterba 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4374ed0fb78fSIlya Dryomov 				/* this is (3) */
4375ed0fb78fSIlya Dryomov 				need_unlock = false;
4376ed0fb78fSIlya Dryomov 				goto locked;
4377ed0fb78fSIlya Dryomov 			}
4378ed0fb78fSIlya Dryomov 
4379ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4380ed0fb78fSIlya Dryomov 			goto again;
4381ed0fb78fSIlya Dryomov 		} else {
4382ed0fb78fSIlya Dryomov 			/* this is (2) */
4383ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4384ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4385ed0fb78fSIlya Dryomov 			goto out;
4386ed0fb78fSIlya Dryomov 		}
4387ed0fb78fSIlya Dryomov 	} else {
4388ed0fb78fSIlya Dryomov 		/* this is (1) */
4389ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4390e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4391ed0fb78fSIlya Dryomov 		goto out;
4392ed0fb78fSIlya Dryomov 	}
4393ed0fb78fSIlya Dryomov 
4394ed0fb78fSIlya Dryomov locked:
4395171938e5SDavid Sterba 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4396c9e9f97bSIlya Dryomov 
4397c9e9f97bSIlya Dryomov 	if (arg) {
4398c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4399c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4400c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4401ed0fb78fSIlya Dryomov 			goto out_unlock;
4402c9e9f97bSIlya Dryomov 		}
4403de322263SIlya Dryomov 
4404de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4405de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4406de322263SIlya Dryomov 				ret = -ENOTCONN;
4407de322263SIlya Dryomov 				goto out_bargs;
4408de322263SIlya Dryomov 			}
4409de322263SIlya Dryomov 
4410de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4411de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4412de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4413de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4414de322263SIlya Dryomov 
4415de322263SIlya Dryomov 			goto do_balance;
4416de322263SIlya Dryomov 		}
4417c9e9f97bSIlya Dryomov 	} else {
4418c9e9f97bSIlya Dryomov 		bargs = NULL;
4419c9e9f97bSIlya Dryomov 	}
4420c9e9f97bSIlya Dryomov 
4421ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4422837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4423837d5b6eSIlya Dryomov 		goto out_bargs;
4424837d5b6eSIlya Dryomov 	}
4425837d5b6eSIlya Dryomov 
44268d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4427c9e9f97bSIlya Dryomov 	if (!bctl) {
4428c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4429c9e9f97bSIlya Dryomov 		goto out_bargs;
4430c9e9f97bSIlya Dryomov 	}
4431c9e9f97bSIlya Dryomov 
4432c9e9f97bSIlya Dryomov 	if (arg) {
4433c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4434c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4435c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4436c9e9f97bSIlya Dryomov 
4437c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4438f43ffb60SIlya Dryomov 	} else {
4439f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4440f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4441c9e9f97bSIlya Dryomov 	}
4442c9e9f97bSIlya Dryomov 
44438eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
44448eb93459SDavid Sterba 		ret = -EINVAL;
44450f89abf5SChristian Engelmayer 		goto out_bctl;
44468eb93459SDavid Sterba 	}
44478eb93459SDavid Sterba 
4448de322263SIlya Dryomov do_balance:
4449c9e9f97bSIlya Dryomov 	/*
4450149196a2SDavid Sterba 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
4451149196a2SDavid Sterba 	 * btrfs_balance.  bctl is freed in reset_balance_state, or, if
4452149196a2SDavid Sterba 	 * restriper was paused all the way until unmount, in free_fs_info.
4453149196a2SDavid Sterba 	 * The flag should be cleared after reset_balance_state.
4454c9e9f97bSIlya Dryomov 	 */
4455ed0fb78fSIlya Dryomov 	need_unlock = false;
4456ed0fb78fSIlya Dryomov 
44576fcf6e2bSDavid Sterba 	ret = btrfs_balance(fs_info, bctl, bargs);
44580f89abf5SChristian Engelmayer 	bctl = NULL;
4459ed0fb78fSIlya Dryomov 
4460c9e9f97bSIlya Dryomov 	if (arg) {
4461c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4462c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4463c9e9f97bSIlya Dryomov 	}
4464c9e9f97bSIlya Dryomov 
44650f89abf5SChristian Engelmayer out_bctl:
44660f89abf5SChristian Engelmayer 	kfree(bctl);
4467c9e9f97bSIlya Dryomov out_bargs:
4468c9e9f97bSIlya Dryomov 	kfree(bargs);
4469ed0fb78fSIlya Dryomov out_unlock:
4470c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4471ed0fb78fSIlya Dryomov 	if (need_unlock)
4472171938e5SDavid Sterba 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4473ed0fb78fSIlya Dryomov out:
4474e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4475c9e9f97bSIlya Dryomov 	return ret;
4476c9e9f97bSIlya Dryomov }
4477c9e9f97bSIlya Dryomov 
44782ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4479837d5b6eSIlya Dryomov {
4480837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4481837d5b6eSIlya Dryomov 		return -EPERM;
4482837d5b6eSIlya Dryomov 
4483837d5b6eSIlya Dryomov 	switch (cmd) {
4484837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
44850b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4486a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
44870b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4488837d5b6eSIlya Dryomov 	}
4489837d5b6eSIlya Dryomov 
4490837d5b6eSIlya Dryomov 	return -EINVAL;
4491837d5b6eSIlya Dryomov }
4492837d5b6eSIlya Dryomov 
44932ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
449419a39dceSIlya Dryomov 					 void __user *arg)
449519a39dceSIlya Dryomov {
449619a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
449719a39dceSIlya Dryomov 	int ret = 0;
449819a39dceSIlya Dryomov 
449919a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
450019a39dceSIlya Dryomov 		return -EPERM;
450119a39dceSIlya Dryomov 
450219a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
450319a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
450419a39dceSIlya Dryomov 		ret = -ENOTCONN;
450519a39dceSIlya Dryomov 		goto out;
450619a39dceSIlya Dryomov 	}
450719a39dceSIlya Dryomov 
45088d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
450919a39dceSIlya Dryomov 	if (!bargs) {
451019a39dceSIlya Dryomov 		ret = -ENOMEM;
451119a39dceSIlya Dryomov 		goto out;
451219a39dceSIlya Dryomov 	}
451319a39dceSIlya Dryomov 
4514008ef096SDavid Sterba 	btrfs_update_ioctl_balance_args(fs_info, bargs);
451519a39dceSIlya Dryomov 
451619a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
451719a39dceSIlya Dryomov 		ret = -EFAULT;
451819a39dceSIlya Dryomov 
451919a39dceSIlya Dryomov 	kfree(bargs);
452019a39dceSIlya Dryomov out:
452119a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
452219a39dceSIlya Dryomov 	return ret;
452319a39dceSIlya Dryomov }
452419a39dceSIlya Dryomov 
4525905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
45265d13a37bSArne Jansen {
45270b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
45280b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
45295d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
45305d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
45315d13a37bSArne Jansen 	int ret;
45325d13a37bSArne Jansen 	int err;
45335d13a37bSArne Jansen 
45345d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
45355d13a37bSArne Jansen 		return -EPERM;
45365d13a37bSArne Jansen 
4537905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4538905b0ddaSMiao Xie 	if (ret)
4539905b0ddaSMiao Xie 		return ret;
45405d13a37bSArne Jansen 
45415d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4542905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4543905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4544905b0ddaSMiao Xie 		goto drop_write;
4545905b0ddaSMiao Xie 	}
45465d13a37bSArne Jansen 
45470b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
45480b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 2);
45495d13a37bSArne Jansen 	if (IS_ERR(trans)) {
45505d13a37bSArne Jansen 		ret = PTR_ERR(trans);
45515d13a37bSArne Jansen 		goto out;
45525d13a37bSArne Jansen 	}
45535d13a37bSArne Jansen 
45545d13a37bSArne Jansen 	switch (sa->cmd) {
45555d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
45560b246afaSJeff Mahoney 		ret = btrfs_quota_enable(trans, fs_info);
45575d13a37bSArne Jansen 		break;
45585d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
45590b246afaSJeff Mahoney 		ret = btrfs_quota_disable(trans, fs_info);
45605d13a37bSArne Jansen 		break;
45615d13a37bSArne Jansen 	default:
45625d13a37bSArne Jansen 		ret = -EINVAL;
45635d13a37bSArne Jansen 		break;
45645d13a37bSArne Jansen 	}
45655d13a37bSArne Jansen 
45663a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
45675d13a37bSArne Jansen 	if (err && !ret)
45685d13a37bSArne Jansen 		ret = err;
45695d13a37bSArne Jansen out:
45705d13a37bSArne Jansen 	kfree(sa);
45710b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4572905b0ddaSMiao Xie drop_write:
4573905b0ddaSMiao Xie 	mnt_drop_write_file(file);
45745d13a37bSArne Jansen 	return ret;
45755d13a37bSArne Jansen }
45765d13a37bSArne Jansen 
4577905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
45785d13a37bSArne Jansen {
45790b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
45800b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
45810b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
45825d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
45835d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
45845d13a37bSArne Jansen 	int ret;
45855d13a37bSArne Jansen 	int err;
45865d13a37bSArne Jansen 
45875d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
45885d13a37bSArne Jansen 		return -EPERM;
45895d13a37bSArne Jansen 
4590905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4591905b0ddaSMiao Xie 	if (ret)
4592905b0ddaSMiao Xie 		return ret;
45935d13a37bSArne Jansen 
45945d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4595905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4596905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4597905b0ddaSMiao Xie 		goto drop_write;
4598905b0ddaSMiao Xie 	}
45995d13a37bSArne Jansen 
46005d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
46015d13a37bSArne Jansen 	if (IS_ERR(trans)) {
46025d13a37bSArne Jansen 		ret = PTR_ERR(trans);
46035d13a37bSArne Jansen 		goto out;
46045d13a37bSArne Jansen 	}
46055d13a37bSArne Jansen 
46065d13a37bSArne Jansen 	if (sa->assign) {
46070b246afaSJeff Mahoney 		ret = btrfs_add_qgroup_relation(trans, fs_info,
46085d13a37bSArne Jansen 						sa->src, sa->dst);
46095d13a37bSArne Jansen 	} else {
46100b246afaSJeff Mahoney 		ret = btrfs_del_qgroup_relation(trans, fs_info,
46115d13a37bSArne Jansen 						sa->src, sa->dst);
46125d13a37bSArne Jansen 	}
46135d13a37bSArne Jansen 
4614e082f563SQu Wenruo 	/* update qgroup status and info */
46150b246afaSJeff Mahoney 	err = btrfs_run_qgroups(trans, fs_info);
4616e082f563SQu Wenruo 	if (err < 0)
46170b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4618ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
46193a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
46205d13a37bSArne Jansen 	if (err && !ret)
46215d13a37bSArne Jansen 		ret = err;
46225d13a37bSArne Jansen 
46235d13a37bSArne Jansen out:
46245d13a37bSArne Jansen 	kfree(sa);
4625905b0ddaSMiao Xie drop_write:
4626905b0ddaSMiao Xie 	mnt_drop_write_file(file);
46275d13a37bSArne Jansen 	return ret;
46285d13a37bSArne Jansen }
46295d13a37bSArne Jansen 
4630905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
46315d13a37bSArne Jansen {
46320b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
46330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46340b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
46355d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
46365d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
46375d13a37bSArne Jansen 	int ret;
46385d13a37bSArne Jansen 	int err;
46395d13a37bSArne Jansen 
46405d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
46415d13a37bSArne Jansen 		return -EPERM;
46425d13a37bSArne Jansen 
4643905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4644905b0ddaSMiao Xie 	if (ret)
4645905b0ddaSMiao Xie 		return ret;
46465d13a37bSArne Jansen 
46475d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4648905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4649905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4650905b0ddaSMiao Xie 		goto drop_write;
4651905b0ddaSMiao Xie 	}
46525d13a37bSArne Jansen 
4653d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4654d86e56cfSMiao Xie 		ret = -EINVAL;
4655d86e56cfSMiao Xie 		goto out;
4656d86e56cfSMiao Xie 	}
4657d86e56cfSMiao Xie 
46585d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
46595d13a37bSArne Jansen 	if (IS_ERR(trans)) {
46605d13a37bSArne Jansen 		ret = PTR_ERR(trans);
46615d13a37bSArne Jansen 		goto out;
46625d13a37bSArne Jansen 	}
46635d13a37bSArne Jansen 
46645d13a37bSArne Jansen 	if (sa->create) {
46650b246afaSJeff Mahoney 		ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
46665d13a37bSArne Jansen 	} else {
46670b246afaSJeff Mahoney 		ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
46685d13a37bSArne Jansen 	}
46695d13a37bSArne Jansen 
46703a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
46715d13a37bSArne Jansen 	if (err && !ret)
46725d13a37bSArne Jansen 		ret = err;
46735d13a37bSArne Jansen 
46745d13a37bSArne Jansen out:
46755d13a37bSArne Jansen 	kfree(sa);
4676905b0ddaSMiao Xie drop_write:
4677905b0ddaSMiao Xie 	mnt_drop_write_file(file);
46785d13a37bSArne Jansen 	return ret;
46795d13a37bSArne Jansen }
46805d13a37bSArne Jansen 
4681905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
46825d13a37bSArne Jansen {
46830b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
46840b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46850b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
46865d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
46875d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
46885d13a37bSArne Jansen 	int ret;
46895d13a37bSArne Jansen 	int err;
46905d13a37bSArne Jansen 	u64 qgroupid;
46915d13a37bSArne Jansen 
46925d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
46935d13a37bSArne Jansen 		return -EPERM;
46945d13a37bSArne Jansen 
4695905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4696905b0ddaSMiao Xie 	if (ret)
4697905b0ddaSMiao Xie 		return ret;
46985d13a37bSArne Jansen 
46995d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4700905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4701905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4702905b0ddaSMiao Xie 		goto drop_write;
4703905b0ddaSMiao Xie 	}
47045d13a37bSArne Jansen 
47055d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
47065d13a37bSArne Jansen 	if (IS_ERR(trans)) {
47075d13a37bSArne Jansen 		ret = PTR_ERR(trans);
47085d13a37bSArne Jansen 		goto out;
47095d13a37bSArne Jansen 	}
47105d13a37bSArne Jansen 
47115d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
47125d13a37bSArne Jansen 	if (!qgroupid) {
47135d13a37bSArne Jansen 		/* take the current subvol as qgroup */
47145d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
47155d13a37bSArne Jansen 	}
47165d13a37bSArne Jansen 
47170b246afaSJeff Mahoney 	ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
47185d13a37bSArne Jansen 
47193a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
47205d13a37bSArne Jansen 	if (err && !ret)
47215d13a37bSArne Jansen 		ret = err;
47225d13a37bSArne Jansen 
47235d13a37bSArne Jansen out:
47245d13a37bSArne Jansen 	kfree(sa);
4725905b0ddaSMiao Xie drop_write:
4726905b0ddaSMiao Xie 	mnt_drop_write_file(file);
47275d13a37bSArne Jansen 	return ret;
47285d13a37bSArne Jansen }
47295d13a37bSArne Jansen 
47302f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
47312f232036SJan Schmidt {
47320b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47342f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
47352f232036SJan Schmidt 	int ret;
47362f232036SJan Schmidt 
47372f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
47382f232036SJan Schmidt 		return -EPERM;
47392f232036SJan Schmidt 
47402f232036SJan Schmidt 	ret = mnt_want_write_file(file);
47412f232036SJan Schmidt 	if (ret)
47422f232036SJan Schmidt 		return ret;
47432f232036SJan Schmidt 
47442f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
47452f232036SJan Schmidt 	if (IS_ERR(qsa)) {
47462f232036SJan Schmidt 		ret = PTR_ERR(qsa);
47472f232036SJan Schmidt 		goto drop_write;
47482f232036SJan Schmidt 	}
47492f232036SJan Schmidt 
47502f232036SJan Schmidt 	if (qsa->flags) {
47512f232036SJan Schmidt 		ret = -EINVAL;
47522f232036SJan Schmidt 		goto out;
47532f232036SJan Schmidt 	}
47542f232036SJan Schmidt 
47550b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
47562f232036SJan Schmidt 
47572f232036SJan Schmidt out:
47582f232036SJan Schmidt 	kfree(qsa);
47592f232036SJan Schmidt drop_write:
47602f232036SJan Schmidt 	mnt_drop_write_file(file);
47612f232036SJan Schmidt 	return ret;
47622f232036SJan Schmidt }
47632f232036SJan Schmidt 
47642f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
47652f232036SJan Schmidt {
47660b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47670b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47682f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
47692f232036SJan Schmidt 	int ret = 0;
47702f232036SJan Schmidt 
47712f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
47722f232036SJan Schmidt 		return -EPERM;
47732f232036SJan Schmidt 
47748d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
47752f232036SJan Schmidt 	if (!qsa)
47762f232036SJan Schmidt 		return -ENOMEM;
47772f232036SJan Schmidt 
47780b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
47792f232036SJan Schmidt 		qsa->flags = 1;
47800b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
47812f232036SJan Schmidt 	}
47822f232036SJan Schmidt 
47832f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
47842f232036SJan Schmidt 		ret = -EFAULT;
47852f232036SJan Schmidt 
47862f232036SJan Schmidt 	kfree(qsa);
47872f232036SJan Schmidt 	return ret;
47882f232036SJan Schmidt }
47892f232036SJan Schmidt 
479057254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
479157254b6eSJan Schmidt {
47920b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
479457254b6eSJan Schmidt 
479557254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
479657254b6eSJan Schmidt 		return -EPERM;
479757254b6eSJan Schmidt 
47980b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
479957254b6eSJan Schmidt }
480057254b6eSJan Schmidt 
4801abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
4802abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
48038ea05e3aSAlexander Block {
4804496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
48050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48068ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
48078ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
48088ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
4809c2050a45SDeepa Dinamani 	struct timespec ct = current_time(inode);
48108ea05e3aSAlexander Block 	int ret = 0;
4811dd5f9615SStefan Behrens 	int received_uuid_changed;
48128ea05e3aSAlexander Block 
4813bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
4814bd60ea0fSDavid Sterba 		return -EPERM;
4815bd60ea0fSDavid Sterba 
48168ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
48178ea05e3aSAlexander Block 	if (ret < 0)
48188ea05e3aSAlexander Block 		return ret;
48198ea05e3aSAlexander Block 
48200b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
48218ea05e3aSAlexander Block 
48224a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
48238ea05e3aSAlexander Block 		ret = -EINVAL;
48248ea05e3aSAlexander Block 		goto out;
48258ea05e3aSAlexander Block 	}
48268ea05e3aSAlexander Block 
48278ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
48288ea05e3aSAlexander Block 		ret = -EROFS;
48298ea05e3aSAlexander Block 		goto out;
48308ea05e3aSAlexander Block 	}
48318ea05e3aSAlexander Block 
4832dd5f9615SStefan Behrens 	/*
4833dd5f9615SStefan Behrens 	 * 1 - root item
4834dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
4835dd5f9615SStefan Behrens 	 */
4836dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
48378ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
48388ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
48398ea05e3aSAlexander Block 		trans = NULL;
48408ea05e3aSAlexander Block 		goto out;
48418ea05e3aSAlexander Block 	}
48428ea05e3aSAlexander Block 
48438ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
48448ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
48458ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
48468ea05e3aSAlexander Block 
4847dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4848dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
4849dd5f9615SStefan Behrens 	if (received_uuid_changed &&
4850d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
4851d87ff758SNikolay Borisov 		ret = btrfs_uuid_tree_rem(trans, fs_info,
4852d87ff758SNikolay Borisov 					  root_item->received_uuid,
4853dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4854dd5f9615SStefan Behrens 					  root->root_key.objectid);
4855d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
4856d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
4857d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
4858d87ff758SNikolay Borisov 		        goto out;
4859d87ff758SNikolay Borisov 		}
4860d87ff758SNikolay Borisov 	}
48618ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
48628ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
48638ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
48643cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
48653cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
48663cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
48673cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
48688ea05e3aSAlexander Block 
48690b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
48708ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
48718ea05e3aSAlexander Block 	if (ret < 0) {
48723a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
48738ea05e3aSAlexander Block 		goto out;
4874dd5f9615SStefan Behrens 	}
4875dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
48760b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_add(trans, fs_info, sa->uuid,
4877dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4878dd5f9615SStefan Behrens 					  root->root_key.objectid);
4879dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
488066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
4881efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
4882dd5f9615SStefan Behrens 			goto out;
4883dd5f9615SStefan Behrens 		}
4884dd5f9615SStefan Behrens 	}
48853a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
4886abccd00fSHugo Mills out:
48870b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4888abccd00fSHugo Mills 	mnt_drop_write_file(file);
4889abccd00fSHugo Mills 	return ret;
4890abccd00fSHugo Mills }
4891abccd00fSHugo Mills 
4892abccd00fSHugo Mills #ifdef CONFIG_64BIT
4893abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4894abccd00fSHugo Mills 						void __user *arg)
4895abccd00fSHugo Mills {
4896abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4897abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4898abccd00fSHugo Mills 	int ret = 0;
4899abccd00fSHugo Mills 
4900abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
49017b9ea627SShailendra Verma 	if (IS_ERR(args32))
49027b9ea627SShailendra Verma 		return PTR_ERR(args32);
4903abccd00fSHugo Mills 
49048d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
490584dbeb87SDan Carpenter 	if (!args64) {
490684dbeb87SDan Carpenter 		ret = -ENOMEM;
4907abccd00fSHugo Mills 		goto out;
4908abccd00fSHugo Mills 	}
4909abccd00fSHugo Mills 
4910abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4911abccd00fSHugo Mills 	args64->stransid = args32->stransid;
4912abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
4913abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
4914abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
4915abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
4916abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
4917abccd00fSHugo Mills 	args64->flags = args32->flags;
4918abccd00fSHugo Mills 
4919abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
4920abccd00fSHugo Mills 	if (ret)
4921abccd00fSHugo Mills 		goto out;
4922abccd00fSHugo Mills 
4923abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4924abccd00fSHugo Mills 	args32->stransid = args64->stransid;
4925abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
4926abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
4927abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
4928abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
4929abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
4930abccd00fSHugo Mills 	args32->flags = args64->flags;
4931abccd00fSHugo Mills 
4932abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
4933abccd00fSHugo Mills 	if (ret)
4934abccd00fSHugo Mills 		ret = -EFAULT;
4935abccd00fSHugo Mills 
4936abccd00fSHugo Mills out:
4937abccd00fSHugo Mills 	kfree(args32);
4938abccd00fSHugo Mills 	kfree(args64);
4939abccd00fSHugo Mills 	return ret;
4940abccd00fSHugo Mills }
4941abccd00fSHugo Mills #endif
4942abccd00fSHugo Mills 
4943abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
4944abccd00fSHugo Mills 					    void __user *arg)
4945abccd00fSHugo Mills {
4946abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
4947abccd00fSHugo Mills 	int ret = 0;
4948abccd00fSHugo Mills 
4949abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
49507b9ea627SShailendra Verma 	if (IS_ERR(sa))
49517b9ea627SShailendra Verma 		return PTR_ERR(sa);
4952abccd00fSHugo Mills 
4953abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
4954abccd00fSHugo Mills 
4955abccd00fSHugo Mills 	if (ret)
4956abccd00fSHugo Mills 		goto out;
4957abccd00fSHugo Mills 
49588ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
49598ea05e3aSAlexander Block 	if (ret)
49608ea05e3aSAlexander Block 		ret = -EFAULT;
49618ea05e3aSAlexander Block 
49628ea05e3aSAlexander Block out:
49638ea05e3aSAlexander Block 	kfree(sa);
49648ea05e3aSAlexander Block 	return ret;
49658ea05e3aSAlexander Block }
49668ea05e3aSAlexander Block 
4967867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
4968867ab667Sjeff.liu {
49690b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4971a1b83ac5SAnand Jain 	size_t len;
4972867ab667Sjeff.liu 	int ret;
4973a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
4974a1b83ac5SAnand Jain 
49750b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
49760b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
49770b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
4978a1b83ac5SAnand Jain 
4979a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
4980867ab667Sjeff.liu 
4981867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
49820b246afaSJeff Mahoney 		btrfs_warn(fs_info,
49830b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
49840b246afaSJeff Mahoney 			   --len);
4985867ab667Sjeff.liu 	}
4986867ab667Sjeff.liu 
4987867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
4988867ab667Sjeff.liu 
4989867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
4990867ab667Sjeff.liu }
4991867ab667Sjeff.liu 
4992a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4993a8bfd4abSjeff.liu {
49940b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49950b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49960b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
49970b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
4998a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
4999a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5000a8bfd4abSjeff.liu 	int ret;
5001a8bfd4abSjeff.liu 
5002a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5003a8bfd4abSjeff.liu 		return -EPERM;
5004a8bfd4abSjeff.liu 
5005a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5006a8bfd4abSjeff.liu 		return -EFAULT;
5007a8bfd4abSjeff.liu 
5008a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
50090b246afaSJeff Mahoney 		btrfs_err(fs_info,
50105d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5011a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5012a8bfd4abSjeff.liu 		return -EINVAL;
5013a8bfd4abSjeff.liu 	}
5014a8bfd4abSjeff.liu 
5015a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5016a8bfd4abSjeff.liu 	if (ret)
5017a8bfd4abSjeff.liu 		return ret;
5018a8bfd4abSjeff.liu 
5019a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5020a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5021a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5022a8bfd4abSjeff.liu 		goto out_unlock;
5023a8bfd4abSjeff.liu 	}
5024a8bfd4abSjeff.liu 
50250b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5026a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
50270b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
50283a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5029a8bfd4abSjeff.liu 
5030a8bfd4abSjeff.liu out_unlock:
5031a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5032a8bfd4abSjeff.liu 	return ret;
5033a8bfd4abSjeff.liu }
5034a8bfd4abSjeff.liu 
50352eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
50362eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
50372eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
50382eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
50392eaa055fSJeff Mahoney 
5040d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
50412eaa055fSJeff Mahoney {
50424d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
50432eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
50442eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
50452eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
50462eaa055fSJeff Mahoney 	};
50472eaa055fSJeff Mahoney 
50482eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
50492eaa055fSJeff Mahoney 		return -EFAULT;
50502eaa055fSJeff Mahoney 
50512eaa055fSJeff Mahoney 	return 0;
50522eaa055fSJeff Mahoney }
50532eaa055fSJeff Mahoney 
50542eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
50552eaa055fSJeff Mahoney {
50560b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50580b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
50592eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
50602eaa055fSJeff Mahoney 
50612eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
50622eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
50632eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
50642eaa055fSJeff Mahoney 
50652eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
50662eaa055fSJeff Mahoney 		return -EFAULT;
50672eaa055fSJeff Mahoney 
50682eaa055fSJeff Mahoney 	return 0;
50692eaa055fSJeff Mahoney }
50702eaa055fSJeff Mahoney 
50712ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
50723b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
50732eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
50742eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
50752eaa055fSJeff Mahoney {
50763b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
50773b02a68aSJeff Mahoney 	char *names;
50782eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
50792eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
50802eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
50812eaa055fSJeff Mahoney 
50822eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
50832eaa055fSJeff Mahoney 	if (unsupported) {
50843b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
50853b02a68aSJeff Mahoney 		if (names) {
50860b246afaSJeff Mahoney 			btrfs_warn(fs_info,
50873b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
50883b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
50893b02a68aSJeff Mahoney 			kfree(names);
50903b02a68aSJeff Mahoney 		} else
50910b246afaSJeff Mahoney 			btrfs_warn(fs_info,
50922eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
50932eaa055fSJeff Mahoney 				   type, unsupported);
50942eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
50952eaa055fSJeff Mahoney 	}
50962eaa055fSJeff Mahoney 
50972eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
50982eaa055fSJeff Mahoney 	if (disallowed) {
50993b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
51003b02a68aSJeff Mahoney 		if (names) {
51010b246afaSJeff Mahoney 			btrfs_warn(fs_info,
51023b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
51033b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
51043b02a68aSJeff Mahoney 			kfree(names);
51053b02a68aSJeff Mahoney 		} else
51060b246afaSJeff Mahoney 			btrfs_warn(fs_info,
51072eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
51082eaa055fSJeff Mahoney 				   type, disallowed);
51092eaa055fSJeff Mahoney 		return -EPERM;
51102eaa055fSJeff Mahoney 	}
51112eaa055fSJeff Mahoney 
51122eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
51132eaa055fSJeff Mahoney 	if (disallowed) {
51143b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
51153b02a68aSJeff Mahoney 		if (names) {
51160b246afaSJeff Mahoney 			btrfs_warn(fs_info,
51173b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
51183b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
51193b02a68aSJeff Mahoney 			kfree(names);
51203b02a68aSJeff Mahoney 		} else
51210b246afaSJeff Mahoney 			btrfs_warn(fs_info,
51222eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
51232eaa055fSJeff Mahoney 				   type, disallowed);
51242eaa055fSJeff Mahoney 		return -EPERM;
51252eaa055fSJeff Mahoney 	}
51262eaa055fSJeff Mahoney 
51272eaa055fSJeff Mahoney 	return 0;
51282eaa055fSJeff Mahoney }
51292eaa055fSJeff Mahoney 
51302ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
51312ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
51322eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
51332eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
51342eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
51352eaa055fSJeff Mahoney 
51362eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
51372eaa055fSJeff Mahoney {
51380b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51390b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51400b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
51410b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
51422eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
51432eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
51442eaa055fSJeff Mahoney 	u64 newflags;
51452eaa055fSJeff Mahoney 	int ret;
51462eaa055fSJeff Mahoney 
51472eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
51482eaa055fSJeff Mahoney 		return -EPERM;
51492eaa055fSJeff Mahoney 
51502eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
51512eaa055fSJeff Mahoney 		return -EFAULT;
51522eaa055fSJeff Mahoney 
51532eaa055fSJeff Mahoney 	/* Nothing to do */
51542eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
51552eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
51562eaa055fSJeff Mahoney 		return 0;
51572eaa055fSJeff Mahoney 
51582ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
51592eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
51602eaa055fSJeff Mahoney 	if (ret)
51612eaa055fSJeff Mahoney 		return ret;
51622eaa055fSJeff Mahoney 
51632ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
51642eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
51652eaa055fSJeff Mahoney 	if (ret)
51662eaa055fSJeff Mahoney 		return ret;
51672eaa055fSJeff Mahoney 
51682ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
51692eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
51702eaa055fSJeff Mahoney 	if (ret)
51712eaa055fSJeff Mahoney 		return ret;
51722eaa055fSJeff Mahoney 
51737ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
51747ab19625SDavid Sterba 	if (ret)
51757ab19625SDavid Sterba 		return ret;
51767ab19625SDavid Sterba 
51778051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
51787ab19625SDavid Sterba 	if (IS_ERR(trans)) {
51797ab19625SDavid Sterba 		ret = PTR_ERR(trans);
51807ab19625SDavid Sterba 		goto out_drop_write;
51817ab19625SDavid Sterba 	}
51822eaa055fSJeff Mahoney 
51830b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
51842eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
51852eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
51862eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
51872eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
51882eaa055fSJeff Mahoney 
51892eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
51902eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
51912eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
51922eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
51932eaa055fSJeff Mahoney 
51942eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
51952eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
51962eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
51972eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
51980b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
51992eaa055fSJeff Mahoney 
52003a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
52017ab19625SDavid Sterba out_drop_write:
52027ab19625SDavid Sterba 	mnt_drop_write_file(file);
52037ab19625SDavid Sterba 
52047ab19625SDavid Sterba 	return ret;
52052eaa055fSJeff Mahoney }
52062eaa055fSJeff Mahoney 
52072351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
52082351f431SJosef Bacik {
52092351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
52102351f431SJosef Bacik 	int ret;
52112351f431SJosef Bacik 
52122351f431SJosef Bacik 	if (compat) {
52132351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
52142351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
52152351f431SJosef Bacik 
52162351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
52172351f431SJosef Bacik 		if (ret)
52182351f431SJosef Bacik 			return -EFAULT;
52192351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
52202351f431SJosef Bacik 		if (!arg)
52212351f431SJosef Bacik 			return -ENOMEM;
52222351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
52232351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
52242351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
52252351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
52262351f431SJosef Bacik 		arg->flags = args32.flags;
52272351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
52282351f431SJosef Bacik 		       sizeof(args32.reserved));
52292351f431SJosef Bacik #else
52302351f431SJosef Bacik 		return -ENOTTY;
52312351f431SJosef Bacik #endif
52322351f431SJosef Bacik 	} else {
52332351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
52342351f431SJosef Bacik 		if (IS_ERR(arg))
52352351f431SJosef Bacik 			return PTR_ERR(arg);
52362351f431SJosef Bacik 	}
52372351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
52382351f431SJosef Bacik 	kfree(arg);
52392351f431SJosef Bacik 	return ret;
52402351f431SJosef Bacik }
52412351f431SJosef Bacik 
5242f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5243f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5244f46b5a66SChristoph Hellwig {
52450b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52470b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
52484bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5249f46b5a66SChristoph Hellwig 
5250f46b5a66SChristoph Hellwig 	switch (cmd) {
52516cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
52526cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
52536cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
52546cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
52556cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
52566cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5257f7039b1dSLi Dongyang 	case FITRIM:
5258f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5259f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5260fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5261fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5262fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
52633de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5264fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
52656f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
52666f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
526776dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
526876dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
52690caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
52700caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
52710caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
52720caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
52736ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
52746ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5275f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
52761e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
52771e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
52781e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5279f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5280198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5281f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
52822ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5283f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5284da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
52856b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
52866b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5287475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
52882ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5289475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
52902ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5291f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
52929ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5293ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5294ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5295cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5296cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5297ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5298ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5299d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5300d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5301d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5302d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5303d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
5304d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
53051406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
53062ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
53079b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
53089b199859SFilipe David Borba Manana 		int ret;
53099b199859SFilipe David Borba Manana 
531082b3e53bSNikolay Borisov 		ret = btrfs_start_delalloc_roots(fs_info, -1);
53119b199859SFilipe David Borba Manana 		if (ret)
53129b199859SFilipe David Borba Manana 			return ret;
53130b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
53142fad4e83SDavid Sterba 		/*
53152fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
531601327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
53172fad4e83SDavid Sterba 		 * processing uncleaned subvols.
53182fad4e83SDavid Sterba 		 */
53190b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
53209b199859SFilipe David Borba Manana 		return ret;
53219b199859SFilipe David Borba Manana 	}
532246204592SSage Weil 	case BTRFS_IOC_START_SYNC:
53239a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
532446204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
53252ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5326475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5327b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5328475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
53292ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5330475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
53312ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5332c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
53339ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5334837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
53352ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
533619a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
53372ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
53388ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
53398ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5340abccd00fSHugo Mills #ifdef CONFIG_64BIT
5341abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5342abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5343abccd00fSHugo Mills #endif
534431db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
53452351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
53462351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
53472351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
53482351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
53492351f431SJosef Bacik #endif
5350c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
53512ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
53525d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5353905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
53545d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5355905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
53565d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5357905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
53585d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5359905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
53602f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
53612f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
53622f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
53632f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
536457254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
536557254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
53663f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
53672ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5368867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5369867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5370a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5371a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
53722eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5373d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
53742eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
53752eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
53762eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
53772eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5378f46b5a66SChristoph Hellwig 	}
5379f46b5a66SChristoph Hellwig 
5380f46b5a66SChristoph Hellwig 	return -ENOTTY;
5381f46b5a66SChristoph Hellwig }
53824c63c245SLuke Dashjr 
53834c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
53844c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
53854c63c245SLuke Dashjr {
53862a362249SJeff Mahoney 	/*
53872a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
53882a362249SJeff Mahoney 	 * handling is necessary.
53892a362249SJeff Mahoney 	 */
53904c63c245SLuke Dashjr 	switch (cmd) {
53914c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
53924c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
53934c63c245SLuke Dashjr 		break;
53944c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
53954c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
53964c63c245SLuke Dashjr 		break;
53974c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
53984c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
53994c63c245SLuke Dashjr 		break;
54004c63c245SLuke Dashjr 	}
54014c63c245SLuke Dashjr 
54024c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
54034c63c245SLuke Dashjr }
54044c63c245SLuke Dashjr #endif
5405