xref: /openbmc/linux/fs/btrfs/ioctl.c (revision 7b6a221e)
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. */
9638e82de8SDavid Sterba static unsigned int btrfs_mask_flags(umode_t mode, unsigned int flags)
976cbff00fSChristoph Hellwig {
986cbff00fSChristoph Hellwig 	if (S_ISDIR(mode))
996cbff00fSChristoph Hellwig 		return flags;
1006cbff00fSChristoph Hellwig 	else if (S_ISREG(mode))
1016cbff00fSChristoph Hellwig 		return flags & ~FS_DIRSYNC_FL;
1026cbff00fSChristoph Hellwig 	else
1036cbff00fSChristoph Hellwig 		return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
1046cbff00fSChristoph Hellwig }
105f46b5a66SChristoph Hellwig 
1066cbff00fSChristoph Hellwig /*
1076cbff00fSChristoph Hellwig  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
1086cbff00fSChristoph Hellwig  */
1096cbff00fSChristoph Hellwig static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
1106cbff00fSChristoph Hellwig {
1116cbff00fSChristoph Hellwig 	unsigned int iflags = 0;
1126cbff00fSChristoph Hellwig 
1136cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_SYNC)
1146cbff00fSChristoph Hellwig 		iflags |= FS_SYNC_FL;
1156cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_IMMUTABLE)
1166cbff00fSChristoph Hellwig 		iflags |= FS_IMMUTABLE_FL;
1176cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_APPEND)
1186cbff00fSChristoph Hellwig 		iflags |= FS_APPEND_FL;
1196cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NODUMP)
1206cbff00fSChristoph Hellwig 		iflags |= FS_NODUMP_FL;
1216cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NOATIME)
1226cbff00fSChristoph Hellwig 		iflags |= FS_NOATIME_FL;
1236cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_DIRSYNC)
1246cbff00fSChristoph Hellwig 		iflags |= FS_DIRSYNC_FL;
125d0092bddSLi Zefan 	if (flags & BTRFS_INODE_NODATACOW)
126d0092bddSLi Zefan 		iflags |= FS_NOCOW_FL;
127d0092bddSLi Zefan 
12813f48dc9SSatoru Takeuchi 	if (flags & BTRFS_INODE_NOCOMPRESS)
129d0092bddSLi Zefan 		iflags |= FS_NOCOMP_FL;
13013f48dc9SSatoru Takeuchi 	else if (flags & BTRFS_INODE_COMPRESS)
13113f48dc9SSatoru Takeuchi 		iflags |= FS_COMPR_FL;
1326cbff00fSChristoph Hellwig 
1336cbff00fSChristoph Hellwig 	return iflags;
1346cbff00fSChristoph Hellwig }
1356cbff00fSChristoph Hellwig 
1366cbff00fSChristoph Hellwig /*
1376cbff00fSChristoph Hellwig  * Update inode->i_flags based on the btrfs internal flags.
1386cbff00fSChristoph Hellwig  */
1397b6a221eSDavid Sterba void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
1406cbff00fSChristoph Hellwig {
1416cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
1423cc79392SFilipe Manana 	unsigned int new_fl = 0;
1436cbff00fSChristoph Hellwig 
1446cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_SYNC)
1453cc79392SFilipe Manana 		new_fl |= S_SYNC;
1466cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_IMMUTABLE)
1473cc79392SFilipe Manana 		new_fl |= S_IMMUTABLE;
1486cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_APPEND)
1493cc79392SFilipe Manana 		new_fl |= S_APPEND;
1506cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_NOATIME)
1513cc79392SFilipe Manana 		new_fl |= S_NOATIME;
1526cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_DIRSYNC)
1533cc79392SFilipe Manana 		new_fl |= S_DIRSYNC;
1543cc79392SFilipe Manana 
1553cc79392SFilipe Manana 	set_mask_bits(&inode->i_flags,
1563cc79392SFilipe Manana 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
1573cc79392SFilipe Manana 		      new_fl);
1586cbff00fSChristoph Hellwig }
1596cbff00fSChristoph Hellwig 
1606cbff00fSChristoph Hellwig static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
1616cbff00fSChristoph Hellwig {
162496ad9aaSAl Viro 	struct btrfs_inode *ip = BTRFS_I(file_inode(file));
1636cbff00fSChristoph Hellwig 	unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
1646cbff00fSChristoph Hellwig 
1656cbff00fSChristoph Hellwig 	if (copy_to_user(arg, &flags, sizeof(flags)))
1666cbff00fSChristoph Hellwig 		return -EFAULT;
1676cbff00fSChristoph Hellwig 	return 0;
1686cbff00fSChristoph Hellwig }
1696cbff00fSChristoph Hellwig 
17075e7cb7fSLiu Bo static int check_flags(unsigned int flags)
17175e7cb7fSLiu Bo {
17275e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
17375e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
17475e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
175e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
176e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
17775e7cb7fSLiu Bo 		return -EOPNOTSUPP;
17875e7cb7fSLiu Bo 
17975e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
18075e7cb7fSLiu Bo 		return -EINVAL;
18175e7cb7fSLiu Bo 
18275e7cb7fSLiu Bo 	return 0;
18375e7cb7fSLiu Bo }
18475e7cb7fSLiu Bo 
1856cbff00fSChristoph Hellwig static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
1866cbff00fSChristoph Hellwig {
187496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
1880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1896cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
1906cbff00fSChristoph Hellwig 	struct btrfs_root *root = ip->root;
1916cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
1926cbff00fSChristoph Hellwig 	unsigned int flags, oldflags;
1936cbff00fSChristoph Hellwig 	int ret;
194f062abf0SLi Zefan 	u64 ip_oldflags;
195f062abf0SLi Zefan 	unsigned int i_oldflags;
1967e97b8daSDavid Sterba 	umode_t mode;
1976cbff00fSChristoph Hellwig 
198bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
199bd60ea0fSDavid Sterba 		return -EPERM;
200bd60ea0fSDavid Sterba 
201b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
202b83cc969SLi Zefan 		return -EROFS;
203b83cc969SLi Zefan 
2046cbff00fSChristoph Hellwig 	if (copy_from_user(&flags, arg, sizeof(flags)))
2056cbff00fSChristoph Hellwig 		return -EFAULT;
2066cbff00fSChristoph Hellwig 
20775e7cb7fSLiu Bo 	ret = check_flags(flags);
20875e7cb7fSLiu Bo 	if (ret)
20975e7cb7fSLiu Bo 		return ret;
2106cbff00fSChristoph Hellwig 
211e7848683SJan Kara 	ret = mnt_want_write_file(file);
212e7848683SJan Kara 	if (ret)
213e7848683SJan Kara 		return ret;
214e7848683SJan Kara 
2155955102cSAl Viro 	inode_lock(inode);
2166cbff00fSChristoph Hellwig 
217f062abf0SLi Zefan 	ip_oldflags = ip->flags;
218f062abf0SLi Zefan 	i_oldflags = inode->i_flags;
2197e97b8daSDavid Sterba 	mode = inode->i_mode;
220f062abf0SLi Zefan 
2216cbff00fSChristoph Hellwig 	flags = btrfs_mask_flags(inode->i_mode, flags);
2226cbff00fSChristoph Hellwig 	oldflags = btrfs_flags_to_ioctl(ip->flags);
2236cbff00fSChristoph Hellwig 	if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
2246cbff00fSChristoph Hellwig 		if (!capable(CAP_LINUX_IMMUTABLE)) {
2256cbff00fSChristoph Hellwig 			ret = -EPERM;
2266cbff00fSChristoph Hellwig 			goto out_unlock;
2276cbff00fSChristoph Hellwig 		}
2286cbff00fSChristoph Hellwig 	}
2296cbff00fSChristoph Hellwig 
2306cbff00fSChristoph Hellwig 	if (flags & FS_SYNC_FL)
2316cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_SYNC;
2326cbff00fSChristoph Hellwig 	else
2336cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_SYNC;
2346cbff00fSChristoph Hellwig 	if (flags & FS_IMMUTABLE_FL)
2356cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_IMMUTABLE;
2366cbff00fSChristoph Hellwig 	else
2376cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_IMMUTABLE;
2386cbff00fSChristoph Hellwig 	if (flags & FS_APPEND_FL)
2396cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_APPEND;
2406cbff00fSChristoph Hellwig 	else
2416cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_APPEND;
2426cbff00fSChristoph Hellwig 	if (flags & FS_NODUMP_FL)
2436cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NODUMP;
2446cbff00fSChristoph Hellwig 	else
2456cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NODUMP;
2466cbff00fSChristoph Hellwig 	if (flags & FS_NOATIME_FL)
2476cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NOATIME;
2486cbff00fSChristoph Hellwig 	else
2496cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NOATIME;
2506cbff00fSChristoph Hellwig 	if (flags & FS_DIRSYNC_FL)
2516cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_DIRSYNC;
2526cbff00fSChristoph Hellwig 	else
2536cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_DIRSYNC;
2547e97b8daSDavid Sterba 	if (flags & FS_NOCOW_FL) {
2557e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2567e97b8daSDavid Sterba 			/*
2577e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2587e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2597e97b8daSDavid Sterba 			 * status of the file and will not set it.
2607e97b8daSDavid Sterba 			 */
2617e97b8daSDavid Sterba 			if (inode->i_size == 0)
2627e97b8daSDavid Sterba 				ip->flags |= BTRFS_INODE_NODATACOW
2637e97b8daSDavid Sterba 					   | BTRFS_INODE_NODATASUM;
2647e97b8daSDavid Sterba 		} else {
265e1e8fb6aSLi Zefan 			ip->flags |= BTRFS_INODE_NODATACOW;
2667e97b8daSDavid Sterba 		}
2677e97b8daSDavid Sterba 	} else {
2687e97b8daSDavid Sterba 		/*
26901327610SNicholas D Steeves 		 * Revert back under same assumptions as above
2707e97b8daSDavid Sterba 		 */
2717e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2727e97b8daSDavid Sterba 			if (inode->i_size == 0)
2737e97b8daSDavid Sterba 				ip->flags &= ~(BTRFS_INODE_NODATACOW
2747e97b8daSDavid Sterba 				             | BTRFS_INODE_NODATASUM);
2757e97b8daSDavid Sterba 		} else {
276e1e8fb6aSLi Zefan 			ip->flags &= ~BTRFS_INODE_NODATACOW;
2777e97b8daSDavid Sterba 		}
2787e97b8daSDavid Sterba 	}
2796cbff00fSChristoph Hellwig 
28075e7cb7fSLiu Bo 	/*
28175e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
28275e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
28375e7cb7fSLiu Bo 	 * things smaller.
28475e7cb7fSLiu Bo 	 */
28575e7cb7fSLiu Bo 	if (flags & FS_NOCOMP_FL) {
28675e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_COMPRESS;
28775e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_NOCOMPRESS;
28863541927SFilipe David Borba Manana 
28963541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
29063541927SFilipe David Borba Manana 		if (ret && ret != -ENODATA)
29163541927SFilipe David Borba Manana 			goto out_drop;
29275e7cb7fSLiu Bo 	} else if (flags & FS_COMPR_FL) {
29363541927SFilipe David Borba Manana 		const char *comp;
29463541927SFilipe David Borba Manana 
29575e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_COMPRESS;
29675e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
29763541927SFilipe David Borba Manana 
29893370509SDavid Sterba 		comp = btrfs_compress_type2str(fs_info->compress_type);
29993370509SDavid Sterba 		if (!comp || comp[0] == 0)
30093370509SDavid Sterba 			comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
30193370509SDavid Sterba 
30263541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression",
30363541927SFilipe David Borba Manana 				     comp, strlen(comp), 0);
30463541927SFilipe David Borba Manana 		if (ret)
30563541927SFilipe David Borba Manana 			goto out_drop;
30663541927SFilipe David Borba Manana 
307ebcb904dSLi Zefan 	} else {
30878a017a2SFilipe Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
30978a017a2SFilipe Manana 		if (ret && ret != -ENODATA)
31078a017a2SFilipe Manana 			goto out_drop;
311ebcb904dSLi Zefan 		ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
31275e7cb7fSLiu Bo 	}
3136cbff00fSChristoph Hellwig 
3144da6f1a3SLi Zefan 	trans = btrfs_start_transaction(root, 1);
315f062abf0SLi Zefan 	if (IS_ERR(trans)) {
316f062abf0SLi Zefan 		ret = PTR_ERR(trans);
317f062abf0SLi Zefan 		goto out_drop;
318f062abf0SLi Zefan 	}
3196cbff00fSChristoph Hellwig 
3207b6a221eSDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
3210c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
322c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3236cbff00fSChristoph Hellwig 	ret = btrfs_update_inode(trans, root, inode);
3246cbff00fSChristoph Hellwig 
3253a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
326f062abf0SLi Zefan  out_drop:
327f062abf0SLi Zefan 	if (ret) {
328f062abf0SLi Zefan 		ip->flags = ip_oldflags;
329f062abf0SLi Zefan 		inode->i_flags = i_oldflags;
330f062abf0SLi Zefan 	}
3316cbff00fSChristoph Hellwig 
3326cbff00fSChristoph Hellwig  out_unlock:
3335955102cSAl Viro 	inode_unlock(inode);
334e7848683SJan Kara 	mnt_drop_write_file(file);
3352d4e6f6aSliubo 	return ret;
3366cbff00fSChristoph Hellwig }
3376cbff00fSChristoph Hellwig 
3386cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
3396cbff00fSChristoph Hellwig {
340496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3416cbff00fSChristoph Hellwig 
3426cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
3436cbff00fSChristoph Hellwig }
344f46b5a66SChristoph Hellwig 
345f7039b1dSLi Dongyang static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
346f7039b1dSLi Dongyang {
3470b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
3480b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
349f7039b1dSLi Dongyang 	struct btrfs_device *device;
350f7039b1dSLi Dongyang 	struct request_queue *q;
351f7039b1dSLi Dongyang 	struct fstrim_range range;
352f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
353f7039b1dSLi Dongyang 	u64 num_devices = 0;
354815745cfSAl Viro 	u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
355f7039b1dSLi Dongyang 	int ret;
356f7039b1dSLi Dongyang 
357f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
358f7039b1dSLi Dongyang 		return -EPERM;
359f7039b1dSLi Dongyang 
3601f78160cSXiao Guangrong 	rcu_read_lock();
3611f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
3621f78160cSXiao Guangrong 				dev_list) {
363f7039b1dSLi Dongyang 		if (!device->bdev)
364f7039b1dSLi Dongyang 			continue;
365f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
366f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
367f7039b1dSLi Dongyang 			num_devices++;
36850d0446eSSeraphime Kirkovski 			minlen = min_t(u64, q->limits.discard_granularity,
369f7039b1dSLi Dongyang 				     minlen);
370f7039b1dSLi Dongyang 		}
371f7039b1dSLi Dongyang 	}
3721f78160cSXiao Guangrong 	rcu_read_unlock();
373f4c697e6SLukas Czerner 
374f7039b1dSLi Dongyang 	if (!num_devices)
375f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
376f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
377f7039b1dSLi Dongyang 		return -EFAULT;
378e515c18bSLukas Czerner 	if (range.start > total_bytes ||
379e515c18bSLukas Czerner 	    range.len < fs_info->sb->s_blocksize)
380f4c697e6SLukas Czerner 		return -EINVAL;
381f7039b1dSLi Dongyang 
382f4c697e6SLukas Czerner 	range.len = min(range.len, total_bytes - range.start);
383f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
3842ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
385f7039b1dSLi Dongyang 	if (ret < 0)
386f7039b1dSLi Dongyang 		return ret;
387f7039b1dSLi Dongyang 
388f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
389f7039b1dSLi Dongyang 		return -EFAULT;
390f7039b1dSLi Dongyang 
391f7039b1dSLi Dongyang 	return 0;
392f7039b1dSLi Dongyang }
393f7039b1dSLi Dongyang 
394dd5f9615SStefan Behrens int btrfs_is_empty_uuid(u8 *uuid)
395dd5f9615SStefan Behrens {
39646e0f66aSChris Mason 	int i;
39746e0f66aSChris Mason 
39846e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
39946e0f66aSChris Mason 		if (uuid[i])
40046e0f66aSChris Mason 			return 0;
40146e0f66aSChris Mason 	}
40246e0f66aSChris Mason 	return 1;
403dd5f9615SStefan Behrens }
404dd5f9615SStefan Behrens 
405d5c12070SMiao Xie static noinline int create_subvol(struct inode *dir,
406cb8e7090SChristoph Hellwig 				  struct dentry *dentry,
40752f75f4fSDavid Sterba 				  const char *name, int namelen,
4086f72c7e2SArne Jansen 				  u64 *async_transid,
4098696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
410f46b5a66SChristoph Hellwig {
4110b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
412f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
413f46b5a66SChristoph Hellwig 	struct btrfs_key key;
41449a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
415f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
416f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
417d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
41876dda93cSYan, Zheng 	struct btrfs_root *new_root;
419d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
420c2050a45SDeepa Dinamani 	struct timespec cur_time = current_time(dir);
4215662344bSTsutomu Itoh 	struct inode *inode;
422f46b5a66SChristoph Hellwig 	int ret;
423f46b5a66SChristoph Hellwig 	int err;
424f46b5a66SChristoph Hellwig 	u64 objectid;
425f46b5a66SChristoph Hellwig 	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
4263de4586cSChris Mason 	u64 index = 0;
427d5c12070SMiao Xie 	u64 qgroup_reserved;
4288ea05e3aSAlexander Block 	uuid_le new_uuid;
429f46b5a66SChristoph Hellwig 
43049a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
43149a3c4d9SDavid Sterba 	if (!root_item)
43249a3c4d9SDavid Sterba 		return -ENOMEM;
43349a3c4d9SDavid Sterba 
4340b246afaSJeff Mahoney 	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
4352fbe8c8aSAl Viro 	if (ret)
43649a3c4d9SDavid Sterba 		goto fail_free;
4376a912213SJosef Bacik 
438e09fe2d2SQu Wenruo 	/*
439e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
44001327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
441e09fe2d2SQu Wenruo 	 */
44249a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
44349a3c4d9SDavid Sterba 		ret = -ENOSPC;
44449a3c4d9SDavid Sterba 		goto fail_free;
44549a3c4d9SDavid Sterba 	}
446e09fe2d2SQu Wenruo 
447d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4489ed74f2dSJosef Bacik 	/*
449d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
450d5c12070SMiao Xie 	 * of create_snapshot().
4519ed74f2dSJosef Bacik 	 */
452d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
453dd5f9615SStefan Behrens 					       8, &qgroup_reserved, false);
454d5c12070SMiao Xie 	if (ret)
45549a3c4d9SDavid Sterba 		goto fail_free;
456f46b5a66SChristoph Hellwig 
457d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
458d5c12070SMiao Xie 	if (IS_ERR(trans)) {
459d5c12070SMiao Xie 		ret = PTR_ERR(trans);
4607775c818SDavid Sterba 		btrfs_subvolume_release_metadata(fs_info, &block_rsv);
46149a3c4d9SDavid Sterba 		goto fail_free;
462d5c12070SMiao Xie 	}
463d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
464d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
465f46b5a66SChristoph Hellwig 
4660b246afaSJeff Mahoney 	ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
4676f72c7e2SArne Jansen 	if (ret)
4686f72c7e2SArne Jansen 		goto fail;
4696f72c7e2SArne Jansen 
4704d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
4718e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
4728e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
4738e8a1e31SJosef Bacik 		goto fail;
4748e8a1e31SJosef Bacik 	}
475f46b5a66SChristoph Hellwig 
476b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
477f46b5a66SChristoph Hellwig 	btrfs_set_header_bytenr(leaf, leaf->start);
478f46b5a66SChristoph Hellwig 	btrfs_set_header_generation(leaf, trans->transid);
4795d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
480f46b5a66SChristoph Hellwig 	btrfs_set_header_owner(leaf, objectid);
481f46b5a66SChristoph Hellwig 
4820b246afaSJeff Mahoney 	write_extent_buffer_fsid(leaf, fs_info->fsid);
4830b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
484f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
485f46b5a66SChristoph Hellwig 
48649a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
4873cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
4883cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
4893cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
490da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
4910b246afaSJeff Mahoney 				     fs_info->nodesize);
4923cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
493f46b5a66SChristoph Hellwig 
49449a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
49549a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
4963cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
49708fe4db1SLi Zefan 
49849a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
49949a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
50049a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
50149a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
50249a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
50349a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
504f46b5a66SChristoph Hellwig 
50549a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
50649a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
5078ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
50849a3c4d9SDavid Sterba 	memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
50949a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
51049a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
51149a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
51249a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
51349a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
514f46b5a66SChristoph Hellwig 
515925baeddSChris Mason 	btrfs_tree_unlock(leaf);
516f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
517f46b5a66SChristoph Hellwig 	leaf = NULL;
518f46b5a66SChristoph Hellwig 
51949a3c4d9SDavid Sterba 	btrfs_set_root_dirid(root_item, new_dirid);
520f46b5a66SChristoph Hellwig 
521f46b5a66SChristoph Hellwig 	key.objectid = objectid;
5225d4f98a2SYan Zheng 	key.offset = 0;
523962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
5240b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
52549a3c4d9SDavid Sterba 				root_item);
526f46b5a66SChristoph Hellwig 	if (ret)
527f46b5a66SChristoph Hellwig 		goto fail;
528f46b5a66SChristoph Hellwig 
52976dda93cSYan, Zheng 	key.offset = (u64)-1;
5300b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &key);
53179787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
53279787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
53366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
53479787eaaSJeff Mahoney 		goto fail;
53579787eaaSJeff Mahoney 	}
53676dda93cSYan, Zheng 
53776dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
53876dda93cSYan, Zheng 
53963541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
540ce598979SMark Fasheh 	if (ret) {
541ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
54266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
543ce598979SMark Fasheh 		goto fail;
544ce598979SMark Fasheh 	}
545ce598979SMark Fasheh 
546f32e48e9SChandan Rajendra 	mutex_lock(&new_root->objectid_mutex);
547f32e48e9SChandan Rajendra 	new_root->highest_objectid = new_dirid;
548f32e48e9SChandan Rajendra 	mutex_unlock(&new_root->objectid_mutex);
549f32e48e9SChandan Rajendra 
550f46b5a66SChristoph Hellwig 	/*
551f46b5a66SChristoph Hellwig 	 * insert the directory item
552f46b5a66SChristoph Hellwig 	 */
553877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
55479787eaaSJeff Mahoney 	if (ret) {
55566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
55679787eaaSJeff Mahoney 		goto fail;
55779787eaaSJeff Mahoney 	}
5583de4586cSChris Mason 
5593de4586cSChris Mason 	ret = btrfs_insert_dir_item(trans, root,
5608e7611cfSNikolay Borisov 				    name, namelen, BTRFS_I(dir), &key,
5613de4586cSChris Mason 				    BTRFS_FT_DIR, index);
56279787eaaSJeff Mahoney 	if (ret) {
56366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
564f46b5a66SChristoph Hellwig 		goto fail;
56579787eaaSJeff Mahoney 	}
5660660b5afSChris Mason 
5676ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
56852c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
56952c26179SYan Zheng 	BUG_ON(ret);
57052c26179SYan Zheng 
5710b246afaSJeff Mahoney 	ret = btrfs_add_root_ref(trans, fs_info,
5724df27c4dSYan, Zheng 				 objectid, root->root_key.objectid,
5734a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
5740660b5afSChris Mason 	BUG_ON(ret);
5750660b5afSChris Mason 
5760b246afaSJeff Mahoney 	ret = btrfs_uuid_tree_add(trans, fs_info, root_item->uuid,
5776bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
578dd5f9615SStefan Behrens 	if (ret)
57966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
580dd5f9615SStefan Behrens 
581f46b5a66SChristoph Hellwig fail:
58249a3c4d9SDavid Sterba 	kfree(root_item);
583d5c12070SMiao Xie 	trans->block_rsv = NULL;
584d5c12070SMiao Xie 	trans->bytes_reserved = 0;
5857775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
586de6e8200SLiu Bo 
58772fd032eSSage Weil 	if (async_transid) {
58872fd032eSSage Weil 		*async_transid = trans->transid;
5893a45bb20SJeff Mahoney 		err = btrfs_commit_transaction_async(trans, 1);
59000d71c9cSMiao Xie 		if (err)
5913a45bb20SJeff Mahoney 			err = btrfs_commit_transaction(trans);
59272fd032eSSage Weil 	} else {
5933a45bb20SJeff Mahoney 		err = btrfs_commit_transaction(trans);
59472fd032eSSage Weil 	}
595f46b5a66SChristoph Hellwig 	if (err && !ret)
596f46b5a66SChristoph Hellwig 		ret = err;
5971a65e24bSChris Mason 
5985662344bSTsutomu Itoh 	if (!ret) {
5995662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
600de6e8200SLiu Bo 		if (IS_ERR(inode))
601de6e8200SLiu Bo 			return PTR_ERR(inode);
6025662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
6035662344bSTsutomu Itoh 	}
604f46b5a66SChristoph Hellwig 	return ret;
60549a3c4d9SDavid Sterba 
60649a3c4d9SDavid Sterba fail_free:
60749a3c4d9SDavid Sterba 	kfree(root_item);
60849a3c4d9SDavid Sterba 	return ret;
609f46b5a66SChristoph Hellwig }
610f46b5a66SChristoph Hellwig 
611e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
61261d7e4cbSDavid Sterba 			   struct dentry *dentry,
613e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
614e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
615f46b5a66SChristoph Hellwig {
6160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6172e4bfab9SYan, Zheng 	struct inode *inode;
618f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
619f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
6202e4bfab9SYan, Zheng 	int ret;
621f46b5a66SChristoph Hellwig 
62227cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
623f46b5a66SChristoph Hellwig 		return -EINVAL;
624f46b5a66SChristoph Hellwig 
62523269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
626a1ee7362SDavid Sterba 	if (!pending_snapshot)
627a1ee7362SDavid Sterba 		return -ENOMEM;
628a1ee7362SDavid Sterba 
629b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
63023269bf5SDavid Sterba 			GFP_KERNEL);
6318546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
6328546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
633b0c0ea63SDavid Sterba 		ret = -ENOMEM;
634b0c0ea63SDavid Sterba 		goto free_pending;
635b0c0ea63SDavid Sterba 	}
636b0c0ea63SDavid Sterba 
637ea14b57fSDavid Sterba 	atomic_inc(&root->will_be_snapshotted);
6384e857c58SPeter Zijlstra 	smp_mb__after_atomic();
63945bac0f3SLiu Bo 	/* wait for no snapshot writes */
64045bac0f3SLiu Bo 	wait_event(root->subv_writers->wait,
64145bac0f3SLiu Bo 		   percpu_counter_sum(&root->subv_writers->counter) == 0);
6428257b2dcSMiao Xie 
64376f32e24SNikolay Borisov 	ret = btrfs_start_delalloc_inodes(root);
6446a03843dSMiao Xie 	if (ret)
645a1ee7362SDavid Sterba 		goto dec_and_free;
6466a03843dSMiao Xie 
6476374e57aSChris Mason 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
6486a03843dSMiao Xie 
64966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
65066d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
651d5c12070SMiao Xie 	/*
652d5c12070SMiao Xie 	 * 1 - parent dir inode
653d5c12070SMiao Xie 	 * 2 - dir entries
654d5c12070SMiao Xie 	 * 1 - root item
655d5c12070SMiao Xie 	 * 2 - root ref/backref
656d5c12070SMiao Xie 	 * 1 - root of snapshot
657dd5f9615SStefan Behrens 	 * 1 - UUID item
658d5c12070SMiao Xie 	 */
659d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
660dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
661ee3441b4SJeff Mahoney 					&pending_snapshot->qgroup_reserved,
662ee3441b4SJeff Mahoney 					false);
663d5c12070SMiao Xie 	if (ret)
664a1ee7362SDavid Sterba 		goto dec_and_free;
665d5c12070SMiao Xie 
666a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
667a22285a6SYan, Zheng 	pending_snapshot->root = root;
668b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
669e9662f70SMiao Xie 	pending_snapshot->dir = dir;
6708696c533SMiao Xie 	pending_snapshot->inherit = inherit;
671a22285a6SYan, Zheng 
672d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
673a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
674a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
675a22285a6SYan, Zheng 		goto fail;
676a22285a6SYan, Zheng 	}
677a22285a6SYan, Zheng 
6780b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
679a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
680a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
6810b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
68272fd032eSSage Weil 	if (async_transid) {
68372fd032eSSage Weil 		*async_transid = trans->transid;
6843a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction_async(trans, 1);
68500d71c9cSMiao Xie 		if (ret)
6863a45bb20SJeff Mahoney 			ret = btrfs_commit_transaction(trans);
68772fd032eSSage Weil 	} else {
6883a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
68972fd032eSSage Weil 	}
690aec8030aSMiao Xie 	if (ret)
691c37b2b62SJosef Bacik 		goto fail;
692a22285a6SYan, Zheng 
693a22285a6SYan, Zheng 	ret = pending_snapshot->error;
694f46b5a66SChristoph Hellwig 	if (ret)
6952e4bfab9SYan, Zheng 		goto fail;
696f46b5a66SChristoph Hellwig 
697d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
698d3797308SChris Mason 	if (ret)
699d3797308SChris Mason 		goto fail;
700d3797308SChris Mason 
7012b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
7022e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
7032e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
7042e4bfab9SYan, Zheng 		goto fail;
7052e4bfab9SYan, Zheng 	}
7065662344bSTsutomu Itoh 
7072e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
7082e4bfab9SYan, Zheng 	ret = 0;
7092e4bfab9SYan, Zheng fail:
7107775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
711a1ee7362SDavid Sterba dec_and_free:
712ea14b57fSDavid Sterba 	if (atomic_dec_and_test(&root->will_be_snapshotted))
7134625956aSPeter Zijlstra 		wake_up_var(&root->will_be_snapshotted);
714b0c0ea63SDavid Sterba free_pending:
715b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
7168546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
717a1ee7362SDavid Sterba 	kfree(pending_snapshot);
718a1ee7362SDavid Sterba 
719f46b5a66SChristoph Hellwig 	return ret;
720f46b5a66SChristoph Hellwig }
721f46b5a66SChristoph Hellwig 
7224260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
7234260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
7244260f7c7SSage Weil  *  whether the type of victim is right.
7254260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
7264260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
7274260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
7284260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
7294260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
7304260f7c7SSage Weil  *	a. be owner of dir, or
7314260f7c7SSage Weil  *	b. be owner of victim, or
7324260f7c7SSage Weil  *	c. have CAP_FOWNER capability
73301327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
7344260f7c7SSage Weil  *     links pointing to it.
7354260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
7364260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
7374260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
7384260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
7394260f7c7SSage Weil  *     nfs_async_unlink().
7404260f7c7SSage Weil  */
7414260f7c7SSage Weil 
7424260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
7434260f7c7SSage Weil {
7444260f7c7SSage Weil 	int error;
7454260f7c7SSage Weil 
7462b0143b5SDavid Howells 	if (d_really_is_negative(victim))
7474260f7c7SSage Weil 		return -ENOENT;
7484260f7c7SSage Weil 
7492b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
7504fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
7514260f7c7SSage Weil 
7524260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
7534260f7c7SSage Weil 	if (error)
7544260f7c7SSage Weil 		return error;
7554260f7c7SSage Weil 	if (IS_APPEND(dir))
7564260f7c7SSage Weil 		return -EPERM;
7572b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
7582b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
7594260f7c7SSage Weil 		return -EPERM;
7604260f7c7SSage Weil 	if (isdir) {
761e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
7624260f7c7SSage Weil 			return -ENOTDIR;
7634260f7c7SSage Weil 		if (IS_ROOT(victim))
7644260f7c7SSage Weil 			return -EBUSY;
765e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
7664260f7c7SSage Weil 		return -EISDIR;
7674260f7c7SSage Weil 	if (IS_DEADDIR(dir))
7684260f7c7SSage Weil 		return -ENOENT;
7694260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
7704260f7c7SSage Weil 		return -EBUSY;
7714260f7c7SSage Weil 	return 0;
7724260f7c7SSage Weil }
7734260f7c7SSage Weil 
774cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
775cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
776cb8e7090SChristoph Hellwig {
7772b0143b5SDavid Howells 	if (d_really_is_positive(child))
778cb8e7090SChristoph Hellwig 		return -EEXIST;
779cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
780cb8e7090SChristoph Hellwig 		return -ENOENT;
781cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
782cb8e7090SChristoph Hellwig }
783cb8e7090SChristoph Hellwig 
784cb8e7090SChristoph Hellwig /*
785cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
786cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
787cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
788cb8e7090SChristoph Hellwig  */
78992872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
79052f75f4fSDavid Sterba 				   const char *name, int namelen,
79172fd032eSSage Weil 				   struct btrfs_root *snap_src,
7926f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
7938696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
794cb8e7090SChristoph Hellwig {
7952b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
7960b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
797cb8e7090SChristoph Hellwig 	struct dentry *dentry;
798cb8e7090SChristoph Hellwig 	int error;
799cb8e7090SChristoph Hellwig 
80000235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
80100235411SAl Viro 	if (error == -EINTR)
80200235411SAl Viro 		return error;
803cb8e7090SChristoph Hellwig 
804cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
805cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
806cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
807cb8e7090SChristoph Hellwig 		goto out_unlock;
808cb8e7090SChristoph Hellwig 
80976dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
810cb8e7090SChristoph Hellwig 	if (error)
811a874a63eSLiu Bo 		goto out_dput;
812cb8e7090SChristoph Hellwig 
8139c52057cSChris Mason 	/*
8149c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
8159c52057cSChris Mason 	 * check for them now when we can safely fail
8169c52057cSChris Mason 	 */
8179c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
8189c52057cSChris Mason 					       dir->i_ino, name,
8199c52057cSChris Mason 					       namelen);
8209c52057cSChris Mason 	if (error)
8219c52057cSChris Mason 		goto out_dput;
8229c52057cSChris Mason 
8230b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
82476dda93cSYan, Zheng 
82576dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
82676dda93cSYan, Zheng 		goto out_up_read;
82776dda93cSYan, Zheng 
8283de4586cSChris Mason 	if (snap_src) {
82961d7e4cbSDavid Sterba 		error = create_snapshot(snap_src, dir, dentry,
8306f72c7e2SArne Jansen 					async_transid, readonly, inherit);
8313de4586cSChris Mason 	} else {
832d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
833d5c12070SMiao Xie 				      async_transid, inherit);
8343de4586cSChris Mason 	}
83576dda93cSYan, Zheng 	if (!error)
83676dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
83776dda93cSYan, Zheng out_up_read:
8380b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
839cb8e7090SChristoph Hellwig out_dput:
840cb8e7090SChristoph Hellwig 	dput(dentry);
841cb8e7090SChristoph Hellwig out_unlock:
8425955102cSAl Viro 	inode_unlock(dir);
843cb8e7090SChristoph Hellwig 	return error;
844cb8e7090SChristoph Hellwig }
845cb8e7090SChristoph Hellwig 
8464cb5300bSChris Mason /*
8474cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
8484cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
8494cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
8504cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
8514cb5300bSChris Mason  * part of the file
8524cb5300bSChris Mason  */
853aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
8544cb5300bSChris Mason {
8554cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8564cb5300bSChris Mason 	struct extent_map *em = NULL;
8574cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8584cb5300bSChris Mason 	u64 end;
8594cb5300bSChris Mason 
8604cb5300bSChris Mason 	read_lock(&em_tree->lock);
86109cbfeafSKirill A. Shutemov 	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
8624cb5300bSChris Mason 	read_unlock(&em_tree->lock);
8634cb5300bSChris Mason 
8644cb5300bSChris Mason 	if (em) {
8654cb5300bSChris Mason 		end = extent_map_end(em);
8664cb5300bSChris Mason 		free_extent_map(em);
8674cb5300bSChris Mason 		if (end - offset > thresh)
8684cb5300bSChris Mason 			return 0;
8694cb5300bSChris Mason 	}
8704cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
8714cb5300bSChris Mason 	thresh /= 2;
8724cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
8734cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
8744cb5300bSChris Mason 	if (end >= thresh)
8754cb5300bSChris Mason 		return 0;
8764cb5300bSChris Mason 	return 1;
8774cb5300bSChris Mason }
8784cb5300bSChris Mason 
8794cb5300bSChris Mason /*
8804cb5300bSChris Mason  * helper function to walk through a file and find extents
8814cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
8824cb5300bSChris Mason  *
8834cb5300bSChris Mason  * This is used by the defragging code to find new and small
8844cb5300bSChris Mason  * extents
8854cb5300bSChris Mason  */
8864cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
8874cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
888aab110abSDavid Sterba 			    u64 *off, u32 thresh)
8894cb5300bSChris Mason {
8904cb5300bSChris Mason 	struct btrfs_path *path;
8914cb5300bSChris Mason 	struct btrfs_key min_key;
8924cb5300bSChris Mason 	struct extent_buffer *leaf;
8934cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
8944cb5300bSChris Mason 	int type;
8954cb5300bSChris Mason 	int ret;
8964a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
8974cb5300bSChris Mason 
8984cb5300bSChris Mason 	path = btrfs_alloc_path();
8994cb5300bSChris Mason 	if (!path)
9004cb5300bSChris Mason 		return -ENOMEM;
9014cb5300bSChris Mason 
902a4689d2bSDavid Sterba 	min_key.objectid = ino;
9034cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
9044cb5300bSChris Mason 	min_key.offset = *off;
9054cb5300bSChris Mason 
9064cb5300bSChris Mason 	while (1) {
9076174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
9084cb5300bSChris Mason 		if (ret != 0)
9094cb5300bSChris Mason 			goto none;
910f094c9bdSFilipe Manana process_slot:
911a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
9124cb5300bSChris Mason 			goto none;
9134cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
9144cb5300bSChris Mason 			goto none;
9154cb5300bSChris Mason 
9164cb5300bSChris Mason 		leaf = path->nodes[0];
9174cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
9184cb5300bSChris Mason 					struct btrfs_file_extent_item);
9194cb5300bSChris Mason 
9204cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
9214cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
9224cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
9234cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
9244cb5300bSChris Mason 			*off = min_key.offset;
9254cb5300bSChris Mason 			btrfs_free_path(path);
9264cb5300bSChris Mason 			return 0;
9274cb5300bSChris Mason 		}
9284cb5300bSChris Mason 
929f094c9bdSFilipe Manana 		path->slots[0]++;
930f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
931f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
932f094c9bdSFilipe Manana 			goto process_slot;
933f094c9bdSFilipe Manana 		}
934f094c9bdSFilipe Manana 
9354cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
9364cb5300bSChris Mason 			goto none;
9374cb5300bSChris Mason 
9384cb5300bSChris Mason 		min_key.offset++;
9394cb5300bSChris Mason 		btrfs_release_path(path);
9404cb5300bSChris Mason 	}
9414cb5300bSChris Mason none:
9424cb5300bSChris Mason 	btrfs_free_path(path);
9434cb5300bSChris Mason 	return -ENOENT;
9444cb5300bSChris Mason }
9454cb5300bSChris Mason 
9466c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
94717ce6ef8SLiu Bo {
94817ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
949940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9506c282eb4SLi Zefan 	struct extent_map *em;
95109cbfeafSKirill A. Shutemov 	u64 len = PAGE_SIZE;
952940100a4SChris Mason 
953940100a4SChris Mason 	/*
954940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
955940100a4SChris Mason 	 * the full extent lock
956940100a4SChris Mason 	 */
957940100a4SChris Mason 	read_lock(&em_tree->lock);
958940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
959940100a4SChris Mason 	read_unlock(&em_tree->lock);
960940100a4SChris Mason 
961940100a4SChris Mason 	if (!em) {
962308d9800SFilipe Manana 		struct extent_state *cached = NULL;
963308d9800SFilipe Manana 		u64 end = start + len - 1;
964308d9800SFilipe Manana 
965940100a4SChris Mason 		/* get the big lock and read metadata off disk */
966ff13db41SDavid Sterba 		lock_extent_bits(io_tree, start, end, &cached);
967fc4f21b1SNikolay Borisov 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
968e43bbe5eSDavid Sterba 		unlock_extent_cached(io_tree, start, end, &cached);
969940100a4SChris Mason 
9706cf8bfbfSDan Carpenter 		if (IS_ERR(em))
9716c282eb4SLi Zefan 			return NULL;
972940100a4SChris Mason 	}
973940100a4SChris Mason 
9746c282eb4SLi Zefan 	return em;
9756c282eb4SLi Zefan }
9766c282eb4SLi Zefan 
9776c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
9786c282eb4SLi Zefan {
9796c282eb4SLi Zefan 	struct extent_map *next;
9806c282eb4SLi Zefan 	bool ret = true;
9816c282eb4SLi Zefan 
9826c282eb4SLi Zefan 	/* this is the last extent */
9836c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
9846c282eb4SLi Zefan 		return false;
9856c282eb4SLi Zefan 
9866c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
987e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
988e9512d72SChris Mason 		ret = false;
989e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
990ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
9916c282eb4SLi Zefan 		ret = false;
9926c282eb4SLi Zefan 
9936c282eb4SLi Zefan 	free_extent_map(next);
9946c282eb4SLi Zefan 	return ret;
9956c282eb4SLi Zefan }
9966c282eb4SLi Zefan 
997aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
998a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
999a43a2111SAndrew Mahone 			       int compress)
10006c282eb4SLi Zefan {
10016c282eb4SLi Zefan 	struct extent_map *em;
10026c282eb4SLi Zefan 	int ret = 1;
10036c282eb4SLi Zefan 	bool next_mergeable = true;
10044a3560c4SLiu Bo 	bool prev_mergeable = true;
10056c282eb4SLi Zefan 
10066c282eb4SLi Zefan 	/*
10076c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
10086c282eb4SLi Zefan 	 * defragging it
10096c282eb4SLi Zefan 	 */
10106c282eb4SLi Zefan 	if (start < *defrag_end)
10116c282eb4SLi Zefan 		return 1;
10126c282eb4SLi Zefan 
10136c282eb4SLi Zefan 	*skip = 0;
10146c282eb4SLi Zefan 
10156c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
10166c282eb4SLi Zefan 	if (!em)
10176c282eb4SLi Zefan 		return 0;
10186c282eb4SLi Zefan 
1019940100a4SChris Mason 	/* this will cover holes, and inline extents */
102017ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1021940100a4SChris Mason 		ret = 0;
102217ce6ef8SLiu Bo 		goto out;
102317ce6ef8SLiu Bo 	}
102417ce6ef8SLiu Bo 
10254a3560c4SLiu Bo 	if (!*defrag_end)
10264a3560c4SLiu Bo 		prev_mergeable = false;
10274a3560c4SLiu Bo 
10286c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1029940100a4SChris Mason 	/*
10306c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
10316c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1032940100a4SChris Mason 	 */
1033a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
10344a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1035940100a4SChris Mason 		ret = 0;
103617ce6ef8SLiu Bo out:
1037940100a4SChris Mason 	/*
1038940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1039940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1040940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1041940100a4SChris Mason 	 *
1042940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1043940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1044940100a4SChris Mason 	 */
1045940100a4SChris Mason 	if (ret) {
1046940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1047940100a4SChris Mason 	} else {
1048940100a4SChris Mason 		*last_len = 0;
1049940100a4SChris Mason 		*skip = extent_map_end(em);
1050940100a4SChris Mason 		*defrag_end = 0;
1051940100a4SChris Mason 	}
1052940100a4SChris Mason 
1053940100a4SChris Mason 	free_extent_map(em);
1054940100a4SChris Mason 	return ret;
1055940100a4SChris Mason }
1056940100a4SChris Mason 
10574cb5300bSChris Mason /*
10584cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
10594cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
10604cb5300bSChris Mason  * to COW and defrag.
10614cb5300bSChris Mason  *
10624cb5300bSChris Mason  * It also makes sure the delalloc code has enough
10634cb5300bSChris Mason  * dirty data to avoid making new small extents as part
10644cb5300bSChris Mason  * of the defrag
10654cb5300bSChris Mason  *
10664cb5300bSChris Mason  * It's a good idea to start RA on this range
10674cb5300bSChris Mason  * before calling this.
10684cb5300bSChris Mason  */
10694cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
10704cb5300bSChris Mason 				    struct page **pages,
10714cb5300bSChris Mason 				    unsigned long start_index,
1072c41570c9SJustin Maggard 				    unsigned long num_pages)
1073f46b5a66SChristoph Hellwig {
10744cb5300bSChris Mason 	unsigned long file_end;
10754cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1076f46b5a66SChristoph Hellwig 	u64 page_start;
1077f46b5a66SChristoph Hellwig 	u64 page_end;
10781f12bd06SLiu Bo 	u64 page_cnt;
10794cb5300bSChris Mason 	int ret;
10804cb5300bSChris Mason 	int i;
10814cb5300bSChris Mason 	int i_done;
10824cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
10834cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1084600a45e1SMiao Xie 	struct extent_io_tree *tree;
1085364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
10863b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
10874cb5300bSChris Mason 
108809cbfeafSKirill A. Shutemov 	file_end = (isize - 1) >> PAGE_SHIFT;
10891f12bd06SLiu Bo 	if (!isize || start_index > file_end)
10901f12bd06SLiu Bo 		return 0;
10911f12bd06SLiu Bo 
10921f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
10934cb5300bSChris Mason 
1094364ecf36SQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
109509cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
109609cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
10974cb5300bSChris Mason 	if (ret)
10984cb5300bSChris Mason 		return ret;
10994cb5300bSChris Mason 	i_done = 0;
1100600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
11014cb5300bSChris Mason 
11024cb5300bSChris Mason 	/* step one, lock all the pages */
11031f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
11044cb5300bSChris Mason 		struct page *page;
1105600a45e1SMiao Xie again:
1106a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
11073b16a4e3SJosef Bacik 					   start_index + i, mask);
11084cb5300bSChris Mason 		if (!page)
11094cb5300bSChris Mason 			break;
11104cb5300bSChris Mason 
1111600a45e1SMiao Xie 		page_start = page_offset(page);
111209cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
1113600a45e1SMiao Xie 		while (1) {
1114308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1115ff13db41SDavid Sterba 					 &cached_state);
1116600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1117600a45e1SMiao Xie 							      page_start);
1118308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1119e43bbe5eSDavid Sterba 					     &cached_state);
1120600a45e1SMiao Xie 			if (!ordered)
1121600a45e1SMiao Xie 				break;
1122600a45e1SMiao Xie 
1123600a45e1SMiao Xie 			unlock_page(page);
1124600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1125600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1126600a45e1SMiao Xie 			lock_page(page);
11271f12bd06SLiu Bo 			/*
11281f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
11291f12bd06SLiu Bo 			 * it was released or not.
11301f12bd06SLiu Bo 			 */
11311f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
11321f12bd06SLiu Bo 				unlock_page(page);
113309cbfeafSKirill A. Shutemov 				put_page(page);
11341f12bd06SLiu Bo 				goto again;
11351f12bd06SLiu Bo 			}
1136600a45e1SMiao Xie 		}
1137600a45e1SMiao Xie 
11384cb5300bSChris Mason 		if (!PageUptodate(page)) {
11394cb5300bSChris Mason 			btrfs_readpage(NULL, page);
11404cb5300bSChris Mason 			lock_page(page);
11414cb5300bSChris Mason 			if (!PageUptodate(page)) {
11424cb5300bSChris Mason 				unlock_page(page);
114309cbfeafSKirill A. Shutemov 				put_page(page);
11444cb5300bSChris Mason 				ret = -EIO;
11454cb5300bSChris Mason 				break;
11464cb5300bSChris Mason 			}
11474cb5300bSChris Mason 		}
1148600a45e1SMiao Xie 
1149600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1150600a45e1SMiao Xie 			unlock_page(page);
115109cbfeafSKirill A. Shutemov 			put_page(page);
1152600a45e1SMiao Xie 			goto again;
1153600a45e1SMiao Xie 		}
1154600a45e1SMiao Xie 
11554cb5300bSChris Mason 		pages[i] = page;
11564cb5300bSChris Mason 		i_done++;
11574cb5300bSChris Mason 	}
11584cb5300bSChris Mason 	if (!i_done || ret)
11594cb5300bSChris Mason 		goto out;
11604cb5300bSChris Mason 
11611751e8a6SLinus Torvalds 	if (!(inode->i_sb->s_flags & SB_ACTIVE))
11624cb5300bSChris Mason 		goto out;
11634cb5300bSChris Mason 
11644cb5300bSChris Mason 	/*
11654cb5300bSChris Mason 	 * so now we have a nice long stream of locked
11664cb5300bSChris Mason 	 * and up to date pages, lets wait on them
11674cb5300bSChris Mason 	 */
11684cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
11694cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
11704cb5300bSChris Mason 
11714cb5300bSChris Mason 	page_start = page_offset(pages[0]);
117209cbfeafSKirill A. Shutemov 	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
11734cb5300bSChris Mason 
11744cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1175ff13db41SDavid Sterba 			 page_start, page_end - 1, &cached_state);
11764cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
11774cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
11789e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1179ae0f1625SDavid Sterba 			  &cached_state);
11804cb5300bSChris Mason 
11811f12bd06SLiu Bo 	if (i_done != page_cnt) {
11829e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
11839e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
11849e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
1185bc42bda2SQu Wenruo 		btrfs_delalloc_release_space(inode, data_reserved,
118609cbfeafSKirill A. Shutemov 				start_index << PAGE_SHIFT,
118743b18595SQu Wenruo 				(page_cnt - i_done) << PAGE_SHIFT, true);
11884cb5300bSChris Mason 	}
11894cb5300bSChris Mason 
11904cb5300bSChris Mason 
11919e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1192018ed4f7SDavid Sterba 			  &cached_state);
11934cb5300bSChris Mason 
11944cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1195e43bbe5eSDavid Sterba 			     page_start, page_end - 1, &cached_state);
11964cb5300bSChris Mason 
11974cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
11984cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
11994cb5300bSChris Mason 		ClearPageChecked(pages[i]);
12004cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
12014cb5300bSChris Mason 		set_page_dirty(pages[i]);
12024cb5300bSChris Mason 		unlock_page(pages[i]);
120309cbfeafSKirill A. Shutemov 		put_page(pages[i]);
12044cb5300bSChris Mason 	}
120543b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
120643b18595SQu Wenruo 				       false);
1207364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
12084cb5300bSChris Mason 	return i_done;
12094cb5300bSChris Mason out:
12104cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12114cb5300bSChris Mason 		unlock_page(pages[i]);
121209cbfeafSKirill A. Shutemov 		put_page(pages[i]);
12134cb5300bSChris Mason 	}
1214bc42bda2SQu Wenruo 	btrfs_delalloc_release_space(inode, data_reserved,
121509cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
121643b18595SQu Wenruo 			page_cnt << PAGE_SHIFT, true);
121743b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
121843b18595SQu Wenruo 				       true);
1219364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
12204cb5300bSChris Mason 	return ret;
12214cb5300bSChris Mason 
12224cb5300bSChris Mason }
12234cb5300bSChris Mason 
12244cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
12254cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
12264cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
12274cb5300bSChris Mason {
12280b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
12294cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
12304cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
12314cb5300bSChris Mason 	unsigned long last_index;
1232151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1233940100a4SChris Mason 	u64 last_len = 0;
1234940100a4SChris Mason 	u64 skip = 0;
1235940100a4SChris Mason 	u64 defrag_end = 0;
12364cb5300bSChris Mason 	u64 newer_off = range->start;
1237f46b5a66SChristoph Hellwig 	unsigned long i;
1238008873eaSLi Zefan 	unsigned long ra_index = 0;
1239f46b5a66SChristoph Hellwig 	int ret;
12404cb5300bSChris Mason 	int defrag_count = 0;
12411a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1242aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
124309cbfeafSKirill A. Shutemov 	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1244c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
1245ee22184bSByongho Lee 	u64 new_align = ~((u64)SZ_128K - 1);
12464cb5300bSChris Mason 	struct page **pages = NULL;
12471e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
12484cb5300bSChris Mason 
12490abd5b17SLiu Bo 	if (isize == 0)
12500abd5b17SLiu Bo 		return 0;
12510abd5b17SLiu Bo 
12520abd5b17SLiu Bo 	if (range->start >= isize)
12530abd5b17SLiu Bo 		return -EINVAL;
12541a419d85SLi Zefan 
12551e2ef46dSDavid Sterba 	if (do_compress) {
12561a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
12571a419d85SLi Zefan 			return -EINVAL;
12581a419d85SLi Zefan 		if (range->compress_type)
12591a419d85SLi Zefan 			compress_type = range->compress_type;
12601a419d85SLi Zefan 	}
1261f46b5a66SChristoph Hellwig 
12620abd5b17SLiu Bo 	if (extent_thresh == 0)
1263ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1264f46b5a66SChristoph Hellwig 
12654cb5300bSChris Mason 	/*
12660a52d108SDavid Sterba 	 * If we were not given a file, allocate a readahead context. As
12670a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
12680a52d108SDavid Sterba 	 * we don't error out.
12694cb5300bSChris Mason 	 */
12704cb5300bSChris Mason 	if (!file) {
127163e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
12720a52d108SDavid Sterba 		if (ra)
12734cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
12744cb5300bSChris Mason 	} else {
12754cb5300bSChris Mason 		ra = &file->f_ra;
12764cb5300bSChris Mason 	}
12774cb5300bSChris Mason 
127863e727ecSDavid Sterba 	pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
12794cb5300bSChris Mason 	if (!pages) {
12804cb5300bSChris Mason 		ret = -ENOMEM;
12814cb5300bSChris Mason 		goto out_ra;
12824cb5300bSChris Mason 	}
12834cb5300bSChris Mason 
12844cb5300bSChris Mason 	/* find the last page to defrag */
12851e701a32SChris Mason 	if (range->start + range->len > range->start) {
1286151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
128709cbfeafSKirill A. Shutemov 			 range->start + range->len - 1) >> PAGE_SHIFT;
12881e701a32SChris Mason 	} else {
128909cbfeafSKirill A. Shutemov 		last_index = (isize - 1) >> PAGE_SHIFT;
12901e701a32SChris Mason 	}
12911e701a32SChris Mason 
12924cb5300bSChris Mason 	if (newer_than) {
12934cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
1294ee22184bSByongho Lee 				       &newer_off, SZ_64K);
12954cb5300bSChris Mason 		if (!ret) {
12964cb5300bSChris Mason 			range->start = newer_off;
12974cb5300bSChris Mason 			/*
12984cb5300bSChris Mason 			 * we always align our defrag to help keep
12994cb5300bSChris Mason 			 * the extents in the file evenly spaced
13004cb5300bSChris Mason 			 */
130109cbfeafSKirill A. Shutemov 			i = (newer_off & new_align) >> PAGE_SHIFT;
13024cb5300bSChris Mason 		} else
13034cb5300bSChris Mason 			goto out_ra;
13044cb5300bSChris Mason 	} else {
130509cbfeafSKirill A. Shutemov 		i = range->start >> PAGE_SHIFT;
13064cb5300bSChris Mason 	}
13074cb5300bSChris Mason 	if (!max_to_defrag)
1308070034bdSchandan 		max_to_defrag = last_index - i + 1;
13094cb5300bSChris Mason 
13102a0f7f57SLi Zefan 	/*
13112a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
13122a0f7f57SLi Zefan 	 * written sequentially.
13132a0f7f57SLi Zefan 	 */
13142a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
13152a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
13162a0f7f57SLi Zefan 
1317f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
131809cbfeafSKirill A. Shutemov 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
13194cb5300bSChris Mason 		/*
13204cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
13214cb5300bSChris Mason 		 * the FS
13224cb5300bSChris Mason 		 */
13231751e8a6SLinus Torvalds 		if (!(inode->i_sb->s_flags & SB_ACTIVE))
13244cb5300bSChris Mason 			break;
13254cb5300bSChris Mason 
13260b246afaSJeff Mahoney 		if (btrfs_defrag_cancelled(fs_info)) {
13270b246afaSJeff Mahoney 			btrfs_debug(fs_info, "defrag_file cancelled");
1328210549ebSDavid Sterba 			ret = -EAGAIN;
1329210549ebSDavid Sterba 			break;
1330210549ebSDavid Sterba 		}
1331210549ebSDavid Sterba 
133209cbfeafSKirill A. Shutemov 		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
13336c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
13341e2ef46dSDavid Sterba 					 &defrag_end, do_compress)){
1335940100a4SChris Mason 			unsigned long next;
1336940100a4SChris Mason 			/*
1337940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1338940100a4SChris Mason 			 * bump our counter by the suggested amount
1339940100a4SChris Mason 			 */
134009cbfeafSKirill A. Shutemov 			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1341940100a4SChris Mason 			i = max(i + 1, next);
1342940100a4SChris Mason 			continue;
1343940100a4SChris Mason 		}
1344008873eaSLi Zefan 
1345008873eaSLi Zefan 		if (!newer_than) {
134609cbfeafSKirill A. Shutemov 			cluster = (PAGE_ALIGN(defrag_end) >>
134709cbfeafSKirill A. Shutemov 				   PAGE_SHIFT) - i;
1348008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1349008873eaSLi Zefan 		} else {
1350008873eaSLi Zefan 			cluster = max_cluster;
1351008873eaSLi Zefan 		}
1352008873eaSLi Zefan 
1353008873eaSLi Zefan 		if (i + cluster > ra_index) {
1354008873eaSLi Zefan 			ra_index = max(i, ra_index);
13550a52d108SDavid Sterba 			if (ra)
1356d3c0bab5SDavid Sterba 				page_cache_sync_readahead(inode->i_mapping, ra,
1357d3c0bab5SDavid Sterba 						file, ra_index, cluster);
1358e4826a5bSchandan 			ra_index += cluster;
1359008873eaSLi Zefan 		}
13604cb5300bSChris Mason 
13615955102cSAl Viro 		inode_lock(inode);
13621e2ef46dSDavid Sterba 		if (do_compress)
1363eec63c65SDavid Sterba 			BTRFS_I(inode)->defrag_compress = compress_type;
1364008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1365ecb8bea8SLiu Bo 		if (ret < 0) {
13665955102cSAl Viro 			inode_unlock(inode);
13674cb5300bSChris Mason 			goto out_ra;
1368ecb8bea8SLiu Bo 		}
13694cb5300bSChris Mason 
13704cb5300bSChris Mason 		defrag_count += ret;
1371d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
13725955102cSAl Viro 		inode_unlock(inode);
13734cb5300bSChris Mason 
13744cb5300bSChris Mason 		if (newer_than) {
13754cb5300bSChris Mason 			if (newer_off == (u64)-1)
13764cb5300bSChris Mason 				break;
13774cb5300bSChris Mason 
1378e1f041e1SLiu Bo 			if (ret > 0)
1379e1f041e1SLiu Bo 				i += ret;
1380e1f041e1SLiu Bo 
13814cb5300bSChris Mason 			newer_off = max(newer_off + 1,
138209cbfeafSKirill A. Shutemov 					(u64)i << PAGE_SHIFT);
13834cb5300bSChris Mason 
1384ee22184bSByongho Lee 			ret = find_new_extents(root, inode, newer_than,
1385ee22184bSByongho Lee 					       &newer_off, SZ_64K);
13864cb5300bSChris Mason 			if (!ret) {
13874cb5300bSChris Mason 				range->start = newer_off;
138809cbfeafSKirill A. Shutemov 				i = (newer_off & new_align) >> PAGE_SHIFT;
13894cb5300bSChris Mason 			} else {
13904cb5300bSChris Mason 				break;
1391940100a4SChris Mason 			}
13924cb5300bSChris Mason 		} else {
1393008873eaSLi Zefan 			if (ret > 0) {
1394cbcc8326SLi Zefan 				i += ret;
139509cbfeafSKirill A. Shutemov 				last_len += ret << PAGE_SHIFT;
1396008873eaSLi Zefan 			} else {
1397940100a4SChris Mason 				i++;
1398008873eaSLi Zefan 				last_len = 0;
1399008873eaSLi Zefan 			}
1400f46b5a66SChristoph Hellwig 		}
14014cb5300bSChris Mason 	}
1402f46b5a66SChristoph Hellwig 
1403dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
14041e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1405dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1406dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1407dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1408dec8ef90SFilipe Manana 	}
14091e701a32SChris Mason 
14101a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
14110b246afaSJeff Mahoney 		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
14125c1aab1dSNick Terrell 	} else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
14135c1aab1dSNick Terrell 		btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
14141a419d85SLi Zefan 	}
14151a419d85SLi Zefan 
141660ccf82fSDiego Calleja 	ret = defrag_count;
1417940100a4SChris Mason 
14184cb5300bSChris Mason out_ra:
14191e2ef46dSDavid Sterba 	if (do_compress) {
14205955102cSAl Viro 		inode_lock(inode);
1421eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
14225955102cSAl Viro 		inode_unlock(inode);
1423633085c7SFilipe David Borba Manana 	}
14244cb5300bSChris Mason 	if (!file)
14254cb5300bSChris Mason 		kfree(ra);
14264cb5300bSChris Mason 	kfree(pages);
1427940100a4SChris Mason 	return ret;
1428f46b5a66SChristoph Hellwig }
1429f46b5a66SChristoph Hellwig 
1430198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
143176dda93cSYan, Zheng 					void __user *arg)
1432f46b5a66SChristoph Hellwig {
14330b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
14340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1435f46b5a66SChristoph Hellwig 	u64 new_size;
1436f46b5a66SChristoph Hellwig 	u64 old_size;
1437f46b5a66SChristoph Hellwig 	u64 devid = 1;
14380b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1439f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1440f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1441f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1442f46b5a66SChristoph Hellwig 	char *sizestr;
14439a40f122SGui Hecheng 	char *retptr;
1444f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1445f46b5a66SChristoph Hellwig 	int ret = 0;
1446f46b5a66SChristoph Hellwig 	int mod = 0;
1447f46b5a66SChristoph Hellwig 
1448e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1449e441d54dSChris Mason 		return -EPERM;
1450e441d54dSChris Mason 
1451198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1452198605a8SMiao Xie 	if (ret)
1453198605a8SMiao Xie 		return ret;
1454198605a8SMiao Xie 
1455171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
145697547676SMiao Xie 		mnt_drop_write_file(file);
1457e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1458c9e9f97bSIlya Dryomov 	}
1459c9e9f97bSIlya Dryomov 
1460dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1461c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1462c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1463c9e9f97bSIlya Dryomov 		goto out;
1464c9e9f97bSIlya Dryomov 	}
14655516e595SMark Fasheh 
14665516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1467f46b5a66SChristoph Hellwig 
1468f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1469f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1470f46b5a66SChristoph Hellwig 	if (devstr) {
1471f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1472f46b5a66SChristoph Hellwig 		*devstr = '\0';
1473f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
147458dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
147558dfae63SZhangZhen 		if (ret)
147658dfae63SZhangZhen 			goto out_free;
1477dfd79829SMiao Xie 		if (!devid) {
1478dfd79829SMiao Xie 			ret = -EINVAL;
1479dfd79829SMiao Xie 			goto out_free;
1480dfd79829SMiao Xie 		}
14810b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1482f46b5a66SChristoph Hellwig 	}
1483dba60f3fSMiao Xie 
14840b246afaSJeff Mahoney 	device = btrfs_find_device(fs_info, devid, NULL, NULL);
1485f46b5a66SChristoph Hellwig 	if (!device) {
14860b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1487c1c9ff7cSGeert Uytterhoeven 			   devid);
1488dfd79829SMiao Xie 		ret = -ENODEV;
1489c9e9f97bSIlya Dryomov 		goto out_free;
1490f46b5a66SChristoph Hellwig 	}
1491dba60f3fSMiao Xie 
1492ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
14930b246afaSJeff Mahoney 		btrfs_info(fs_info,
1494efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1495c1c9ff7cSGeert Uytterhoeven 		       devid);
1496dfd79829SMiao Xie 		ret = -EPERM;
14974e42ae1bSLiu Bo 		goto out_free;
14984e42ae1bSLiu Bo 	}
14994e42ae1bSLiu Bo 
1500f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1501f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1502f46b5a66SChristoph Hellwig 	else {
1503f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1504f46b5a66SChristoph Hellwig 			mod = -1;
1505f46b5a66SChristoph Hellwig 			sizestr++;
1506f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1507f46b5a66SChristoph Hellwig 			mod = 1;
1508f46b5a66SChristoph Hellwig 			sizestr++;
1509f46b5a66SChristoph Hellwig 		}
15109a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
15119a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1512f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1513c9e9f97bSIlya Dryomov 			goto out_free;
1514f46b5a66SChristoph Hellwig 		}
1515f46b5a66SChristoph Hellwig 	}
1516f46b5a66SChristoph Hellwig 
1517401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1518dfd79829SMiao Xie 		ret = -EPERM;
151963a212abSStefan Behrens 		goto out_free;
152063a212abSStefan Behrens 	}
152163a212abSStefan Behrens 
15227cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1523f46b5a66SChristoph Hellwig 
1524f46b5a66SChristoph Hellwig 	if (mod < 0) {
1525f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1526f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1527c9e9f97bSIlya Dryomov 			goto out_free;
1528f46b5a66SChristoph Hellwig 		}
1529f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1530f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1531eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1532902c68a4SGui Hecheng 			ret = -ERANGE;
1533eb8052e0SWenliang Fan 			goto out_free;
1534eb8052e0SWenliang Fan 		}
1535f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1536f46b5a66SChristoph Hellwig 	}
1537f46b5a66SChristoph Hellwig 
1538ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1539f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1540c9e9f97bSIlya Dryomov 		goto out_free;
1541f46b5a66SChristoph Hellwig 	}
1542f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1543f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1544c9e9f97bSIlya Dryomov 		goto out_free;
1545f46b5a66SChristoph Hellwig 	}
1546f46b5a66SChristoph Hellwig 
154747f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1548f46b5a66SChristoph Hellwig 
15490b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1550c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1551f46b5a66SChristoph Hellwig 
1552f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1553a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
155498d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
155598d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1556c9e9f97bSIlya Dryomov 			goto out_free;
155798d5dc13STsutomu Itoh 		}
1558f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
15593a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1560ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1561f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
15620253f40eSjeff.liu 	} /* equal, nothing need to do */
1563f46b5a66SChristoph Hellwig 
1564c9e9f97bSIlya Dryomov out_free:
1565f46b5a66SChristoph Hellwig 	kfree(vol_args);
1566c9e9f97bSIlya Dryomov out:
1567171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
156818f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1569f46b5a66SChristoph Hellwig 	return ret;
1570f46b5a66SChristoph Hellwig }
1571f46b5a66SChristoph Hellwig 
157272fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
157352f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
15746f72c7e2SArne Jansen 				u64 *transid, bool readonly,
15758696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1576f46b5a66SChristoph Hellwig {
1577f46b5a66SChristoph Hellwig 	int namelen;
15783de4586cSChris Mason 	int ret = 0;
1579f46b5a66SChristoph Hellwig 
1580325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1581325c50e3SJeff Mahoney 		return -ENOTDIR;
1582325c50e3SJeff Mahoney 
1583a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1584a874a63eSLiu Bo 	if (ret)
1585a874a63eSLiu Bo 		goto out;
1586a874a63eSLiu Bo 
158772fd032eSSage Weil 	namelen = strlen(name);
158872fd032eSSage Weil 	if (strchr(name, '/')) {
1589f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1590a874a63eSLiu Bo 		goto out_drop_write;
1591f46b5a66SChristoph Hellwig 	}
1592f46b5a66SChristoph Hellwig 
159316780cabSChris Mason 	if (name[0] == '.' &&
159416780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
159516780cabSChris Mason 		ret = -EEXIST;
1596a874a63eSLiu Bo 		goto out_drop_write;
159716780cabSChris Mason 	}
159816780cabSChris Mason 
15993de4586cSChris Mason 	if (subvol) {
160072fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
16016f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1602cb8e7090SChristoph Hellwig 	} else {
16032903ff01SAl Viro 		struct fd src = fdget(fd);
16043de4586cSChris Mason 		struct inode *src_inode;
16052903ff01SAl Viro 		if (!src.file) {
16063de4586cSChris Mason 			ret = -EINVAL;
1607a874a63eSLiu Bo 			goto out_drop_write;
16083de4586cSChris Mason 		}
16093de4586cSChris Mason 
1610496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1611496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1612c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1613efe120a0SFrank Holton 				   "Snapshot src from another FS");
161423ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1615d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1616d0242061SDavid Sterba 			/*
1617d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1618d0242061SDavid Sterba 			 * are limited to own subvolumes only
1619d0242061SDavid Sterba 			 */
1620d0242061SDavid Sterba 			ret = -EPERM;
1621ecd18815SAl Viro 		} else {
162272fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
162372fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
16246f72c7e2SArne Jansen 					     transid, readonly, inherit);
1625ecd18815SAl Viro 		}
16262903ff01SAl Viro 		fdput(src);
1627cb8e7090SChristoph Hellwig 	}
1628a874a63eSLiu Bo out_drop_write:
1629a874a63eSLiu Bo 	mnt_drop_write_file(file);
1630f46b5a66SChristoph Hellwig out:
163172fd032eSSage Weil 	return ret;
163272fd032eSSage Weil }
163372fd032eSSage Weil 
163472fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1635fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
163672fd032eSSage Weil {
1637fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
163872fd032eSSage Weil 	int ret;
163972fd032eSSage Weil 
1640325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1641325c50e3SJeff Mahoney 		return -ENOTDIR;
1642325c50e3SJeff Mahoney 
1643fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1644fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1645fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1646fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1647fa0d2b9bSLi Zefan 
1648fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1649b83cc969SLi Zefan 					      vol_args->fd, subvol,
16506f72c7e2SArne Jansen 					      NULL, false, NULL);
1651fa0d2b9bSLi Zefan 
1652fa0d2b9bSLi Zefan 	kfree(vol_args);
1653fa0d2b9bSLi Zefan 	return ret;
1654fa0d2b9bSLi Zefan }
1655fa0d2b9bSLi Zefan 
1656fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1657fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1658fa0d2b9bSLi Zefan {
1659fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1660fa0d2b9bSLi Zefan 	int ret;
1661fdfb1e4fSLi Zefan 	u64 transid = 0;
1662fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1663b83cc969SLi Zefan 	bool readonly = false;
16646f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
166572fd032eSSage Weil 
1666325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1667325c50e3SJeff Mahoney 		return -ENOTDIR;
1668325c50e3SJeff Mahoney 
1669fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1670fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1671fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1672fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1673fdfb1e4fSLi Zefan 
1674b83cc969SLi Zefan 	if (vol_args->flags &
16756f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
16766f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1677b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1678c47ca32dSDan Carpenter 		goto free_args;
1679fdfb1e4fSLi Zefan 	}
1680fdfb1e4fSLi Zefan 
1681fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1682fdfb1e4fSLi Zefan 		ptr = &transid;
1683b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1684b83cc969SLi Zefan 		readonly = true;
16856f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
168609cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
16876f72c7e2SArne Jansen 			ret = -EINVAL;
1688c47ca32dSDan Carpenter 			goto free_args;
16896f72c7e2SArne Jansen 		}
16906f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
16916f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
16926f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1693c47ca32dSDan Carpenter 			goto free_args;
16946f72c7e2SArne Jansen 		}
16956f72c7e2SArne Jansen 	}
169675eaa0e2SSage Weil 
1697fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
16986f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
16998696c533SMiao Xie 					      readonly, inherit);
1700c47ca32dSDan Carpenter 	if (ret)
1701c47ca32dSDan Carpenter 		goto free_inherit;
170275eaa0e2SSage Weil 
1703c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1704fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1705c47ca32dSDan Carpenter 					transid),
1706c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
170775eaa0e2SSage Weil 		ret = -EFAULT;
1708c47ca32dSDan Carpenter 
1709c47ca32dSDan Carpenter free_inherit:
17106f72c7e2SArne Jansen 	kfree(inherit);
1711c47ca32dSDan Carpenter free_args:
1712c47ca32dSDan Carpenter 	kfree(vol_args);
1713f46b5a66SChristoph Hellwig 	return ret;
1714f46b5a66SChristoph Hellwig }
1715f46b5a66SChristoph Hellwig 
17160caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
17170caa102dSLi Zefan 						void __user *arg)
17180caa102dSLi Zefan {
1719496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17210caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17220caa102dSLi Zefan 	int ret = 0;
17230caa102dSLi Zefan 	u64 flags = 0;
17240caa102dSLi Zefan 
17254a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
17260caa102dSLi Zefan 		return -EINVAL;
17270caa102dSLi Zefan 
17280b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
17290caa102dSLi Zefan 	if (btrfs_root_readonly(root))
17300caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
17310b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
17320caa102dSLi Zefan 
17330caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
17340caa102dSLi Zefan 		ret = -EFAULT;
17350caa102dSLi Zefan 
17360caa102dSLi Zefan 	return ret;
17370caa102dSLi Zefan }
17380caa102dSLi Zefan 
17390caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
17400caa102dSLi Zefan 					      void __user *arg)
17410caa102dSLi Zefan {
1742496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17440caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17450caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
17460caa102dSLi Zefan 	u64 root_flags;
17470caa102dSLi Zefan 	u64 flags;
17480caa102dSLi Zefan 	int ret = 0;
17490caa102dSLi Zefan 
1750bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1751bd60ea0fSDavid Sterba 		return -EPERM;
1752bd60ea0fSDavid Sterba 
1753b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1754b9ca0664SLiu Bo 	if (ret)
1755b9ca0664SLiu Bo 		goto out;
17560caa102dSLi Zefan 
17574a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1758b9ca0664SLiu Bo 		ret = -EINVAL;
1759b9ca0664SLiu Bo 		goto out_drop_write;
1760b9ca0664SLiu Bo 	}
17610caa102dSLi Zefan 
1762b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1763b9ca0664SLiu Bo 		ret = -EFAULT;
1764b9ca0664SLiu Bo 		goto out_drop_write;
1765b9ca0664SLiu Bo 	}
17660caa102dSLi Zefan 
1767b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1768b9ca0664SLiu Bo 		ret = -EINVAL;
1769b9ca0664SLiu Bo 		goto out_drop_write;
1770b9ca0664SLiu Bo 	}
17710caa102dSLi Zefan 
1772b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1773b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1774b9ca0664SLiu Bo 		goto out_drop_write;
1775b9ca0664SLiu Bo 	}
17760caa102dSLi Zefan 
17770b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
17780caa102dSLi Zefan 
17790caa102dSLi Zefan 	/* nothing to do */
17800caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1781b9ca0664SLiu Bo 		goto out_drop_sem;
17820caa102dSLi Zefan 
17830caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
17842c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
17850caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
17860caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
17872c686537SDavid Sterba 	} else {
17882c686537SDavid Sterba 		/*
17892c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
17902c686537SDavid Sterba 		 * send
17912c686537SDavid Sterba 		 */
17922c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
17932c686537SDavid Sterba 		if (root->send_in_progress == 0) {
17940caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
17950caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
17962c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
17972c686537SDavid Sterba 		} else {
17982c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
17990b246afaSJeff Mahoney 			btrfs_warn(fs_info,
18002c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
18012c686537SDavid Sterba 				   root->root_key.objectid);
18022c686537SDavid Sterba 			ret = -EPERM;
18032c686537SDavid Sterba 			goto out_drop_sem;
18042c686537SDavid Sterba 		}
18052c686537SDavid Sterba 	}
18060caa102dSLi Zefan 
18070caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
18080caa102dSLi Zefan 	if (IS_ERR(trans)) {
18090caa102dSLi Zefan 		ret = PTR_ERR(trans);
18100caa102dSLi Zefan 		goto out_reset;
18110caa102dSLi Zefan 	}
18120caa102dSLi Zefan 
18130b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
18140caa102dSLi Zefan 				&root->root_key, &root->root_item);
18159417ebc8SNikolay Borisov 	if (ret < 0) {
18169417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
18179417ebc8SNikolay Borisov 		goto out_reset;
18189417ebc8SNikolay Borisov 	}
18190caa102dSLi Zefan 
18209417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
18219417ebc8SNikolay Borisov 
18220caa102dSLi Zefan out_reset:
18230caa102dSLi Zefan 	if (ret)
18240caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1825b9ca0664SLiu Bo out_drop_sem:
18260b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
1827b9ca0664SLiu Bo out_drop_write:
1828b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1829b9ca0664SLiu Bo out:
18300caa102dSLi Zefan 	return ret;
18310caa102dSLi Zefan }
18320caa102dSLi Zefan 
1833ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1834ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1835ac8e9819SChris Mason {
1836abc6e134SChris Mason 	struct btrfs_key test;
1837abc6e134SChris Mason 	int ret;
1838abc6e134SChris Mason 
1839abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1840abc6e134SChris Mason 	test.type = sk->min_type;
1841abc6e134SChris Mason 	test.offset = sk->min_offset;
1842abc6e134SChris Mason 
1843abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1844abc6e134SChris Mason 	if (ret < 0)
1845ac8e9819SChris Mason 		return 0;
1846abc6e134SChris Mason 
1847abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1848abc6e134SChris Mason 	test.type = sk->max_type;
1849abc6e134SChris Mason 	test.offset = sk->max_offset;
1850abc6e134SChris Mason 
1851abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1852abc6e134SChris Mason 	if (ret > 0)
1853ac8e9819SChris Mason 		return 0;
1854ac8e9819SChris Mason 	return 1;
1855ac8e9819SChris Mason }
1856ac8e9819SChris Mason 
1857df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
1858ac8e9819SChris Mason 			       struct btrfs_key *key,
1859ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
18609b6e817dSGerhard Heift 			       size_t *buf_size,
1861ba346b35SGerhard Heift 			       char __user *ubuf,
1862ac8e9819SChris Mason 			       unsigned long *sk_offset,
1863ac8e9819SChris Mason 			       int *num_found)
1864ac8e9819SChris Mason {
1865ac8e9819SChris Mason 	u64 found_transid;
1866ac8e9819SChris Mason 	struct extent_buffer *leaf;
1867ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
1868dd81d459SNaohiro Aota 	struct btrfs_key test;
1869ac8e9819SChris Mason 	unsigned long item_off;
1870ac8e9819SChris Mason 	unsigned long item_len;
1871ac8e9819SChris Mason 	int nritems;
1872ac8e9819SChris Mason 	int i;
1873ac8e9819SChris Mason 	int slot;
1874ac8e9819SChris Mason 	int ret = 0;
1875ac8e9819SChris Mason 
1876ac8e9819SChris Mason 	leaf = path->nodes[0];
1877ac8e9819SChris Mason 	slot = path->slots[0];
1878ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
1879ac8e9819SChris Mason 
1880ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
1881ac8e9819SChris Mason 		i = nritems;
1882ac8e9819SChris Mason 		goto advance_key;
1883ac8e9819SChris Mason 	}
1884ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
1885ac8e9819SChris Mason 
1886ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
1887ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
1888ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
1889ac8e9819SChris Mason 
189003b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
189103b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
189203b71c6cSGabriel de Perthuis 			continue;
189303b71c6cSGabriel de Perthuis 
18949b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
18958f5f6178SGerhard Heift 			if (*num_found) {
1896ac8e9819SChris Mason 				ret = 1;
18978f5f6178SGerhard Heift 				goto out;
18988f5f6178SGerhard Heift 			}
18998f5f6178SGerhard Heift 
19008f5f6178SGerhard Heift 			/*
19018f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
19028f5f6178SGerhard Heift 			 * handle -EOVERFLOW
19038f5f6178SGerhard Heift 			 */
19048f5f6178SGerhard Heift 
19059b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
1906ac8e9819SChris Mason 			item_len = 0;
19078f5f6178SGerhard Heift 			ret = -EOVERFLOW;
19088f5f6178SGerhard Heift 		}
1909ac8e9819SChris Mason 
19109b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
1911ac8e9819SChris Mason 			ret = 1;
191225c9bc2eSGerhard Heift 			goto out;
1913ac8e9819SChris Mason 		}
1914ac8e9819SChris Mason 
1915ac8e9819SChris Mason 		sh.objectid = key->objectid;
1916ac8e9819SChris Mason 		sh.offset = key->offset;
1917ac8e9819SChris Mason 		sh.type = key->type;
1918ac8e9819SChris Mason 		sh.len = item_len;
1919ac8e9819SChris Mason 		sh.transid = found_transid;
1920ac8e9819SChris Mason 
1921ac8e9819SChris Mason 		/* copy search result header */
1922ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
1923ba346b35SGerhard Heift 			ret = -EFAULT;
1924ba346b35SGerhard Heift 			goto out;
1925ba346b35SGerhard Heift 		}
1926ba346b35SGerhard Heift 
1927ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
1928ac8e9819SChris Mason 
1929ac8e9819SChris Mason 		if (item_len) {
1930ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
1931ac8e9819SChris Mason 			/* copy the item */
1932ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
1933ba346b35SGerhard Heift 						       item_off, item_len)) {
1934ba346b35SGerhard Heift 				ret = -EFAULT;
1935ba346b35SGerhard Heift 				goto out;
1936ba346b35SGerhard Heift 			}
1937ba346b35SGerhard Heift 
1938ac8e9819SChris Mason 			*sk_offset += item_len;
1939ac8e9819SChris Mason 		}
1940e2156867SHugo Mills 		(*num_found)++;
1941ac8e9819SChris Mason 
19428f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
19438f5f6178SGerhard Heift 			goto out;
19448f5f6178SGerhard Heift 
194525c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
194625c9bc2eSGerhard Heift 			ret = 1;
194725c9bc2eSGerhard Heift 			goto out;
194825c9bc2eSGerhard Heift 		}
1949ac8e9819SChris Mason 	}
1950ac8e9819SChris Mason advance_key:
1951ac8e9819SChris Mason 	ret = 0;
1952dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
1953dd81d459SNaohiro Aota 	test.type = sk->max_type;
1954dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
1955dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
1956dd81d459SNaohiro Aota 		ret = 1;
1957dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
1958abc6e134SChris Mason 		key->offset++;
1959dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
1960abc6e134SChris Mason 		key->offset = 0;
1961abc6e134SChris Mason 		key->type++;
1962dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
1963abc6e134SChris Mason 		key->offset = 0;
1964abc6e134SChris Mason 		key->type = 0;
1965abc6e134SChris Mason 		key->objectid++;
1966abc6e134SChris Mason 	} else
1967abc6e134SChris Mason 		ret = 1;
196825c9bc2eSGerhard Heift out:
1969ba346b35SGerhard Heift 	/*
1970ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
1971ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
1972ba346b35SGerhard Heift 	 *     * all items were found
1973ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
1974ba346b35SGerhard Heift 	 *     leaf
1975ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
1976ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
1977ba346b35SGerhard Heift 	 */
1978ac8e9819SChris Mason 	return ret;
1979ac8e9819SChris Mason }
1980ac8e9819SChris Mason 
1981ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
198212544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
19839b6e817dSGerhard Heift 				 size_t *buf_size,
1984ba346b35SGerhard Heift 				 char __user *ubuf)
1985ac8e9819SChris Mason {
19860b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
1987ac8e9819SChris Mason 	struct btrfs_root *root;
1988ac8e9819SChris Mason 	struct btrfs_key key;
1989ac8e9819SChris Mason 	struct btrfs_path *path;
1990ac8e9819SChris Mason 	int ret;
1991ac8e9819SChris Mason 	int num_found = 0;
1992ac8e9819SChris Mason 	unsigned long sk_offset = 0;
1993ac8e9819SChris Mason 
19949b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
19959b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
199612544442SGerhard Heift 		return -EOVERFLOW;
19979b6e817dSGerhard Heift 	}
199812544442SGerhard Heift 
1999ac8e9819SChris Mason 	path = btrfs_alloc_path();
2000ac8e9819SChris Mason 	if (!path)
2001ac8e9819SChris Mason 		return -ENOMEM;
2002ac8e9819SChris Mason 
2003ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2004ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2005ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2006ac8e9819SChris Mason 	} else {
2007ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2008ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2009ac8e9819SChris Mason 		key.offset = (u64)-1;
2010ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2011ac8e9819SChris Mason 		if (IS_ERR(root)) {
2012ac8e9819SChris Mason 			btrfs_free_path(path);
2013ac8e9819SChris Mason 			return -ENOENT;
2014ac8e9819SChris Mason 		}
2015ac8e9819SChris Mason 	}
2016ac8e9819SChris Mason 
2017ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2018ac8e9819SChris Mason 	key.type = sk->min_type;
2019ac8e9819SChris Mason 	key.offset = sk->min_offset;
2020ac8e9819SChris Mason 
2021ac8e9819SChris Mason 	while (1) {
20226174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2023ac8e9819SChris Mason 		if (ret != 0) {
2024ac8e9819SChris Mason 			if (ret > 0)
2025ac8e9819SChris Mason 				ret = 0;
2026ac8e9819SChris Mason 			goto err;
2027ac8e9819SChris Mason 		}
2028df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2029ac8e9819SChris Mason 				 &sk_offset, &num_found);
2030b3b4aa74SDavid Sterba 		btrfs_release_path(path);
203125c9bc2eSGerhard Heift 		if (ret)
2032ac8e9819SChris Mason 			break;
2033ac8e9819SChris Mason 
2034ac8e9819SChris Mason 	}
20358f5f6178SGerhard Heift 	if (ret > 0)
2036ac8e9819SChris Mason 		ret = 0;
2037ac8e9819SChris Mason err:
2038ac8e9819SChris Mason 	sk->nr_items = num_found;
2039ac8e9819SChris Mason 	btrfs_free_path(path);
2040ac8e9819SChris Mason 	return ret;
2041ac8e9819SChris Mason }
2042ac8e9819SChris Mason 
2043ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2044ac8e9819SChris Mason 					   void __user *argp)
2045ac8e9819SChris Mason {
2046ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2047ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2048ac8e9819SChris Mason 	struct inode *inode;
2049ac8e9819SChris Mason 	int ret;
20509b6e817dSGerhard Heift 	size_t buf_size;
2051ac8e9819SChris Mason 
2052ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2053ac8e9819SChris Mason 		return -EPERM;
2054ac8e9819SChris Mason 
2055ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2056ac8e9819SChris Mason 
2057ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2058ba346b35SGerhard Heift 		return -EFAULT;
2059ba346b35SGerhard Heift 
2060ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2061ac8e9819SChris Mason 
2062496ad9aaSAl Viro 	inode = file_inode(file);
2063ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
20648f5f6178SGerhard Heift 
20658f5f6178SGerhard Heift 	/*
20668f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
20678f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
20688f5f6178SGerhard Heift 	 */
20698f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
20708f5f6178SGerhard Heift 		ret = 0;
20718f5f6178SGerhard Heift 
2072ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2073ac8e9819SChris Mason 		ret = -EFAULT;
2074ac8e9819SChris Mason 	return ret;
2075ac8e9819SChris Mason }
2076ac8e9819SChris Mason 
2077cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2078cc68a8a5SGerhard Heift 					       void __user *argp)
2079cc68a8a5SGerhard Heift {
2080cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2081cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2082cc68a8a5SGerhard Heift 	struct inode *inode;
2083cc68a8a5SGerhard Heift 	int ret;
2084cc68a8a5SGerhard Heift 	size_t buf_size;
2085ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2086cc68a8a5SGerhard Heift 
2087cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2088cc68a8a5SGerhard Heift 		return -EPERM;
2089cc68a8a5SGerhard Heift 
2090cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2091cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2092cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2093cc68a8a5SGerhard Heift 		return -EFAULT;
2094cc68a8a5SGerhard Heift 
2095cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2096cc68a8a5SGerhard Heift 
2097cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2098cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2099cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2100cc68a8a5SGerhard Heift 
2101cc68a8a5SGerhard Heift 	inode = file_inode(file);
2102cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2103718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2104cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2105cc68a8a5SGerhard Heift 		ret = -EFAULT;
2106cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2107cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2108cc68a8a5SGerhard Heift 		ret = -EFAULT;
2109cc68a8a5SGerhard Heift 
211076dda93cSYan, Zheng 	return ret;
211176dda93cSYan, Zheng }
211276dda93cSYan, Zheng 
211398d377a0STARUISI Hiroaki /*
2114ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2115ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
211698d377a0STARUISI Hiroaki  */
211798d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
211898d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
211998d377a0STARUISI Hiroaki {
212098d377a0STARUISI Hiroaki 	struct btrfs_root *root;
212198d377a0STARUISI Hiroaki 	struct btrfs_key key;
2122ac8e9819SChris Mason 	char *ptr;
212398d377a0STARUISI Hiroaki 	int ret = -1;
212498d377a0STARUISI Hiroaki 	int slot;
212598d377a0STARUISI Hiroaki 	int len;
212698d377a0STARUISI Hiroaki 	int total_len = 0;
212798d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
212898d377a0STARUISI Hiroaki 	struct extent_buffer *l;
212998d377a0STARUISI Hiroaki 	struct btrfs_path *path;
213098d377a0STARUISI Hiroaki 
213198d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
213298d377a0STARUISI Hiroaki 		name[0]='\0';
213398d377a0STARUISI Hiroaki 		return 0;
213498d377a0STARUISI Hiroaki 	}
213598d377a0STARUISI Hiroaki 
213698d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
213798d377a0STARUISI Hiroaki 	if (!path)
213898d377a0STARUISI Hiroaki 		return -ENOMEM;
213998d377a0STARUISI Hiroaki 
2140c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
214198d377a0STARUISI Hiroaki 
214298d377a0STARUISI Hiroaki 	key.objectid = tree_id;
214398d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
214498d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
214598d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
214698d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2147f14d104dSDavid Sterba 		btrfs_err(info, "could not find root %llu", tree_id);
21488ad6fcabSChris Mason 		ret = -ENOENT;
21498ad6fcabSChris Mason 		goto out;
215098d377a0STARUISI Hiroaki 	}
215198d377a0STARUISI Hiroaki 
215298d377a0STARUISI Hiroaki 	key.objectid = dirid;
215398d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
21548ad6fcabSChris Mason 	key.offset = (u64)-1;
215598d377a0STARUISI Hiroaki 
215698d377a0STARUISI Hiroaki 	while (1) {
215798d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
215898d377a0STARUISI Hiroaki 		if (ret < 0)
215998d377a0STARUISI Hiroaki 			goto out;
216018674c6cSFilipe David Borba Manana 		else if (ret > 0) {
216118674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
216218674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
216318674c6cSFilipe David Borba Manana 			if (ret < 0)
216418674c6cSFilipe David Borba Manana 				goto out;
216518674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2166ac8e9819SChris Mason 				ret = -ENOENT;
216798d377a0STARUISI Hiroaki 				goto out;
2168ac8e9819SChris Mason 			}
216918674c6cSFilipe David Borba Manana 		}
217018674c6cSFilipe David Borba Manana 
217118674c6cSFilipe David Borba Manana 		l = path->nodes[0];
217218674c6cSFilipe David Borba Manana 		slot = path->slots[0];
217318674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
217498d377a0STARUISI Hiroaki 
217598d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
217698d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
217798d377a0STARUISI Hiroaki 		ptr -= len + 1;
217898d377a0STARUISI Hiroaki 		total_len += len + 1;
2179a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2180a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
218198d377a0STARUISI Hiroaki 			goto out;
2182a696cf35SFilipe David Borba Manana 		}
218398d377a0STARUISI Hiroaki 
218498d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
218598d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
218698d377a0STARUISI Hiroaki 
218798d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
218898d377a0STARUISI Hiroaki 			break;
218998d377a0STARUISI Hiroaki 
2190b3b4aa74SDavid Sterba 		btrfs_release_path(path);
219198d377a0STARUISI Hiroaki 		key.objectid = key.offset;
21928ad6fcabSChris Mason 		key.offset = (u64)-1;
219398d377a0STARUISI Hiroaki 		dirid = key.objectid;
219498d377a0STARUISI Hiroaki 	}
219577906a50SLi Zefan 	memmove(name, ptr, total_len);
219698d377a0STARUISI Hiroaki 	name[total_len] = '\0';
219798d377a0STARUISI Hiroaki 	ret = 0;
219898d377a0STARUISI Hiroaki out:
219998d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2200ac8e9819SChris Mason 	return ret;
2201ac8e9819SChris Mason }
2202ac8e9819SChris Mason 
2203ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2204ac8e9819SChris Mason 					   void __user *argp)
2205ac8e9819SChris Mason {
2206ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2207ac8e9819SChris Mason 	 struct inode *inode;
220801b810b8SDavid Sterba 	int ret = 0;
2209ac8e9819SChris Mason 
22102354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
22112354d08fSJulia Lawall 	if (IS_ERR(args))
22122354d08fSJulia Lawall 		return PTR_ERR(args);
2213c2b96929SDan Carpenter 
2214496ad9aaSAl Viro 	inode = file_inode(file);
2215ac8e9819SChris Mason 
221601b810b8SDavid Sterba 	/*
221701b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
221801b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
221901b810b8SDavid Sterba 	 */
22201b53ac4dSChris Mason 	if (args->treeid == 0)
22211b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
22221b53ac4dSChris Mason 
222301b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
222401b810b8SDavid Sterba 		args->name[0] = 0;
222501b810b8SDavid Sterba 		goto out;
222601b810b8SDavid Sterba 	}
222701b810b8SDavid Sterba 
222801b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
222901b810b8SDavid Sterba 		ret = -EPERM;
223001b810b8SDavid Sterba 		goto out;
223101b810b8SDavid Sterba 	}
223201b810b8SDavid Sterba 
2233ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2234ac8e9819SChris Mason 					args->treeid, args->objectid,
2235ac8e9819SChris Mason 					args->name);
2236ac8e9819SChris Mason 
223701b810b8SDavid Sterba out:
2238ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2239ac8e9819SChris Mason 		ret = -EFAULT;
2240ac8e9819SChris Mason 
2241ac8e9819SChris Mason 	kfree(args);
224298d377a0STARUISI Hiroaki 	return ret;
224398d377a0STARUISI Hiroaki }
224498d377a0STARUISI Hiroaki 
224576dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
224676dda93cSYan, Zheng 					     void __user *arg)
224776dda93cSYan, Zheng {
224854563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
22490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
225076dda93cSYan, Zheng 	struct dentry *dentry;
22512b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
225276dda93cSYan, Zheng 	struct inode *inode;
225376dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
225476dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
225576dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
225676dda93cSYan, Zheng 	int namelen;
225776dda93cSYan, Zheng 	int err = 0;
225876dda93cSYan, Zheng 
2259325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2260325c50e3SJeff Mahoney 		return -ENOTDIR;
2261325c50e3SJeff Mahoney 
226276dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
226376dda93cSYan, Zheng 	if (IS_ERR(vol_args))
226476dda93cSYan, Zheng 		return PTR_ERR(vol_args);
226576dda93cSYan, Zheng 
226676dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
226776dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
226876dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
226976dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
227076dda93cSYan, Zheng 		err = -EINVAL;
227176dda93cSYan, Zheng 		goto out;
227276dda93cSYan, Zheng 	}
227376dda93cSYan, Zheng 
2274a561be71SAl Viro 	err = mnt_want_write_file(file);
227576dda93cSYan, Zheng 	if (err)
227676dda93cSYan, Zheng 		goto out;
227776dda93cSYan, Zheng 
2278521e0546SDavid Sterba 
227900235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
228000235411SAl Viro 	if (err == -EINTR)
228100235411SAl Viro 		goto out_drop_write;
228276dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
228376dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
228476dda93cSYan, Zheng 		err = PTR_ERR(dentry);
228576dda93cSYan, Zheng 		goto out_unlock_dir;
228676dda93cSYan, Zheng 	}
228776dda93cSYan, Zheng 
22882b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
228976dda93cSYan, Zheng 		err = -ENOENT;
229076dda93cSYan, Zheng 		goto out_dput;
229176dda93cSYan, Zheng 	}
229276dda93cSYan, Zheng 
22932b0143b5SDavid Howells 	inode = d_inode(dentry);
22944260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
22954260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
22964260f7c7SSage Weil 		/*
22974260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
22984260f7c7SSage Weil 		 * option, when the user has write+exec access to the
22994260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
23004260f7c7SSage Weil 		 * allowed.
23014260f7c7SSage Weil 		 *
23024260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
23034260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
23044260f7c7SSage Weil 		 * otherwise be able to delete.
23054260f7c7SSage Weil 		 *
23064260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
23074260f7c7SSage Weil 		 * rmdir(2).
23084260f7c7SSage Weil 		 */
23094260f7c7SSage Weil 		err = -EPERM;
23100b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
23114260f7c7SSage Weil 			goto out_dput;
23124260f7c7SSage Weil 
23134260f7c7SSage Weil 		/*
23144260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
23154260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
23164260f7c7SSage Weil 		 * must be called on the dentry referencing the root
23174260f7c7SSage Weil 		 * of the subvol, not a random directory contained
23184260f7c7SSage Weil 		 * within it.
23194260f7c7SSage Weil 		 */
23204260f7c7SSage Weil 		err = -EINVAL;
23214260f7c7SSage Weil 		if (root == dest)
23224260f7c7SSage Weil 			goto out_dput;
23234260f7c7SSage Weil 
23244260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
23254260f7c7SSage Weil 		if (err)
23264260f7c7SSage Weil 			goto out_dput;
23275c39da5bSMiao Xie 	}
23284260f7c7SSage Weil 
23295c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
23304260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
23314260f7c7SSage Weil 	if (err)
23324260f7c7SSage Weil 		goto out_dput;
23334260f7c7SSage Weil 
23344a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
233576dda93cSYan, Zheng 		err = -EINVAL;
233676dda93cSYan, Zheng 		goto out_dput;
233776dda93cSYan, Zheng 	}
233876dda93cSYan, Zheng 
23395955102cSAl Viro 	inode_lock(inode);
2340f60a2364SMisono Tomohiro 	err = btrfs_delete_subvolume(dir, dentry);
23415955102cSAl Viro 	inode_unlock(inode);
2342f60a2364SMisono Tomohiro 	if (!err)
234376dda93cSYan, Zheng 		d_delete(dentry);
2344fa6ac876SLiu Bo 
234576dda93cSYan, Zheng out_dput:
234676dda93cSYan, Zheng 	dput(dentry);
234776dda93cSYan, Zheng out_unlock_dir:
23485955102cSAl Viro 	inode_unlock(dir);
234900235411SAl Viro out_drop_write:
23502a79f17eSAl Viro 	mnt_drop_write_file(file);
235176dda93cSYan, Zheng out:
235276dda93cSYan, Zheng 	kfree(vol_args);
235376dda93cSYan, Zheng 	return err;
235476dda93cSYan, Zheng }
235576dda93cSYan, Zheng 
23561e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2357f46b5a66SChristoph Hellwig {
2358496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2359f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
23601e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2361c146afadSYan Zheng 	int ret;
2362c146afadSYan Zheng 
236325122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
236425122d15SIlya Dryomov 	if (ret)
236525122d15SIlya Dryomov 		return ret;
2366b83cc969SLi Zefan 
236725122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
236825122d15SIlya Dryomov 		ret = -EROFS;
236925122d15SIlya Dryomov 		goto out;
23705ac00addSStefan Behrens 	}
2371f46b5a66SChristoph Hellwig 
2372f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2373f46b5a66SChristoph Hellwig 	case S_IFDIR:
2374e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2375e441d54dSChris Mason 			ret = -EPERM;
2376e441d54dSChris Mason 			goto out;
2377e441d54dSChris Mason 		}
2378de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
2379f46b5a66SChristoph Hellwig 		break;
2380f46b5a66SChristoph Hellwig 	case S_IFREG:
2381e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2382e441d54dSChris Mason 			ret = -EINVAL;
2383e441d54dSChris Mason 			goto out;
2384e441d54dSChris Mason 		}
23851e701a32SChris Mason 
23861e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
23871e701a32SChris Mason 		if (!range) {
23881e701a32SChris Mason 			ret = -ENOMEM;
23891e701a32SChris Mason 			goto out;
23901e701a32SChris Mason 		}
23911e701a32SChris Mason 
23921e701a32SChris Mason 		if (argp) {
23931e701a32SChris Mason 			if (copy_from_user(range, argp,
23941e701a32SChris Mason 					   sizeof(*range))) {
23951e701a32SChris Mason 				ret = -EFAULT;
23961e701a32SChris Mason 				kfree(range);
2397683be16eSDan Carpenter 				goto out;
23981e701a32SChris Mason 			}
23991e701a32SChris Mason 			/* compression requires us to start the IO */
24001e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
24011e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
24021e701a32SChris Mason 				range->extent_thresh = (u32)-1;
24031e701a32SChris Mason 			}
24041e701a32SChris Mason 		} else {
24051e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
24061e701a32SChris Mason 			range->len = (u64)-1;
24071e701a32SChris Mason 		}
2408496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
24097c829b72SAnand Jain 					range, BTRFS_OLDEST_GENERATION, 0);
24104cb5300bSChris Mason 		if (ret > 0)
24114cb5300bSChris Mason 			ret = 0;
24121e701a32SChris Mason 		kfree(range);
2413f46b5a66SChristoph Hellwig 		break;
24148929ecfaSYan, Zheng 	default:
24158929ecfaSYan, Zheng 		ret = -EINVAL;
2416f46b5a66SChristoph Hellwig 	}
2417e441d54dSChris Mason out:
241825122d15SIlya Dryomov 	mnt_drop_write_file(file);
2419e441d54dSChris Mason 	return ret;
2420f46b5a66SChristoph Hellwig }
2421f46b5a66SChristoph Hellwig 
24222ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2423f46b5a66SChristoph Hellwig {
2424f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2425f46b5a66SChristoph Hellwig 	int ret;
2426f46b5a66SChristoph Hellwig 
2427e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2428e441d54dSChris Mason 		return -EPERM;
2429e441d54dSChris Mason 
2430171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2431e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2432c9e9f97bSIlya Dryomov 
2433dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2434c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2435c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2436c9e9f97bSIlya Dryomov 		goto out;
2437c9e9f97bSIlya Dryomov 	}
2438f46b5a66SChristoph Hellwig 
24395516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
24402ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
2441f46b5a66SChristoph Hellwig 
244243d20761SAnand Jain 	if (!ret)
24430b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
244443d20761SAnand Jain 
2445f46b5a66SChristoph Hellwig 	kfree(vol_args);
2446c9e9f97bSIlya Dryomov out:
2447171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2448f46b5a66SChristoph Hellwig 	return ret;
2449f46b5a66SChristoph Hellwig }
2450f46b5a66SChristoph Hellwig 
24516b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
2452f46b5a66SChristoph Hellwig {
24530b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
24540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
24556b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
2456f46b5a66SChristoph Hellwig 	int ret;
2457f46b5a66SChristoph Hellwig 
2458e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2459e441d54dSChris Mason 		return -EPERM;
2460e441d54dSChris Mason 
2461da24927bSMiao Xie 	ret = mnt_want_write_file(file);
2462da24927bSMiao Xie 	if (ret)
2463da24927bSMiao Xie 		return ret;
2464c146afadSYan Zheng 
2465dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2466c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2467c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2468c47ca32dSDan Carpenter 		goto err_drop;
2469c9e9f97bSIlya Dryomov 	}
2470f46b5a66SChristoph Hellwig 
24716b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
2472735654eaSDavid Sterba 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED)
2473735654eaSDavid Sterba 		return -EOPNOTSUPP;
2474f46b5a66SChristoph Hellwig 
2475171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2476183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2477183860f6SAnand Jain 		goto out;
2478183860f6SAnand Jain 	}
2479183860f6SAnand Jain 
2480735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
24812ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
24826b526ed7SAnand Jain 	} else {
24836b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
24842ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
24856b526ed7SAnand Jain 	}
2486171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2487183860f6SAnand Jain 
24886b526ed7SAnand Jain 	if (!ret) {
2489735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
24900b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
24916b526ed7SAnand Jain 					vol_args->devid);
24926b526ed7SAnand Jain 		else
24930b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
24946b526ed7SAnand Jain 					vol_args->name);
24956b526ed7SAnand Jain 	}
2496183860f6SAnand Jain out:
2497183860f6SAnand Jain 	kfree(vol_args);
2498c47ca32dSDan Carpenter err_drop:
24994ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
2500f46b5a66SChristoph Hellwig 	return ret;
2501f46b5a66SChristoph Hellwig }
2502f46b5a66SChristoph Hellwig 
2503f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2504f46b5a66SChristoph Hellwig {
25050b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
25060b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2507f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2508f46b5a66SChristoph Hellwig 	int ret;
2509f46b5a66SChristoph Hellwig 
2510f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
2511f46b5a66SChristoph Hellwig 		return -EPERM;
2512f46b5a66SChristoph Hellwig 
2513f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
2514f46b5a66SChristoph Hellwig 	if (ret)
2515f46b5a66SChristoph Hellwig 		return ret;
2516f46b5a66SChristoph Hellwig 
2517171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2518f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
251958d7bbf8SDavid Sterba 		goto out_drop_write;
252058d7bbf8SDavid Sterba 	}
252158d7bbf8SDavid Sterba 
252258d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
252358d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
252458d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
2525f46b5a66SChristoph Hellwig 		goto out;
2526f46b5a66SChristoph Hellwig 	}
2527f46b5a66SChristoph Hellwig 
252858d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
25292ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
2530f46b5a66SChristoph Hellwig 
2531f46b5a66SChristoph Hellwig 	if (!ret)
25320b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
2533f46b5a66SChristoph Hellwig 	kfree(vol_args);
253458d7bbf8SDavid Sterba out:
2535171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
253658d7bbf8SDavid Sterba out_drop_write:
2537f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
253858d7bbf8SDavid Sterba 
2539f46b5a66SChristoph Hellwig 	return ret;
2540f46b5a66SChristoph Hellwig }
2541f46b5a66SChristoph Hellwig 
25422ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
25432ff7e61eSJeff Mahoney 				void __user *arg)
2544475f6387SJan Schmidt {
2545027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
2546475f6387SJan Schmidt 	struct btrfs_device *device;
25470b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2548027ed2f0SLi Zefan 	int ret = 0;
2549475f6387SJan Schmidt 
2550027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2551027ed2f0SLi Zefan 	if (!fi_args)
2552027ed2f0SLi Zefan 		return -ENOMEM;
2553027ed2f0SLi Zefan 
2554d03262c7SDavid Sterba 	rcu_read_lock();
2555027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
2556475f6387SJan Schmidt 
2557d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2558027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
2559027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
2560475f6387SJan Schmidt 	}
2561d03262c7SDavid Sterba 	rcu_read_unlock();
2562475f6387SJan Schmidt 
2563d03262c7SDavid Sterba 	memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
2564bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
2565bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
2566bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
256780a773fbSDavid Sterba 
2568027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2569027ed2f0SLi Zefan 		ret = -EFAULT;
2570475f6387SJan Schmidt 
2571027ed2f0SLi Zefan 	kfree(fi_args);
2572027ed2f0SLi Zefan 	return ret;
2573475f6387SJan Schmidt }
2574475f6387SJan Schmidt 
25752ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
25762ff7e61eSJeff Mahoney 				 void __user *arg)
2577475f6387SJan Schmidt {
2578475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
2579475f6387SJan Schmidt 	struct btrfs_device *dev;
2580475f6387SJan Schmidt 	int ret = 0;
2581475f6387SJan Schmidt 	char *s_uuid = NULL;
2582475f6387SJan Schmidt 
2583475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
2584475f6387SJan Schmidt 	if (IS_ERR(di_args))
2585475f6387SJan Schmidt 		return PTR_ERR(di_args);
2586475f6387SJan Schmidt 
2587dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
2588475f6387SJan Schmidt 		s_uuid = di_args->uuid;
2589475f6387SJan Schmidt 
2590c5593ca3SDavid Sterba 	rcu_read_lock();
25910b246afaSJeff Mahoney 	dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
2592475f6387SJan Schmidt 
2593475f6387SJan Schmidt 	if (!dev) {
2594475f6387SJan Schmidt 		ret = -ENODEV;
2595475f6387SJan Schmidt 		goto out;
2596475f6387SJan Schmidt 	}
2597475f6387SJan Schmidt 
2598475f6387SJan Schmidt 	di_args->devid = dev->devid;
25997cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
26007cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2601475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2602a27202fbSJim Meyering 	if (dev->name) {
2603606686eeSJosef Bacik 		struct rcu_string *name;
2604606686eeSJosef Bacik 
2605606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
26066670d4c2SXiongfeng Wang 		strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
2607a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
2608a27202fbSJim Meyering 	} else {
260999ba55adSStefan Behrens 		di_args->path[0] = '\0';
2610a27202fbSJim Meyering 	}
2611475f6387SJan Schmidt 
2612475f6387SJan Schmidt out:
2613c5593ca3SDavid Sterba 	rcu_read_unlock();
2614475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2615475f6387SJan Schmidt 		ret = -EFAULT;
2616475f6387SJan Schmidt 
2617475f6387SJan Schmidt 	kfree(di_args);
2618475f6387SJan Schmidt 	return ret;
2619475f6387SJan Schmidt }
2620475f6387SJan Schmidt 
2621f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2622416161dbSMark Fasheh {
2623416161dbSMark Fasheh 	struct page *page;
2624416161dbSMark Fasheh 
2625416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
2626416161dbSMark Fasheh 	if (!page)
262731314002SFilipe Manana 		return ERR_PTR(-ENOMEM);
2628416161dbSMark Fasheh 
2629416161dbSMark Fasheh 	if (!PageUptodate(page)) {
263031314002SFilipe Manana 		int ret;
263131314002SFilipe Manana 
263231314002SFilipe Manana 		ret = btrfs_readpage(NULL, page);
263331314002SFilipe Manana 		if (ret)
263431314002SFilipe Manana 			return ERR_PTR(ret);
2635416161dbSMark Fasheh 		lock_page(page);
2636416161dbSMark Fasheh 		if (!PageUptodate(page)) {
2637416161dbSMark Fasheh 			unlock_page(page);
263809cbfeafSKirill A. Shutemov 			put_page(page);
263931314002SFilipe Manana 			return ERR_PTR(-EIO);
2640416161dbSMark Fasheh 		}
264131314002SFilipe Manana 		if (page->mapping != inode->i_mapping) {
2642416161dbSMark Fasheh 			unlock_page(page);
264309cbfeafSKirill A. Shutemov 			put_page(page);
264431314002SFilipe Manana 			return ERR_PTR(-EAGAIN);
2645416161dbSMark Fasheh 		}
2646416161dbSMark Fasheh 	}
2647416161dbSMark Fasheh 
2648416161dbSMark Fasheh 	return page;
2649416161dbSMark Fasheh }
2650416161dbSMark Fasheh 
2651f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
2652f4414602SMark Fasheh 			       int num_pages, u64 off)
2653f4414602SMark Fasheh {
2654f4414602SMark Fasheh 	int i;
265509cbfeafSKirill A. Shutemov 	pgoff_t index = off >> PAGE_SHIFT;
2656f4414602SMark Fasheh 
2657f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
265831314002SFilipe Manana again:
2659f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
266031314002SFilipe Manana 		if (IS_ERR(pages[i])) {
266131314002SFilipe Manana 			int err = PTR_ERR(pages[i]);
266231314002SFilipe Manana 
266331314002SFilipe Manana 			if (err == -EAGAIN)
266431314002SFilipe Manana 				goto again;
266531314002SFilipe Manana 			pages[i] = NULL;
266631314002SFilipe Manana 			return err;
266731314002SFilipe Manana 		}
2668f4414602SMark Fasheh 	}
2669f4414602SMark Fasheh 	return 0;
2670f4414602SMark Fasheh }
2671f4414602SMark Fasheh 
2672e0bd70c6SFilipe Manana static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2673e0bd70c6SFilipe Manana 			     bool retry_range_locking)
267477fe20dcSMark Fasheh {
2675e0bd70c6SFilipe Manana 	/*
2676e0bd70c6SFilipe Manana 	 * Do any pending delalloc/csum calculations on inode, one way or
2677e0bd70c6SFilipe Manana 	 * another, and lock file content.
2678e0bd70c6SFilipe Manana 	 * The locking order is:
2679e0bd70c6SFilipe Manana 	 *
2680e0bd70c6SFilipe Manana 	 *   1) pages
2681e0bd70c6SFilipe Manana 	 *   2) range in the inode's io tree
2682e0bd70c6SFilipe Manana 	 */
268377fe20dcSMark Fasheh 	while (1) {
268477fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
268577fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
268677fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
268777fe20dcSMark Fasheh 							    off + len - 1);
2688ff5df9b8SFilipe Manana 		if ((!ordered ||
2689ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
2690ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
269177fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2692ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2693ff5df9b8SFilipe Manana 			if (ordered)
2694ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
269577fe20dcSMark Fasheh 			break;
2696ff5df9b8SFilipe Manana 		}
269777fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
269877fe20dcSMark Fasheh 		if (ordered)
269977fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
2700e0bd70c6SFilipe Manana 		if (!retry_range_locking)
2701e0bd70c6SFilipe Manana 			return -EAGAIN;
270277fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
270377fe20dcSMark Fasheh 	}
2704e0bd70c6SFilipe Manana 	return 0;
270577fe20dcSMark Fasheh }
270677fe20dcSMark Fasheh 
2707f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2708416161dbSMark Fasheh {
27095955102cSAl Viro 	inode_unlock(inode1);
27105955102cSAl Viro 	inode_unlock(inode2);
2711416161dbSMark Fasheh }
2712416161dbSMark Fasheh 
2713f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2714f4414602SMark Fasheh {
2715f4414602SMark Fasheh 	if (inode1 < inode2)
2716f4414602SMark Fasheh 		swap(inode1, inode2);
2717f4414602SMark Fasheh 
27185955102cSAl Viro 	inode_lock_nested(inode1, I_MUTEX_PARENT);
27195955102cSAl Viro 	inode_lock_nested(inode2, I_MUTEX_CHILD);
2720f4414602SMark Fasheh }
2721f4414602SMark Fasheh 
2722f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2723f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
2724f4414602SMark Fasheh {
2725f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2726f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2727f4414602SMark Fasheh }
2728f4414602SMark Fasheh 
2729e0bd70c6SFilipe Manana static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2730e0bd70c6SFilipe Manana 				    struct inode *inode2, u64 loff2, u64 len,
2731e0bd70c6SFilipe Manana 				    bool retry_range_locking)
2732416161dbSMark Fasheh {
2733e0bd70c6SFilipe Manana 	int ret;
2734e0bd70c6SFilipe Manana 
2735416161dbSMark Fasheh 	if (inode1 < inode2) {
2736416161dbSMark Fasheh 		swap(inode1, inode2);
2737416161dbSMark Fasheh 		swap(loff1, loff2);
2738416161dbSMark Fasheh 	}
2739e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2740e0bd70c6SFilipe Manana 	if (ret)
2741e0bd70c6SFilipe Manana 		return ret;
2742e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2743e0bd70c6SFilipe Manana 	if (ret)
2744e0bd70c6SFilipe Manana 		unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2745e0bd70c6SFilipe Manana 			      loff1 + len - 1);
2746e0bd70c6SFilipe Manana 	return ret;
2747416161dbSMark Fasheh }
2748f4414602SMark Fasheh 
2749f4414602SMark Fasheh struct cmp_pages {
2750f4414602SMark Fasheh 	int		num_pages;
2751f4414602SMark Fasheh 	struct page	**src_pages;
2752f4414602SMark Fasheh 	struct page	**dst_pages;
2753f4414602SMark Fasheh };
2754f4414602SMark Fasheh 
2755f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2756f4414602SMark Fasheh {
2757f4414602SMark Fasheh 	int i;
2758f4414602SMark Fasheh 	struct page *pg;
2759f4414602SMark Fasheh 
2760f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
2761f4414602SMark Fasheh 		pg = cmp->src_pages[i];
2762e0bd70c6SFilipe Manana 		if (pg) {
2763e0bd70c6SFilipe Manana 			unlock_page(pg);
276409cbfeafSKirill A. Shutemov 			put_page(pg);
2765e0bd70c6SFilipe Manana 		}
2766f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
2767e0bd70c6SFilipe Manana 		if (pg) {
2768e0bd70c6SFilipe Manana 			unlock_page(pg);
276909cbfeafSKirill A. Shutemov 			put_page(pg);
2770f4414602SMark Fasheh 		}
2771e0bd70c6SFilipe Manana 	}
2772f4414602SMark Fasheh 	kfree(cmp->src_pages);
2773f4414602SMark Fasheh 	kfree(cmp->dst_pages);
2774f4414602SMark Fasheh }
2775f4414602SMark Fasheh 
2776f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2777f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
2778f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
2779f4414602SMark Fasheh {
2780f4414602SMark Fasheh 	int ret;
278109cbfeafSKirill A. Shutemov 	int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
2782f4414602SMark Fasheh 	struct page **src_pgarr, **dst_pgarr;
2783f4414602SMark Fasheh 
2784f4414602SMark Fasheh 	/*
2785f4414602SMark Fasheh 	 * We must gather up all the pages before we initiate our
2786f4414602SMark Fasheh 	 * extent locking. We use an array for the page pointers. Size
2787f4414602SMark Fasheh 	 * of the array is bounded by len, which is in turn bounded by
2788f4414602SMark Fasheh 	 * BTRFS_MAX_DEDUPE_LEN.
2789f4414602SMark Fasheh 	 */
279066722f7cSDavid Sterba 	src_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
279166722f7cSDavid Sterba 	dst_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
2792f4414602SMark Fasheh 	if (!src_pgarr || !dst_pgarr) {
2793f4414602SMark Fasheh 		kfree(src_pgarr);
2794f4414602SMark Fasheh 		kfree(dst_pgarr);
2795f4414602SMark Fasheh 		return -ENOMEM;
2796f4414602SMark Fasheh 	}
2797f4414602SMark Fasheh 	cmp->num_pages = num_pages;
2798f4414602SMark Fasheh 	cmp->src_pages = src_pgarr;
2799f4414602SMark Fasheh 	cmp->dst_pages = dst_pgarr;
2800f4414602SMark Fasheh 
2801b1517622SFilipe Manana 	/*
2802b1517622SFilipe Manana 	 * If deduping ranges in the same inode, locking rules make it mandatory
2803b1517622SFilipe Manana 	 * to always lock pages in ascending order to avoid deadlocks with
2804b1517622SFilipe Manana 	 * concurrent tasks (such as starting writeback/delalloc).
2805b1517622SFilipe Manana 	 */
2806b1517622SFilipe Manana 	if (src == dst && dst_loff < loff) {
2807b1517622SFilipe Manana 		swap(src_pgarr, dst_pgarr);
2808b1517622SFilipe Manana 		swap(loff, dst_loff);
2809b1517622SFilipe Manana 	}
2810b1517622SFilipe Manana 
2811b1517622SFilipe Manana 	ret = gather_extent_pages(src, src_pgarr, cmp->num_pages, loff);
2812f4414602SMark Fasheh 	if (ret)
2813f4414602SMark Fasheh 		goto out;
2814f4414602SMark Fasheh 
2815b1517622SFilipe Manana 	ret = gather_extent_pages(dst, dst_pgarr, cmp->num_pages, dst_loff);
2816f4414602SMark Fasheh 
2817f4414602SMark Fasheh out:
2818f4414602SMark Fasheh 	if (ret)
2819f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
282078ad4ce0SNaohiro Aota 	return ret;
2821416161dbSMark Fasheh }
2822416161dbSMark Fasheh 
28231a287cfeSDavid Sterba static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
2824416161dbSMark Fasheh {
2825416161dbSMark Fasheh 	int ret = 0;
2826f4414602SMark Fasheh 	int i;
2827416161dbSMark Fasheh 	struct page *src_page, *dst_page;
282809cbfeafSKirill A. Shutemov 	unsigned int cmp_len = PAGE_SIZE;
2829416161dbSMark Fasheh 	void *addr, *dst_addr;
2830416161dbSMark Fasheh 
2831f4414602SMark Fasheh 	i = 0;
2832416161dbSMark Fasheh 	while (len) {
283309cbfeafSKirill A. Shutemov 		if (len < PAGE_SIZE)
2834416161dbSMark Fasheh 			cmp_len = len;
2835416161dbSMark Fasheh 
2836f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
2837f4414602SMark Fasheh 
2838f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
2839f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
2840e0bd70c6SFilipe Manana 		ASSERT(PageLocked(src_page));
2841e0bd70c6SFilipe Manana 		ASSERT(PageLocked(dst_page));
2842f4414602SMark Fasheh 
2843416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
2844416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
2845416161dbSMark Fasheh 
2846416161dbSMark Fasheh 		flush_dcache_page(src_page);
2847416161dbSMark Fasheh 		flush_dcache_page(dst_page);
2848416161dbSMark Fasheh 
2849416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
28502b3909f8SDarrick J. Wong 			ret = -EBADE;
2851416161dbSMark Fasheh 
2852416161dbSMark Fasheh 		kunmap_atomic(addr);
2853416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
2854416161dbSMark Fasheh 
2855416161dbSMark Fasheh 		if (ret)
2856416161dbSMark Fasheh 			break;
2857416161dbSMark Fasheh 
2858416161dbSMark Fasheh 		len -= cmp_len;
2859f4414602SMark Fasheh 		i++;
2860416161dbSMark Fasheh 	}
2861416161dbSMark Fasheh 
2862416161dbSMark Fasheh 	return ret;
2863416161dbSMark Fasheh }
2864416161dbSMark Fasheh 
2865e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
2866e1d227a4SMark Fasheh 				     u64 olen)
2867416161dbSMark Fasheh {
2868e1d227a4SMark Fasheh 	u64 len = *plen;
2869416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2870416161dbSMark Fasheh 
2871e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
2872416161dbSMark Fasheh 		return -EINVAL;
2873e1d227a4SMark Fasheh 
2874e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
2875e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
2876e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
2877e1d227a4SMark Fasheh 
2878416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
2879416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2880416161dbSMark Fasheh 		return -EINVAL;
2881416161dbSMark Fasheh 
2882416161dbSMark Fasheh 	return 0;
2883416161dbSMark Fasheh }
2884416161dbSMark Fasheh 
2885e1d227a4SMark Fasheh static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
2886416161dbSMark Fasheh 			     struct inode *dst, u64 dst_loff)
2887416161dbSMark Fasheh {
2888416161dbSMark Fasheh 	int ret;
2889e1d227a4SMark Fasheh 	u64 len = olen;
2890f4414602SMark Fasheh 	struct cmp_pages cmp;
2891fc4badd9SOmar Sandoval 	bool same_inode = (src == dst);
28920efa9f48SMark Fasheh 	u64 same_lock_start = 0;
28930efa9f48SMark Fasheh 	u64 same_lock_len = 0;
2894416161dbSMark Fasheh 
2895113e8283SFilipe Manana 	if (len == 0)
2896113e8283SFilipe Manana 		return 0;
2897113e8283SFilipe Manana 
2898fc4badd9SOmar Sandoval 	if (same_inode)
28995955102cSAl Viro 		inode_lock(src);
2900fc4badd9SOmar Sandoval 	else
2901fc4badd9SOmar Sandoval 		btrfs_double_inode_lock(src, dst);
29020efa9f48SMark Fasheh 
29030efa9f48SMark Fasheh 	ret = extent_same_check_offsets(src, loff, &len, olen);
29040efa9f48SMark Fasheh 	if (ret)
29050efa9f48SMark Fasheh 		goto out_unlock;
2906fc4badd9SOmar Sandoval 
2907fc4badd9SOmar Sandoval 	ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
2908f4dfe687SFilipe Manana 	if (ret)
2909f4dfe687SFilipe Manana 		goto out_unlock;
29100efa9f48SMark Fasheh 
2911fc4badd9SOmar Sandoval 	if (same_inode) {
29120efa9f48SMark Fasheh 		/*
29130efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
29140efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
29150efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
29160efa9f48SMark Fasheh 		 *
29170efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
29180efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
29190efa9f48SMark Fasheh 		 * reject the request.
29200efa9f48SMark Fasheh 		 *
29210efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
29220efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
29230efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
29240efa9f48SMark Fasheh 		 * i_size.
29250efa9f48SMark Fasheh 		 */
29260efa9f48SMark Fasheh 		if (len != olen) {
29270efa9f48SMark Fasheh 			ret = -EINVAL;
29280efa9f48SMark Fasheh 			goto out_unlock;
29290efa9f48SMark Fasheh 		}
29300efa9f48SMark Fasheh 
29310efa9f48SMark Fasheh 		/* Check for overlapping ranges */
29320efa9f48SMark Fasheh 		if (dst_loff + len > loff && dst_loff < loff + len) {
29330efa9f48SMark Fasheh 			ret = -EINVAL;
29340efa9f48SMark Fasheh 			goto out_unlock;
29350efa9f48SMark Fasheh 		}
29360efa9f48SMark Fasheh 
29370efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
29380efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
29390efa9f48SMark Fasheh 	}
2940416161dbSMark Fasheh 
2941416161dbSMark Fasheh 	/* don't make the dst file partly checksummed */
2942416161dbSMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2943416161dbSMark Fasheh 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
2944416161dbSMark Fasheh 		ret = -EINVAL;
2945416161dbSMark Fasheh 		goto out_unlock;
2946416161dbSMark Fasheh 	}
2947416161dbSMark Fasheh 
2948e0bd70c6SFilipe Manana again:
2949f4414602SMark Fasheh 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
2950f4414602SMark Fasheh 	if (ret)
2951f4414602SMark Fasheh 		goto out_unlock;
2952f4414602SMark Fasheh 
29530efa9f48SMark Fasheh 	if (same_inode)
2954e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, same_lock_start, same_lock_len,
2955e0bd70c6SFilipe Manana 					false);
29560efa9f48SMark Fasheh 	else
2957e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
2958e0bd70c6SFilipe Manana 					       false);
2959e0bd70c6SFilipe Manana 	/*
2960e0bd70c6SFilipe Manana 	 * If one of the inodes has dirty pages in the respective range or
2961e0bd70c6SFilipe Manana 	 * ordered extents, we need to flush dellaloc and wait for all ordered
2962e0bd70c6SFilipe Manana 	 * extents in the range. We must unlock the pages and the ranges in the
2963e0bd70c6SFilipe Manana 	 * io trees to avoid deadlocks when flushing delalloc (requires locking
2964e0bd70c6SFilipe Manana 	 * pages) and when waiting for ordered extents to complete (they require
2965e0bd70c6SFilipe Manana 	 * range locking).
2966e0bd70c6SFilipe Manana 	 */
2967e0bd70c6SFilipe Manana 	if (ret == -EAGAIN) {
2968e0bd70c6SFilipe Manana 		/*
2969e0bd70c6SFilipe Manana 		 * Ranges in the io trees already unlocked. Now unlock all
2970e0bd70c6SFilipe Manana 		 * pages before waiting for all IO to complete.
2971e0bd70c6SFilipe Manana 		 */
2972e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
2973e0bd70c6SFilipe Manana 		if (same_inode) {
2974e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, same_lock_start,
2975e0bd70c6SFilipe Manana 						 same_lock_len);
2976e0bd70c6SFilipe Manana 		} else {
2977e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, loff, len);
2978e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(dst, dst_loff, len);
2979e0bd70c6SFilipe Manana 		}
2980e0bd70c6SFilipe Manana 		goto again;
2981e0bd70c6SFilipe Manana 	}
2982e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
2983e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
2984e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
2985e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
2986e0bd70c6SFilipe Manana 		return ret;
2987e0bd70c6SFilipe Manana 	}
2988f4414602SMark Fasheh 
2989207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
29901a287cfeSDavid Sterba 	ret = btrfs_cmp_data(olen, &cmp);
2991416161dbSMark Fasheh 	if (ret == 0)
29921c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
2993416161dbSMark Fasheh 
29940efa9f48SMark Fasheh 	if (same_inode)
29950efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
29960efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
29970efa9f48SMark Fasheh 	else
2998f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
2999f4414602SMark Fasheh 
3000f4414602SMark Fasheh 	btrfs_cmp_data_free(&cmp);
3001416161dbSMark Fasheh out_unlock:
30020efa9f48SMark Fasheh 	if (same_inode)
30035955102cSAl Viro 		inode_unlock(src);
30040efa9f48SMark Fasheh 	else
3005f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3006416161dbSMark Fasheh 
3007416161dbSMark Fasheh 	return ret;
3008416161dbSMark Fasheh }
3009416161dbSMark Fasheh 
3010ee22184bSByongho Lee #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3011416161dbSMark Fasheh 
30122b3909f8SDarrick J. Wong ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
30132b3909f8SDarrick J. Wong 				struct file *dst_file, u64 dst_loff)
3014416161dbSMark Fasheh {
30152b3909f8SDarrick J. Wong 	struct inode *src = file_inode(src_file);
30162b3909f8SDarrick J. Wong 	struct inode *dst = file_inode(dst_file);
3017416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
30182b3909f8SDarrick J. Wong 	ssize_t res;
3019416161dbSMark Fasheh 
30202b3909f8SDarrick J. Wong 	if (olen > BTRFS_MAX_DEDUPE_LEN)
30212b3909f8SDarrick J. Wong 		olen = BTRFS_MAX_DEDUPE_LEN;
3022416161dbSMark Fasheh 
302309cbfeafSKirill A. Shutemov 	if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3024416161dbSMark Fasheh 		/*
3025416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3026416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3027416161dbSMark Fasheh 		 * this situation without an update.
3028416161dbSMark Fasheh 		 */
30292b3909f8SDarrick J. Wong 		return -EINVAL;
3030416161dbSMark Fasheh 	}
3031416161dbSMark Fasheh 
30322b3909f8SDarrick J. Wong 	res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
30332b3909f8SDarrick J. Wong 	if (res)
30342b3909f8SDarrick J. Wong 		return res;
30352b3909f8SDarrick J. Wong 	return olen;
3036416161dbSMark Fasheh }
3037416161dbSMark Fasheh 
3038f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3039f82a9901SFilipe Manana 				     struct inode *inode,
3040f82a9901SFilipe Manana 				     u64 endoff,
3041f82a9901SFilipe Manana 				     const u64 destoff,
30421c919a5eSMark Fasheh 				     const u64 olen,
30431c919a5eSMark Fasheh 				     int no_time_update)
3044f82a9901SFilipe Manana {
3045f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3046f82a9901SFilipe Manana 	int ret;
3047f82a9901SFilipe Manana 
3048f82a9901SFilipe Manana 	inode_inc_iversion(inode);
30491c919a5eSMark Fasheh 	if (!no_time_update)
3050c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3051f82a9901SFilipe Manana 	/*
3052f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3053f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3054f82a9901SFilipe Manana 	 */
3055f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3056f82a9901SFilipe Manana 		endoff = destoff + olen;
3057f82a9901SFilipe Manana 	if (endoff > inode->i_size)
30586ef06d27SNikolay Borisov 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3059f82a9901SFilipe Manana 
3060f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3061f82a9901SFilipe Manana 	if (ret) {
306266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
30633a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3064f82a9901SFilipe Manana 		goto out;
3065f82a9901SFilipe Manana 	}
30663a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
3067f82a9901SFilipe Manana out:
3068f82a9901SFilipe Manana 	return ret;
3069f82a9901SFilipe Manana }
3070f82a9901SFilipe Manana 
3071a2f392e4SNikolay Borisov static void clone_update_extent_map(struct btrfs_inode *inode,
30727ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
30737ffbb598SFilipe Manana 				    const struct btrfs_path *path,
30747ffbb598SFilipe Manana 				    const u64 hole_offset,
30757ffbb598SFilipe Manana 				    const u64 hole_len)
30767ffbb598SFilipe Manana {
3077a2f392e4SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
30787ffbb598SFilipe Manana 	struct extent_map *em;
30797ffbb598SFilipe Manana 	int ret;
30807ffbb598SFilipe Manana 
30817ffbb598SFilipe Manana 	em = alloc_extent_map();
30827ffbb598SFilipe Manana 	if (!em) {
3083a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
30847ffbb598SFilipe Manana 		return;
30857ffbb598SFilipe Manana 	}
30867ffbb598SFilipe Manana 
308714f59796SFilipe Manana 	if (path) {
308814f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
308914f59796SFilipe Manana 
309014f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
309114f59796SFilipe Manana 				    struct btrfs_file_extent_item);
3092a2f392e4SNikolay Borisov 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
30937ffbb598SFilipe Manana 		em->generation = -1;
30947ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
30957ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
30967ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3097a2f392e4SNikolay Borisov 					&inode->runtime_flags);
30987ffbb598SFilipe Manana 	} else {
30997ffbb598SFilipe Manana 		em->start = hole_offset;
31007ffbb598SFilipe Manana 		em->len = hole_len;
31017ffbb598SFilipe Manana 		em->ram_bytes = em->len;
31027ffbb598SFilipe Manana 		em->orig_start = hole_offset;
31037ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
31047ffbb598SFilipe Manana 		em->block_len = 0;
31057ffbb598SFilipe Manana 		em->orig_block_len = 0;
31067ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
31077ffbb598SFilipe Manana 		em->generation = trans->transid;
31087ffbb598SFilipe Manana 	}
31097ffbb598SFilipe Manana 
31107ffbb598SFilipe Manana 	while (1) {
31117ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
31127ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
31137ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
31147ffbb598SFilipe Manana 		if (ret != -EEXIST) {
31157ffbb598SFilipe Manana 			free_extent_map(em);
31167ffbb598SFilipe Manana 			break;
31177ffbb598SFilipe Manana 		}
3118a2f392e4SNikolay Borisov 		btrfs_drop_extent_cache(inode, em->start,
31197ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
31207ffbb598SFilipe Manana 	}
31217ffbb598SFilipe Manana 
3122ee39b432SDavid Sterba 	if (ret)
3123a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
31247ffbb598SFilipe Manana }
31257ffbb598SFilipe Manana 
31268039d87dSFilipe Manana /*
31278039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
31288039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
31298039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
31308039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
31318039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
31328039d87dSFilipe Manana  *
31338039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
31348039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
31358039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
31368039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
31378039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
31388039d87dSFilipe Manana  * i_mutex, which we are holding here).
31398039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
31408039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
31418039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
31428039d87dSFilipe Manana  *
31438039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
31448039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
31458039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
31468039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
31478039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
31488039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
31498039d87dSFilipe Manana  * the former.
31508039d87dSFilipe Manana  */
31514a0ab9d7SDavid Sterba static int clone_copy_inline_extent(struct inode *dst,
31528039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
31538039d87dSFilipe Manana 				    struct btrfs_path *path,
31548039d87dSFilipe Manana 				    struct btrfs_key *new_key,
31558039d87dSFilipe Manana 				    const u64 drop_start,
31568039d87dSFilipe Manana 				    const u64 datal,
31578039d87dSFilipe Manana 				    const u64 skip,
31588039d87dSFilipe Manana 				    const u64 size,
31598039d87dSFilipe Manana 				    char *inline_data)
31608039d87dSFilipe Manana {
31610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
31628039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
31638039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
31640b246afaSJeff Mahoney 				      fs_info->sectorsize);
31658039d87dSFilipe Manana 	int ret;
31668039d87dSFilipe Manana 	struct btrfs_key key;
31678039d87dSFilipe Manana 
31688039d87dSFilipe Manana 	if (new_key->offset > 0)
31698039d87dSFilipe Manana 		return -EOPNOTSUPP;
31708039d87dSFilipe Manana 
31714a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(dst));
31728039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
31738039d87dSFilipe Manana 	key.offset = 0;
31748039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
31758039d87dSFilipe Manana 	if (ret < 0) {
31768039d87dSFilipe Manana 		return ret;
31778039d87dSFilipe Manana 	} else if (ret > 0) {
31788039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
31798039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
31808039d87dSFilipe Manana 			if (ret < 0)
31818039d87dSFilipe Manana 				return ret;
31828039d87dSFilipe Manana 			else if (ret > 0)
31838039d87dSFilipe Manana 				goto copy_inline_extent;
31848039d87dSFilipe Manana 		}
31858039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
31864a0cc7caSNikolay Borisov 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
31878039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
31888039d87dSFilipe Manana 			ASSERT(key.offset > 0);
31898039d87dSFilipe Manana 			return -EOPNOTSUPP;
31908039d87dSFilipe Manana 		}
31918039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
31928039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
31938039d87dSFilipe Manana 		u64 ext_len;
31948039d87dSFilipe Manana 
31958039d87dSFilipe Manana 		/*
31968039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
31978039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
31988039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
31998039d87dSFilipe Manana 		 */
32008039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
32018039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
32028039d87dSFilipe Manana 		/*
32038039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
32048039d87dSFilipe Manana 		 * following it.
32058039d87dSFilipe Manana 		 */
32068039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
32078039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
32088039d87dSFilipe Manana 			goto copy_inline_extent;
32098039d87dSFilipe Manana 
32108039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
32118039d87dSFilipe Manana 		if (ext_len > aligned_end)
32128039d87dSFilipe Manana 			return -EOPNOTSUPP;
32138039d87dSFilipe Manana 
32148039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
32158039d87dSFilipe Manana 		if (ret < 0) {
32168039d87dSFilipe Manana 			return ret;
32178039d87dSFilipe Manana 		} else if (ret == 0) {
32188039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
32198039d87dSFilipe Manana 					      path->slots[0]);
32204a0cc7caSNikolay Borisov 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
32218039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
32228039d87dSFilipe Manana 				return -EOPNOTSUPP;
32238039d87dSFilipe Manana 		}
32248039d87dSFilipe Manana 	}
32258039d87dSFilipe Manana 
32268039d87dSFilipe Manana copy_inline_extent:
32278039d87dSFilipe Manana 	/*
32288039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
32298039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
32308039d87dSFilipe Manana 	 */
32318039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
32328039d87dSFilipe Manana 		/*
32338039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
32348039d87dSFilipe Manana 		 * This would require copying the data from the source inline
32358039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
32368039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
32378039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
32388039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
32398039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
32408039d87dSFilipe Manana 		 * inline extent).
32418039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
32428039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
32438039d87dSFilipe Manana 		 */
32448039d87dSFilipe Manana 		return -EOPNOTSUPP;
32458039d87dSFilipe Manana 	}
32468039d87dSFilipe Manana 
32478039d87dSFilipe Manana 	btrfs_release_path(path);
32488039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
32498039d87dSFilipe Manana 	if (ret)
32508039d87dSFilipe Manana 		return ret;
32518039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
32528039d87dSFilipe Manana 	if (ret)
32538039d87dSFilipe Manana 		return ret;
32548039d87dSFilipe Manana 
32558039d87dSFilipe Manana 	if (skip) {
32568039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
32578039d87dSFilipe Manana 
32588039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
32598039d87dSFilipe Manana 	}
32608039d87dSFilipe Manana 
32618039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
32628039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
32638039d87dSFilipe Manana 						  path->slots[0]),
32648039d87dSFilipe Manana 			    size);
32658039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
32668039d87dSFilipe Manana 
32678039d87dSFilipe Manana 	return 0;
32688039d87dSFilipe Manana }
32698039d87dSFilipe Manana 
327032b7c687SMark Fasheh /**
327132b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
327232b7c687SMark Fasheh  *
327332b7c687SMark Fasheh  * @src: Inode to clone from
327432b7c687SMark Fasheh  * @inode: Inode to clone to
327532b7c687SMark Fasheh  * @off: Offset within source to start clone from
327632b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
32771c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
327832b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
32791c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
328032b7c687SMark Fasheh  */
328132b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3282f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
32831c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3284f46b5a66SChristoph Hellwig {
32850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3286f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
328732b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3288f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
328932b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
329032b7c687SMark Fasheh 	char *buf = NULL;
3291ae01a0abSYan Zheng 	struct btrfs_key key;
3292f46b5a66SChristoph Hellwig 	u32 nritems;
3293f46b5a66SChristoph Hellwig 	int slot;
3294ae01a0abSYan Zheng 	int ret;
3295f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3296f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3297ae01a0abSYan Zheng 
3298ae01a0abSYan Zheng 	ret = -ENOMEM;
3299752ade68SMichal Hocko 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3300ae01a0abSYan Zheng 	if (!buf)
330132b7c687SMark Fasheh 		return ret;
3302ae01a0abSYan Zheng 
3303ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3304ae01a0abSYan Zheng 	if (!path) {
330515351955SDavid Sterba 		kvfree(buf);
330632b7c687SMark Fasheh 		return ret;
3307ae01a0abSYan Zheng 	}
330832b7c687SMark Fasheh 
3309e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3310c5c9cd4dSSage Weil 	/* clone data */
33114a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(src));
3312ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
33132c463823SFilipe Manana 	key.offset = off;
3314f46b5a66SChristoph Hellwig 
3315f46b5a66SChristoph Hellwig 	while (1) {
3316de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3317df858e76SFilipe Manana 
3318f46b5a66SChristoph Hellwig 		/*
3319f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3320f46b5a66SChristoph Hellwig 		 * tree.
3321f46b5a66SChristoph Hellwig 		 */
3322e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3323362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3324362a20c5SDavid Sterba 				0, 0);
3325f46b5a66SChristoph Hellwig 		if (ret < 0)
3326f46b5a66SChristoph Hellwig 			goto out;
33272c463823SFilipe Manana 		/*
33282c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
33292c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
33302c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
33312c463823SFilipe Manana 		 */
33322c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
33332c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
33342c463823SFilipe Manana 					      path->slots[0] - 1);
33352c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
33362c463823SFilipe Manana 				path->slots[0]--;
33372c463823SFilipe Manana 		}
3338f46b5a66SChristoph Hellwig 
3339ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3340e4355f34SFilipe David Borba Manana process_slot:
3341ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3342362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3343f46b5a66SChristoph Hellwig 			if (ret < 0)
3344f46b5a66SChristoph Hellwig 				goto out;
3345f46b5a66SChristoph Hellwig 			if (ret > 0)
3346f46b5a66SChristoph Hellwig 				break;
3347ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3348f46b5a66SChristoph Hellwig 		}
3349f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3350f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3351f46b5a66SChristoph Hellwig 
3352ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3353962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
33544a0cc7caSNikolay Borisov 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3355f46b5a66SChristoph Hellwig 			break;
3356f46b5a66SChristoph Hellwig 
3357962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3358c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3359c5c9cd4dSSage Weil 			int type;
336031840ae1SZheng Yan 			u32 size;
336131840ae1SZheng Yan 			struct btrfs_key new_key;
3362c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3363c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3364c5c9cd4dSSage Weil 			u8 comp;
3365f82a9901SFilipe Manana 			u64 drop_start;
336631840ae1SZheng Yan 
3367c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3368c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3369c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3370c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3371c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3372c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3373d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3374d397712bSChris Mason 								      extent);
3375d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3376d397712bSChris Mason 								 extent);
3377c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3378d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3379d397712bSChris Mason 								    extent);
3380c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3381c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3382c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3383c5c9cd4dSSage Weil 								    extent);
3384c5c9cd4dSSage Weil 			}
338531840ae1SZheng Yan 
33862c463823SFilipe Manana 			/*
33872c463823SFilipe Manana 			 * The first search might have left us at an extent
33882c463823SFilipe Manana 			 * item that ends before our target range's start, can
33892c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
33902c463823SFilipe Manana 			 */
33912c463823SFilipe Manana 			if (key.offset + datal <= off) {
3392e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3393e4355f34SFilipe David Borba Manana 				goto process_slot;
33942c463823SFilipe Manana 			} else if (key.offset >= off + len) {
33952c463823SFilipe Manana 				break;
3396e4355f34SFilipe David Borba Manana 			}
3397df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3398e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3399e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3400e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3401e4355f34SFilipe David Borba Manana 					   size);
3402e4355f34SFilipe David Borba Manana 
3403e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3404e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3405c5c9cd4dSSage Weil 
340631840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
34074a0cc7caSNikolay Borisov 			new_key.objectid = btrfs_ino(BTRFS_I(inode));
34084d728ec7SLi Zefan 			if (off <= key.offset)
3409c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
34104d728ec7SLi Zefan 			else
34114d728ec7SLi Zefan 				new_key.offset = destoff;
3412c5c9cd4dSSage Weil 
3413b6f3409bSSage Weil 			/*
3414f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3415f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3416f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3417f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3418f82a9901SFilipe Manana 			 * partially overlaps it).
3419f82a9901SFilipe Manana 			 */
3420f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3421f82a9901SFilipe Manana 				drop_start = last_dest_end;
3422f82a9901SFilipe Manana 			else
3423f82a9901SFilipe Manana 				drop_start = new_key.offset;
3424f82a9901SFilipe Manana 
3425f82a9901SFilipe Manana 			/*
3426b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3427b6f3409bSSage Weil 			 * 1 - add new extent
3428b6f3409bSSage Weil 			 * 1 - inode update
3429b6f3409bSSage Weil 			 */
3430b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3431a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3432a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3433a22285a6SYan, Zheng 				goto out;
3434a22285a6SYan, Zheng 			}
3435a22285a6SYan, Zheng 
3436c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3437c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3438d72c0842SLi Zefan 				/*
3439d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3440d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3441d72c0842SLi Zefan 				 */
3442d72c0842SLi Zefan 
344393915584SAntonio Ospite 				/* subtract range b */
3444d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3445d72c0842SLi Zefan 					datal = off + len - key.offset;
3446d72c0842SLi Zefan 
344793915584SAntonio Ospite 				/* subtract range a */
3448a22285a6SYan, Zheng 				if (off > key.offset) {
3449a22285a6SYan, Zheng 					datao += off - key.offset;
3450a22285a6SYan, Zheng 					datal -= off - key.offset;
3451a22285a6SYan, Zheng 				}
3452a22285a6SYan, Zheng 
34535dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3454f82a9901SFilipe Manana 							 drop_start,
3455a22285a6SYan, Zheng 							 new_key.offset + datal,
34562671485dSJosef Bacik 							 1);
345779787eaaSJeff Mahoney 				if (ret) {
34583f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
345900fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
346066642832SJeff Mahoney 									ret);
34613a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
346279787eaaSJeff Mahoney 					goto out;
346379787eaaSJeff Mahoney 				}
3464a22285a6SYan, Zheng 
346531840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
346631840ae1SZheng Yan 							      &new_key, size);
346779787eaaSJeff Mahoney 				if (ret) {
346866642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
34693a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
347079787eaaSJeff Mahoney 					goto out;
347179787eaaSJeff Mahoney 				}
347231840ae1SZheng Yan 
347331840ae1SZheng Yan 				leaf = path->nodes[0];
347431840ae1SZheng Yan 				slot = path->slots[0];
347531840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
347631840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
347731840ae1SZheng Yan 					    size);
3478ae01a0abSYan Zheng 
3479f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3480f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3481c5c9cd4dSSage Weil 
3482c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3483c5c9cd4dSSage Weil 				if (!disko)
3484c5c9cd4dSSage Weil 					datao = 0;
3485c5c9cd4dSSage Weil 
3486c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3487c5c9cd4dSSage Weil 							     datao);
3488c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3489c5c9cd4dSSage Weil 								datal);
3490fcebe456SJosef Bacik 
3491c5c9cd4dSSage Weil 				if (disko) {
3492c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
34932ff7e61eSJeff Mahoney 					ret = btrfs_inc_extent_ref(trans,
349484f7d8e6SJosef Bacik 							root,
34955d4f98a2SYan Zheng 							disko, diskl, 0,
3496f46b5a66SChristoph Hellwig 							root->root_key.objectid,
34974a0cc7caSNikolay Borisov 							btrfs_ino(BTRFS_I(inode)),
3498b06c4bf5SFilipe Manana 							new_key.offset - datao);
349979787eaaSJeff Mahoney 					if (ret) {
350079787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
350179787eaaSJeff Mahoney 									ret);
35023a45bb20SJeff Mahoney 						btrfs_end_transaction(trans);
350379787eaaSJeff Mahoney 						goto out;
350479787eaaSJeff Mahoney 
350579787eaaSJeff Mahoney 					}
3506f46b5a66SChristoph Hellwig 				}
3507c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3508c5c9cd4dSSage Weil 				u64 skip = 0;
3509c5c9cd4dSSage Weil 				u64 trim = 0;
3510ed958762SFilipe Manana 
3511c5c9cd4dSSage Weil 				if (off > key.offset) {
3512c5c9cd4dSSage Weil 					skip = off - key.offset;
3513c5c9cd4dSSage Weil 					new_key.offset += skip;
351431840ae1SZheng Yan 				}
3515d397712bSChris Mason 
3516c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3517c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3518d397712bSChris Mason 
3519c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3520c5c9cd4dSSage Weil 					ret = -EINVAL;
35213a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
3522c5c9cd4dSSage Weil 					goto out;
352331840ae1SZheng Yan 				}
3524c5c9cd4dSSage Weil 				size -= skip + trim;
3525c5c9cd4dSSage Weil 				datal -= skip + trim;
3526a22285a6SYan, Zheng 
35274a0ab9d7SDavid Sterba 				ret = clone_copy_inline_extent(inode,
35288039d87dSFilipe Manana 							       trans, path,
35298039d87dSFilipe Manana 							       &new_key,
3530f82a9901SFilipe Manana 							       drop_start,
35318039d87dSFilipe Manana 							       datal,
35328039d87dSFilipe Manana 							       skip, size, buf);
353379787eaaSJeff Mahoney 				if (ret) {
35343f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
35353a29bc09SChris Mason 						btrfs_abort_transaction(trans,
353679787eaaSJeff Mahoney 									ret);
35373a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
353879787eaaSJeff Mahoney 					goto out;
353979787eaaSJeff Mahoney 				}
3540c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3541c5c9cd4dSSage Weil 				slot = path->slots[0];
3542c5c9cd4dSSage Weil 			}
3543c5c9cd4dSSage Weil 
35447ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
35457ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
3546a2f392e4SNikolay Borisov 				clone_update_extent_map(BTRFS_I(inode), trans,
354714f59796SFilipe Manana 						NULL, drop_start,
35487ffbb598SFilipe Manana 						new_key.offset - drop_start);
35497ffbb598SFilipe Manana 
3550a2f392e4SNikolay Borisov 			clone_update_extent_map(BTRFS_I(inode), trans,
3551a2f392e4SNikolay Borisov 					path, 0, 0);
35527ffbb598SFilipe Manana 
3553c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3554b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3555c5c9cd4dSSage Weil 
355662e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
35570b246afaSJeff Mahoney 					      fs_info->sectorsize);
3558f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3559f82a9901SFilipe Manana 							last_dest_end,
35601c919a5eSMark Fasheh 							destoff, olen,
35611c919a5eSMark Fasheh 							no_time_update);
3562f82a9901SFilipe Manana 			if (ret)
356379787eaaSJeff Mahoney 				goto out;
35642c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
35652c463823SFilipe Manana 				break;
3566a22285a6SYan, Zheng 		}
3567b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3568df858e76SFilipe Manana 		key.offset = next_key_min_offset;
356969ae5e44SWang Xiaoguang 
357069ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
357169ae5e44SWang Xiaoguang 			ret = -EINTR;
357269ae5e44SWang Xiaoguang 			goto out;
357369ae5e44SWang Xiaoguang 		}
3574ae01a0abSYan Zheng 	}
3575f46b5a66SChristoph Hellwig 	ret = 0;
357632b7c687SMark Fasheh 
3577f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3578f82a9901SFilipe Manana 		/*
3579f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3580f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3581f82a9901SFilipe Manana 		 */
3582b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3583f82a9901SFilipe Manana 
3584f82a9901SFilipe Manana 		/*
3585f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3586f82a9901SFilipe Manana 		 * 1 - inode update
3587f82a9901SFilipe Manana 		 */
3588f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3589f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3590f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3591f82a9901SFilipe Manana 			goto out;
3592f82a9901SFilipe Manana 		}
3593f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3594f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3595f82a9901SFilipe Manana 		if (ret) {
3596f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
359766642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
35983a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
3599f82a9901SFilipe Manana 			goto out;
3600f82a9901SFilipe Manana 		}
3601a2f392e4SNikolay Borisov 		clone_update_extent_map(BTRFS_I(inode), trans, NULL,
3602a2f392e4SNikolay Borisov 				last_dest_end,
360314f59796SFilipe Manana 				destoff + len - last_dest_end);
3604f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
36051c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3606f82a9901SFilipe Manana 	}
3607f82a9901SFilipe Manana 
3608f46b5a66SChristoph Hellwig out:
360932b7c687SMark Fasheh 	btrfs_free_path(path);
361015351955SDavid Sterba 	kvfree(buf);
361132b7c687SMark Fasheh 	return ret;
361232b7c687SMark Fasheh }
361332b7c687SMark Fasheh 
36143db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
361532b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
361632b7c687SMark Fasheh {
361754563d41SAl Viro 	struct inode *inode = file_inode(file);
36183db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
36190b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
362032b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
362132b7c687SMark Fasheh 	int ret;
362232b7c687SMark Fasheh 	u64 len = olen;
36230b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
36243db11b2eSZach Brown 	int same_inode = src == inode;
362532b7c687SMark Fasheh 
362632b7c687SMark Fasheh 	/*
362732b7c687SMark Fasheh 	 * TODO:
362832b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
362932b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
363032b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
363132b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
363200fdf13aSLiu Bo 	 *
363300fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
363400fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
363532b7c687SMark Fasheh 	 */
363632b7c687SMark Fasheh 
363732b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
363832b7c687SMark Fasheh 		return -EROFS;
363932b7c687SMark Fasheh 
36403db11b2eSZach Brown 	if (file_src->f_path.mnt != file->f_path.mnt ||
36413db11b2eSZach Brown 	    src->i_sb != inode->i_sb)
36423db11b2eSZach Brown 		return -EXDEV;
364332b7c687SMark Fasheh 
364432b7c687SMark Fasheh 	/* don't make the dst file partly checksummed */
364532b7c687SMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
364632b7c687SMark Fasheh 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
36473db11b2eSZach Brown 		return -EINVAL;
364832b7c687SMark Fasheh 
364932b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
36503db11b2eSZach Brown 		return -EISDIR;
365132b7c687SMark Fasheh 
365232b7c687SMark Fasheh 	if (!same_inode) {
3653293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
365432b7c687SMark Fasheh 	} else {
36555955102cSAl Viro 		inode_lock(src);
365632b7c687SMark Fasheh 	}
365732b7c687SMark Fasheh 
365832b7c687SMark Fasheh 	/* determine range to clone */
365932b7c687SMark Fasheh 	ret = -EINVAL;
366032b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
366132b7c687SMark Fasheh 		goto out_unlock;
366232b7c687SMark Fasheh 	if (len == 0)
366332b7c687SMark Fasheh 		olen = len = src->i_size - off;
366432b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
366532b7c687SMark Fasheh 	if (off + len == src->i_size)
366632b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
366732b7c687SMark Fasheh 
3668ccccf3d6SFilipe Manana 	if (len == 0) {
3669ccccf3d6SFilipe Manana 		ret = 0;
3670ccccf3d6SFilipe Manana 		goto out_unlock;
3671ccccf3d6SFilipe Manana 	}
3672ccccf3d6SFilipe Manana 
367332b7c687SMark Fasheh 	/* verify the end result is block aligned */
367432b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
367532b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
367632b7c687SMark Fasheh 		goto out_unlock;
367732b7c687SMark Fasheh 
367832b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
367932b7c687SMark Fasheh 	if (same_inode) {
368032b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
368132b7c687SMark Fasheh 			goto out_unlock;
368232b7c687SMark Fasheh 	}
368332b7c687SMark Fasheh 
368432b7c687SMark Fasheh 	if (destoff > inode->i_size) {
368532b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
368632b7c687SMark Fasheh 		if (ret)
368732b7c687SMark Fasheh 			goto out_unlock;
368832b7c687SMark Fasheh 	}
368932b7c687SMark Fasheh 
3690c125b8bfSFilipe Manana 	/*
3691c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
3692c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
3693c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
3694c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
3695c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
3696c125b8bfSFilipe Manana 	 */
3697c125b8bfSFilipe Manana 	if (same_inode) {
3698c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3699c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
370032b7c687SMark Fasheh 
3701e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, lock_start, lock_len, true);
3702c125b8bfSFilipe Manana 	} else {
3703e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
3704e0bd70c6SFilipe Manana 					       true);
3705e0bd70c6SFilipe Manana 	}
3706e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3707e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3708e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3709e0bd70c6SFilipe Manana 		goto out_unlock;
3710c125b8bfSFilipe Manana 	}
371132b7c687SMark Fasheh 
37121c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
371332b7c687SMark Fasheh 
3714c125b8bfSFilipe Manana 	if (same_inode) {
3715c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3716c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
3717c125b8bfSFilipe Manana 
3718c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3719c125b8bfSFilipe Manana 	} else {
3720293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
3721c125b8bfSFilipe Manana 	}
3722c125b8bfSFilipe Manana 	/*
3723c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3724c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3725c125b8bfSFilipe Manana 	 */
372665bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
372709cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
372809cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
3729f46b5a66SChristoph Hellwig out_unlock:
3730293a8489SMark Fasheh 	if (!same_inode)
3731293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
3732293a8489SMark Fasheh 	else
37335955102cSAl Viro 		inode_unlock(src);
37343db11b2eSZach Brown 	return ret;
37353db11b2eSZach Brown }
37363db11b2eSZach Brown 
373704b38d60SChristoph Hellwig int btrfs_clone_file_range(struct file *src_file, loff_t off,
373804b38d60SChristoph Hellwig 		struct file *dst_file, loff_t destoff, u64 len)
37393db11b2eSZach Brown {
374004b38d60SChristoph Hellwig 	return btrfs_clone_files(dst_file, src_file, off, len, destoff);
3741c5c9cd4dSSage Weil }
3742c5c9cd4dSSage Weil 
37436ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
37446ef5ed0dSJosef Bacik {
3745496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
37460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
37476ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
37486ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
37496ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
37506ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
37516ef5ed0dSJosef Bacik 	struct btrfs_path *path;
37526ef5ed0dSJosef Bacik 	struct btrfs_key location;
37536ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
37546ef5ed0dSJosef Bacik 	u64 objectid = 0;
37556ef5ed0dSJosef Bacik 	u64 dir_id;
37563c04ce01SMiao Xie 	int ret;
37576ef5ed0dSJosef Bacik 
37586ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
37596ef5ed0dSJosef Bacik 		return -EPERM;
37606ef5ed0dSJosef Bacik 
37613c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
37623c04ce01SMiao Xie 	if (ret)
37633c04ce01SMiao Xie 		return ret;
37643c04ce01SMiao Xie 
37653c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
37663c04ce01SMiao Xie 		ret = -EFAULT;
37673c04ce01SMiao Xie 		goto out;
37683c04ce01SMiao Xie 	}
37696ef5ed0dSJosef Bacik 
37706ef5ed0dSJosef Bacik 	if (!objectid)
37711cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
37726ef5ed0dSJosef Bacik 
37736ef5ed0dSJosef Bacik 	location.objectid = objectid;
37746ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
37756ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
37766ef5ed0dSJosef Bacik 
37770b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
37783c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
37793c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
37803c04ce01SMiao Xie 		goto out;
37813c04ce01SMiao Xie 	}
37826d6d2829Ssatoru takeuchi 	if (!is_fstree(new_root->objectid)) {
37836d6d2829Ssatoru takeuchi 		ret = -ENOENT;
37846d6d2829Ssatoru takeuchi 		goto out;
37856d6d2829Ssatoru takeuchi 	}
37866ef5ed0dSJosef Bacik 
37876ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
37883c04ce01SMiao Xie 	if (!path) {
37893c04ce01SMiao Xie 		ret = -ENOMEM;
37903c04ce01SMiao Xie 		goto out;
37913c04ce01SMiao Xie 	}
37926ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
37936ef5ed0dSJosef Bacik 
37946ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
379598d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
37966ef5ed0dSJosef Bacik 		btrfs_free_path(path);
37973c04ce01SMiao Xie 		ret = PTR_ERR(trans);
37983c04ce01SMiao Xie 		goto out;
37996ef5ed0dSJosef Bacik 	}
38006ef5ed0dSJosef Bacik 
38010b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
38020b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
38036ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
3804cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
38056ef5ed0dSJosef Bacik 		btrfs_free_path(path);
38063a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
38070b246afaSJeff Mahoney 		btrfs_err(fs_info,
38085d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
38093c04ce01SMiao Xie 		ret = -ENOENT;
38103c04ce01SMiao Xie 		goto out;
38116ef5ed0dSJosef Bacik 	}
38126ef5ed0dSJosef Bacik 
38136ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
38146ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
38156ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
38166ef5ed0dSJosef Bacik 	btrfs_free_path(path);
38176ef5ed0dSJosef Bacik 
38180b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
38193a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
38203c04ce01SMiao Xie out:
38213c04ce01SMiao Xie 	mnt_drop_write_file(file);
38223c04ce01SMiao Xie 	return ret;
38236ef5ed0dSJosef Bacik }
38246ef5ed0dSJosef Bacik 
3825c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
3826bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
3827bf5fc093SJosef Bacik {
3828bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
3829bf5fc093SJosef Bacik 
3830bf5fc093SJosef Bacik 	space->total_bytes = 0;
3831bf5fc093SJosef Bacik 	space->used_bytes = 0;
3832bf5fc093SJosef Bacik 	space->flags = 0;
3833bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
3834bf5fc093SJosef Bacik 		space->flags = block_group->flags;
3835bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
3836bf5fc093SJosef Bacik 		space->used_bytes +=
3837bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
3838bf5fc093SJosef Bacik 	}
3839bf5fc093SJosef Bacik }
3840bf5fc093SJosef Bacik 
38412ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
38422ff7e61eSJeff Mahoney 				   void __user *arg)
38431406e432SJosef Bacik {
38441406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
38451406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
38461406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
38477fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
384813f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
38491406e432SJosef Bacik 	struct btrfs_space_info *info;
3850315d8e98SColin Ian King 	static const u64 types[] = {
3851315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
3852bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
3853bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
3854315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3855315d8e98SColin Ian King 	};
3856bf5fc093SJosef Bacik 	int num_types = 4;
38577fde62bfSChris Mason 	int alloc_size;
38581406e432SJosef Bacik 	int ret = 0;
385951788b1bSDan Rosenberg 	u64 slot_count = 0;
3860bf5fc093SJosef Bacik 	int i, c;
38611406e432SJosef Bacik 
38621406e432SJosef Bacik 	if (copy_from_user(&space_args,
38631406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
38641406e432SJosef Bacik 			   sizeof(space_args)))
38651406e432SJosef Bacik 		return -EFAULT;
38661406e432SJosef Bacik 
3867bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
3868bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
3869bf5fc093SJosef Bacik 
3870bf5fc093SJosef Bacik 		info = NULL;
38717fde62bfSChris Mason 		rcu_read_lock();
38720b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
3873bf5fc093SJosef Bacik 					list) {
3874bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
3875bf5fc093SJosef Bacik 				info = tmp;
3876bf5fc093SJosef Bacik 				break;
3877bf5fc093SJosef Bacik 			}
3878bf5fc093SJosef Bacik 		}
38797fde62bfSChris Mason 		rcu_read_unlock();
38801406e432SJosef Bacik 
3881bf5fc093SJosef Bacik 		if (!info)
3882bf5fc093SJosef Bacik 			continue;
3883bf5fc093SJosef Bacik 
3884bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
3885bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3886bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
3887bf5fc093SJosef Bacik 				slot_count++;
3888bf5fc093SJosef Bacik 		}
3889bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
3890bf5fc093SJosef Bacik 	}
3891bf5fc093SJosef Bacik 
389236523e95SDavid Sterba 	/*
389336523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
389436523e95SDavid Sterba 	 */
389536523e95SDavid Sterba 	slot_count++;
389636523e95SDavid Sterba 
38977fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
38987fde62bfSChris Mason 	if (space_args.space_slots == 0) {
38997fde62bfSChris Mason 		space_args.total_spaces = slot_count;
39007fde62bfSChris Mason 		goto out;
39017fde62bfSChris Mason 	}
3902bf5fc093SJosef Bacik 
390351788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
3904bf5fc093SJosef Bacik 
39057fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
3906bf5fc093SJosef Bacik 
39077fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
39087fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
39097fde62bfSChris Mason 	 */
391009cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
39117fde62bfSChris Mason 		return -ENOMEM;
39127fde62bfSChris Mason 
39137fde62bfSChris Mason 	space_args.total_spaces = 0;
39148d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
39157fde62bfSChris Mason 	if (!dest)
39167fde62bfSChris Mason 		return -ENOMEM;
39177fde62bfSChris Mason 	dest_orig = dest;
39187fde62bfSChris Mason 
39197fde62bfSChris Mason 	/* now we have a buffer to copy into */
3920bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
3921bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
3922bf5fc093SJosef Bacik 
392351788b1bSDan Rosenberg 		if (!slot_count)
392451788b1bSDan Rosenberg 			break;
392551788b1bSDan Rosenberg 
3926bf5fc093SJosef Bacik 		info = NULL;
39271406e432SJosef Bacik 		rcu_read_lock();
39280b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
3929bf5fc093SJosef Bacik 					list) {
3930bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
3931bf5fc093SJosef Bacik 				info = tmp;
39327fde62bfSChris Mason 				break;
3933bf5fc093SJosef Bacik 			}
3934bf5fc093SJosef Bacik 		}
3935bf5fc093SJosef Bacik 		rcu_read_unlock();
39367fde62bfSChris Mason 
3937bf5fc093SJosef Bacik 		if (!info)
3938bf5fc093SJosef Bacik 			continue;
3939bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
3940bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3941bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
3942c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
3943c065f5b1SSu Yue 						     &space);
39447fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
39451406e432SJosef Bacik 				dest++;
39461406e432SJosef Bacik 				space_args.total_spaces++;
394751788b1bSDan Rosenberg 				slot_count--;
39481406e432SJosef Bacik 			}
394951788b1bSDan Rosenberg 			if (!slot_count)
395051788b1bSDan Rosenberg 				break;
3951bf5fc093SJosef Bacik 		}
3952bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
3953bf5fc093SJosef Bacik 	}
39541406e432SJosef Bacik 
395536523e95SDavid Sterba 	/*
395636523e95SDavid Sterba 	 * Add global block reserve
395736523e95SDavid Sterba 	 */
395836523e95SDavid Sterba 	if (slot_count) {
39590b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
396036523e95SDavid Sterba 
396136523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
396236523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
396336523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
396436523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
396536523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
396636523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
396736523e95SDavid Sterba 		space_args.total_spaces++;
396836523e95SDavid Sterba 	}
396936523e95SDavid Sterba 
39702eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
39717fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
39727fde62bfSChris Mason 
39737fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
39747fde62bfSChris Mason 		ret = -EFAULT;
39757fde62bfSChris Mason 
39767fde62bfSChris Mason 	kfree(dest_orig);
39777fde62bfSChris Mason out:
39787fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
39791406e432SJosef Bacik 		ret = -EFAULT;
39801406e432SJosef Bacik 
39811406e432SJosef Bacik 	return ret;
39821406e432SJosef Bacik }
39831406e432SJosef Bacik 
39849a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
39859a8c28beSMiao Xie 					    void __user *argp)
398646204592SSage Weil {
398746204592SSage Weil 	struct btrfs_trans_handle *trans;
398846204592SSage Weil 	u64 transid;
3989db5b493aSTsutomu Itoh 	int ret;
399046204592SSage Weil 
3991d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
3992ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
3993ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
399498d5dc13STsutomu Itoh 			return PTR_ERR(trans);
3995ff7c1d33SMiao Xie 
3996ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
3997ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
3998ff7c1d33SMiao Xie 		goto out;
3999ff7c1d33SMiao Xie 	}
400046204592SSage Weil 	transid = trans->transid;
40013a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction_async(trans, 0);
40028b2b2d3cSTsutomu Itoh 	if (ret) {
40033a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
4004db5b493aSTsutomu Itoh 		return ret;
40058b2b2d3cSTsutomu Itoh 	}
4006ff7c1d33SMiao Xie out:
400746204592SSage Weil 	if (argp)
400846204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
400946204592SSage Weil 			return -EFAULT;
401046204592SSage Weil 	return 0;
401146204592SSage Weil }
401246204592SSage Weil 
40132ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
40149a8c28beSMiao Xie 					   void __user *argp)
401546204592SSage Weil {
401646204592SSage Weil 	u64 transid;
401746204592SSage Weil 
401846204592SSage Weil 	if (argp) {
401946204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
402046204592SSage Weil 			return -EFAULT;
402146204592SSage Weil 	} else {
402246204592SSage Weil 		transid = 0;  /* current trans */
402346204592SSage Weil 	}
40242ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
402546204592SSage Weil }
402646204592SSage Weil 
4027b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4028475f6387SJan Schmidt {
40290b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4030475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4031b8e95489SMiao Xie 	int ret;
4032475f6387SJan Schmidt 
4033475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4034475f6387SJan Schmidt 		return -EPERM;
4035475f6387SJan Schmidt 
4036475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4037475f6387SJan Schmidt 	if (IS_ERR(sa))
4038475f6387SJan Schmidt 		return PTR_ERR(sa);
4039475f6387SJan Schmidt 
4040b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4041b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4042b8e95489SMiao Xie 		if (ret)
4043b8e95489SMiao Xie 			goto out;
4044b8e95489SMiao Xie 	}
4045b8e95489SMiao Xie 
40460b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
404763a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
404863a212abSStefan Behrens 			      0);
4049475f6387SJan Schmidt 
4050475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4051475f6387SJan Schmidt 		ret = -EFAULT;
4052475f6387SJan Schmidt 
4053b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4054b8e95489SMiao Xie 		mnt_drop_write_file(file);
4055b8e95489SMiao Xie out:
4056475f6387SJan Schmidt 	kfree(sa);
4057475f6387SJan Schmidt 	return ret;
4058475f6387SJan Schmidt }
4059475f6387SJan Schmidt 
40602ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4061475f6387SJan Schmidt {
4062475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4063475f6387SJan Schmidt 		return -EPERM;
4064475f6387SJan Schmidt 
40652ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4066475f6387SJan Schmidt }
4067475f6387SJan Schmidt 
40682ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4069475f6387SJan Schmidt 				       void __user *arg)
4070475f6387SJan Schmidt {
4071475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4072475f6387SJan Schmidt 	int ret;
4073475f6387SJan Schmidt 
4074475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4075475f6387SJan Schmidt 		return -EPERM;
4076475f6387SJan Schmidt 
4077475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4078475f6387SJan Schmidt 	if (IS_ERR(sa))
4079475f6387SJan Schmidt 		return PTR_ERR(sa);
4080475f6387SJan Schmidt 
40812ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4082475f6387SJan Schmidt 
4083475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4084475f6387SJan Schmidt 		ret = -EFAULT;
4085475f6387SJan Schmidt 
4086475f6387SJan Schmidt 	kfree(sa);
4087475f6387SJan Schmidt 	return ret;
4088475f6387SJan Schmidt }
4089475f6387SJan Schmidt 
40902ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4091b27f7c0cSDavid Sterba 				      void __user *arg)
4092c11d2c23SStefan Behrens {
4093c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4094c11d2c23SStefan Behrens 	int ret;
4095c11d2c23SStefan Behrens 
4096c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4097c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4098c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4099c11d2c23SStefan Behrens 
4100b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4101b27f7c0cSDavid Sterba 		kfree(sa);
4102b27f7c0cSDavid Sterba 		return -EPERM;
4103b27f7c0cSDavid Sterba 	}
4104b27f7c0cSDavid Sterba 
41052ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4106c11d2c23SStefan Behrens 
4107c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4108c11d2c23SStefan Behrens 		ret = -EFAULT;
4109c11d2c23SStefan Behrens 
4110c11d2c23SStefan Behrens 	kfree(sa);
4111c11d2c23SStefan Behrens 	return ret;
4112c11d2c23SStefan Behrens }
4113c11d2c23SStefan Behrens 
41142ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
41152ff7e61eSJeff Mahoney 				    void __user *arg)
41163f6bcfbdSStefan Behrens {
41173f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
41183f6bcfbdSStefan Behrens 	int ret;
41193f6bcfbdSStefan Behrens 
41203f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
41213f6bcfbdSStefan Behrens 		return -EPERM;
41223f6bcfbdSStefan Behrens 
41233f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
41243f6bcfbdSStefan Behrens 	if (IS_ERR(p))
41253f6bcfbdSStefan Behrens 		return PTR_ERR(p);
41263f6bcfbdSStefan Behrens 
41273f6bcfbdSStefan Behrens 	switch (p->cmd) {
41283f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4129bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
4130adfa97cbSIlya Dryomov 			ret = -EROFS;
4131adfa97cbSIlya Dryomov 			goto out;
4132adfa97cbSIlya Dryomov 		}
4133171938e5SDavid Sterba 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4134e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
41353f6bcfbdSStefan Behrens 		} else {
41362ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4137171938e5SDavid Sterba 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
41383f6bcfbdSStefan Behrens 		}
41393f6bcfbdSStefan Behrens 		break;
41403f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
41410b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
41423f6bcfbdSStefan Behrens 		ret = 0;
41433f6bcfbdSStefan Behrens 		break;
41443f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
414517d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
414697282031SAnand Jain 		ret = 0;
41473f6bcfbdSStefan Behrens 		break;
41483f6bcfbdSStefan Behrens 	default:
41493f6bcfbdSStefan Behrens 		ret = -EINVAL;
41503f6bcfbdSStefan Behrens 		break;
41513f6bcfbdSStefan Behrens 	}
41523f6bcfbdSStefan Behrens 
41533f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
41543f6bcfbdSStefan Behrens 		ret = -EFAULT;
4155adfa97cbSIlya Dryomov out:
41563f6bcfbdSStefan Behrens 	kfree(p);
41573f6bcfbdSStefan Behrens 	return ret;
41583f6bcfbdSStefan Behrens }
41593f6bcfbdSStefan Behrens 
4160d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4161d7728c96SJan Schmidt {
4162d7728c96SJan Schmidt 	int ret = 0;
4163d7728c96SJan Schmidt 	int i;
4164740c3d22SChris Mason 	u64 rel_ptr;
4165d7728c96SJan Schmidt 	int size;
4166806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4167d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4168d7728c96SJan Schmidt 	struct btrfs_path *path;
4169d7728c96SJan Schmidt 
417082b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4171d7728c96SJan Schmidt 		return -EPERM;
4172d7728c96SJan Schmidt 
4173d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4174d7728c96SJan Schmidt 	if (!path) {
4175d7728c96SJan Schmidt 		ret = -ENOMEM;
4176d7728c96SJan Schmidt 		goto out;
4177d7728c96SJan Schmidt 	}
4178d7728c96SJan Schmidt 
4179d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4180d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4181d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4182d7728c96SJan Schmidt 		ipa = NULL;
4183d7728c96SJan Schmidt 		goto out;
4184d7728c96SJan Schmidt 	}
4185d7728c96SJan Schmidt 
4186d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4187d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4188d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4189d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4190d7728c96SJan Schmidt 		ipath = NULL;
4191d7728c96SJan Schmidt 		goto out;
4192d7728c96SJan Schmidt 	}
4193d7728c96SJan Schmidt 
4194d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4195d7728c96SJan Schmidt 	if (ret < 0)
4196d7728c96SJan Schmidt 		goto out;
4197d7728c96SJan Schmidt 
4198d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4199745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4200745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4201740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4202d7728c96SJan Schmidt 	}
4203d7728c96SJan Schmidt 
4204718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4205718dc5faSOmar Sandoval 			   ipath->fspath, size);
4206d7728c96SJan Schmidt 	if (ret) {
4207d7728c96SJan Schmidt 		ret = -EFAULT;
4208d7728c96SJan Schmidt 		goto out;
4209d7728c96SJan Schmidt 	}
4210d7728c96SJan Schmidt 
4211d7728c96SJan Schmidt out:
4212d7728c96SJan Schmidt 	btrfs_free_path(path);
4213d7728c96SJan Schmidt 	free_ipath(ipath);
4214d7728c96SJan Schmidt 	kfree(ipa);
4215d7728c96SJan Schmidt 
4216d7728c96SJan Schmidt 	return ret;
4217d7728c96SJan Schmidt }
4218d7728c96SJan Schmidt 
4219d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4220d7728c96SJan Schmidt {
4221d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4222d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4223d7728c96SJan Schmidt 
4224d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4225d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4226d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4227d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4228d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4229d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4230d7728c96SJan Schmidt 	} else {
4231d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4232d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4233d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4234d7728c96SJan Schmidt 	}
4235d7728c96SJan Schmidt 
4236d7728c96SJan Schmidt 	return 0;
4237d7728c96SJan Schmidt }
4238d7728c96SJan Schmidt 
42392ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4240d24a67b2SZygo Blaxell 					void __user *arg, int version)
4241d7728c96SJan Schmidt {
4242d7728c96SJan Schmidt 	int ret = 0;
4243d7728c96SJan Schmidt 	int size;
4244d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4245d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4246d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4247d24a67b2SZygo Blaxell 	bool ignore_offset;
4248d7728c96SJan Schmidt 
4249d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4250d7728c96SJan Schmidt 		return -EPERM;
4251d7728c96SJan Schmidt 
4252d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
42537b9ea627SShailendra Verma 	if (IS_ERR(loi))
42547b9ea627SShailendra Verma 		return PTR_ERR(loi);
4255d7728c96SJan Schmidt 
4256d24a67b2SZygo Blaxell 	if (version == 1) {
4257d24a67b2SZygo Blaxell 		ignore_offset = false;
4258b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
4259d24a67b2SZygo Blaxell 	} else {
4260d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
4261d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4262d24a67b2SZygo Blaxell 			ret = -EINVAL;
4263d24a67b2SZygo Blaxell 			goto out_loi;
4264d24a67b2SZygo Blaxell 		}
4265d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
4266d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4267d24a67b2SZygo Blaxell 			ret = -EINVAL;
4268d24a67b2SZygo Blaxell 			goto out_loi;
4269d24a67b2SZygo Blaxell 		}
4270d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4271b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
4272d24a67b2SZygo Blaxell 	}
4273d24a67b2SZygo Blaxell 
4274d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4275d7728c96SJan Schmidt 	if (!path) {
4276d7728c96SJan Schmidt 		ret = -ENOMEM;
4277d7728c96SJan Schmidt 		goto out;
4278d7728c96SJan Schmidt 	}
4279d7728c96SJan Schmidt 
4280d7728c96SJan Schmidt 	inodes = init_data_container(size);
4281d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4282d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4283d7728c96SJan Schmidt 		inodes = NULL;
4284d7728c96SJan Schmidt 		goto out;
4285d7728c96SJan Schmidt 	}
4286d7728c96SJan Schmidt 
42872ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4288d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
4289df031f07SLiu Bo 	if (ret == -EINVAL)
4290d7728c96SJan Schmidt 		ret = -ENOENT;
4291d7728c96SJan Schmidt 	if (ret < 0)
4292d7728c96SJan Schmidt 		goto out;
4293d7728c96SJan Schmidt 
4294718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4295718dc5faSOmar Sandoval 			   size);
4296d7728c96SJan Schmidt 	if (ret)
4297d7728c96SJan Schmidt 		ret = -EFAULT;
4298d7728c96SJan Schmidt 
4299d7728c96SJan Schmidt out:
4300d7728c96SJan Schmidt 	btrfs_free_path(path);
4301f54de068SDavid Sterba 	kvfree(inodes);
4302d24a67b2SZygo Blaxell out_loi:
4303d7728c96SJan Schmidt 	kfree(loi);
4304d7728c96SJan Schmidt 
4305d7728c96SJan Schmidt 	return ret;
4306d7728c96SJan Schmidt }
4307d7728c96SJan Schmidt 
4308008ef096SDavid Sterba void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4309c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4310c9e9f97bSIlya Dryomov {
4311c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4312c9e9f97bSIlya Dryomov 
4313c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4314c9e9f97bSIlya Dryomov 
43153009a62fSDavid Sterba 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4316837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4317837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4318837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4319a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4320a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4321837d5b6eSIlya Dryomov 
4322c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4323c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4324c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
432519a39dceSIlya Dryomov 
432619a39dceSIlya Dryomov 	spin_lock(&fs_info->balance_lock);
432719a39dceSIlya Dryomov 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
432819a39dceSIlya Dryomov 	spin_unlock(&fs_info->balance_lock);
4329c9e9f97bSIlya Dryomov }
4330c9e9f97bSIlya Dryomov 
43319ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4332c9e9f97bSIlya Dryomov {
4333496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4334c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4335c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4336c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4337ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4338c9e9f97bSIlya Dryomov 	int ret;
4339c9e9f97bSIlya Dryomov 
4340c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4341c9e9f97bSIlya Dryomov 		return -EPERM;
4342c9e9f97bSIlya Dryomov 
4343e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
43449ba1f6e4SLiu Bo 	if (ret)
43459ba1f6e4SLiu Bo 		return ret;
43469ba1f6e4SLiu Bo 
4347ed0fb78fSIlya Dryomov again:
4348171938e5SDavid Sterba 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4349c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4350ed0fb78fSIlya Dryomov 		need_unlock = true;
4351ed0fb78fSIlya Dryomov 		goto locked;
4352ed0fb78fSIlya Dryomov 	}
4353ed0fb78fSIlya Dryomov 
4354ed0fb78fSIlya Dryomov 	/*
435501327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4356ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4357ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4358ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4359ed0fb78fSIlya Dryomov 	 */
4360ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4361ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4362ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
43633009a62fSDavid Sterba 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4364ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4365dccdb07bSDavid Sterba 			/*
4366dccdb07bSDavid Sterba 			 * Lock released to allow other waiters to continue,
4367dccdb07bSDavid Sterba 			 * we'll reexamine the status again.
4368dccdb07bSDavid Sterba 			 */
4369ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4370ed0fb78fSIlya Dryomov 
4371ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
43723009a62fSDavid Sterba 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4373ed0fb78fSIlya Dryomov 				/* this is (3) */
4374ed0fb78fSIlya Dryomov 				need_unlock = false;
4375ed0fb78fSIlya Dryomov 				goto locked;
4376ed0fb78fSIlya Dryomov 			}
4377ed0fb78fSIlya Dryomov 
4378ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4379ed0fb78fSIlya Dryomov 			goto again;
4380ed0fb78fSIlya Dryomov 		} else {
4381ed0fb78fSIlya Dryomov 			/* this is (2) */
4382ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4383ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4384ed0fb78fSIlya Dryomov 			goto out;
4385ed0fb78fSIlya Dryomov 		}
4386ed0fb78fSIlya Dryomov 	} else {
4387ed0fb78fSIlya Dryomov 		/* this is (1) */
4388ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4389e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4390ed0fb78fSIlya Dryomov 		goto out;
4391ed0fb78fSIlya Dryomov 	}
4392ed0fb78fSIlya Dryomov 
4393ed0fb78fSIlya Dryomov locked:
4394171938e5SDavid Sterba 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4395c9e9f97bSIlya Dryomov 
4396c9e9f97bSIlya Dryomov 	if (arg) {
4397c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4398c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4399c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4400ed0fb78fSIlya Dryomov 			goto out_unlock;
4401c9e9f97bSIlya Dryomov 		}
4402de322263SIlya Dryomov 
4403de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4404de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4405de322263SIlya Dryomov 				ret = -ENOTCONN;
4406de322263SIlya Dryomov 				goto out_bargs;
4407de322263SIlya Dryomov 			}
4408de322263SIlya Dryomov 
4409de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4410de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4411de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4412de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4413de322263SIlya Dryomov 
4414de322263SIlya Dryomov 			goto do_balance;
4415de322263SIlya Dryomov 		}
4416c9e9f97bSIlya Dryomov 	} else {
4417c9e9f97bSIlya Dryomov 		bargs = NULL;
4418c9e9f97bSIlya Dryomov 	}
4419c9e9f97bSIlya Dryomov 
4420ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4421837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4422837d5b6eSIlya Dryomov 		goto out_bargs;
4423837d5b6eSIlya Dryomov 	}
4424837d5b6eSIlya Dryomov 
44258d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4426c9e9f97bSIlya Dryomov 	if (!bctl) {
4427c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4428c9e9f97bSIlya Dryomov 		goto out_bargs;
4429c9e9f97bSIlya Dryomov 	}
4430c9e9f97bSIlya Dryomov 
4431c9e9f97bSIlya Dryomov 	if (arg) {
4432c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4433c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4434c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4435c9e9f97bSIlya Dryomov 
4436c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4437f43ffb60SIlya Dryomov 	} else {
4438f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4439f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4440c9e9f97bSIlya Dryomov 	}
4441c9e9f97bSIlya Dryomov 
44428eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
44438eb93459SDavid Sterba 		ret = -EINVAL;
44440f89abf5SChristian Engelmayer 		goto out_bctl;
44458eb93459SDavid Sterba 	}
44468eb93459SDavid Sterba 
4447de322263SIlya Dryomov do_balance:
4448c9e9f97bSIlya Dryomov 	/*
4449149196a2SDavid Sterba 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
4450149196a2SDavid Sterba 	 * btrfs_balance.  bctl is freed in reset_balance_state, or, if
4451149196a2SDavid Sterba 	 * restriper was paused all the way until unmount, in free_fs_info.
4452149196a2SDavid Sterba 	 * The flag should be cleared after reset_balance_state.
4453c9e9f97bSIlya Dryomov 	 */
4454ed0fb78fSIlya Dryomov 	need_unlock = false;
4455ed0fb78fSIlya Dryomov 
44566fcf6e2bSDavid Sterba 	ret = btrfs_balance(fs_info, bctl, bargs);
44570f89abf5SChristian Engelmayer 	bctl = NULL;
4458ed0fb78fSIlya Dryomov 
4459c9e9f97bSIlya Dryomov 	if (arg) {
4460c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4461c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4462c9e9f97bSIlya Dryomov 	}
4463c9e9f97bSIlya Dryomov 
44640f89abf5SChristian Engelmayer out_bctl:
44650f89abf5SChristian Engelmayer 	kfree(bctl);
4466c9e9f97bSIlya Dryomov out_bargs:
4467c9e9f97bSIlya Dryomov 	kfree(bargs);
4468ed0fb78fSIlya Dryomov out_unlock:
4469c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4470ed0fb78fSIlya Dryomov 	if (need_unlock)
4471171938e5SDavid Sterba 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4472ed0fb78fSIlya Dryomov out:
4473e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4474c9e9f97bSIlya Dryomov 	return ret;
4475c9e9f97bSIlya Dryomov }
4476c9e9f97bSIlya Dryomov 
44772ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4478837d5b6eSIlya Dryomov {
4479837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4480837d5b6eSIlya Dryomov 		return -EPERM;
4481837d5b6eSIlya Dryomov 
4482837d5b6eSIlya Dryomov 	switch (cmd) {
4483837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
44840b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4485a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
44860b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4487837d5b6eSIlya Dryomov 	}
4488837d5b6eSIlya Dryomov 
4489837d5b6eSIlya Dryomov 	return -EINVAL;
4490837d5b6eSIlya Dryomov }
4491837d5b6eSIlya Dryomov 
44922ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
449319a39dceSIlya Dryomov 					 void __user *arg)
449419a39dceSIlya Dryomov {
449519a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
449619a39dceSIlya Dryomov 	int ret = 0;
449719a39dceSIlya Dryomov 
449819a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
449919a39dceSIlya Dryomov 		return -EPERM;
450019a39dceSIlya Dryomov 
450119a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
450219a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
450319a39dceSIlya Dryomov 		ret = -ENOTCONN;
450419a39dceSIlya Dryomov 		goto out;
450519a39dceSIlya Dryomov 	}
450619a39dceSIlya Dryomov 
45078d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
450819a39dceSIlya Dryomov 	if (!bargs) {
450919a39dceSIlya Dryomov 		ret = -ENOMEM;
451019a39dceSIlya Dryomov 		goto out;
451119a39dceSIlya Dryomov 	}
451219a39dceSIlya Dryomov 
4513008ef096SDavid Sterba 	btrfs_update_ioctl_balance_args(fs_info, bargs);
451419a39dceSIlya Dryomov 
451519a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
451619a39dceSIlya Dryomov 		ret = -EFAULT;
451719a39dceSIlya Dryomov 
451819a39dceSIlya Dryomov 	kfree(bargs);
451919a39dceSIlya Dryomov out:
452019a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
452119a39dceSIlya Dryomov 	return ret;
452219a39dceSIlya Dryomov }
452319a39dceSIlya Dryomov 
4524905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
45255d13a37bSArne Jansen {
45260b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
45270b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
45285d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
45295d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
45305d13a37bSArne Jansen 	int ret;
45315d13a37bSArne Jansen 	int err;
45325d13a37bSArne Jansen 
45335d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
45345d13a37bSArne Jansen 		return -EPERM;
45355d13a37bSArne Jansen 
4536905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4537905b0ddaSMiao Xie 	if (ret)
4538905b0ddaSMiao Xie 		return ret;
45395d13a37bSArne Jansen 
45405d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4541905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4542905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4543905b0ddaSMiao Xie 		goto drop_write;
4544905b0ddaSMiao Xie 	}
45455d13a37bSArne Jansen 
45460b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
45470b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 2);
45485d13a37bSArne Jansen 	if (IS_ERR(trans)) {
45495d13a37bSArne Jansen 		ret = PTR_ERR(trans);
45505d13a37bSArne Jansen 		goto out;
45515d13a37bSArne Jansen 	}
45525d13a37bSArne Jansen 
45535d13a37bSArne Jansen 	switch (sa->cmd) {
45545d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
45550b246afaSJeff Mahoney 		ret = btrfs_quota_enable(trans, fs_info);
45565d13a37bSArne Jansen 		break;
45575d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
45580b246afaSJeff Mahoney 		ret = btrfs_quota_disable(trans, fs_info);
45595d13a37bSArne Jansen 		break;
45605d13a37bSArne Jansen 	default:
45615d13a37bSArne Jansen 		ret = -EINVAL;
45625d13a37bSArne Jansen 		break;
45635d13a37bSArne Jansen 	}
45645d13a37bSArne Jansen 
45653a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
45665d13a37bSArne Jansen 	if (err && !ret)
45675d13a37bSArne Jansen 		ret = err;
45685d13a37bSArne Jansen out:
45695d13a37bSArne Jansen 	kfree(sa);
45700b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4571905b0ddaSMiao Xie drop_write:
4572905b0ddaSMiao Xie 	mnt_drop_write_file(file);
45735d13a37bSArne Jansen 	return ret;
45745d13a37bSArne Jansen }
45755d13a37bSArne Jansen 
4576905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
45775d13a37bSArne Jansen {
45780b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
45790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
45800b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
45815d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
45825d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
45835d13a37bSArne Jansen 	int ret;
45845d13a37bSArne Jansen 	int err;
45855d13a37bSArne Jansen 
45865d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
45875d13a37bSArne Jansen 		return -EPERM;
45885d13a37bSArne Jansen 
4589905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4590905b0ddaSMiao Xie 	if (ret)
4591905b0ddaSMiao Xie 		return ret;
45925d13a37bSArne Jansen 
45935d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4594905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4595905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4596905b0ddaSMiao Xie 		goto drop_write;
4597905b0ddaSMiao Xie 	}
45985d13a37bSArne Jansen 
45995d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
46005d13a37bSArne Jansen 	if (IS_ERR(trans)) {
46015d13a37bSArne Jansen 		ret = PTR_ERR(trans);
46025d13a37bSArne Jansen 		goto out;
46035d13a37bSArne Jansen 	}
46045d13a37bSArne Jansen 
46055d13a37bSArne Jansen 	if (sa->assign) {
46060b246afaSJeff Mahoney 		ret = btrfs_add_qgroup_relation(trans, fs_info,
46075d13a37bSArne Jansen 						sa->src, sa->dst);
46085d13a37bSArne Jansen 	} else {
46090b246afaSJeff Mahoney 		ret = btrfs_del_qgroup_relation(trans, fs_info,
46105d13a37bSArne Jansen 						sa->src, sa->dst);
46115d13a37bSArne Jansen 	}
46125d13a37bSArne Jansen 
4613e082f563SQu Wenruo 	/* update qgroup status and info */
46140b246afaSJeff Mahoney 	err = btrfs_run_qgroups(trans, fs_info);
4615e082f563SQu Wenruo 	if (err < 0)
46160b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4617ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
46183a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
46195d13a37bSArne Jansen 	if (err && !ret)
46205d13a37bSArne Jansen 		ret = err;
46215d13a37bSArne Jansen 
46225d13a37bSArne Jansen out:
46235d13a37bSArne Jansen 	kfree(sa);
4624905b0ddaSMiao Xie drop_write:
4625905b0ddaSMiao Xie 	mnt_drop_write_file(file);
46265d13a37bSArne Jansen 	return ret;
46275d13a37bSArne Jansen }
46285d13a37bSArne Jansen 
4629905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
46305d13a37bSArne Jansen {
46310b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
46320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46330b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
46345d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
46355d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
46365d13a37bSArne Jansen 	int ret;
46375d13a37bSArne Jansen 	int err;
46385d13a37bSArne Jansen 
46395d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
46405d13a37bSArne Jansen 		return -EPERM;
46415d13a37bSArne Jansen 
4642905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4643905b0ddaSMiao Xie 	if (ret)
4644905b0ddaSMiao Xie 		return ret;
46455d13a37bSArne Jansen 
46465d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4647905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4648905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4649905b0ddaSMiao Xie 		goto drop_write;
4650905b0ddaSMiao Xie 	}
46515d13a37bSArne Jansen 
4652d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4653d86e56cfSMiao Xie 		ret = -EINVAL;
4654d86e56cfSMiao Xie 		goto out;
4655d86e56cfSMiao Xie 	}
4656d86e56cfSMiao Xie 
46575d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
46585d13a37bSArne Jansen 	if (IS_ERR(trans)) {
46595d13a37bSArne Jansen 		ret = PTR_ERR(trans);
46605d13a37bSArne Jansen 		goto out;
46615d13a37bSArne Jansen 	}
46625d13a37bSArne Jansen 
46635d13a37bSArne Jansen 	if (sa->create) {
46640b246afaSJeff Mahoney 		ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
46655d13a37bSArne Jansen 	} else {
46660b246afaSJeff Mahoney 		ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
46675d13a37bSArne Jansen 	}
46685d13a37bSArne Jansen 
46693a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
46705d13a37bSArne Jansen 	if (err && !ret)
46715d13a37bSArne Jansen 		ret = err;
46725d13a37bSArne Jansen 
46735d13a37bSArne Jansen out:
46745d13a37bSArne Jansen 	kfree(sa);
4675905b0ddaSMiao Xie drop_write:
4676905b0ddaSMiao Xie 	mnt_drop_write_file(file);
46775d13a37bSArne Jansen 	return ret;
46785d13a37bSArne Jansen }
46795d13a37bSArne Jansen 
4680905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
46815d13a37bSArne Jansen {
46820b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
46830b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46840b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
46855d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
46865d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
46875d13a37bSArne Jansen 	int ret;
46885d13a37bSArne Jansen 	int err;
46895d13a37bSArne Jansen 	u64 qgroupid;
46905d13a37bSArne Jansen 
46915d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
46925d13a37bSArne Jansen 		return -EPERM;
46935d13a37bSArne Jansen 
4694905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4695905b0ddaSMiao Xie 	if (ret)
4696905b0ddaSMiao Xie 		return ret;
46975d13a37bSArne Jansen 
46985d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4699905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4700905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4701905b0ddaSMiao Xie 		goto drop_write;
4702905b0ddaSMiao Xie 	}
47035d13a37bSArne Jansen 
47045d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
47055d13a37bSArne Jansen 	if (IS_ERR(trans)) {
47065d13a37bSArne Jansen 		ret = PTR_ERR(trans);
47075d13a37bSArne Jansen 		goto out;
47085d13a37bSArne Jansen 	}
47095d13a37bSArne Jansen 
47105d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
47115d13a37bSArne Jansen 	if (!qgroupid) {
47125d13a37bSArne Jansen 		/* take the current subvol as qgroup */
47135d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
47145d13a37bSArne Jansen 	}
47155d13a37bSArne Jansen 
47160b246afaSJeff Mahoney 	ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
47175d13a37bSArne Jansen 
47183a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
47195d13a37bSArne Jansen 	if (err && !ret)
47205d13a37bSArne Jansen 		ret = err;
47215d13a37bSArne Jansen 
47225d13a37bSArne Jansen out:
47235d13a37bSArne Jansen 	kfree(sa);
4724905b0ddaSMiao Xie drop_write:
4725905b0ddaSMiao Xie 	mnt_drop_write_file(file);
47265d13a37bSArne Jansen 	return ret;
47275d13a37bSArne Jansen }
47285d13a37bSArne Jansen 
47292f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
47302f232036SJan Schmidt {
47310b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47332f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
47342f232036SJan Schmidt 	int ret;
47352f232036SJan Schmidt 
47362f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
47372f232036SJan Schmidt 		return -EPERM;
47382f232036SJan Schmidt 
47392f232036SJan Schmidt 	ret = mnt_want_write_file(file);
47402f232036SJan Schmidt 	if (ret)
47412f232036SJan Schmidt 		return ret;
47422f232036SJan Schmidt 
47432f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
47442f232036SJan Schmidt 	if (IS_ERR(qsa)) {
47452f232036SJan Schmidt 		ret = PTR_ERR(qsa);
47462f232036SJan Schmidt 		goto drop_write;
47472f232036SJan Schmidt 	}
47482f232036SJan Schmidt 
47492f232036SJan Schmidt 	if (qsa->flags) {
47502f232036SJan Schmidt 		ret = -EINVAL;
47512f232036SJan Schmidt 		goto out;
47522f232036SJan Schmidt 	}
47532f232036SJan Schmidt 
47540b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
47552f232036SJan Schmidt 
47562f232036SJan Schmidt out:
47572f232036SJan Schmidt 	kfree(qsa);
47582f232036SJan Schmidt drop_write:
47592f232036SJan Schmidt 	mnt_drop_write_file(file);
47602f232036SJan Schmidt 	return ret;
47612f232036SJan Schmidt }
47622f232036SJan Schmidt 
47632f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
47642f232036SJan Schmidt {
47650b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47672f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
47682f232036SJan Schmidt 	int ret = 0;
47692f232036SJan Schmidt 
47702f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
47712f232036SJan Schmidt 		return -EPERM;
47722f232036SJan Schmidt 
47738d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
47742f232036SJan Schmidt 	if (!qsa)
47752f232036SJan Schmidt 		return -ENOMEM;
47762f232036SJan Schmidt 
47770b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
47782f232036SJan Schmidt 		qsa->flags = 1;
47790b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
47802f232036SJan Schmidt 	}
47812f232036SJan Schmidt 
47822f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
47832f232036SJan Schmidt 		ret = -EFAULT;
47842f232036SJan Schmidt 
47852f232036SJan Schmidt 	kfree(qsa);
47862f232036SJan Schmidt 	return ret;
47872f232036SJan Schmidt }
47882f232036SJan Schmidt 
478957254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
479057254b6eSJan Schmidt {
47910b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47920b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
479357254b6eSJan Schmidt 
479457254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
479557254b6eSJan Schmidt 		return -EPERM;
479657254b6eSJan Schmidt 
47970b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
479857254b6eSJan Schmidt }
479957254b6eSJan Schmidt 
4800abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
4801abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
48028ea05e3aSAlexander Block {
4803496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
48040b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48058ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
48068ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
48078ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
4808c2050a45SDeepa Dinamani 	struct timespec ct = current_time(inode);
48098ea05e3aSAlexander Block 	int ret = 0;
4810dd5f9615SStefan Behrens 	int received_uuid_changed;
48118ea05e3aSAlexander Block 
4812bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
4813bd60ea0fSDavid Sterba 		return -EPERM;
4814bd60ea0fSDavid Sterba 
48158ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
48168ea05e3aSAlexander Block 	if (ret < 0)
48178ea05e3aSAlexander Block 		return ret;
48188ea05e3aSAlexander Block 
48190b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
48208ea05e3aSAlexander Block 
48214a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
48228ea05e3aSAlexander Block 		ret = -EINVAL;
48238ea05e3aSAlexander Block 		goto out;
48248ea05e3aSAlexander Block 	}
48258ea05e3aSAlexander Block 
48268ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
48278ea05e3aSAlexander Block 		ret = -EROFS;
48288ea05e3aSAlexander Block 		goto out;
48298ea05e3aSAlexander Block 	}
48308ea05e3aSAlexander Block 
4831dd5f9615SStefan Behrens 	/*
4832dd5f9615SStefan Behrens 	 * 1 - root item
4833dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
4834dd5f9615SStefan Behrens 	 */
4835dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
48368ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
48378ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
48388ea05e3aSAlexander Block 		trans = NULL;
48398ea05e3aSAlexander Block 		goto out;
48408ea05e3aSAlexander Block 	}
48418ea05e3aSAlexander Block 
48428ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
48438ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
48448ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
48458ea05e3aSAlexander Block 
4846dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4847dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
4848dd5f9615SStefan Behrens 	if (received_uuid_changed &&
4849d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
4850d87ff758SNikolay Borisov 		ret = btrfs_uuid_tree_rem(trans, fs_info,
4851d87ff758SNikolay Borisov 					  root_item->received_uuid,
4852dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4853dd5f9615SStefan Behrens 					  root->root_key.objectid);
4854d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
4855d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
4856d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
4857d87ff758SNikolay Borisov 		        goto out;
4858d87ff758SNikolay Borisov 		}
4859d87ff758SNikolay Borisov 	}
48608ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
48618ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
48628ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
48633cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
48643cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
48653cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
48663cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
48678ea05e3aSAlexander Block 
48680b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
48698ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
48708ea05e3aSAlexander Block 	if (ret < 0) {
48713a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
48728ea05e3aSAlexander Block 		goto out;
4873dd5f9615SStefan Behrens 	}
4874dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
48750b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_add(trans, fs_info, sa->uuid,
4876dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4877dd5f9615SStefan Behrens 					  root->root_key.objectid);
4878dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
487966642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
4880efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
4881dd5f9615SStefan Behrens 			goto out;
4882dd5f9615SStefan Behrens 		}
4883dd5f9615SStefan Behrens 	}
48843a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
4885abccd00fSHugo Mills out:
48860b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4887abccd00fSHugo Mills 	mnt_drop_write_file(file);
4888abccd00fSHugo Mills 	return ret;
4889abccd00fSHugo Mills }
4890abccd00fSHugo Mills 
4891abccd00fSHugo Mills #ifdef CONFIG_64BIT
4892abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4893abccd00fSHugo Mills 						void __user *arg)
4894abccd00fSHugo Mills {
4895abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4896abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4897abccd00fSHugo Mills 	int ret = 0;
4898abccd00fSHugo Mills 
4899abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
49007b9ea627SShailendra Verma 	if (IS_ERR(args32))
49017b9ea627SShailendra Verma 		return PTR_ERR(args32);
4902abccd00fSHugo Mills 
49038d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
490484dbeb87SDan Carpenter 	if (!args64) {
490584dbeb87SDan Carpenter 		ret = -ENOMEM;
4906abccd00fSHugo Mills 		goto out;
4907abccd00fSHugo Mills 	}
4908abccd00fSHugo Mills 
4909abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4910abccd00fSHugo Mills 	args64->stransid = args32->stransid;
4911abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
4912abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
4913abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
4914abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
4915abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
4916abccd00fSHugo Mills 	args64->flags = args32->flags;
4917abccd00fSHugo Mills 
4918abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
4919abccd00fSHugo Mills 	if (ret)
4920abccd00fSHugo Mills 		goto out;
4921abccd00fSHugo Mills 
4922abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4923abccd00fSHugo Mills 	args32->stransid = args64->stransid;
4924abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
4925abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
4926abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
4927abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
4928abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
4929abccd00fSHugo Mills 	args32->flags = args64->flags;
4930abccd00fSHugo Mills 
4931abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
4932abccd00fSHugo Mills 	if (ret)
4933abccd00fSHugo Mills 		ret = -EFAULT;
4934abccd00fSHugo Mills 
4935abccd00fSHugo Mills out:
4936abccd00fSHugo Mills 	kfree(args32);
4937abccd00fSHugo Mills 	kfree(args64);
4938abccd00fSHugo Mills 	return ret;
4939abccd00fSHugo Mills }
4940abccd00fSHugo Mills #endif
4941abccd00fSHugo Mills 
4942abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
4943abccd00fSHugo Mills 					    void __user *arg)
4944abccd00fSHugo Mills {
4945abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
4946abccd00fSHugo Mills 	int ret = 0;
4947abccd00fSHugo Mills 
4948abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
49497b9ea627SShailendra Verma 	if (IS_ERR(sa))
49507b9ea627SShailendra Verma 		return PTR_ERR(sa);
4951abccd00fSHugo Mills 
4952abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
4953abccd00fSHugo Mills 
4954abccd00fSHugo Mills 	if (ret)
4955abccd00fSHugo Mills 		goto out;
4956abccd00fSHugo Mills 
49578ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
49588ea05e3aSAlexander Block 	if (ret)
49598ea05e3aSAlexander Block 		ret = -EFAULT;
49608ea05e3aSAlexander Block 
49618ea05e3aSAlexander Block out:
49628ea05e3aSAlexander Block 	kfree(sa);
49638ea05e3aSAlexander Block 	return ret;
49648ea05e3aSAlexander Block }
49658ea05e3aSAlexander Block 
4966867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
4967867ab667Sjeff.liu {
49680b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4970a1b83ac5SAnand Jain 	size_t len;
4971867ab667Sjeff.liu 	int ret;
4972a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
4973a1b83ac5SAnand Jain 
49740b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
49750b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
49760b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
4977a1b83ac5SAnand Jain 
4978a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
4979867ab667Sjeff.liu 
4980867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
49810b246afaSJeff Mahoney 		btrfs_warn(fs_info,
49820b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
49830b246afaSJeff Mahoney 			   --len);
4984867ab667Sjeff.liu 	}
4985867ab667Sjeff.liu 
4986867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
4987867ab667Sjeff.liu 
4988867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
4989867ab667Sjeff.liu }
4990867ab667Sjeff.liu 
4991a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4992a8bfd4abSjeff.liu {
49930b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49950b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
49960b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
4997a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
4998a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
4999a8bfd4abSjeff.liu 	int ret;
5000a8bfd4abSjeff.liu 
5001a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5002a8bfd4abSjeff.liu 		return -EPERM;
5003a8bfd4abSjeff.liu 
5004a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5005a8bfd4abSjeff.liu 		return -EFAULT;
5006a8bfd4abSjeff.liu 
5007a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
50080b246afaSJeff Mahoney 		btrfs_err(fs_info,
50095d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5010a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5011a8bfd4abSjeff.liu 		return -EINVAL;
5012a8bfd4abSjeff.liu 	}
5013a8bfd4abSjeff.liu 
5014a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5015a8bfd4abSjeff.liu 	if (ret)
5016a8bfd4abSjeff.liu 		return ret;
5017a8bfd4abSjeff.liu 
5018a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5019a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5020a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5021a8bfd4abSjeff.liu 		goto out_unlock;
5022a8bfd4abSjeff.liu 	}
5023a8bfd4abSjeff.liu 
50240b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5025a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
50260b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
50273a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5028a8bfd4abSjeff.liu 
5029a8bfd4abSjeff.liu out_unlock:
5030a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5031a8bfd4abSjeff.liu 	return ret;
5032a8bfd4abSjeff.liu }
5033a8bfd4abSjeff.liu 
50342eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
50352eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
50362eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
50372eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
50382eaa055fSJeff Mahoney 
5039d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
50402eaa055fSJeff Mahoney {
50414d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
50422eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
50432eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
50442eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
50452eaa055fSJeff Mahoney 	};
50462eaa055fSJeff Mahoney 
50472eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
50482eaa055fSJeff Mahoney 		return -EFAULT;
50492eaa055fSJeff Mahoney 
50502eaa055fSJeff Mahoney 	return 0;
50512eaa055fSJeff Mahoney }
50522eaa055fSJeff Mahoney 
50532eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
50542eaa055fSJeff Mahoney {
50550b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50570b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
50582eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
50592eaa055fSJeff Mahoney 
50602eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
50612eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
50622eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
50632eaa055fSJeff Mahoney 
50642eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
50652eaa055fSJeff Mahoney 		return -EFAULT;
50662eaa055fSJeff Mahoney 
50672eaa055fSJeff Mahoney 	return 0;
50682eaa055fSJeff Mahoney }
50692eaa055fSJeff Mahoney 
50702ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
50713b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
50722eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
50732eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
50742eaa055fSJeff Mahoney {
50753b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
50763b02a68aSJeff Mahoney 	char *names;
50772eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
50782eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
50792eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
50802eaa055fSJeff Mahoney 
50812eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
50822eaa055fSJeff Mahoney 	if (unsupported) {
50833b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
50843b02a68aSJeff Mahoney 		if (names) {
50850b246afaSJeff Mahoney 			btrfs_warn(fs_info,
50863b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
50873b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
50883b02a68aSJeff Mahoney 			kfree(names);
50893b02a68aSJeff Mahoney 		} else
50900b246afaSJeff Mahoney 			btrfs_warn(fs_info,
50912eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
50922eaa055fSJeff Mahoney 				   type, unsupported);
50932eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
50942eaa055fSJeff Mahoney 	}
50952eaa055fSJeff Mahoney 
50962eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
50972eaa055fSJeff Mahoney 	if (disallowed) {
50983b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
50993b02a68aSJeff Mahoney 		if (names) {
51000b246afaSJeff Mahoney 			btrfs_warn(fs_info,
51013b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
51023b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
51033b02a68aSJeff Mahoney 			kfree(names);
51043b02a68aSJeff Mahoney 		} else
51050b246afaSJeff Mahoney 			btrfs_warn(fs_info,
51062eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
51072eaa055fSJeff Mahoney 				   type, disallowed);
51082eaa055fSJeff Mahoney 		return -EPERM;
51092eaa055fSJeff Mahoney 	}
51102eaa055fSJeff Mahoney 
51112eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
51122eaa055fSJeff Mahoney 	if (disallowed) {
51133b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
51143b02a68aSJeff Mahoney 		if (names) {
51150b246afaSJeff Mahoney 			btrfs_warn(fs_info,
51163b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
51173b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
51183b02a68aSJeff Mahoney 			kfree(names);
51193b02a68aSJeff Mahoney 		} else
51200b246afaSJeff Mahoney 			btrfs_warn(fs_info,
51212eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
51222eaa055fSJeff Mahoney 				   type, disallowed);
51232eaa055fSJeff Mahoney 		return -EPERM;
51242eaa055fSJeff Mahoney 	}
51252eaa055fSJeff Mahoney 
51262eaa055fSJeff Mahoney 	return 0;
51272eaa055fSJeff Mahoney }
51282eaa055fSJeff Mahoney 
51292ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
51302ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
51312eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
51322eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
51332eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
51342eaa055fSJeff Mahoney 
51352eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
51362eaa055fSJeff Mahoney {
51370b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51380b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51390b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
51400b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
51412eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
51422eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
51432eaa055fSJeff Mahoney 	u64 newflags;
51442eaa055fSJeff Mahoney 	int ret;
51452eaa055fSJeff Mahoney 
51462eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
51472eaa055fSJeff Mahoney 		return -EPERM;
51482eaa055fSJeff Mahoney 
51492eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
51502eaa055fSJeff Mahoney 		return -EFAULT;
51512eaa055fSJeff Mahoney 
51522eaa055fSJeff Mahoney 	/* Nothing to do */
51532eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
51542eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
51552eaa055fSJeff Mahoney 		return 0;
51562eaa055fSJeff Mahoney 
51572ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
51582eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
51592eaa055fSJeff Mahoney 	if (ret)
51602eaa055fSJeff Mahoney 		return ret;
51612eaa055fSJeff Mahoney 
51622ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
51632eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
51642eaa055fSJeff Mahoney 	if (ret)
51652eaa055fSJeff Mahoney 		return ret;
51662eaa055fSJeff Mahoney 
51672ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
51682eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
51692eaa055fSJeff Mahoney 	if (ret)
51702eaa055fSJeff Mahoney 		return ret;
51712eaa055fSJeff Mahoney 
51727ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
51737ab19625SDavid Sterba 	if (ret)
51747ab19625SDavid Sterba 		return ret;
51757ab19625SDavid Sterba 
51768051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
51777ab19625SDavid Sterba 	if (IS_ERR(trans)) {
51787ab19625SDavid Sterba 		ret = PTR_ERR(trans);
51797ab19625SDavid Sterba 		goto out_drop_write;
51807ab19625SDavid Sterba 	}
51812eaa055fSJeff Mahoney 
51820b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
51832eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
51842eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
51852eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
51862eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
51872eaa055fSJeff Mahoney 
51882eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
51892eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
51902eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
51912eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
51922eaa055fSJeff Mahoney 
51932eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
51942eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
51952eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
51962eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
51970b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
51982eaa055fSJeff Mahoney 
51993a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
52007ab19625SDavid Sterba out_drop_write:
52017ab19625SDavid Sterba 	mnt_drop_write_file(file);
52027ab19625SDavid Sterba 
52037ab19625SDavid Sterba 	return ret;
52042eaa055fSJeff Mahoney }
52052eaa055fSJeff Mahoney 
52062351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
52072351f431SJosef Bacik {
52082351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
52092351f431SJosef Bacik 	int ret;
52102351f431SJosef Bacik 
52112351f431SJosef Bacik 	if (compat) {
52122351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
52132351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
52142351f431SJosef Bacik 
52152351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
52162351f431SJosef Bacik 		if (ret)
52172351f431SJosef Bacik 			return -EFAULT;
52182351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
52192351f431SJosef Bacik 		if (!arg)
52202351f431SJosef Bacik 			return -ENOMEM;
52212351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
52222351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
52232351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
52242351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
52252351f431SJosef Bacik 		arg->flags = args32.flags;
52262351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
52272351f431SJosef Bacik 		       sizeof(args32.reserved));
52282351f431SJosef Bacik #else
52292351f431SJosef Bacik 		return -ENOTTY;
52302351f431SJosef Bacik #endif
52312351f431SJosef Bacik 	} else {
52322351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
52332351f431SJosef Bacik 		if (IS_ERR(arg))
52342351f431SJosef Bacik 			return PTR_ERR(arg);
52352351f431SJosef Bacik 	}
52362351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
52372351f431SJosef Bacik 	kfree(arg);
52382351f431SJosef Bacik 	return ret;
52392351f431SJosef Bacik }
52402351f431SJosef Bacik 
5241f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5242f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5243f46b5a66SChristoph Hellwig {
52440b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52450b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52460b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
52474bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5248f46b5a66SChristoph Hellwig 
5249f46b5a66SChristoph Hellwig 	switch (cmd) {
52506cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
52516cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
52526cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
52536cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
52546cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
52556cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5256f7039b1dSLi Dongyang 	case FITRIM:
5257f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5258f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5259fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5260fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5261fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
52623de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5263fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
52646f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
52656f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
526676dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
526776dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
52680caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
52690caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
52700caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
52710caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
52726ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
52736ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5274f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
52751e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
52761e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
52771e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5278f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5279198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5280f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
52812ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5282f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5283da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
52846b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
52856b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5286475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
52872ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5288475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
52892ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5290f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
52919ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5292ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5293ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5294cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5295cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5296ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5297ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5298d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5299d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5300d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5301d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5302d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
5303d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
53041406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
53052ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
53069b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
53079b199859SFilipe David Borba Manana 		int ret;
53089b199859SFilipe David Borba Manana 
530982b3e53bSNikolay Borisov 		ret = btrfs_start_delalloc_roots(fs_info, -1);
53109b199859SFilipe David Borba Manana 		if (ret)
53119b199859SFilipe David Borba Manana 			return ret;
53120b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
53132fad4e83SDavid Sterba 		/*
53142fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
531501327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
53162fad4e83SDavid Sterba 		 * processing uncleaned subvols.
53172fad4e83SDavid Sterba 		 */
53180b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
53199b199859SFilipe David Borba Manana 		return ret;
53209b199859SFilipe David Borba Manana 	}
532146204592SSage Weil 	case BTRFS_IOC_START_SYNC:
53229a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
532346204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
53242ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5325475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5326b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5327475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
53282ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5329475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
53302ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5331c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
53329ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5333837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
53342ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
533519a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
53362ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
53378ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
53388ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5339abccd00fSHugo Mills #ifdef CONFIG_64BIT
5340abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5341abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5342abccd00fSHugo Mills #endif
534331db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
53442351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
53452351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
53462351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
53472351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
53482351f431SJosef Bacik #endif
5349c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
53502ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
53515d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5352905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
53535d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5354905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
53555d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5356905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
53575d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5358905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
53592f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
53602f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
53612f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
53622f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
536357254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
536457254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
53653f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
53662ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5367867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5368867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5369a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5370a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
53712eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5372d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
53732eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
53742eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
53752eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
53762eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5377f46b5a66SChristoph Hellwig 	}
5378f46b5a66SChristoph Hellwig 
5379f46b5a66SChristoph Hellwig 	return -ENOTTY;
5380f46b5a66SChristoph Hellwig }
53814c63c245SLuke Dashjr 
53824c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
53834c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
53844c63c245SLuke Dashjr {
53852a362249SJeff Mahoney 	/*
53862a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
53872a362249SJeff Mahoney 	 * handling is necessary.
53882a362249SJeff Mahoney 	 */
53894c63c245SLuke Dashjr 	switch (cmd) {
53904c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
53914c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
53924c63c245SLuke Dashjr 		break;
53934c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
53944c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
53954c63c245SLuke Dashjr 		break;
53964c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
53974c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
53984c63c245SLuke Dashjr 		break;
53994c63c245SLuke Dashjr 	}
54004c63c245SLuke Dashjr 
54014c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
54024c63c245SLuke Dashjr }
54034c63c245SLuke Dashjr #endif
5404