xref: /openbmc/linux/fs/btrfs/ioctl.c (revision c065f5b1)
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  */
1396cbff00fSChristoph Hellwig void btrfs_update_iflags(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 
320306424ccSLi Zefan 	btrfs_update_iflags(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 
6436a03843dSMiao Xie 	ret = btrfs_start_delalloc_inodes(root, 0);
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 
14600b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
1461dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1462c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1463c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1464c9e9f97bSIlya Dryomov 		goto out;
1465c9e9f97bSIlya Dryomov 	}
14665516e595SMark Fasheh 
14675516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1468f46b5a66SChristoph Hellwig 
1469f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1470f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1471f46b5a66SChristoph Hellwig 	if (devstr) {
1472f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1473f46b5a66SChristoph Hellwig 		*devstr = '\0';
1474f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
147558dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
147658dfae63SZhangZhen 		if (ret)
147758dfae63SZhangZhen 			goto out_free;
1478dfd79829SMiao Xie 		if (!devid) {
1479dfd79829SMiao Xie 			ret = -EINVAL;
1480dfd79829SMiao Xie 			goto out_free;
1481dfd79829SMiao Xie 		}
14820b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1483f46b5a66SChristoph Hellwig 	}
1484dba60f3fSMiao Xie 
14850b246afaSJeff Mahoney 	device = btrfs_find_device(fs_info, devid, NULL, NULL);
1486f46b5a66SChristoph Hellwig 	if (!device) {
14870b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1488c1c9ff7cSGeert Uytterhoeven 			   devid);
1489dfd79829SMiao Xie 		ret = -ENODEV;
1490c9e9f97bSIlya Dryomov 		goto out_free;
1491f46b5a66SChristoph Hellwig 	}
1492dba60f3fSMiao Xie 
1493ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
14940b246afaSJeff Mahoney 		btrfs_info(fs_info,
1495efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1496c1c9ff7cSGeert Uytterhoeven 		       devid);
1497dfd79829SMiao Xie 		ret = -EPERM;
14984e42ae1bSLiu Bo 		goto out_free;
14994e42ae1bSLiu Bo 	}
15004e42ae1bSLiu Bo 
1501f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1502f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1503f46b5a66SChristoph Hellwig 	else {
1504f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1505f46b5a66SChristoph Hellwig 			mod = -1;
1506f46b5a66SChristoph Hellwig 			sizestr++;
1507f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1508f46b5a66SChristoph Hellwig 			mod = 1;
1509f46b5a66SChristoph Hellwig 			sizestr++;
1510f46b5a66SChristoph Hellwig 		}
15119a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
15129a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1513f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1514c9e9f97bSIlya Dryomov 			goto out_free;
1515f46b5a66SChristoph Hellwig 		}
1516f46b5a66SChristoph Hellwig 	}
1517f46b5a66SChristoph Hellwig 
1518401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1519dfd79829SMiao Xie 		ret = -EPERM;
152063a212abSStefan Behrens 		goto out_free;
152163a212abSStefan Behrens 	}
152263a212abSStefan Behrens 
15237cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1524f46b5a66SChristoph Hellwig 
1525f46b5a66SChristoph Hellwig 	if (mod < 0) {
1526f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1527f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1528c9e9f97bSIlya Dryomov 			goto out_free;
1529f46b5a66SChristoph Hellwig 		}
1530f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1531f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1532eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1533902c68a4SGui Hecheng 			ret = -ERANGE;
1534eb8052e0SWenliang Fan 			goto out_free;
1535eb8052e0SWenliang Fan 		}
1536f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1537f46b5a66SChristoph Hellwig 	}
1538f46b5a66SChristoph Hellwig 
1539ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1540f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1541c9e9f97bSIlya Dryomov 		goto out_free;
1542f46b5a66SChristoph Hellwig 	}
1543f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1544f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1545c9e9f97bSIlya Dryomov 		goto out_free;
1546f46b5a66SChristoph Hellwig 	}
1547f46b5a66SChristoph Hellwig 
154847f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1549f46b5a66SChristoph Hellwig 
15500b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1551c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1552f46b5a66SChristoph Hellwig 
1553f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1554a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
155598d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
155698d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1557c9e9f97bSIlya Dryomov 			goto out_free;
155898d5dc13STsutomu Itoh 		}
1559f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
15603a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1561ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1562f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
15630253f40eSjeff.liu 	} /* equal, nothing need to do */
1564f46b5a66SChristoph Hellwig 
1565c9e9f97bSIlya Dryomov out_free:
1566f46b5a66SChristoph Hellwig 	kfree(vol_args);
1567c9e9f97bSIlya Dryomov out:
15680b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
1569171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
157018f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1571f46b5a66SChristoph Hellwig 	return ret;
1572f46b5a66SChristoph Hellwig }
1573f46b5a66SChristoph Hellwig 
157472fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
157552f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
15766f72c7e2SArne Jansen 				u64 *transid, bool readonly,
15778696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1578f46b5a66SChristoph Hellwig {
1579f46b5a66SChristoph Hellwig 	int namelen;
15803de4586cSChris Mason 	int ret = 0;
1581f46b5a66SChristoph Hellwig 
1582325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1583325c50e3SJeff Mahoney 		return -ENOTDIR;
1584325c50e3SJeff Mahoney 
1585a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1586a874a63eSLiu Bo 	if (ret)
1587a874a63eSLiu Bo 		goto out;
1588a874a63eSLiu Bo 
158972fd032eSSage Weil 	namelen = strlen(name);
159072fd032eSSage Weil 	if (strchr(name, '/')) {
1591f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1592a874a63eSLiu Bo 		goto out_drop_write;
1593f46b5a66SChristoph Hellwig 	}
1594f46b5a66SChristoph Hellwig 
159516780cabSChris Mason 	if (name[0] == '.' &&
159616780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
159716780cabSChris Mason 		ret = -EEXIST;
1598a874a63eSLiu Bo 		goto out_drop_write;
159916780cabSChris Mason 	}
160016780cabSChris Mason 
16013de4586cSChris Mason 	if (subvol) {
160272fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
16036f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1604cb8e7090SChristoph Hellwig 	} else {
16052903ff01SAl Viro 		struct fd src = fdget(fd);
16063de4586cSChris Mason 		struct inode *src_inode;
16072903ff01SAl Viro 		if (!src.file) {
16083de4586cSChris Mason 			ret = -EINVAL;
1609a874a63eSLiu Bo 			goto out_drop_write;
16103de4586cSChris Mason 		}
16113de4586cSChris Mason 
1612496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1613496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1614c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1615efe120a0SFrank Holton 				   "Snapshot src from another FS");
161623ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1617d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1618d0242061SDavid Sterba 			/*
1619d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1620d0242061SDavid Sterba 			 * are limited to own subvolumes only
1621d0242061SDavid Sterba 			 */
1622d0242061SDavid Sterba 			ret = -EPERM;
1623ecd18815SAl Viro 		} else {
162472fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
162572fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
16266f72c7e2SArne Jansen 					     transid, readonly, inherit);
1627ecd18815SAl Viro 		}
16282903ff01SAl Viro 		fdput(src);
1629cb8e7090SChristoph Hellwig 	}
1630a874a63eSLiu Bo out_drop_write:
1631a874a63eSLiu Bo 	mnt_drop_write_file(file);
1632f46b5a66SChristoph Hellwig out:
163372fd032eSSage Weil 	return ret;
163472fd032eSSage Weil }
163572fd032eSSage Weil 
163672fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1637fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
163872fd032eSSage Weil {
1639fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
164072fd032eSSage Weil 	int ret;
164172fd032eSSage Weil 
1642325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1643325c50e3SJeff Mahoney 		return -ENOTDIR;
1644325c50e3SJeff Mahoney 
1645fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1646fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1647fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1648fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1649fa0d2b9bSLi Zefan 
1650fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1651b83cc969SLi Zefan 					      vol_args->fd, subvol,
16526f72c7e2SArne Jansen 					      NULL, false, NULL);
1653fa0d2b9bSLi Zefan 
1654fa0d2b9bSLi Zefan 	kfree(vol_args);
1655fa0d2b9bSLi Zefan 	return ret;
1656fa0d2b9bSLi Zefan }
1657fa0d2b9bSLi Zefan 
1658fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1659fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1660fa0d2b9bSLi Zefan {
1661fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1662fa0d2b9bSLi Zefan 	int ret;
1663fdfb1e4fSLi Zefan 	u64 transid = 0;
1664fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1665b83cc969SLi Zefan 	bool readonly = false;
16666f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
166772fd032eSSage Weil 
1668325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1669325c50e3SJeff Mahoney 		return -ENOTDIR;
1670325c50e3SJeff Mahoney 
1671fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1672fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1673fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1674fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1675fdfb1e4fSLi Zefan 
1676b83cc969SLi Zefan 	if (vol_args->flags &
16776f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
16786f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1679b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1680c47ca32dSDan Carpenter 		goto free_args;
1681fdfb1e4fSLi Zefan 	}
1682fdfb1e4fSLi Zefan 
1683fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1684fdfb1e4fSLi Zefan 		ptr = &transid;
1685b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1686b83cc969SLi Zefan 		readonly = true;
16876f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
168809cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
16896f72c7e2SArne Jansen 			ret = -EINVAL;
1690c47ca32dSDan Carpenter 			goto free_args;
16916f72c7e2SArne Jansen 		}
16926f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
16936f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
16946f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1695c47ca32dSDan Carpenter 			goto free_args;
16966f72c7e2SArne Jansen 		}
16976f72c7e2SArne Jansen 	}
169875eaa0e2SSage Weil 
1699fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
17006f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
17018696c533SMiao Xie 					      readonly, inherit);
1702c47ca32dSDan Carpenter 	if (ret)
1703c47ca32dSDan Carpenter 		goto free_inherit;
170475eaa0e2SSage Weil 
1705c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1706fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1707c47ca32dSDan Carpenter 					transid),
1708c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
170975eaa0e2SSage Weil 		ret = -EFAULT;
1710c47ca32dSDan Carpenter 
1711c47ca32dSDan Carpenter free_inherit:
17126f72c7e2SArne Jansen 	kfree(inherit);
1713c47ca32dSDan Carpenter free_args:
1714c47ca32dSDan Carpenter 	kfree(vol_args);
1715f46b5a66SChristoph Hellwig 	return ret;
1716f46b5a66SChristoph Hellwig }
1717f46b5a66SChristoph Hellwig 
17180caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
17190caa102dSLi Zefan 						void __user *arg)
17200caa102dSLi Zefan {
1721496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17230caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17240caa102dSLi Zefan 	int ret = 0;
17250caa102dSLi Zefan 	u64 flags = 0;
17260caa102dSLi Zefan 
17274a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
17280caa102dSLi Zefan 		return -EINVAL;
17290caa102dSLi Zefan 
17300b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
17310caa102dSLi Zefan 	if (btrfs_root_readonly(root))
17320caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
17330b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
17340caa102dSLi Zefan 
17350caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
17360caa102dSLi Zefan 		ret = -EFAULT;
17370caa102dSLi Zefan 
17380caa102dSLi Zefan 	return ret;
17390caa102dSLi Zefan }
17400caa102dSLi Zefan 
17410caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
17420caa102dSLi Zefan 					      void __user *arg)
17430caa102dSLi Zefan {
1744496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17450b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17460caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17470caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
17480caa102dSLi Zefan 	u64 root_flags;
17490caa102dSLi Zefan 	u64 flags;
17500caa102dSLi Zefan 	int ret = 0;
17510caa102dSLi Zefan 
1752bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1753bd60ea0fSDavid Sterba 		return -EPERM;
1754bd60ea0fSDavid Sterba 
1755b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1756b9ca0664SLiu Bo 	if (ret)
1757b9ca0664SLiu Bo 		goto out;
17580caa102dSLi Zefan 
17594a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1760b9ca0664SLiu Bo 		ret = -EINVAL;
1761b9ca0664SLiu Bo 		goto out_drop_write;
1762b9ca0664SLiu Bo 	}
17630caa102dSLi Zefan 
1764b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1765b9ca0664SLiu Bo 		ret = -EFAULT;
1766b9ca0664SLiu Bo 		goto out_drop_write;
1767b9ca0664SLiu Bo 	}
17680caa102dSLi Zefan 
1769b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1770b9ca0664SLiu Bo 		ret = -EINVAL;
1771b9ca0664SLiu Bo 		goto out_drop_write;
1772b9ca0664SLiu Bo 	}
17730caa102dSLi Zefan 
1774b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1775b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1776b9ca0664SLiu Bo 		goto out_drop_write;
1777b9ca0664SLiu Bo 	}
17780caa102dSLi Zefan 
17790b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
17800caa102dSLi Zefan 
17810caa102dSLi Zefan 	/* nothing to do */
17820caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1783b9ca0664SLiu Bo 		goto out_drop_sem;
17840caa102dSLi Zefan 
17850caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
17862c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
17870caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
17880caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
17892c686537SDavid Sterba 	} else {
17902c686537SDavid Sterba 		/*
17912c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
17922c686537SDavid Sterba 		 * send
17932c686537SDavid Sterba 		 */
17942c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
17952c686537SDavid Sterba 		if (root->send_in_progress == 0) {
17960caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
17970caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
17982c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
17992c686537SDavid Sterba 		} else {
18002c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18010b246afaSJeff Mahoney 			btrfs_warn(fs_info,
18022c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
18032c686537SDavid Sterba 				   root->root_key.objectid);
18042c686537SDavid Sterba 			ret = -EPERM;
18052c686537SDavid Sterba 			goto out_drop_sem;
18062c686537SDavid Sterba 		}
18072c686537SDavid Sterba 	}
18080caa102dSLi Zefan 
18090caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
18100caa102dSLi Zefan 	if (IS_ERR(trans)) {
18110caa102dSLi Zefan 		ret = PTR_ERR(trans);
18120caa102dSLi Zefan 		goto out_reset;
18130caa102dSLi Zefan 	}
18140caa102dSLi Zefan 
18150b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
18160caa102dSLi Zefan 				&root->root_key, &root->root_item);
18179417ebc8SNikolay Borisov 	if (ret < 0) {
18189417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
18199417ebc8SNikolay Borisov 		goto out_reset;
18209417ebc8SNikolay Borisov 	}
18210caa102dSLi Zefan 
18229417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
18239417ebc8SNikolay Borisov 
18240caa102dSLi Zefan out_reset:
18250caa102dSLi Zefan 	if (ret)
18260caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1827b9ca0664SLiu Bo out_drop_sem:
18280b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
1829b9ca0664SLiu Bo out_drop_write:
1830b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1831b9ca0664SLiu Bo out:
18320caa102dSLi Zefan 	return ret;
18330caa102dSLi Zefan }
18340caa102dSLi Zefan 
183576dda93cSYan, Zheng /*
183676dda93cSYan, Zheng  * helper to check if the subvolume references other subvolumes
183776dda93cSYan, Zheng  */
183876dda93cSYan, Zheng static noinline int may_destroy_subvol(struct btrfs_root *root)
183976dda93cSYan, Zheng {
18400b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
184176dda93cSYan, Zheng 	struct btrfs_path *path;
1842175a2b87SJosef Bacik 	struct btrfs_dir_item *di;
184376dda93cSYan, Zheng 	struct btrfs_key key;
1844175a2b87SJosef Bacik 	u64 dir_id;
184576dda93cSYan, Zheng 	int ret;
184676dda93cSYan, Zheng 
184776dda93cSYan, Zheng 	path = btrfs_alloc_path();
184876dda93cSYan, Zheng 	if (!path)
184976dda93cSYan, Zheng 		return -ENOMEM;
185076dda93cSYan, Zheng 
1851175a2b87SJosef Bacik 	/* Make sure this root isn't set as the default subvol */
18520b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
18530b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
1854175a2b87SJosef Bacik 				   dir_id, "default", 7, 0);
1855175a2b87SJosef Bacik 	if (di && !IS_ERR(di)) {
1856175a2b87SJosef Bacik 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1857175a2b87SJosef Bacik 		if (key.objectid == root->root_key.objectid) {
185872de6b53SGuangyu Sun 			ret = -EPERM;
18590b246afaSJeff Mahoney 			btrfs_err(fs_info,
18605d163e0eSJeff Mahoney 				  "deleting default subvolume %llu is not allowed",
18615d163e0eSJeff Mahoney 				  key.objectid);
1862175a2b87SJosef Bacik 			goto out;
1863175a2b87SJosef Bacik 		}
1864175a2b87SJosef Bacik 		btrfs_release_path(path);
1865175a2b87SJosef Bacik 	}
1866175a2b87SJosef Bacik 
186776dda93cSYan, Zheng 	key.objectid = root->root_key.objectid;
186876dda93cSYan, Zheng 	key.type = BTRFS_ROOT_REF_KEY;
186976dda93cSYan, Zheng 	key.offset = (u64)-1;
187076dda93cSYan, Zheng 
18710b246afaSJeff Mahoney 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
187276dda93cSYan, Zheng 	if (ret < 0)
187376dda93cSYan, Zheng 		goto out;
187476dda93cSYan, Zheng 	BUG_ON(ret == 0);
187576dda93cSYan, Zheng 
187676dda93cSYan, Zheng 	ret = 0;
187776dda93cSYan, Zheng 	if (path->slots[0] > 0) {
187876dda93cSYan, Zheng 		path->slots[0]--;
187976dda93cSYan, Zheng 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
188076dda93cSYan, Zheng 		if (key.objectid == root->root_key.objectid &&
188176dda93cSYan, Zheng 		    key.type == BTRFS_ROOT_REF_KEY)
188276dda93cSYan, Zheng 			ret = -ENOTEMPTY;
188376dda93cSYan, Zheng 	}
188476dda93cSYan, Zheng out:
188576dda93cSYan, Zheng 	btrfs_free_path(path);
188676dda93cSYan, Zheng 	return ret;
188776dda93cSYan, Zheng }
188876dda93cSYan, Zheng 
1889ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1890ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1891ac8e9819SChris Mason {
1892abc6e134SChris Mason 	struct btrfs_key test;
1893abc6e134SChris Mason 	int ret;
1894abc6e134SChris Mason 
1895abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1896abc6e134SChris Mason 	test.type = sk->min_type;
1897abc6e134SChris Mason 	test.offset = sk->min_offset;
1898abc6e134SChris Mason 
1899abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1900abc6e134SChris Mason 	if (ret < 0)
1901ac8e9819SChris Mason 		return 0;
1902abc6e134SChris Mason 
1903abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1904abc6e134SChris Mason 	test.type = sk->max_type;
1905abc6e134SChris Mason 	test.offset = sk->max_offset;
1906abc6e134SChris Mason 
1907abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1908abc6e134SChris Mason 	if (ret > 0)
1909ac8e9819SChris Mason 		return 0;
1910ac8e9819SChris Mason 	return 1;
1911ac8e9819SChris Mason }
1912ac8e9819SChris Mason 
1913df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
1914ac8e9819SChris Mason 			       struct btrfs_key *key,
1915ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
19169b6e817dSGerhard Heift 			       size_t *buf_size,
1917ba346b35SGerhard Heift 			       char __user *ubuf,
1918ac8e9819SChris Mason 			       unsigned long *sk_offset,
1919ac8e9819SChris Mason 			       int *num_found)
1920ac8e9819SChris Mason {
1921ac8e9819SChris Mason 	u64 found_transid;
1922ac8e9819SChris Mason 	struct extent_buffer *leaf;
1923ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
1924dd81d459SNaohiro Aota 	struct btrfs_key test;
1925ac8e9819SChris Mason 	unsigned long item_off;
1926ac8e9819SChris Mason 	unsigned long item_len;
1927ac8e9819SChris Mason 	int nritems;
1928ac8e9819SChris Mason 	int i;
1929ac8e9819SChris Mason 	int slot;
1930ac8e9819SChris Mason 	int ret = 0;
1931ac8e9819SChris Mason 
1932ac8e9819SChris Mason 	leaf = path->nodes[0];
1933ac8e9819SChris Mason 	slot = path->slots[0];
1934ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
1935ac8e9819SChris Mason 
1936ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
1937ac8e9819SChris Mason 		i = nritems;
1938ac8e9819SChris Mason 		goto advance_key;
1939ac8e9819SChris Mason 	}
1940ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
1941ac8e9819SChris Mason 
1942ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
1943ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
1944ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
1945ac8e9819SChris Mason 
194603b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
194703b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
194803b71c6cSGabriel de Perthuis 			continue;
194903b71c6cSGabriel de Perthuis 
19509b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
19518f5f6178SGerhard Heift 			if (*num_found) {
1952ac8e9819SChris Mason 				ret = 1;
19538f5f6178SGerhard Heift 				goto out;
19548f5f6178SGerhard Heift 			}
19558f5f6178SGerhard Heift 
19568f5f6178SGerhard Heift 			/*
19578f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
19588f5f6178SGerhard Heift 			 * handle -EOVERFLOW
19598f5f6178SGerhard Heift 			 */
19608f5f6178SGerhard Heift 
19619b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
1962ac8e9819SChris Mason 			item_len = 0;
19638f5f6178SGerhard Heift 			ret = -EOVERFLOW;
19648f5f6178SGerhard Heift 		}
1965ac8e9819SChris Mason 
19669b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
1967ac8e9819SChris Mason 			ret = 1;
196825c9bc2eSGerhard Heift 			goto out;
1969ac8e9819SChris Mason 		}
1970ac8e9819SChris Mason 
1971ac8e9819SChris Mason 		sh.objectid = key->objectid;
1972ac8e9819SChris Mason 		sh.offset = key->offset;
1973ac8e9819SChris Mason 		sh.type = key->type;
1974ac8e9819SChris Mason 		sh.len = item_len;
1975ac8e9819SChris Mason 		sh.transid = found_transid;
1976ac8e9819SChris Mason 
1977ac8e9819SChris Mason 		/* copy search result header */
1978ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
1979ba346b35SGerhard Heift 			ret = -EFAULT;
1980ba346b35SGerhard Heift 			goto out;
1981ba346b35SGerhard Heift 		}
1982ba346b35SGerhard Heift 
1983ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
1984ac8e9819SChris Mason 
1985ac8e9819SChris Mason 		if (item_len) {
1986ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
1987ac8e9819SChris Mason 			/* copy the item */
1988ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
1989ba346b35SGerhard Heift 						       item_off, item_len)) {
1990ba346b35SGerhard Heift 				ret = -EFAULT;
1991ba346b35SGerhard Heift 				goto out;
1992ba346b35SGerhard Heift 			}
1993ba346b35SGerhard Heift 
1994ac8e9819SChris Mason 			*sk_offset += item_len;
1995ac8e9819SChris Mason 		}
1996e2156867SHugo Mills 		(*num_found)++;
1997ac8e9819SChris Mason 
19988f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
19998f5f6178SGerhard Heift 			goto out;
20008f5f6178SGerhard Heift 
200125c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
200225c9bc2eSGerhard Heift 			ret = 1;
200325c9bc2eSGerhard Heift 			goto out;
200425c9bc2eSGerhard Heift 		}
2005ac8e9819SChris Mason 	}
2006ac8e9819SChris Mason advance_key:
2007ac8e9819SChris Mason 	ret = 0;
2008dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2009dd81d459SNaohiro Aota 	test.type = sk->max_type;
2010dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2011dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2012dd81d459SNaohiro Aota 		ret = 1;
2013dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2014abc6e134SChris Mason 		key->offset++;
2015dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2016abc6e134SChris Mason 		key->offset = 0;
2017abc6e134SChris Mason 		key->type++;
2018dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2019abc6e134SChris Mason 		key->offset = 0;
2020abc6e134SChris Mason 		key->type = 0;
2021abc6e134SChris Mason 		key->objectid++;
2022abc6e134SChris Mason 	} else
2023abc6e134SChris Mason 		ret = 1;
202425c9bc2eSGerhard Heift out:
2025ba346b35SGerhard Heift 	/*
2026ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2027ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2028ba346b35SGerhard Heift 	 *     * all items were found
2029ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2030ba346b35SGerhard Heift 	 *     leaf
2031ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2032ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2033ba346b35SGerhard Heift 	 */
2034ac8e9819SChris Mason 	return ret;
2035ac8e9819SChris Mason }
2036ac8e9819SChris Mason 
2037ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
203812544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
20399b6e817dSGerhard Heift 				 size_t *buf_size,
2040ba346b35SGerhard Heift 				 char __user *ubuf)
2041ac8e9819SChris Mason {
20420b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2043ac8e9819SChris Mason 	struct btrfs_root *root;
2044ac8e9819SChris Mason 	struct btrfs_key key;
2045ac8e9819SChris Mason 	struct btrfs_path *path;
2046ac8e9819SChris Mason 	int ret;
2047ac8e9819SChris Mason 	int num_found = 0;
2048ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2049ac8e9819SChris Mason 
20509b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
20519b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
205212544442SGerhard Heift 		return -EOVERFLOW;
20539b6e817dSGerhard Heift 	}
205412544442SGerhard Heift 
2055ac8e9819SChris Mason 	path = btrfs_alloc_path();
2056ac8e9819SChris Mason 	if (!path)
2057ac8e9819SChris Mason 		return -ENOMEM;
2058ac8e9819SChris Mason 
2059ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2060ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2061ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2062ac8e9819SChris Mason 	} else {
2063ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2064ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2065ac8e9819SChris Mason 		key.offset = (u64)-1;
2066ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2067ac8e9819SChris Mason 		if (IS_ERR(root)) {
2068ac8e9819SChris Mason 			btrfs_free_path(path);
2069ac8e9819SChris Mason 			return -ENOENT;
2070ac8e9819SChris Mason 		}
2071ac8e9819SChris Mason 	}
2072ac8e9819SChris Mason 
2073ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2074ac8e9819SChris Mason 	key.type = sk->min_type;
2075ac8e9819SChris Mason 	key.offset = sk->min_offset;
2076ac8e9819SChris Mason 
2077ac8e9819SChris Mason 	while (1) {
20786174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2079ac8e9819SChris Mason 		if (ret != 0) {
2080ac8e9819SChris Mason 			if (ret > 0)
2081ac8e9819SChris Mason 				ret = 0;
2082ac8e9819SChris Mason 			goto err;
2083ac8e9819SChris Mason 		}
2084df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2085ac8e9819SChris Mason 				 &sk_offset, &num_found);
2086b3b4aa74SDavid Sterba 		btrfs_release_path(path);
208725c9bc2eSGerhard Heift 		if (ret)
2088ac8e9819SChris Mason 			break;
2089ac8e9819SChris Mason 
2090ac8e9819SChris Mason 	}
20918f5f6178SGerhard Heift 	if (ret > 0)
2092ac8e9819SChris Mason 		ret = 0;
2093ac8e9819SChris Mason err:
2094ac8e9819SChris Mason 	sk->nr_items = num_found;
2095ac8e9819SChris Mason 	btrfs_free_path(path);
2096ac8e9819SChris Mason 	return ret;
2097ac8e9819SChris Mason }
2098ac8e9819SChris Mason 
2099ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2100ac8e9819SChris Mason 					   void __user *argp)
2101ac8e9819SChris Mason {
2102ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2103ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2104ac8e9819SChris Mason 	struct inode *inode;
2105ac8e9819SChris Mason 	int ret;
21069b6e817dSGerhard Heift 	size_t buf_size;
2107ac8e9819SChris Mason 
2108ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2109ac8e9819SChris Mason 		return -EPERM;
2110ac8e9819SChris Mason 
2111ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2112ac8e9819SChris Mason 
2113ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2114ba346b35SGerhard Heift 		return -EFAULT;
2115ba346b35SGerhard Heift 
2116ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2117ac8e9819SChris Mason 
2118496ad9aaSAl Viro 	inode = file_inode(file);
2119ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
21208f5f6178SGerhard Heift 
21218f5f6178SGerhard Heift 	/*
21228f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
21238f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
21248f5f6178SGerhard Heift 	 */
21258f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
21268f5f6178SGerhard Heift 		ret = 0;
21278f5f6178SGerhard Heift 
2128ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2129ac8e9819SChris Mason 		ret = -EFAULT;
2130ac8e9819SChris Mason 	return ret;
2131ac8e9819SChris Mason }
2132ac8e9819SChris Mason 
2133cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2134cc68a8a5SGerhard Heift 					       void __user *argp)
2135cc68a8a5SGerhard Heift {
2136cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2137cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2138cc68a8a5SGerhard Heift 	struct inode *inode;
2139cc68a8a5SGerhard Heift 	int ret;
2140cc68a8a5SGerhard Heift 	size_t buf_size;
2141ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2142cc68a8a5SGerhard Heift 
2143cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2144cc68a8a5SGerhard Heift 		return -EPERM;
2145cc68a8a5SGerhard Heift 
2146cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2147cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2148cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2149cc68a8a5SGerhard Heift 		return -EFAULT;
2150cc68a8a5SGerhard Heift 
2151cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2152cc68a8a5SGerhard Heift 
2153cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2154cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2155cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2156cc68a8a5SGerhard Heift 
2157cc68a8a5SGerhard Heift 	inode = file_inode(file);
2158cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2159718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2160cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2161cc68a8a5SGerhard Heift 		ret = -EFAULT;
2162cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2163cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2164cc68a8a5SGerhard Heift 		ret = -EFAULT;
2165cc68a8a5SGerhard Heift 
216676dda93cSYan, Zheng 	return ret;
216776dda93cSYan, Zheng }
216876dda93cSYan, Zheng 
216998d377a0STARUISI Hiroaki /*
2170ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2171ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
217298d377a0STARUISI Hiroaki  */
217398d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
217498d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
217598d377a0STARUISI Hiroaki {
217698d377a0STARUISI Hiroaki 	struct btrfs_root *root;
217798d377a0STARUISI Hiroaki 	struct btrfs_key key;
2178ac8e9819SChris Mason 	char *ptr;
217998d377a0STARUISI Hiroaki 	int ret = -1;
218098d377a0STARUISI Hiroaki 	int slot;
218198d377a0STARUISI Hiroaki 	int len;
218298d377a0STARUISI Hiroaki 	int total_len = 0;
218398d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
218498d377a0STARUISI Hiroaki 	struct extent_buffer *l;
218598d377a0STARUISI Hiroaki 	struct btrfs_path *path;
218698d377a0STARUISI Hiroaki 
218798d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
218898d377a0STARUISI Hiroaki 		name[0]='\0';
218998d377a0STARUISI Hiroaki 		return 0;
219098d377a0STARUISI Hiroaki 	}
219198d377a0STARUISI Hiroaki 
219298d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
219398d377a0STARUISI Hiroaki 	if (!path)
219498d377a0STARUISI Hiroaki 		return -ENOMEM;
219598d377a0STARUISI Hiroaki 
2196c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
219798d377a0STARUISI Hiroaki 
219898d377a0STARUISI Hiroaki 	key.objectid = tree_id;
219998d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
220098d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
220198d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
220298d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2203f14d104dSDavid Sterba 		btrfs_err(info, "could not find root %llu", tree_id);
22048ad6fcabSChris Mason 		ret = -ENOENT;
22058ad6fcabSChris Mason 		goto out;
220698d377a0STARUISI Hiroaki 	}
220798d377a0STARUISI Hiroaki 
220898d377a0STARUISI Hiroaki 	key.objectid = dirid;
220998d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
22108ad6fcabSChris Mason 	key.offset = (u64)-1;
221198d377a0STARUISI Hiroaki 
221298d377a0STARUISI Hiroaki 	while (1) {
221398d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
221498d377a0STARUISI Hiroaki 		if (ret < 0)
221598d377a0STARUISI Hiroaki 			goto out;
221618674c6cSFilipe David Borba Manana 		else if (ret > 0) {
221718674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
221818674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
221918674c6cSFilipe David Borba Manana 			if (ret < 0)
222018674c6cSFilipe David Borba Manana 				goto out;
222118674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2222ac8e9819SChris Mason 				ret = -ENOENT;
222398d377a0STARUISI Hiroaki 				goto out;
2224ac8e9819SChris Mason 			}
222518674c6cSFilipe David Borba Manana 		}
222618674c6cSFilipe David Borba Manana 
222718674c6cSFilipe David Borba Manana 		l = path->nodes[0];
222818674c6cSFilipe David Borba Manana 		slot = path->slots[0];
222918674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
223098d377a0STARUISI Hiroaki 
223198d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
223298d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
223398d377a0STARUISI Hiroaki 		ptr -= len + 1;
223498d377a0STARUISI Hiroaki 		total_len += len + 1;
2235a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2236a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
223798d377a0STARUISI Hiroaki 			goto out;
2238a696cf35SFilipe David Borba Manana 		}
223998d377a0STARUISI Hiroaki 
224098d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
224198d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
224298d377a0STARUISI Hiroaki 
224398d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
224498d377a0STARUISI Hiroaki 			break;
224598d377a0STARUISI Hiroaki 
2246b3b4aa74SDavid Sterba 		btrfs_release_path(path);
224798d377a0STARUISI Hiroaki 		key.objectid = key.offset;
22488ad6fcabSChris Mason 		key.offset = (u64)-1;
224998d377a0STARUISI Hiroaki 		dirid = key.objectid;
225098d377a0STARUISI Hiroaki 	}
225177906a50SLi Zefan 	memmove(name, ptr, total_len);
225298d377a0STARUISI Hiroaki 	name[total_len] = '\0';
225398d377a0STARUISI Hiroaki 	ret = 0;
225498d377a0STARUISI Hiroaki out:
225598d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2256ac8e9819SChris Mason 	return ret;
2257ac8e9819SChris Mason }
2258ac8e9819SChris Mason 
2259ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2260ac8e9819SChris Mason 					   void __user *argp)
2261ac8e9819SChris Mason {
2262ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2263ac8e9819SChris Mason 	 struct inode *inode;
226401b810b8SDavid Sterba 	int ret = 0;
2265ac8e9819SChris Mason 
22662354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
22672354d08fSJulia Lawall 	if (IS_ERR(args))
22682354d08fSJulia Lawall 		return PTR_ERR(args);
2269c2b96929SDan Carpenter 
2270496ad9aaSAl Viro 	inode = file_inode(file);
2271ac8e9819SChris Mason 
227201b810b8SDavid Sterba 	/*
227301b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
227401b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
227501b810b8SDavid Sterba 	 */
22761b53ac4dSChris Mason 	if (args->treeid == 0)
22771b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
22781b53ac4dSChris Mason 
227901b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
228001b810b8SDavid Sterba 		args->name[0] = 0;
228101b810b8SDavid Sterba 		goto out;
228201b810b8SDavid Sterba 	}
228301b810b8SDavid Sterba 
228401b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
228501b810b8SDavid Sterba 		ret = -EPERM;
228601b810b8SDavid Sterba 		goto out;
228701b810b8SDavid Sterba 	}
228801b810b8SDavid Sterba 
2289ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2290ac8e9819SChris Mason 					args->treeid, args->objectid,
2291ac8e9819SChris Mason 					args->name);
2292ac8e9819SChris Mason 
229301b810b8SDavid Sterba out:
2294ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2295ac8e9819SChris Mason 		ret = -EFAULT;
2296ac8e9819SChris Mason 
2297ac8e9819SChris Mason 	kfree(args);
229898d377a0STARUISI Hiroaki 	return ret;
229998d377a0STARUISI Hiroaki }
230098d377a0STARUISI Hiroaki 
230176dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
230276dda93cSYan, Zheng 					     void __user *arg)
230376dda93cSYan, Zheng {
230454563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
23050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
230676dda93cSYan, Zheng 	struct dentry *dentry;
23072b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
230876dda93cSYan, Zheng 	struct inode *inode;
230976dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
231076dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
231176dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
231276dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
2313c58aaad2SMiao Xie 	struct btrfs_block_rsv block_rsv;
2314521e0546SDavid Sterba 	u64 root_flags;
2315c58aaad2SMiao Xie 	u64 qgroup_reserved;
231676dda93cSYan, Zheng 	int namelen;
231776dda93cSYan, Zheng 	int ret;
231876dda93cSYan, Zheng 	int err = 0;
231976dda93cSYan, Zheng 
2320325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2321325c50e3SJeff Mahoney 		return -ENOTDIR;
2322325c50e3SJeff Mahoney 
232376dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
232476dda93cSYan, Zheng 	if (IS_ERR(vol_args))
232576dda93cSYan, Zheng 		return PTR_ERR(vol_args);
232676dda93cSYan, Zheng 
232776dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
232876dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
232976dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
233076dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
233176dda93cSYan, Zheng 		err = -EINVAL;
233276dda93cSYan, Zheng 		goto out;
233376dda93cSYan, Zheng 	}
233476dda93cSYan, Zheng 
2335a561be71SAl Viro 	err = mnt_want_write_file(file);
233676dda93cSYan, Zheng 	if (err)
233776dda93cSYan, Zheng 		goto out;
233876dda93cSYan, Zheng 
2339521e0546SDavid Sterba 
234000235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
234100235411SAl Viro 	if (err == -EINTR)
234200235411SAl Viro 		goto out_drop_write;
234376dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
234476dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
234576dda93cSYan, Zheng 		err = PTR_ERR(dentry);
234676dda93cSYan, Zheng 		goto out_unlock_dir;
234776dda93cSYan, Zheng 	}
234876dda93cSYan, Zheng 
23492b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
235076dda93cSYan, Zheng 		err = -ENOENT;
235176dda93cSYan, Zheng 		goto out_dput;
235276dda93cSYan, Zheng 	}
235376dda93cSYan, Zheng 
23542b0143b5SDavid Howells 	inode = d_inode(dentry);
23554260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
23564260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
23574260f7c7SSage Weil 		/*
23584260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
23594260f7c7SSage Weil 		 * option, when the user has write+exec access to the
23604260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
23614260f7c7SSage Weil 		 * allowed.
23624260f7c7SSage Weil 		 *
23634260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
23644260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
23654260f7c7SSage Weil 		 * otherwise be able to delete.
23664260f7c7SSage Weil 		 *
23674260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
23684260f7c7SSage Weil 		 * rmdir(2).
23694260f7c7SSage Weil 		 */
23704260f7c7SSage Weil 		err = -EPERM;
23710b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
23724260f7c7SSage Weil 			goto out_dput;
23734260f7c7SSage Weil 
23744260f7c7SSage Weil 		/*
23754260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
23764260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
23774260f7c7SSage Weil 		 * must be called on the dentry referencing the root
23784260f7c7SSage Weil 		 * of the subvol, not a random directory contained
23794260f7c7SSage Weil 		 * within it.
23804260f7c7SSage Weil 		 */
23814260f7c7SSage Weil 		err = -EINVAL;
23824260f7c7SSage Weil 		if (root == dest)
23834260f7c7SSage Weil 			goto out_dput;
23844260f7c7SSage Weil 
23854260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
23864260f7c7SSage Weil 		if (err)
23874260f7c7SSage Weil 			goto out_dput;
23885c39da5bSMiao Xie 	}
23894260f7c7SSage Weil 
23905c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
23914260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
23924260f7c7SSage Weil 	if (err)
23934260f7c7SSage Weil 		goto out_dput;
23944260f7c7SSage Weil 
23954a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
239676dda93cSYan, Zheng 		err = -EINVAL;
239776dda93cSYan, Zheng 		goto out_dput;
239876dda93cSYan, Zheng 	}
239976dda93cSYan, Zheng 
24005955102cSAl Viro 	inode_lock(inode);
2401521e0546SDavid Sterba 
2402521e0546SDavid Sterba 	/*
2403521e0546SDavid Sterba 	 * Don't allow to delete a subvolume with send in progress. This is
2404521e0546SDavid Sterba 	 * inside the i_mutex so the error handling that has to drop the bit
2405521e0546SDavid Sterba 	 * again is not run concurrently.
2406521e0546SDavid Sterba 	 */
2407521e0546SDavid Sterba 	spin_lock(&dest->root_item_lock);
2408c55bfa67SFilipe Manana 	root_flags = btrfs_root_flags(&dest->root_item);
2409c55bfa67SFilipe Manana 	if (dest->send_in_progress == 0) {
2410c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2411521e0546SDavid Sterba 				root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2412521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2413521e0546SDavid Sterba 	} else {
2414521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
24150b246afaSJeff Mahoney 		btrfs_warn(fs_info,
2416521e0546SDavid Sterba 			   "Attempt to delete subvolume %llu during send",
2417c55bfa67SFilipe Manana 			   dest->root_key.objectid);
2418521e0546SDavid Sterba 		err = -EPERM;
2419909e26dcSOmar Sandoval 		goto out_unlock_inode;
2420521e0546SDavid Sterba 	}
2421521e0546SDavid Sterba 
24220b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
242376dda93cSYan, Zheng 
242476dda93cSYan, Zheng 	err = may_destroy_subvol(dest);
242576dda93cSYan, Zheng 	if (err)
242676dda93cSYan, Zheng 		goto out_up_write;
242776dda93cSYan, Zheng 
2428c58aaad2SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2429c58aaad2SMiao Xie 	/*
2430c58aaad2SMiao Xie 	 * One for dir inode, two for dir entries, two for root
2431c58aaad2SMiao Xie 	 * ref/backref.
2432c58aaad2SMiao Xie 	 */
2433c58aaad2SMiao Xie 	err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2434ee3441b4SJeff Mahoney 					       5, &qgroup_reserved, true);
2435c58aaad2SMiao Xie 	if (err)
2436c58aaad2SMiao Xie 		goto out_up_write;
2437c58aaad2SMiao Xie 
2438a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 0);
2439a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
2440a22285a6SYan, Zheng 		err = PTR_ERR(trans);
2441c58aaad2SMiao Xie 		goto out_release;
2442a22285a6SYan, Zheng 	}
2443c58aaad2SMiao Xie 	trans->block_rsv = &block_rsv;
2444c58aaad2SMiao Xie 	trans->bytes_reserved = block_rsv.size;
2445a22285a6SYan, Zheng 
244643663557SNikolay Borisov 	btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
24472be63d5cSFilipe Manana 
244876dda93cSYan, Zheng 	ret = btrfs_unlink_subvol(trans, root, dir,
244976dda93cSYan, Zheng 				dest->root_key.objectid,
245076dda93cSYan, Zheng 				dentry->d_name.name,
245176dda93cSYan, Zheng 				dentry->d_name.len);
245279787eaaSJeff Mahoney 	if (ret) {
245379787eaaSJeff Mahoney 		err = ret;
245466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
245579787eaaSJeff Mahoney 		goto out_end_trans;
245679787eaaSJeff Mahoney 	}
245776dda93cSYan, Zheng 
245876dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, dest);
245976dda93cSYan, Zheng 
246076dda93cSYan, Zheng 	memset(&dest->root_item.drop_progress, 0,
246176dda93cSYan, Zheng 		sizeof(dest->root_item.drop_progress));
246276dda93cSYan, Zheng 	dest->root_item.drop_level = 0;
246376dda93cSYan, Zheng 	btrfs_set_root_refs(&dest->root_item, 0);
246476dda93cSYan, Zheng 
246527cdeb70SMiao Xie 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
246676dda93cSYan, Zheng 		ret = btrfs_insert_orphan_item(trans,
24670b246afaSJeff Mahoney 					fs_info->tree_root,
246876dda93cSYan, Zheng 					dest->root_key.objectid);
246979787eaaSJeff Mahoney 		if (ret) {
247066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
247179787eaaSJeff Mahoney 			err = ret;
247279787eaaSJeff Mahoney 			goto out_end_trans;
2473d68fc57bSYan, Zheng 		}
247479787eaaSJeff Mahoney 	}
2475dd5f9615SStefan Behrens 
24760b246afaSJeff Mahoney 	ret = btrfs_uuid_tree_rem(trans, fs_info, dest->root_item.uuid,
24776bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL,
2478dd5f9615SStefan Behrens 				  dest->root_key.objectid);
2479dd5f9615SStefan Behrens 	if (ret && ret != -ENOENT) {
248066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
2481dd5f9615SStefan Behrens 		err = ret;
2482dd5f9615SStefan Behrens 		goto out_end_trans;
2483dd5f9615SStefan Behrens 	}
2484dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
24850b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_rem(trans, fs_info,
2486dd5f9615SStefan Behrens 					  dest->root_item.received_uuid,
2487dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2488dd5f9615SStefan Behrens 					  dest->root_key.objectid);
2489dd5f9615SStefan Behrens 		if (ret && ret != -ENOENT) {
249066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
2491dd5f9615SStefan Behrens 			err = ret;
2492dd5f9615SStefan Behrens 			goto out_end_trans;
2493dd5f9615SStefan Behrens 		}
2494dd5f9615SStefan Behrens 	}
2495dd5f9615SStefan Behrens 
249679787eaaSJeff Mahoney out_end_trans:
2497c58aaad2SMiao Xie 	trans->block_rsv = NULL;
2498c58aaad2SMiao Xie 	trans->bytes_reserved = 0;
24993a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
250079787eaaSJeff Mahoney 	if (ret && !err)
250179787eaaSJeff Mahoney 		err = ret;
250276dda93cSYan, Zheng 	inode->i_flags |= S_DEAD;
2503c58aaad2SMiao Xie out_release:
25047775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
250576dda93cSYan, Zheng out_up_write:
25060b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
2507521e0546SDavid Sterba 	if (err) {
2508521e0546SDavid Sterba 		spin_lock(&dest->root_item_lock);
2509c55bfa67SFilipe Manana 		root_flags = btrfs_root_flags(&dest->root_item);
2510c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2511521e0546SDavid Sterba 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2512521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2513521e0546SDavid Sterba 	}
2514909e26dcSOmar Sandoval out_unlock_inode:
25155955102cSAl Viro 	inode_unlock(inode);
251676dda93cSYan, Zheng 	if (!err) {
251764ad6c48SOmar Sandoval 		d_invalidate(dentry);
251876dda93cSYan, Zheng 		btrfs_invalidate_inodes(dest);
251976dda93cSYan, Zheng 		d_delete(dentry);
252061155aa0SDavid Sterba 		ASSERT(dest->send_in_progress == 0);
2521fa6ac876SLiu Bo 
2522fa6ac876SLiu Bo 		/* the last ref */
252357cdc8dbSDavid Sterba 		if (dest->ino_cache_inode) {
252457cdc8dbSDavid Sterba 			iput(dest->ino_cache_inode);
252557cdc8dbSDavid Sterba 			dest->ino_cache_inode = NULL;
2526fa6ac876SLiu Bo 		}
252776dda93cSYan, Zheng 	}
252876dda93cSYan, Zheng out_dput:
252976dda93cSYan, Zheng 	dput(dentry);
253076dda93cSYan, Zheng out_unlock_dir:
25315955102cSAl Viro 	inode_unlock(dir);
253200235411SAl Viro out_drop_write:
25332a79f17eSAl Viro 	mnt_drop_write_file(file);
253476dda93cSYan, Zheng out:
253576dda93cSYan, Zheng 	kfree(vol_args);
253676dda93cSYan, Zheng 	return err;
253776dda93cSYan, Zheng }
253876dda93cSYan, Zheng 
25391e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2540f46b5a66SChristoph Hellwig {
2541496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2542f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
25431e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2544c146afadSYan Zheng 	int ret;
2545c146afadSYan Zheng 
254625122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
254725122d15SIlya Dryomov 	if (ret)
254825122d15SIlya Dryomov 		return ret;
2549b83cc969SLi Zefan 
255025122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
255125122d15SIlya Dryomov 		ret = -EROFS;
255225122d15SIlya Dryomov 		goto out;
25535ac00addSStefan Behrens 	}
2554f46b5a66SChristoph Hellwig 
2555f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2556f46b5a66SChristoph Hellwig 	case S_IFDIR:
2557e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2558e441d54dSChris Mason 			ret = -EPERM;
2559e441d54dSChris Mason 			goto out;
2560e441d54dSChris Mason 		}
2561de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
2562f46b5a66SChristoph Hellwig 		break;
2563f46b5a66SChristoph Hellwig 	case S_IFREG:
2564e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2565e441d54dSChris Mason 			ret = -EINVAL;
2566e441d54dSChris Mason 			goto out;
2567e441d54dSChris Mason 		}
25681e701a32SChris Mason 
25691e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
25701e701a32SChris Mason 		if (!range) {
25711e701a32SChris Mason 			ret = -ENOMEM;
25721e701a32SChris Mason 			goto out;
25731e701a32SChris Mason 		}
25741e701a32SChris Mason 
25751e701a32SChris Mason 		if (argp) {
25761e701a32SChris Mason 			if (copy_from_user(range, argp,
25771e701a32SChris Mason 					   sizeof(*range))) {
25781e701a32SChris Mason 				ret = -EFAULT;
25791e701a32SChris Mason 				kfree(range);
2580683be16eSDan Carpenter 				goto out;
25811e701a32SChris Mason 			}
25821e701a32SChris Mason 			/* compression requires us to start the IO */
25831e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
25841e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
25851e701a32SChris Mason 				range->extent_thresh = (u32)-1;
25861e701a32SChris Mason 			}
25871e701a32SChris Mason 		} else {
25881e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
25891e701a32SChris Mason 			range->len = (u64)-1;
25901e701a32SChris Mason 		}
2591496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
25927c829b72SAnand Jain 					range, BTRFS_OLDEST_GENERATION, 0);
25934cb5300bSChris Mason 		if (ret > 0)
25944cb5300bSChris Mason 			ret = 0;
25951e701a32SChris Mason 		kfree(range);
2596f46b5a66SChristoph Hellwig 		break;
25978929ecfaSYan, Zheng 	default:
25988929ecfaSYan, Zheng 		ret = -EINVAL;
2599f46b5a66SChristoph Hellwig 	}
2600e441d54dSChris Mason out:
260125122d15SIlya Dryomov 	mnt_drop_write_file(file);
2602e441d54dSChris Mason 	return ret;
2603f46b5a66SChristoph Hellwig }
2604f46b5a66SChristoph Hellwig 
26052ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2606f46b5a66SChristoph Hellwig {
2607f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2608f46b5a66SChristoph Hellwig 	int ret;
2609f46b5a66SChristoph Hellwig 
2610e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2611e441d54dSChris Mason 		return -EPERM;
2612e441d54dSChris Mason 
2613171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2614e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2615c9e9f97bSIlya Dryomov 
26160b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
2617dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2618c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2619c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2620c9e9f97bSIlya Dryomov 		goto out;
2621c9e9f97bSIlya Dryomov 	}
2622f46b5a66SChristoph Hellwig 
26235516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
26242ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
2625f46b5a66SChristoph Hellwig 
262643d20761SAnand Jain 	if (!ret)
26270b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
262843d20761SAnand Jain 
2629f46b5a66SChristoph Hellwig 	kfree(vol_args);
2630c9e9f97bSIlya Dryomov out:
26310b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
2632171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2633f46b5a66SChristoph Hellwig 	return ret;
2634f46b5a66SChristoph Hellwig }
2635f46b5a66SChristoph Hellwig 
26366b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
2637f46b5a66SChristoph Hellwig {
26380b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
26390b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
26406b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
2641f46b5a66SChristoph Hellwig 	int ret;
2642f46b5a66SChristoph Hellwig 
2643e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2644e441d54dSChris Mason 		return -EPERM;
2645e441d54dSChris Mason 
2646da24927bSMiao Xie 	ret = mnt_want_write_file(file);
2647da24927bSMiao Xie 	if (ret)
2648da24927bSMiao Xie 		return ret;
2649c146afadSYan Zheng 
2650dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2651c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2652c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2653c47ca32dSDan Carpenter 		goto err_drop;
2654c9e9f97bSIlya Dryomov 	}
2655f46b5a66SChristoph Hellwig 
26566b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
2657735654eaSDavid Sterba 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED)
2658735654eaSDavid Sterba 		return -EOPNOTSUPP;
2659f46b5a66SChristoph Hellwig 
2660171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2661183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2662183860f6SAnand Jain 		goto out;
2663183860f6SAnand Jain 	}
2664183860f6SAnand Jain 
2665735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
26662ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
26676b526ed7SAnand Jain 	} else {
26686b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
26692ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
26706b526ed7SAnand Jain 	}
2671171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2672183860f6SAnand Jain 
26736b526ed7SAnand Jain 	if (!ret) {
2674735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
26750b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
26766b526ed7SAnand Jain 					vol_args->devid);
26776b526ed7SAnand Jain 		else
26780b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
26796b526ed7SAnand Jain 					vol_args->name);
26806b526ed7SAnand Jain 	}
2681183860f6SAnand Jain out:
2682183860f6SAnand Jain 	kfree(vol_args);
2683c47ca32dSDan Carpenter err_drop:
26844ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
2685f46b5a66SChristoph Hellwig 	return ret;
2686f46b5a66SChristoph Hellwig }
2687f46b5a66SChristoph Hellwig 
2688f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2689f46b5a66SChristoph Hellwig {
26900b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
26910b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2692f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2693f46b5a66SChristoph Hellwig 	int ret;
2694f46b5a66SChristoph Hellwig 
2695f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
2696f46b5a66SChristoph Hellwig 		return -EPERM;
2697f46b5a66SChristoph Hellwig 
2698f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
2699f46b5a66SChristoph Hellwig 	if (ret)
2700f46b5a66SChristoph Hellwig 		return ret;
2701f46b5a66SChristoph Hellwig 
2702171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2703f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
270458d7bbf8SDavid Sterba 		goto out_drop_write;
270558d7bbf8SDavid Sterba 	}
270658d7bbf8SDavid Sterba 
270758d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
270858d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
270958d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
2710f46b5a66SChristoph Hellwig 		goto out;
2711f46b5a66SChristoph Hellwig 	}
2712f46b5a66SChristoph Hellwig 
271358d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
27142ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
2715f46b5a66SChristoph Hellwig 
2716f46b5a66SChristoph Hellwig 	if (!ret)
27170b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
2718f46b5a66SChristoph Hellwig 	kfree(vol_args);
271958d7bbf8SDavid Sterba out:
2720171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
272158d7bbf8SDavid Sterba out_drop_write:
2722f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
272358d7bbf8SDavid Sterba 
2724f46b5a66SChristoph Hellwig 	return ret;
2725f46b5a66SChristoph Hellwig }
2726f46b5a66SChristoph Hellwig 
27272ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
27282ff7e61eSJeff Mahoney 				void __user *arg)
2729475f6387SJan Schmidt {
2730027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
2731475f6387SJan Schmidt 	struct btrfs_device *device;
27320b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2733027ed2f0SLi Zefan 	int ret = 0;
2734475f6387SJan Schmidt 
2735027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2736027ed2f0SLi Zefan 	if (!fi_args)
2737027ed2f0SLi Zefan 		return -ENOMEM;
2738027ed2f0SLi Zefan 
2739d03262c7SDavid Sterba 	rcu_read_lock();
2740027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
2741475f6387SJan Schmidt 
2742d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2743027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
2744027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
2745475f6387SJan Schmidt 	}
2746d03262c7SDavid Sterba 	rcu_read_unlock();
2747475f6387SJan Schmidt 
2748d03262c7SDavid Sterba 	memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
2749bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
2750bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
2751bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
275280a773fbSDavid Sterba 
2753027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2754027ed2f0SLi Zefan 		ret = -EFAULT;
2755475f6387SJan Schmidt 
2756027ed2f0SLi Zefan 	kfree(fi_args);
2757027ed2f0SLi Zefan 	return ret;
2758475f6387SJan Schmidt }
2759475f6387SJan Schmidt 
27602ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
27612ff7e61eSJeff Mahoney 				 void __user *arg)
2762475f6387SJan Schmidt {
2763475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
2764475f6387SJan Schmidt 	struct btrfs_device *dev;
2765475f6387SJan Schmidt 	int ret = 0;
2766475f6387SJan Schmidt 	char *s_uuid = NULL;
2767475f6387SJan Schmidt 
2768475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
2769475f6387SJan Schmidt 	if (IS_ERR(di_args))
2770475f6387SJan Schmidt 		return PTR_ERR(di_args);
2771475f6387SJan Schmidt 
2772dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
2773475f6387SJan Schmidt 		s_uuid = di_args->uuid;
2774475f6387SJan Schmidt 
2775c5593ca3SDavid Sterba 	rcu_read_lock();
27760b246afaSJeff Mahoney 	dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
2777475f6387SJan Schmidt 
2778475f6387SJan Schmidt 	if (!dev) {
2779475f6387SJan Schmidt 		ret = -ENODEV;
2780475f6387SJan Schmidt 		goto out;
2781475f6387SJan Schmidt 	}
2782475f6387SJan Schmidt 
2783475f6387SJan Schmidt 	di_args->devid = dev->devid;
27847cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
27857cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2786475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2787a27202fbSJim Meyering 	if (dev->name) {
2788606686eeSJosef Bacik 		struct rcu_string *name;
2789606686eeSJosef Bacik 
2790606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
27916670d4c2SXiongfeng Wang 		strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
2792a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
2793a27202fbSJim Meyering 	} else {
279499ba55adSStefan Behrens 		di_args->path[0] = '\0';
2795a27202fbSJim Meyering 	}
2796475f6387SJan Schmidt 
2797475f6387SJan Schmidt out:
2798c5593ca3SDavid Sterba 	rcu_read_unlock();
2799475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2800475f6387SJan Schmidt 		ret = -EFAULT;
2801475f6387SJan Schmidt 
2802475f6387SJan Schmidt 	kfree(di_args);
2803475f6387SJan Schmidt 	return ret;
2804475f6387SJan Schmidt }
2805475f6387SJan Schmidt 
2806f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2807416161dbSMark Fasheh {
2808416161dbSMark Fasheh 	struct page *page;
2809416161dbSMark Fasheh 
2810416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
2811416161dbSMark Fasheh 	if (!page)
281231314002SFilipe Manana 		return ERR_PTR(-ENOMEM);
2813416161dbSMark Fasheh 
2814416161dbSMark Fasheh 	if (!PageUptodate(page)) {
281531314002SFilipe Manana 		int ret;
281631314002SFilipe Manana 
281731314002SFilipe Manana 		ret = btrfs_readpage(NULL, page);
281831314002SFilipe Manana 		if (ret)
281931314002SFilipe Manana 			return ERR_PTR(ret);
2820416161dbSMark Fasheh 		lock_page(page);
2821416161dbSMark Fasheh 		if (!PageUptodate(page)) {
2822416161dbSMark Fasheh 			unlock_page(page);
282309cbfeafSKirill A. Shutemov 			put_page(page);
282431314002SFilipe Manana 			return ERR_PTR(-EIO);
2825416161dbSMark Fasheh 		}
282631314002SFilipe Manana 		if (page->mapping != inode->i_mapping) {
2827416161dbSMark Fasheh 			unlock_page(page);
282809cbfeafSKirill A. Shutemov 			put_page(page);
282931314002SFilipe Manana 			return ERR_PTR(-EAGAIN);
2830416161dbSMark Fasheh 		}
2831416161dbSMark Fasheh 	}
2832416161dbSMark Fasheh 
2833416161dbSMark Fasheh 	return page;
2834416161dbSMark Fasheh }
2835416161dbSMark Fasheh 
2836f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
2837f4414602SMark Fasheh 			       int num_pages, u64 off)
2838f4414602SMark Fasheh {
2839f4414602SMark Fasheh 	int i;
284009cbfeafSKirill A. Shutemov 	pgoff_t index = off >> PAGE_SHIFT;
2841f4414602SMark Fasheh 
2842f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
284331314002SFilipe Manana again:
2844f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
284531314002SFilipe Manana 		if (IS_ERR(pages[i])) {
284631314002SFilipe Manana 			int err = PTR_ERR(pages[i]);
284731314002SFilipe Manana 
284831314002SFilipe Manana 			if (err == -EAGAIN)
284931314002SFilipe Manana 				goto again;
285031314002SFilipe Manana 			pages[i] = NULL;
285131314002SFilipe Manana 			return err;
285231314002SFilipe Manana 		}
2853f4414602SMark Fasheh 	}
2854f4414602SMark Fasheh 	return 0;
2855f4414602SMark Fasheh }
2856f4414602SMark Fasheh 
2857e0bd70c6SFilipe Manana static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2858e0bd70c6SFilipe Manana 			     bool retry_range_locking)
285977fe20dcSMark Fasheh {
2860e0bd70c6SFilipe Manana 	/*
2861e0bd70c6SFilipe Manana 	 * Do any pending delalloc/csum calculations on inode, one way or
2862e0bd70c6SFilipe Manana 	 * another, and lock file content.
2863e0bd70c6SFilipe Manana 	 * The locking order is:
2864e0bd70c6SFilipe Manana 	 *
2865e0bd70c6SFilipe Manana 	 *   1) pages
2866e0bd70c6SFilipe Manana 	 *   2) range in the inode's io tree
2867e0bd70c6SFilipe Manana 	 */
286877fe20dcSMark Fasheh 	while (1) {
286977fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
287077fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
287177fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
287277fe20dcSMark Fasheh 							    off + len - 1);
2873ff5df9b8SFilipe Manana 		if ((!ordered ||
2874ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
2875ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
287677fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2877ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2878ff5df9b8SFilipe Manana 			if (ordered)
2879ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
288077fe20dcSMark Fasheh 			break;
2881ff5df9b8SFilipe Manana 		}
288277fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
288377fe20dcSMark Fasheh 		if (ordered)
288477fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
2885e0bd70c6SFilipe Manana 		if (!retry_range_locking)
2886e0bd70c6SFilipe Manana 			return -EAGAIN;
288777fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
288877fe20dcSMark Fasheh 	}
2889e0bd70c6SFilipe Manana 	return 0;
289077fe20dcSMark Fasheh }
289177fe20dcSMark Fasheh 
2892f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2893416161dbSMark Fasheh {
28945955102cSAl Viro 	inode_unlock(inode1);
28955955102cSAl Viro 	inode_unlock(inode2);
2896416161dbSMark Fasheh }
2897416161dbSMark Fasheh 
2898f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2899f4414602SMark Fasheh {
2900f4414602SMark Fasheh 	if (inode1 < inode2)
2901f4414602SMark Fasheh 		swap(inode1, inode2);
2902f4414602SMark Fasheh 
29035955102cSAl Viro 	inode_lock_nested(inode1, I_MUTEX_PARENT);
29045955102cSAl Viro 	inode_lock_nested(inode2, I_MUTEX_CHILD);
2905f4414602SMark Fasheh }
2906f4414602SMark Fasheh 
2907f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2908f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
2909f4414602SMark Fasheh {
2910f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2911f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2912f4414602SMark Fasheh }
2913f4414602SMark Fasheh 
2914e0bd70c6SFilipe Manana static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2915e0bd70c6SFilipe Manana 				    struct inode *inode2, u64 loff2, u64 len,
2916e0bd70c6SFilipe Manana 				    bool retry_range_locking)
2917416161dbSMark Fasheh {
2918e0bd70c6SFilipe Manana 	int ret;
2919e0bd70c6SFilipe Manana 
2920416161dbSMark Fasheh 	if (inode1 < inode2) {
2921416161dbSMark Fasheh 		swap(inode1, inode2);
2922416161dbSMark Fasheh 		swap(loff1, loff2);
2923416161dbSMark Fasheh 	}
2924e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2925e0bd70c6SFilipe Manana 	if (ret)
2926e0bd70c6SFilipe Manana 		return ret;
2927e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2928e0bd70c6SFilipe Manana 	if (ret)
2929e0bd70c6SFilipe Manana 		unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2930e0bd70c6SFilipe Manana 			      loff1 + len - 1);
2931e0bd70c6SFilipe Manana 	return ret;
2932416161dbSMark Fasheh }
2933f4414602SMark Fasheh 
2934f4414602SMark Fasheh struct cmp_pages {
2935f4414602SMark Fasheh 	int		num_pages;
2936f4414602SMark Fasheh 	struct page	**src_pages;
2937f4414602SMark Fasheh 	struct page	**dst_pages;
2938f4414602SMark Fasheh };
2939f4414602SMark Fasheh 
2940f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2941f4414602SMark Fasheh {
2942f4414602SMark Fasheh 	int i;
2943f4414602SMark Fasheh 	struct page *pg;
2944f4414602SMark Fasheh 
2945f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
2946f4414602SMark Fasheh 		pg = cmp->src_pages[i];
2947e0bd70c6SFilipe Manana 		if (pg) {
2948e0bd70c6SFilipe Manana 			unlock_page(pg);
294909cbfeafSKirill A. Shutemov 			put_page(pg);
2950e0bd70c6SFilipe Manana 		}
2951f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
2952e0bd70c6SFilipe Manana 		if (pg) {
2953e0bd70c6SFilipe Manana 			unlock_page(pg);
295409cbfeafSKirill A. Shutemov 			put_page(pg);
2955f4414602SMark Fasheh 		}
2956e0bd70c6SFilipe Manana 	}
2957f4414602SMark Fasheh 	kfree(cmp->src_pages);
2958f4414602SMark Fasheh 	kfree(cmp->dst_pages);
2959f4414602SMark Fasheh }
2960f4414602SMark Fasheh 
2961f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2962f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
2963f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
2964f4414602SMark Fasheh {
2965f4414602SMark Fasheh 	int ret;
296609cbfeafSKirill A. Shutemov 	int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
2967f4414602SMark Fasheh 	struct page **src_pgarr, **dst_pgarr;
2968f4414602SMark Fasheh 
2969f4414602SMark Fasheh 	/*
2970f4414602SMark Fasheh 	 * We must gather up all the pages before we initiate our
2971f4414602SMark Fasheh 	 * extent locking. We use an array for the page pointers. Size
2972f4414602SMark Fasheh 	 * of the array is bounded by len, which is in turn bounded by
2973f4414602SMark Fasheh 	 * BTRFS_MAX_DEDUPE_LEN.
2974f4414602SMark Fasheh 	 */
297566722f7cSDavid Sterba 	src_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
297666722f7cSDavid Sterba 	dst_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
2977f4414602SMark Fasheh 	if (!src_pgarr || !dst_pgarr) {
2978f4414602SMark Fasheh 		kfree(src_pgarr);
2979f4414602SMark Fasheh 		kfree(dst_pgarr);
2980f4414602SMark Fasheh 		return -ENOMEM;
2981f4414602SMark Fasheh 	}
2982f4414602SMark Fasheh 	cmp->num_pages = num_pages;
2983f4414602SMark Fasheh 	cmp->src_pages = src_pgarr;
2984f4414602SMark Fasheh 	cmp->dst_pages = dst_pgarr;
2985f4414602SMark Fasheh 
2986b1517622SFilipe Manana 	/*
2987b1517622SFilipe Manana 	 * If deduping ranges in the same inode, locking rules make it mandatory
2988b1517622SFilipe Manana 	 * to always lock pages in ascending order to avoid deadlocks with
2989b1517622SFilipe Manana 	 * concurrent tasks (such as starting writeback/delalloc).
2990b1517622SFilipe Manana 	 */
2991b1517622SFilipe Manana 	if (src == dst && dst_loff < loff) {
2992b1517622SFilipe Manana 		swap(src_pgarr, dst_pgarr);
2993b1517622SFilipe Manana 		swap(loff, dst_loff);
2994b1517622SFilipe Manana 	}
2995b1517622SFilipe Manana 
2996b1517622SFilipe Manana 	ret = gather_extent_pages(src, src_pgarr, cmp->num_pages, loff);
2997f4414602SMark Fasheh 	if (ret)
2998f4414602SMark Fasheh 		goto out;
2999f4414602SMark Fasheh 
3000b1517622SFilipe Manana 	ret = gather_extent_pages(dst, dst_pgarr, cmp->num_pages, dst_loff);
3001f4414602SMark Fasheh 
3002f4414602SMark Fasheh out:
3003f4414602SMark Fasheh 	if (ret)
3004f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
300578ad4ce0SNaohiro Aota 	return ret;
3006416161dbSMark Fasheh }
3007416161dbSMark Fasheh 
30081a287cfeSDavid Sterba static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
3009416161dbSMark Fasheh {
3010416161dbSMark Fasheh 	int ret = 0;
3011f4414602SMark Fasheh 	int i;
3012416161dbSMark Fasheh 	struct page *src_page, *dst_page;
301309cbfeafSKirill A. Shutemov 	unsigned int cmp_len = PAGE_SIZE;
3014416161dbSMark Fasheh 	void *addr, *dst_addr;
3015416161dbSMark Fasheh 
3016f4414602SMark Fasheh 	i = 0;
3017416161dbSMark Fasheh 	while (len) {
301809cbfeafSKirill A. Shutemov 		if (len < PAGE_SIZE)
3019416161dbSMark Fasheh 			cmp_len = len;
3020416161dbSMark Fasheh 
3021f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
3022f4414602SMark Fasheh 
3023f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
3024f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
3025e0bd70c6SFilipe Manana 		ASSERT(PageLocked(src_page));
3026e0bd70c6SFilipe Manana 		ASSERT(PageLocked(dst_page));
3027f4414602SMark Fasheh 
3028416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
3029416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
3030416161dbSMark Fasheh 
3031416161dbSMark Fasheh 		flush_dcache_page(src_page);
3032416161dbSMark Fasheh 		flush_dcache_page(dst_page);
3033416161dbSMark Fasheh 
3034416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
30352b3909f8SDarrick J. Wong 			ret = -EBADE;
3036416161dbSMark Fasheh 
3037416161dbSMark Fasheh 		kunmap_atomic(addr);
3038416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
3039416161dbSMark Fasheh 
3040416161dbSMark Fasheh 		if (ret)
3041416161dbSMark Fasheh 			break;
3042416161dbSMark Fasheh 
3043416161dbSMark Fasheh 		len -= cmp_len;
3044f4414602SMark Fasheh 		i++;
3045416161dbSMark Fasheh 	}
3046416161dbSMark Fasheh 
3047416161dbSMark Fasheh 	return ret;
3048416161dbSMark Fasheh }
3049416161dbSMark Fasheh 
3050e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3051e1d227a4SMark Fasheh 				     u64 olen)
3052416161dbSMark Fasheh {
3053e1d227a4SMark Fasheh 	u64 len = *plen;
3054416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3055416161dbSMark Fasheh 
3056e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
3057416161dbSMark Fasheh 		return -EINVAL;
3058e1d227a4SMark Fasheh 
3059e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
3060e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
3061e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
3062e1d227a4SMark Fasheh 
3063416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
3064416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3065416161dbSMark Fasheh 		return -EINVAL;
3066416161dbSMark Fasheh 
3067416161dbSMark Fasheh 	return 0;
3068416161dbSMark Fasheh }
3069416161dbSMark Fasheh 
3070e1d227a4SMark Fasheh static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3071416161dbSMark Fasheh 			     struct inode *dst, u64 dst_loff)
3072416161dbSMark Fasheh {
3073416161dbSMark Fasheh 	int ret;
3074e1d227a4SMark Fasheh 	u64 len = olen;
3075f4414602SMark Fasheh 	struct cmp_pages cmp;
3076fc4badd9SOmar Sandoval 	bool same_inode = (src == dst);
30770efa9f48SMark Fasheh 	u64 same_lock_start = 0;
30780efa9f48SMark Fasheh 	u64 same_lock_len = 0;
3079416161dbSMark Fasheh 
3080113e8283SFilipe Manana 	if (len == 0)
3081113e8283SFilipe Manana 		return 0;
3082113e8283SFilipe Manana 
3083fc4badd9SOmar Sandoval 	if (same_inode)
30845955102cSAl Viro 		inode_lock(src);
3085fc4badd9SOmar Sandoval 	else
3086fc4badd9SOmar Sandoval 		btrfs_double_inode_lock(src, dst);
30870efa9f48SMark Fasheh 
30880efa9f48SMark Fasheh 	ret = extent_same_check_offsets(src, loff, &len, olen);
30890efa9f48SMark Fasheh 	if (ret)
30900efa9f48SMark Fasheh 		goto out_unlock;
3091fc4badd9SOmar Sandoval 
3092fc4badd9SOmar Sandoval 	ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3093f4dfe687SFilipe Manana 	if (ret)
3094f4dfe687SFilipe Manana 		goto out_unlock;
30950efa9f48SMark Fasheh 
3096fc4badd9SOmar Sandoval 	if (same_inode) {
30970efa9f48SMark Fasheh 		/*
30980efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
30990efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
31000efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
31010efa9f48SMark Fasheh 		 *
31020efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
31030efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
31040efa9f48SMark Fasheh 		 * reject the request.
31050efa9f48SMark Fasheh 		 *
31060efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
31070efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
31080efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
31090efa9f48SMark Fasheh 		 * i_size.
31100efa9f48SMark Fasheh 		 */
31110efa9f48SMark Fasheh 		if (len != olen) {
31120efa9f48SMark Fasheh 			ret = -EINVAL;
31130efa9f48SMark Fasheh 			goto out_unlock;
31140efa9f48SMark Fasheh 		}
31150efa9f48SMark Fasheh 
31160efa9f48SMark Fasheh 		/* Check for overlapping ranges */
31170efa9f48SMark Fasheh 		if (dst_loff + len > loff && dst_loff < loff + len) {
31180efa9f48SMark Fasheh 			ret = -EINVAL;
31190efa9f48SMark Fasheh 			goto out_unlock;
31200efa9f48SMark Fasheh 		}
31210efa9f48SMark Fasheh 
31220efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
31230efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
31240efa9f48SMark Fasheh 	}
3125416161dbSMark Fasheh 
3126416161dbSMark Fasheh 	/* don't make the dst file partly checksummed */
3127416161dbSMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3128416161dbSMark Fasheh 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3129416161dbSMark Fasheh 		ret = -EINVAL;
3130416161dbSMark Fasheh 		goto out_unlock;
3131416161dbSMark Fasheh 	}
3132416161dbSMark Fasheh 
3133e0bd70c6SFilipe Manana again:
3134f4414602SMark Fasheh 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3135f4414602SMark Fasheh 	if (ret)
3136f4414602SMark Fasheh 		goto out_unlock;
3137f4414602SMark Fasheh 
31380efa9f48SMark Fasheh 	if (same_inode)
3139e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, same_lock_start, same_lock_len,
3140e0bd70c6SFilipe Manana 					false);
31410efa9f48SMark Fasheh 	else
3142e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3143e0bd70c6SFilipe Manana 					       false);
3144e0bd70c6SFilipe Manana 	/*
3145e0bd70c6SFilipe Manana 	 * If one of the inodes has dirty pages in the respective range or
3146e0bd70c6SFilipe Manana 	 * ordered extents, we need to flush dellaloc and wait for all ordered
3147e0bd70c6SFilipe Manana 	 * extents in the range. We must unlock the pages and the ranges in the
3148e0bd70c6SFilipe Manana 	 * io trees to avoid deadlocks when flushing delalloc (requires locking
3149e0bd70c6SFilipe Manana 	 * pages) and when waiting for ordered extents to complete (they require
3150e0bd70c6SFilipe Manana 	 * range locking).
3151e0bd70c6SFilipe Manana 	 */
3152e0bd70c6SFilipe Manana 	if (ret == -EAGAIN) {
3153e0bd70c6SFilipe Manana 		/*
3154e0bd70c6SFilipe Manana 		 * Ranges in the io trees already unlocked. Now unlock all
3155e0bd70c6SFilipe Manana 		 * pages before waiting for all IO to complete.
3156e0bd70c6SFilipe Manana 		 */
3157e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
3158e0bd70c6SFilipe Manana 		if (same_inode) {
3159e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, same_lock_start,
3160e0bd70c6SFilipe Manana 						 same_lock_len);
3161e0bd70c6SFilipe Manana 		} else {
3162e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, loff, len);
3163e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(dst, dst_loff, len);
3164e0bd70c6SFilipe Manana 		}
3165e0bd70c6SFilipe Manana 		goto again;
3166e0bd70c6SFilipe Manana 	}
3167e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3168e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3169e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3170e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
3171e0bd70c6SFilipe Manana 		return ret;
3172e0bd70c6SFilipe Manana 	}
3173f4414602SMark Fasheh 
3174207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
31751a287cfeSDavid Sterba 	ret = btrfs_cmp_data(olen, &cmp);
3176416161dbSMark Fasheh 	if (ret == 0)
31771c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3178416161dbSMark Fasheh 
31790efa9f48SMark Fasheh 	if (same_inode)
31800efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
31810efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
31820efa9f48SMark Fasheh 	else
3183f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3184f4414602SMark Fasheh 
3185f4414602SMark Fasheh 	btrfs_cmp_data_free(&cmp);
3186416161dbSMark Fasheh out_unlock:
31870efa9f48SMark Fasheh 	if (same_inode)
31885955102cSAl Viro 		inode_unlock(src);
31890efa9f48SMark Fasheh 	else
3190f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3191416161dbSMark Fasheh 
3192416161dbSMark Fasheh 	return ret;
3193416161dbSMark Fasheh }
3194416161dbSMark Fasheh 
3195ee22184bSByongho Lee #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3196416161dbSMark Fasheh 
31972b3909f8SDarrick J. Wong ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
31982b3909f8SDarrick J. Wong 				struct file *dst_file, u64 dst_loff)
3199416161dbSMark Fasheh {
32002b3909f8SDarrick J. Wong 	struct inode *src = file_inode(src_file);
32012b3909f8SDarrick J. Wong 	struct inode *dst = file_inode(dst_file);
3202416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
32032b3909f8SDarrick J. Wong 	ssize_t res;
3204416161dbSMark Fasheh 
32052b3909f8SDarrick J. Wong 	if (olen > BTRFS_MAX_DEDUPE_LEN)
32062b3909f8SDarrick J. Wong 		olen = BTRFS_MAX_DEDUPE_LEN;
3207416161dbSMark Fasheh 
320809cbfeafSKirill A. Shutemov 	if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3209416161dbSMark Fasheh 		/*
3210416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3211416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3212416161dbSMark Fasheh 		 * this situation without an update.
3213416161dbSMark Fasheh 		 */
32142b3909f8SDarrick J. Wong 		return -EINVAL;
3215416161dbSMark Fasheh 	}
3216416161dbSMark Fasheh 
32172b3909f8SDarrick J. Wong 	res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
32182b3909f8SDarrick J. Wong 	if (res)
32192b3909f8SDarrick J. Wong 		return res;
32202b3909f8SDarrick J. Wong 	return olen;
3221416161dbSMark Fasheh }
3222416161dbSMark Fasheh 
3223f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3224f82a9901SFilipe Manana 				     struct inode *inode,
3225f82a9901SFilipe Manana 				     u64 endoff,
3226f82a9901SFilipe Manana 				     const u64 destoff,
32271c919a5eSMark Fasheh 				     const u64 olen,
32281c919a5eSMark Fasheh 				     int no_time_update)
3229f82a9901SFilipe Manana {
3230f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3231f82a9901SFilipe Manana 	int ret;
3232f82a9901SFilipe Manana 
3233f82a9901SFilipe Manana 	inode_inc_iversion(inode);
32341c919a5eSMark Fasheh 	if (!no_time_update)
3235c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3236f82a9901SFilipe Manana 	/*
3237f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3238f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3239f82a9901SFilipe Manana 	 */
3240f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3241f82a9901SFilipe Manana 		endoff = destoff + olen;
3242f82a9901SFilipe Manana 	if (endoff > inode->i_size)
32436ef06d27SNikolay Borisov 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3244f82a9901SFilipe Manana 
3245f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3246f82a9901SFilipe Manana 	if (ret) {
324766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32483a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3249f82a9901SFilipe Manana 		goto out;
3250f82a9901SFilipe Manana 	}
32513a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
3252f82a9901SFilipe Manana out:
3253f82a9901SFilipe Manana 	return ret;
3254f82a9901SFilipe Manana }
3255f82a9901SFilipe Manana 
3256a2f392e4SNikolay Borisov static void clone_update_extent_map(struct btrfs_inode *inode,
32577ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
32587ffbb598SFilipe Manana 				    const struct btrfs_path *path,
32597ffbb598SFilipe Manana 				    const u64 hole_offset,
32607ffbb598SFilipe Manana 				    const u64 hole_len)
32617ffbb598SFilipe Manana {
3262a2f392e4SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
32637ffbb598SFilipe Manana 	struct extent_map *em;
32647ffbb598SFilipe Manana 	int ret;
32657ffbb598SFilipe Manana 
32667ffbb598SFilipe Manana 	em = alloc_extent_map();
32677ffbb598SFilipe Manana 	if (!em) {
3268a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
32697ffbb598SFilipe Manana 		return;
32707ffbb598SFilipe Manana 	}
32717ffbb598SFilipe Manana 
327214f59796SFilipe Manana 	if (path) {
327314f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
327414f59796SFilipe Manana 
327514f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
327614f59796SFilipe Manana 				    struct btrfs_file_extent_item);
3277a2f392e4SNikolay Borisov 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
32787ffbb598SFilipe Manana 		em->generation = -1;
32797ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
32807ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
32817ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3282a2f392e4SNikolay Borisov 					&inode->runtime_flags);
32837ffbb598SFilipe Manana 	} else {
32847ffbb598SFilipe Manana 		em->start = hole_offset;
32857ffbb598SFilipe Manana 		em->len = hole_len;
32867ffbb598SFilipe Manana 		em->ram_bytes = em->len;
32877ffbb598SFilipe Manana 		em->orig_start = hole_offset;
32887ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
32897ffbb598SFilipe Manana 		em->block_len = 0;
32907ffbb598SFilipe Manana 		em->orig_block_len = 0;
32917ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
32927ffbb598SFilipe Manana 		em->generation = trans->transid;
32937ffbb598SFilipe Manana 	}
32947ffbb598SFilipe Manana 
32957ffbb598SFilipe Manana 	while (1) {
32967ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
32977ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
32987ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
32997ffbb598SFilipe Manana 		if (ret != -EEXIST) {
33007ffbb598SFilipe Manana 			free_extent_map(em);
33017ffbb598SFilipe Manana 			break;
33027ffbb598SFilipe Manana 		}
3303a2f392e4SNikolay Borisov 		btrfs_drop_extent_cache(inode, em->start,
33047ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
33057ffbb598SFilipe Manana 	}
33067ffbb598SFilipe Manana 
3307ee39b432SDavid Sterba 	if (ret)
3308a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
33097ffbb598SFilipe Manana }
33107ffbb598SFilipe Manana 
33118039d87dSFilipe Manana /*
33128039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
33138039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
33148039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
33158039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
33168039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
33178039d87dSFilipe Manana  *
33188039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
33198039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
33208039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
33218039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
33228039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
33238039d87dSFilipe Manana  * i_mutex, which we are holding here).
33248039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
33258039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
33268039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
33278039d87dSFilipe Manana  *
33288039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
33298039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
33308039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
33318039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
33328039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
33338039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
33348039d87dSFilipe Manana  * the former.
33358039d87dSFilipe Manana  */
33364a0ab9d7SDavid Sterba static int clone_copy_inline_extent(struct inode *dst,
33378039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
33388039d87dSFilipe Manana 				    struct btrfs_path *path,
33398039d87dSFilipe Manana 				    struct btrfs_key *new_key,
33408039d87dSFilipe Manana 				    const u64 drop_start,
33418039d87dSFilipe Manana 				    const u64 datal,
33428039d87dSFilipe Manana 				    const u64 skip,
33438039d87dSFilipe Manana 				    const u64 size,
33448039d87dSFilipe Manana 				    char *inline_data)
33458039d87dSFilipe Manana {
33460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
33478039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
33488039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
33490b246afaSJeff Mahoney 				      fs_info->sectorsize);
33508039d87dSFilipe Manana 	int ret;
33518039d87dSFilipe Manana 	struct btrfs_key key;
33528039d87dSFilipe Manana 
33538039d87dSFilipe Manana 	if (new_key->offset > 0)
33548039d87dSFilipe Manana 		return -EOPNOTSUPP;
33558039d87dSFilipe Manana 
33564a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(dst));
33578039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
33588039d87dSFilipe Manana 	key.offset = 0;
33598039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
33608039d87dSFilipe Manana 	if (ret < 0) {
33618039d87dSFilipe Manana 		return ret;
33628039d87dSFilipe Manana 	} else if (ret > 0) {
33638039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
33648039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
33658039d87dSFilipe Manana 			if (ret < 0)
33668039d87dSFilipe Manana 				return ret;
33678039d87dSFilipe Manana 			else if (ret > 0)
33688039d87dSFilipe Manana 				goto copy_inline_extent;
33698039d87dSFilipe Manana 		}
33708039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
33714a0cc7caSNikolay Borisov 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
33728039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
33738039d87dSFilipe Manana 			ASSERT(key.offset > 0);
33748039d87dSFilipe Manana 			return -EOPNOTSUPP;
33758039d87dSFilipe Manana 		}
33768039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
33778039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
33788039d87dSFilipe Manana 		u64 ext_len;
33798039d87dSFilipe Manana 
33808039d87dSFilipe Manana 		/*
33818039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
33828039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
33838039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
33848039d87dSFilipe Manana 		 */
33858039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
33868039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
33878039d87dSFilipe Manana 		/*
33888039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
33898039d87dSFilipe Manana 		 * following it.
33908039d87dSFilipe Manana 		 */
33918039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
33928039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
33938039d87dSFilipe Manana 			goto copy_inline_extent;
33948039d87dSFilipe Manana 
33958039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
33968039d87dSFilipe Manana 		if (ext_len > aligned_end)
33978039d87dSFilipe Manana 			return -EOPNOTSUPP;
33988039d87dSFilipe Manana 
33998039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
34008039d87dSFilipe Manana 		if (ret < 0) {
34018039d87dSFilipe Manana 			return ret;
34028039d87dSFilipe Manana 		} else if (ret == 0) {
34038039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
34048039d87dSFilipe Manana 					      path->slots[0]);
34054a0cc7caSNikolay Borisov 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
34068039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
34078039d87dSFilipe Manana 				return -EOPNOTSUPP;
34088039d87dSFilipe Manana 		}
34098039d87dSFilipe Manana 	}
34108039d87dSFilipe Manana 
34118039d87dSFilipe Manana copy_inline_extent:
34128039d87dSFilipe Manana 	/*
34138039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
34148039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
34158039d87dSFilipe Manana 	 */
34168039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
34178039d87dSFilipe Manana 		/*
34188039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
34198039d87dSFilipe Manana 		 * This would require copying the data from the source inline
34208039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
34218039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
34228039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
34238039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
34248039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
34258039d87dSFilipe Manana 		 * inline extent).
34268039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
34278039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
34288039d87dSFilipe Manana 		 */
34298039d87dSFilipe Manana 		return -EOPNOTSUPP;
34308039d87dSFilipe Manana 	}
34318039d87dSFilipe Manana 
34328039d87dSFilipe Manana 	btrfs_release_path(path);
34338039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
34348039d87dSFilipe Manana 	if (ret)
34358039d87dSFilipe Manana 		return ret;
34368039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
34378039d87dSFilipe Manana 	if (ret)
34388039d87dSFilipe Manana 		return ret;
34398039d87dSFilipe Manana 
34408039d87dSFilipe Manana 	if (skip) {
34418039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
34428039d87dSFilipe Manana 
34438039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
34448039d87dSFilipe Manana 	}
34458039d87dSFilipe Manana 
34468039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
34478039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
34488039d87dSFilipe Manana 						  path->slots[0]),
34498039d87dSFilipe Manana 			    size);
34508039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
34518039d87dSFilipe Manana 
34528039d87dSFilipe Manana 	return 0;
34538039d87dSFilipe Manana }
34548039d87dSFilipe Manana 
345532b7c687SMark Fasheh /**
345632b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
345732b7c687SMark Fasheh  *
345832b7c687SMark Fasheh  * @src: Inode to clone from
345932b7c687SMark Fasheh  * @inode: Inode to clone to
346032b7c687SMark Fasheh  * @off: Offset within source to start clone from
346132b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
34621c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
346332b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
34641c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
346532b7c687SMark Fasheh  */
346632b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3467f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
34681c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3469f46b5a66SChristoph Hellwig {
34700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3471f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
347232b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3473f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
347432b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
347532b7c687SMark Fasheh 	char *buf = NULL;
3476ae01a0abSYan Zheng 	struct btrfs_key key;
3477f46b5a66SChristoph Hellwig 	u32 nritems;
3478f46b5a66SChristoph Hellwig 	int slot;
3479ae01a0abSYan Zheng 	int ret;
3480f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3481f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3482ae01a0abSYan Zheng 
3483ae01a0abSYan Zheng 	ret = -ENOMEM;
3484752ade68SMichal Hocko 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3485ae01a0abSYan Zheng 	if (!buf)
348632b7c687SMark Fasheh 		return ret;
3487ae01a0abSYan Zheng 
3488ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3489ae01a0abSYan Zheng 	if (!path) {
349015351955SDavid Sterba 		kvfree(buf);
349132b7c687SMark Fasheh 		return ret;
3492ae01a0abSYan Zheng 	}
349332b7c687SMark Fasheh 
3494e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3495c5c9cd4dSSage Weil 	/* clone data */
34964a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(src));
3497ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
34982c463823SFilipe Manana 	key.offset = off;
3499f46b5a66SChristoph Hellwig 
3500f46b5a66SChristoph Hellwig 	while (1) {
3501de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3502df858e76SFilipe Manana 
3503f46b5a66SChristoph Hellwig 		/*
3504f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3505f46b5a66SChristoph Hellwig 		 * tree.
3506f46b5a66SChristoph Hellwig 		 */
3507e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3508362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3509362a20c5SDavid Sterba 				0, 0);
3510f46b5a66SChristoph Hellwig 		if (ret < 0)
3511f46b5a66SChristoph Hellwig 			goto out;
35122c463823SFilipe Manana 		/*
35132c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
35142c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
35152c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
35162c463823SFilipe Manana 		 */
35172c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
35182c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
35192c463823SFilipe Manana 					      path->slots[0] - 1);
35202c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
35212c463823SFilipe Manana 				path->slots[0]--;
35222c463823SFilipe Manana 		}
3523f46b5a66SChristoph Hellwig 
3524ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3525e4355f34SFilipe David Borba Manana process_slot:
3526ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3527362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3528f46b5a66SChristoph Hellwig 			if (ret < 0)
3529f46b5a66SChristoph Hellwig 				goto out;
3530f46b5a66SChristoph Hellwig 			if (ret > 0)
3531f46b5a66SChristoph Hellwig 				break;
3532ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3533f46b5a66SChristoph Hellwig 		}
3534f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3535f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3536f46b5a66SChristoph Hellwig 
3537ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3538962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
35394a0cc7caSNikolay Borisov 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3540f46b5a66SChristoph Hellwig 			break;
3541f46b5a66SChristoph Hellwig 
3542962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3543c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3544c5c9cd4dSSage Weil 			int type;
354531840ae1SZheng Yan 			u32 size;
354631840ae1SZheng Yan 			struct btrfs_key new_key;
3547c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3548c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3549c5c9cd4dSSage Weil 			u8 comp;
3550f82a9901SFilipe Manana 			u64 drop_start;
355131840ae1SZheng Yan 
3552c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3553c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3554c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3555c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3556c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3557c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3558d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3559d397712bSChris Mason 								      extent);
3560d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3561d397712bSChris Mason 								 extent);
3562c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3563d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3564d397712bSChris Mason 								    extent);
3565c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3566c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3567c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3568c5c9cd4dSSage Weil 								    extent);
3569c5c9cd4dSSage Weil 			}
357031840ae1SZheng Yan 
35712c463823SFilipe Manana 			/*
35722c463823SFilipe Manana 			 * The first search might have left us at an extent
35732c463823SFilipe Manana 			 * item that ends before our target range's start, can
35742c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
35752c463823SFilipe Manana 			 */
35762c463823SFilipe Manana 			if (key.offset + datal <= off) {
3577e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3578e4355f34SFilipe David Borba Manana 				goto process_slot;
35792c463823SFilipe Manana 			} else if (key.offset >= off + len) {
35802c463823SFilipe Manana 				break;
3581e4355f34SFilipe David Borba Manana 			}
3582df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3583e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3584e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3585e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3586e4355f34SFilipe David Borba Manana 					   size);
3587e4355f34SFilipe David Borba Manana 
3588e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3589e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3590c5c9cd4dSSage Weil 
359131840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
35924a0cc7caSNikolay Borisov 			new_key.objectid = btrfs_ino(BTRFS_I(inode));
35934d728ec7SLi Zefan 			if (off <= key.offset)
3594c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
35954d728ec7SLi Zefan 			else
35964d728ec7SLi Zefan 				new_key.offset = destoff;
3597c5c9cd4dSSage Weil 
3598b6f3409bSSage Weil 			/*
3599f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3600f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3601f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3602f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3603f82a9901SFilipe Manana 			 * partially overlaps it).
3604f82a9901SFilipe Manana 			 */
3605f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3606f82a9901SFilipe Manana 				drop_start = last_dest_end;
3607f82a9901SFilipe Manana 			else
3608f82a9901SFilipe Manana 				drop_start = new_key.offset;
3609f82a9901SFilipe Manana 
3610f82a9901SFilipe Manana 			/*
3611b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3612b6f3409bSSage Weil 			 * 1 - add new extent
3613b6f3409bSSage Weil 			 * 1 - inode update
3614b6f3409bSSage Weil 			 */
3615b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3616a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3617a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3618a22285a6SYan, Zheng 				goto out;
3619a22285a6SYan, Zheng 			}
3620a22285a6SYan, Zheng 
3621c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3622c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3623d72c0842SLi Zefan 				/*
3624d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3625d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3626d72c0842SLi Zefan 				 */
3627d72c0842SLi Zefan 
362893915584SAntonio Ospite 				/* subtract range b */
3629d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3630d72c0842SLi Zefan 					datal = off + len - key.offset;
3631d72c0842SLi Zefan 
363293915584SAntonio Ospite 				/* subtract range a */
3633a22285a6SYan, Zheng 				if (off > key.offset) {
3634a22285a6SYan, Zheng 					datao += off - key.offset;
3635a22285a6SYan, Zheng 					datal -= off - key.offset;
3636a22285a6SYan, Zheng 				}
3637a22285a6SYan, Zheng 
36385dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3639f82a9901SFilipe Manana 							 drop_start,
3640a22285a6SYan, Zheng 							 new_key.offset + datal,
36412671485dSJosef Bacik 							 1);
364279787eaaSJeff Mahoney 				if (ret) {
36433f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
364400fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
364566642832SJeff Mahoney 									ret);
36463a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
364779787eaaSJeff Mahoney 					goto out;
364879787eaaSJeff Mahoney 				}
3649a22285a6SYan, Zheng 
365031840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
365131840ae1SZheng Yan 							      &new_key, size);
365279787eaaSJeff Mahoney 				if (ret) {
365366642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
36543a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
365579787eaaSJeff Mahoney 					goto out;
365679787eaaSJeff Mahoney 				}
365731840ae1SZheng Yan 
365831840ae1SZheng Yan 				leaf = path->nodes[0];
365931840ae1SZheng Yan 				slot = path->slots[0];
366031840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
366131840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
366231840ae1SZheng Yan 					    size);
3663ae01a0abSYan Zheng 
3664f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3665f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3666c5c9cd4dSSage Weil 
3667c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3668c5c9cd4dSSage Weil 				if (!disko)
3669c5c9cd4dSSage Weil 					datao = 0;
3670c5c9cd4dSSage Weil 
3671c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3672c5c9cd4dSSage Weil 							     datao);
3673c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3674c5c9cd4dSSage Weil 								datal);
3675fcebe456SJosef Bacik 
3676c5c9cd4dSSage Weil 				if (disko) {
3677c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
36782ff7e61eSJeff Mahoney 					ret = btrfs_inc_extent_ref(trans,
367984f7d8e6SJosef Bacik 							root,
36805d4f98a2SYan Zheng 							disko, diskl, 0,
3681f46b5a66SChristoph Hellwig 							root->root_key.objectid,
36824a0cc7caSNikolay Borisov 							btrfs_ino(BTRFS_I(inode)),
3683b06c4bf5SFilipe Manana 							new_key.offset - datao);
368479787eaaSJeff Mahoney 					if (ret) {
368579787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
368679787eaaSJeff Mahoney 									ret);
36873a45bb20SJeff Mahoney 						btrfs_end_transaction(trans);
368879787eaaSJeff Mahoney 						goto out;
368979787eaaSJeff Mahoney 
369079787eaaSJeff Mahoney 					}
3691f46b5a66SChristoph Hellwig 				}
3692c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3693c5c9cd4dSSage Weil 				u64 skip = 0;
3694c5c9cd4dSSage Weil 				u64 trim = 0;
3695ed958762SFilipe Manana 
3696c5c9cd4dSSage Weil 				if (off > key.offset) {
3697c5c9cd4dSSage Weil 					skip = off - key.offset;
3698c5c9cd4dSSage Weil 					new_key.offset += skip;
369931840ae1SZheng Yan 				}
3700d397712bSChris Mason 
3701c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3702c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3703d397712bSChris Mason 
3704c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3705c5c9cd4dSSage Weil 					ret = -EINVAL;
37063a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
3707c5c9cd4dSSage Weil 					goto out;
370831840ae1SZheng Yan 				}
3709c5c9cd4dSSage Weil 				size -= skip + trim;
3710c5c9cd4dSSage Weil 				datal -= skip + trim;
3711a22285a6SYan, Zheng 
37124a0ab9d7SDavid Sterba 				ret = clone_copy_inline_extent(inode,
37138039d87dSFilipe Manana 							       trans, path,
37148039d87dSFilipe Manana 							       &new_key,
3715f82a9901SFilipe Manana 							       drop_start,
37168039d87dSFilipe Manana 							       datal,
37178039d87dSFilipe Manana 							       skip, size, buf);
371879787eaaSJeff Mahoney 				if (ret) {
37193f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
37203a29bc09SChris Mason 						btrfs_abort_transaction(trans,
372179787eaaSJeff Mahoney 									ret);
37223a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
372379787eaaSJeff Mahoney 					goto out;
372479787eaaSJeff Mahoney 				}
3725c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3726c5c9cd4dSSage Weil 				slot = path->slots[0];
3727c5c9cd4dSSage Weil 			}
3728c5c9cd4dSSage Weil 
37297ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
37307ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
3731a2f392e4SNikolay Borisov 				clone_update_extent_map(BTRFS_I(inode), trans,
373214f59796SFilipe Manana 						NULL, drop_start,
37337ffbb598SFilipe Manana 						new_key.offset - drop_start);
37347ffbb598SFilipe Manana 
3735a2f392e4SNikolay Borisov 			clone_update_extent_map(BTRFS_I(inode), trans,
3736a2f392e4SNikolay Borisov 					path, 0, 0);
37377ffbb598SFilipe Manana 
3738c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3739b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3740c5c9cd4dSSage Weil 
374162e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
37420b246afaSJeff Mahoney 					      fs_info->sectorsize);
3743f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3744f82a9901SFilipe Manana 							last_dest_end,
37451c919a5eSMark Fasheh 							destoff, olen,
37461c919a5eSMark Fasheh 							no_time_update);
3747f82a9901SFilipe Manana 			if (ret)
374879787eaaSJeff Mahoney 				goto out;
37492c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
37502c463823SFilipe Manana 				break;
3751a22285a6SYan, Zheng 		}
3752b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3753df858e76SFilipe Manana 		key.offset = next_key_min_offset;
375469ae5e44SWang Xiaoguang 
375569ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
375669ae5e44SWang Xiaoguang 			ret = -EINTR;
375769ae5e44SWang Xiaoguang 			goto out;
375869ae5e44SWang Xiaoguang 		}
3759ae01a0abSYan Zheng 	}
3760f46b5a66SChristoph Hellwig 	ret = 0;
376132b7c687SMark Fasheh 
3762f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3763f82a9901SFilipe Manana 		/*
3764f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3765f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3766f82a9901SFilipe Manana 		 */
3767b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3768f82a9901SFilipe Manana 
3769f82a9901SFilipe Manana 		/*
3770f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3771f82a9901SFilipe Manana 		 * 1 - inode update
3772f82a9901SFilipe Manana 		 */
3773f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3774f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3775f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3776f82a9901SFilipe Manana 			goto out;
3777f82a9901SFilipe Manana 		}
3778f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3779f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3780f82a9901SFilipe Manana 		if (ret) {
3781f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
378266642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
37833a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
3784f82a9901SFilipe Manana 			goto out;
3785f82a9901SFilipe Manana 		}
3786a2f392e4SNikolay Borisov 		clone_update_extent_map(BTRFS_I(inode), trans, NULL,
3787a2f392e4SNikolay Borisov 				last_dest_end,
378814f59796SFilipe Manana 				destoff + len - last_dest_end);
3789f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
37901c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3791f82a9901SFilipe Manana 	}
3792f82a9901SFilipe Manana 
3793f46b5a66SChristoph Hellwig out:
379432b7c687SMark Fasheh 	btrfs_free_path(path);
379515351955SDavid Sterba 	kvfree(buf);
379632b7c687SMark Fasheh 	return ret;
379732b7c687SMark Fasheh }
379832b7c687SMark Fasheh 
37993db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
380032b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
380132b7c687SMark Fasheh {
380254563d41SAl Viro 	struct inode *inode = file_inode(file);
38033db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
38040b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
380532b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
380632b7c687SMark Fasheh 	int ret;
380732b7c687SMark Fasheh 	u64 len = olen;
38080b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
38093db11b2eSZach Brown 	int same_inode = src == inode;
381032b7c687SMark Fasheh 
381132b7c687SMark Fasheh 	/*
381232b7c687SMark Fasheh 	 * TODO:
381332b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
381432b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
381532b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
381632b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
381700fdf13aSLiu Bo 	 *
381800fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
381900fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
382032b7c687SMark Fasheh 	 */
382132b7c687SMark Fasheh 
382232b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
382332b7c687SMark Fasheh 		return -EROFS;
382432b7c687SMark Fasheh 
38253db11b2eSZach Brown 	if (file_src->f_path.mnt != file->f_path.mnt ||
38263db11b2eSZach Brown 	    src->i_sb != inode->i_sb)
38273db11b2eSZach Brown 		return -EXDEV;
382832b7c687SMark Fasheh 
382932b7c687SMark Fasheh 	/* don't make the dst file partly checksummed */
383032b7c687SMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
383132b7c687SMark Fasheh 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
38323db11b2eSZach Brown 		return -EINVAL;
383332b7c687SMark Fasheh 
383432b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
38353db11b2eSZach Brown 		return -EISDIR;
383632b7c687SMark Fasheh 
383732b7c687SMark Fasheh 	if (!same_inode) {
3838293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
383932b7c687SMark Fasheh 	} else {
38405955102cSAl Viro 		inode_lock(src);
384132b7c687SMark Fasheh 	}
384232b7c687SMark Fasheh 
384332b7c687SMark Fasheh 	/* determine range to clone */
384432b7c687SMark Fasheh 	ret = -EINVAL;
384532b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
384632b7c687SMark Fasheh 		goto out_unlock;
384732b7c687SMark Fasheh 	if (len == 0)
384832b7c687SMark Fasheh 		olen = len = src->i_size - off;
384932b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
385032b7c687SMark Fasheh 	if (off + len == src->i_size)
385132b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
385232b7c687SMark Fasheh 
3853ccccf3d6SFilipe Manana 	if (len == 0) {
3854ccccf3d6SFilipe Manana 		ret = 0;
3855ccccf3d6SFilipe Manana 		goto out_unlock;
3856ccccf3d6SFilipe Manana 	}
3857ccccf3d6SFilipe Manana 
385832b7c687SMark Fasheh 	/* verify the end result is block aligned */
385932b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
386032b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
386132b7c687SMark Fasheh 		goto out_unlock;
386232b7c687SMark Fasheh 
386332b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
386432b7c687SMark Fasheh 	if (same_inode) {
386532b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
386632b7c687SMark Fasheh 			goto out_unlock;
386732b7c687SMark Fasheh 	}
386832b7c687SMark Fasheh 
386932b7c687SMark Fasheh 	if (destoff > inode->i_size) {
387032b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
387132b7c687SMark Fasheh 		if (ret)
387232b7c687SMark Fasheh 			goto out_unlock;
387332b7c687SMark Fasheh 	}
387432b7c687SMark Fasheh 
3875c125b8bfSFilipe Manana 	/*
3876c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
3877c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
3878c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
3879c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
3880c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
3881c125b8bfSFilipe Manana 	 */
3882c125b8bfSFilipe Manana 	if (same_inode) {
3883c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3884c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
388532b7c687SMark Fasheh 
3886e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, lock_start, lock_len, true);
3887c125b8bfSFilipe Manana 	} else {
3888e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
3889e0bd70c6SFilipe Manana 					       true);
3890e0bd70c6SFilipe Manana 	}
3891e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3892e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3893e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3894e0bd70c6SFilipe Manana 		goto out_unlock;
3895c125b8bfSFilipe Manana 	}
389632b7c687SMark Fasheh 
38971c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
389832b7c687SMark Fasheh 
3899c125b8bfSFilipe Manana 	if (same_inode) {
3900c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3901c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
3902c125b8bfSFilipe Manana 
3903c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3904c125b8bfSFilipe Manana 	} else {
3905293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
3906c125b8bfSFilipe Manana 	}
3907c125b8bfSFilipe Manana 	/*
3908c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3909c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3910c125b8bfSFilipe Manana 	 */
391165bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
391209cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
391309cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
3914f46b5a66SChristoph Hellwig out_unlock:
3915293a8489SMark Fasheh 	if (!same_inode)
3916293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
3917293a8489SMark Fasheh 	else
39185955102cSAl Viro 		inode_unlock(src);
39193db11b2eSZach Brown 	return ret;
39203db11b2eSZach Brown }
39213db11b2eSZach Brown 
392204b38d60SChristoph Hellwig int btrfs_clone_file_range(struct file *src_file, loff_t off,
392304b38d60SChristoph Hellwig 		struct file *dst_file, loff_t destoff, u64 len)
39243db11b2eSZach Brown {
392504b38d60SChristoph Hellwig 	return btrfs_clone_files(dst_file, src_file, off, len, destoff);
3926c5c9cd4dSSage Weil }
3927c5c9cd4dSSage Weil 
39286ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
39296ef5ed0dSJosef Bacik {
3930496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
39310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39326ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
39336ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
39346ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
39356ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
39366ef5ed0dSJosef Bacik 	struct btrfs_path *path;
39376ef5ed0dSJosef Bacik 	struct btrfs_key location;
39386ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
39396ef5ed0dSJosef Bacik 	u64 objectid = 0;
39406ef5ed0dSJosef Bacik 	u64 dir_id;
39413c04ce01SMiao Xie 	int ret;
39426ef5ed0dSJosef Bacik 
39436ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
39446ef5ed0dSJosef Bacik 		return -EPERM;
39456ef5ed0dSJosef Bacik 
39463c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
39473c04ce01SMiao Xie 	if (ret)
39483c04ce01SMiao Xie 		return ret;
39493c04ce01SMiao Xie 
39503c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
39513c04ce01SMiao Xie 		ret = -EFAULT;
39523c04ce01SMiao Xie 		goto out;
39533c04ce01SMiao Xie 	}
39546ef5ed0dSJosef Bacik 
39556ef5ed0dSJosef Bacik 	if (!objectid)
39561cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
39576ef5ed0dSJosef Bacik 
39586ef5ed0dSJosef Bacik 	location.objectid = objectid;
39596ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
39606ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
39616ef5ed0dSJosef Bacik 
39620b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
39633c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
39643c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
39653c04ce01SMiao Xie 		goto out;
39663c04ce01SMiao Xie 	}
39676d6d2829Ssatoru takeuchi 	if (!is_fstree(new_root->objectid)) {
39686d6d2829Ssatoru takeuchi 		ret = -ENOENT;
39696d6d2829Ssatoru takeuchi 		goto out;
39706d6d2829Ssatoru takeuchi 	}
39716ef5ed0dSJosef Bacik 
39726ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
39733c04ce01SMiao Xie 	if (!path) {
39743c04ce01SMiao Xie 		ret = -ENOMEM;
39753c04ce01SMiao Xie 		goto out;
39763c04ce01SMiao Xie 	}
39776ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
39786ef5ed0dSJosef Bacik 
39796ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
398098d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
39816ef5ed0dSJosef Bacik 		btrfs_free_path(path);
39823c04ce01SMiao Xie 		ret = PTR_ERR(trans);
39833c04ce01SMiao Xie 		goto out;
39846ef5ed0dSJosef Bacik 	}
39856ef5ed0dSJosef Bacik 
39860b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
39870b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
39886ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
3989cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
39906ef5ed0dSJosef Bacik 		btrfs_free_path(path);
39913a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
39920b246afaSJeff Mahoney 		btrfs_err(fs_info,
39935d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
39943c04ce01SMiao Xie 		ret = -ENOENT;
39953c04ce01SMiao Xie 		goto out;
39966ef5ed0dSJosef Bacik 	}
39976ef5ed0dSJosef Bacik 
39986ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
39996ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
40006ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
40016ef5ed0dSJosef Bacik 	btrfs_free_path(path);
40026ef5ed0dSJosef Bacik 
40030b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
40043a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
40053c04ce01SMiao Xie out:
40063c04ce01SMiao Xie 	mnt_drop_write_file(file);
40073c04ce01SMiao Xie 	return ret;
40086ef5ed0dSJosef Bacik }
40096ef5ed0dSJosef Bacik 
4010c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
4011bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
4012bf5fc093SJosef Bacik {
4013bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4014bf5fc093SJosef Bacik 
4015bf5fc093SJosef Bacik 	space->total_bytes = 0;
4016bf5fc093SJosef Bacik 	space->used_bytes = 0;
4017bf5fc093SJosef Bacik 	space->flags = 0;
4018bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4019bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4020bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4021bf5fc093SJosef Bacik 		space->used_bytes +=
4022bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4023bf5fc093SJosef Bacik 	}
4024bf5fc093SJosef Bacik }
4025bf5fc093SJosef Bacik 
40262ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
40272ff7e61eSJeff Mahoney 				   void __user *arg)
40281406e432SJosef Bacik {
40291406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
40301406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
40311406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
40327fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
403313f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
40341406e432SJosef Bacik 	struct btrfs_space_info *info;
4035315d8e98SColin Ian King 	static const u64 types[] = {
4036315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
4037bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
4038bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
4039315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4040315d8e98SColin Ian King 	};
4041bf5fc093SJosef Bacik 	int num_types = 4;
40427fde62bfSChris Mason 	int alloc_size;
40431406e432SJosef Bacik 	int ret = 0;
404451788b1bSDan Rosenberg 	u64 slot_count = 0;
4045bf5fc093SJosef Bacik 	int i, c;
40461406e432SJosef Bacik 
40471406e432SJosef Bacik 	if (copy_from_user(&space_args,
40481406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
40491406e432SJosef Bacik 			   sizeof(space_args)))
40501406e432SJosef Bacik 		return -EFAULT;
40511406e432SJosef Bacik 
4052bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4053bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4054bf5fc093SJosef Bacik 
4055bf5fc093SJosef Bacik 		info = NULL;
40567fde62bfSChris Mason 		rcu_read_lock();
40570b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4058bf5fc093SJosef Bacik 					list) {
4059bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4060bf5fc093SJosef Bacik 				info = tmp;
4061bf5fc093SJosef Bacik 				break;
4062bf5fc093SJosef Bacik 			}
4063bf5fc093SJosef Bacik 		}
40647fde62bfSChris Mason 		rcu_read_unlock();
40651406e432SJosef Bacik 
4066bf5fc093SJosef Bacik 		if (!info)
4067bf5fc093SJosef Bacik 			continue;
4068bf5fc093SJosef Bacik 
4069bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4070bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4071bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4072bf5fc093SJosef Bacik 				slot_count++;
4073bf5fc093SJosef Bacik 		}
4074bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4075bf5fc093SJosef Bacik 	}
4076bf5fc093SJosef Bacik 
407736523e95SDavid Sterba 	/*
407836523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
407936523e95SDavid Sterba 	 */
408036523e95SDavid Sterba 	slot_count++;
408136523e95SDavid Sterba 
40827fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
40837fde62bfSChris Mason 	if (space_args.space_slots == 0) {
40847fde62bfSChris Mason 		space_args.total_spaces = slot_count;
40857fde62bfSChris Mason 		goto out;
40867fde62bfSChris Mason 	}
4087bf5fc093SJosef Bacik 
408851788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4089bf5fc093SJosef Bacik 
40907fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4091bf5fc093SJosef Bacik 
40927fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
40937fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
40947fde62bfSChris Mason 	 */
409509cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
40967fde62bfSChris Mason 		return -ENOMEM;
40977fde62bfSChris Mason 
40987fde62bfSChris Mason 	space_args.total_spaces = 0;
40998d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
41007fde62bfSChris Mason 	if (!dest)
41017fde62bfSChris Mason 		return -ENOMEM;
41027fde62bfSChris Mason 	dest_orig = dest;
41037fde62bfSChris Mason 
41047fde62bfSChris Mason 	/* now we have a buffer to copy into */
4105bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4106bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4107bf5fc093SJosef Bacik 
410851788b1bSDan Rosenberg 		if (!slot_count)
410951788b1bSDan Rosenberg 			break;
411051788b1bSDan Rosenberg 
4111bf5fc093SJosef Bacik 		info = NULL;
41121406e432SJosef Bacik 		rcu_read_lock();
41130b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4114bf5fc093SJosef Bacik 					list) {
4115bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4116bf5fc093SJosef Bacik 				info = tmp;
41177fde62bfSChris Mason 				break;
4118bf5fc093SJosef Bacik 			}
4119bf5fc093SJosef Bacik 		}
4120bf5fc093SJosef Bacik 		rcu_read_unlock();
41217fde62bfSChris Mason 
4122bf5fc093SJosef Bacik 		if (!info)
4123bf5fc093SJosef Bacik 			continue;
4124bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4125bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4126bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
4127c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
4128c065f5b1SSu Yue 						     &space);
41297fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
41301406e432SJosef Bacik 				dest++;
41311406e432SJosef Bacik 				space_args.total_spaces++;
413251788b1bSDan Rosenberg 				slot_count--;
41331406e432SJosef Bacik 			}
413451788b1bSDan Rosenberg 			if (!slot_count)
413551788b1bSDan Rosenberg 				break;
4136bf5fc093SJosef Bacik 		}
4137bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4138bf5fc093SJosef Bacik 	}
41391406e432SJosef Bacik 
414036523e95SDavid Sterba 	/*
414136523e95SDavid Sterba 	 * Add global block reserve
414236523e95SDavid Sterba 	 */
414336523e95SDavid Sterba 	if (slot_count) {
41440b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
414536523e95SDavid Sterba 
414636523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
414736523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
414836523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
414936523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
415036523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
415136523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
415236523e95SDavid Sterba 		space_args.total_spaces++;
415336523e95SDavid Sterba 	}
415436523e95SDavid Sterba 
41552eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
41567fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
41577fde62bfSChris Mason 
41587fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
41597fde62bfSChris Mason 		ret = -EFAULT;
41607fde62bfSChris Mason 
41617fde62bfSChris Mason 	kfree(dest_orig);
41627fde62bfSChris Mason out:
41637fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
41641406e432SJosef Bacik 		ret = -EFAULT;
41651406e432SJosef Bacik 
41661406e432SJosef Bacik 	return ret;
41671406e432SJosef Bacik }
41681406e432SJosef Bacik 
41699a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
41709a8c28beSMiao Xie 					    void __user *argp)
417146204592SSage Weil {
417246204592SSage Weil 	struct btrfs_trans_handle *trans;
417346204592SSage Weil 	u64 transid;
4174db5b493aSTsutomu Itoh 	int ret;
417546204592SSage Weil 
4176d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4177ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4178ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
417998d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4180ff7c1d33SMiao Xie 
4181ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4182ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4183ff7c1d33SMiao Xie 		goto out;
4184ff7c1d33SMiao Xie 	}
418546204592SSage Weil 	transid = trans->transid;
41863a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction_async(trans, 0);
41878b2b2d3cSTsutomu Itoh 	if (ret) {
41883a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
4189db5b493aSTsutomu Itoh 		return ret;
41908b2b2d3cSTsutomu Itoh 	}
4191ff7c1d33SMiao Xie out:
419246204592SSage Weil 	if (argp)
419346204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
419446204592SSage Weil 			return -EFAULT;
419546204592SSage Weil 	return 0;
419646204592SSage Weil }
419746204592SSage Weil 
41982ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
41999a8c28beSMiao Xie 					   void __user *argp)
420046204592SSage Weil {
420146204592SSage Weil 	u64 transid;
420246204592SSage Weil 
420346204592SSage Weil 	if (argp) {
420446204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
420546204592SSage Weil 			return -EFAULT;
420646204592SSage Weil 	} else {
420746204592SSage Weil 		transid = 0;  /* current trans */
420846204592SSage Weil 	}
42092ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
421046204592SSage Weil }
421146204592SSage Weil 
4212b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4213475f6387SJan Schmidt {
42140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4215475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4216b8e95489SMiao Xie 	int ret;
4217475f6387SJan Schmidt 
4218475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4219475f6387SJan Schmidt 		return -EPERM;
4220475f6387SJan Schmidt 
4221475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4222475f6387SJan Schmidt 	if (IS_ERR(sa))
4223475f6387SJan Schmidt 		return PTR_ERR(sa);
4224475f6387SJan Schmidt 
4225b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4226b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4227b8e95489SMiao Xie 		if (ret)
4228b8e95489SMiao Xie 			goto out;
4229b8e95489SMiao Xie 	}
4230b8e95489SMiao Xie 
42310b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
423263a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
423363a212abSStefan Behrens 			      0);
4234475f6387SJan Schmidt 
4235475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4236475f6387SJan Schmidt 		ret = -EFAULT;
4237475f6387SJan Schmidt 
4238b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4239b8e95489SMiao Xie 		mnt_drop_write_file(file);
4240b8e95489SMiao Xie out:
4241475f6387SJan Schmidt 	kfree(sa);
4242475f6387SJan Schmidt 	return ret;
4243475f6387SJan Schmidt }
4244475f6387SJan Schmidt 
42452ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4246475f6387SJan Schmidt {
4247475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4248475f6387SJan Schmidt 		return -EPERM;
4249475f6387SJan Schmidt 
42502ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4251475f6387SJan Schmidt }
4252475f6387SJan Schmidt 
42532ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4254475f6387SJan Schmidt 				       void __user *arg)
4255475f6387SJan Schmidt {
4256475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4257475f6387SJan Schmidt 	int ret;
4258475f6387SJan Schmidt 
4259475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4260475f6387SJan Schmidt 		return -EPERM;
4261475f6387SJan Schmidt 
4262475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4263475f6387SJan Schmidt 	if (IS_ERR(sa))
4264475f6387SJan Schmidt 		return PTR_ERR(sa);
4265475f6387SJan Schmidt 
42662ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4267475f6387SJan Schmidt 
4268475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4269475f6387SJan Schmidt 		ret = -EFAULT;
4270475f6387SJan Schmidt 
4271475f6387SJan Schmidt 	kfree(sa);
4272475f6387SJan Schmidt 	return ret;
4273475f6387SJan Schmidt }
4274475f6387SJan Schmidt 
42752ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4276b27f7c0cSDavid Sterba 				      void __user *arg)
4277c11d2c23SStefan Behrens {
4278c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4279c11d2c23SStefan Behrens 	int ret;
4280c11d2c23SStefan Behrens 
4281c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4282c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4283c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4284c11d2c23SStefan Behrens 
4285b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4286b27f7c0cSDavid Sterba 		kfree(sa);
4287b27f7c0cSDavid Sterba 		return -EPERM;
4288b27f7c0cSDavid Sterba 	}
4289b27f7c0cSDavid Sterba 
42902ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4291c11d2c23SStefan Behrens 
4292c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4293c11d2c23SStefan Behrens 		ret = -EFAULT;
4294c11d2c23SStefan Behrens 
4295c11d2c23SStefan Behrens 	kfree(sa);
4296c11d2c23SStefan Behrens 	return ret;
4297c11d2c23SStefan Behrens }
4298c11d2c23SStefan Behrens 
42992ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
43002ff7e61eSJeff Mahoney 				    void __user *arg)
43013f6bcfbdSStefan Behrens {
43023f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
43033f6bcfbdSStefan Behrens 	int ret;
43043f6bcfbdSStefan Behrens 
43053f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
43063f6bcfbdSStefan Behrens 		return -EPERM;
43073f6bcfbdSStefan Behrens 
43083f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
43093f6bcfbdSStefan Behrens 	if (IS_ERR(p))
43103f6bcfbdSStefan Behrens 		return PTR_ERR(p);
43113f6bcfbdSStefan Behrens 
43123f6bcfbdSStefan Behrens 	switch (p->cmd) {
43133f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4314bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
4315adfa97cbSIlya Dryomov 			ret = -EROFS;
4316adfa97cbSIlya Dryomov 			goto out;
4317adfa97cbSIlya Dryomov 		}
4318171938e5SDavid Sterba 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4319e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
43203f6bcfbdSStefan Behrens 		} else {
43212ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4322171938e5SDavid Sterba 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
43233f6bcfbdSStefan Behrens 		}
43243f6bcfbdSStefan Behrens 		break;
43253f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
43260b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
43273f6bcfbdSStefan Behrens 		ret = 0;
43283f6bcfbdSStefan Behrens 		break;
43293f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
433017d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
433197282031SAnand Jain 		ret = 0;
43323f6bcfbdSStefan Behrens 		break;
43333f6bcfbdSStefan Behrens 	default:
43343f6bcfbdSStefan Behrens 		ret = -EINVAL;
43353f6bcfbdSStefan Behrens 		break;
43363f6bcfbdSStefan Behrens 	}
43373f6bcfbdSStefan Behrens 
43383f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
43393f6bcfbdSStefan Behrens 		ret = -EFAULT;
4340adfa97cbSIlya Dryomov out:
43413f6bcfbdSStefan Behrens 	kfree(p);
43423f6bcfbdSStefan Behrens 	return ret;
43433f6bcfbdSStefan Behrens }
43443f6bcfbdSStefan Behrens 
4345d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4346d7728c96SJan Schmidt {
4347d7728c96SJan Schmidt 	int ret = 0;
4348d7728c96SJan Schmidt 	int i;
4349740c3d22SChris Mason 	u64 rel_ptr;
4350d7728c96SJan Schmidt 	int size;
4351806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4352d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4353d7728c96SJan Schmidt 	struct btrfs_path *path;
4354d7728c96SJan Schmidt 
435582b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4356d7728c96SJan Schmidt 		return -EPERM;
4357d7728c96SJan Schmidt 
4358d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4359d7728c96SJan Schmidt 	if (!path) {
4360d7728c96SJan Schmidt 		ret = -ENOMEM;
4361d7728c96SJan Schmidt 		goto out;
4362d7728c96SJan Schmidt 	}
4363d7728c96SJan Schmidt 
4364d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4365d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4366d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4367d7728c96SJan Schmidt 		ipa = NULL;
4368d7728c96SJan Schmidt 		goto out;
4369d7728c96SJan Schmidt 	}
4370d7728c96SJan Schmidt 
4371d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4372d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4373d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4374d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4375d7728c96SJan Schmidt 		ipath = NULL;
4376d7728c96SJan Schmidt 		goto out;
4377d7728c96SJan Schmidt 	}
4378d7728c96SJan Schmidt 
4379d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4380d7728c96SJan Schmidt 	if (ret < 0)
4381d7728c96SJan Schmidt 		goto out;
4382d7728c96SJan Schmidt 
4383d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4384745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4385745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4386740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4387d7728c96SJan Schmidt 	}
4388d7728c96SJan Schmidt 
4389718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4390718dc5faSOmar Sandoval 			   ipath->fspath, size);
4391d7728c96SJan Schmidt 	if (ret) {
4392d7728c96SJan Schmidt 		ret = -EFAULT;
4393d7728c96SJan Schmidt 		goto out;
4394d7728c96SJan Schmidt 	}
4395d7728c96SJan Schmidt 
4396d7728c96SJan Schmidt out:
4397d7728c96SJan Schmidt 	btrfs_free_path(path);
4398d7728c96SJan Schmidt 	free_ipath(ipath);
4399d7728c96SJan Schmidt 	kfree(ipa);
4400d7728c96SJan Schmidt 
4401d7728c96SJan Schmidt 	return ret;
4402d7728c96SJan Schmidt }
4403d7728c96SJan Schmidt 
4404d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4405d7728c96SJan Schmidt {
4406d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4407d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4408d7728c96SJan Schmidt 
4409d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4410d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4411d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4412d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4413d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4414d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4415d7728c96SJan Schmidt 	} else {
4416d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4417d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4418d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4419d7728c96SJan Schmidt 	}
4420d7728c96SJan Schmidt 
4421d7728c96SJan Schmidt 	return 0;
4422d7728c96SJan Schmidt }
4423d7728c96SJan Schmidt 
44242ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4425d24a67b2SZygo Blaxell 					void __user *arg, int version)
4426d7728c96SJan Schmidt {
4427d7728c96SJan Schmidt 	int ret = 0;
4428d7728c96SJan Schmidt 	int size;
4429d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4430d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4431d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4432d24a67b2SZygo Blaxell 	bool ignore_offset;
4433d7728c96SJan Schmidt 
4434d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4435d7728c96SJan Schmidt 		return -EPERM;
4436d7728c96SJan Schmidt 
4437d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
44387b9ea627SShailendra Verma 	if (IS_ERR(loi))
44397b9ea627SShailendra Verma 		return PTR_ERR(loi);
4440d7728c96SJan Schmidt 
4441d24a67b2SZygo Blaxell 	if (version == 1) {
4442d24a67b2SZygo Blaxell 		ignore_offset = false;
4443b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
4444d24a67b2SZygo Blaxell 	} else {
4445d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
4446d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4447d24a67b2SZygo Blaxell 			ret = -EINVAL;
4448d24a67b2SZygo Blaxell 			goto out_loi;
4449d24a67b2SZygo Blaxell 		}
4450d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
4451d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4452d24a67b2SZygo Blaxell 			ret = -EINVAL;
4453d24a67b2SZygo Blaxell 			goto out_loi;
4454d24a67b2SZygo Blaxell 		}
4455d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4456b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
4457d24a67b2SZygo Blaxell 	}
4458d24a67b2SZygo Blaxell 
4459d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4460d7728c96SJan Schmidt 	if (!path) {
4461d7728c96SJan Schmidt 		ret = -ENOMEM;
4462d7728c96SJan Schmidt 		goto out;
4463d7728c96SJan Schmidt 	}
4464d7728c96SJan Schmidt 
4465d7728c96SJan Schmidt 	inodes = init_data_container(size);
4466d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4467d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4468d7728c96SJan Schmidt 		inodes = NULL;
4469d7728c96SJan Schmidt 		goto out;
4470d7728c96SJan Schmidt 	}
4471d7728c96SJan Schmidt 
44722ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4473d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
4474df031f07SLiu Bo 	if (ret == -EINVAL)
4475d7728c96SJan Schmidt 		ret = -ENOENT;
4476d7728c96SJan Schmidt 	if (ret < 0)
4477d7728c96SJan Schmidt 		goto out;
4478d7728c96SJan Schmidt 
4479718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4480718dc5faSOmar Sandoval 			   size);
4481d7728c96SJan Schmidt 	if (ret)
4482d7728c96SJan Schmidt 		ret = -EFAULT;
4483d7728c96SJan Schmidt 
4484d7728c96SJan Schmidt out:
4485d7728c96SJan Schmidt 	btrfs_free_path(path);
4486f54de068SDavid Sterba 	kvfree(inodes);
4487d24a67b2SZygo Blaxell out_loi:
4488d7728c96SJan Schmidt 	kfree(loi);
4489d7728c96SJan Schmidt 
4490d7728c96SJan Schmidt 	return ret;
4491d7728c96SJan Schmidt }
4492d7728c96SJan Schmidt 
449319a39dceSIlya Dryomov void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
4494c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4495c9e9f97bSIlya Dryomov {
4496c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4497c9e9f97bSIlya Dryomov 
4498c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4499c9e9f97bSIlya Dryomov 
4500837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_running))
4501837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4502837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4503837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4504a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4505a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4506837d5b6eSIlya Dryomov 
4507c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4508c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4509c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
451019a39dceSIlya Dryomov 
451119a39dceSIlya Dryomov 	if (lock) {
451219a39dceSIlya Dryomov 		spin_lock(&fs_info->balance_lock);
451319a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
451419a39dceSIlya Dryomov 		spin_unlock(&fs_info->balance_lock);
451519a39dceSIlya Dryomov 	} else {
451619a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
451719a39dceSIlya Dryomov 	}
4518c9e9f97bSIlya Dryomov }
4519c9e9f97bSIlya Dryomov 
45209ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4521c9e9f97bSIlya Dryomov {
4522496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4523c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4524c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4525c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4526ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4527c9e9f97bSIlya Dryomov 	int ret;
4528c9e9f97bSIlya Dryomov 
4529c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4530c9e9f97bSIlya Dryomov 		return -EPERM;
4531c9e9f97bSIlya Dryomov 
4532e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
45339ba1f6e4SLiu Bo 	if (ret)
45349ba1f6e4SLiu Bo 		return ret;
45359ba1f6e4SLiu Bo 
4536ed0fb78fSIlya Dryomov again:
4537171938e5SDavid Sterba 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4538c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->volume_mutex);
4539c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4540ed0fb78fSIlya Dryomov 		need_unlock = true;
4541ed0fb78fSIlya Dryomov 		goto locked;
4542ed0fb78fSIlya Dryomov 	}
4543ed0fb78fSIlya Dryomov 
4544ed0fb78fSIlya Dryomov 	/*
454501327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4546ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4547ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4548ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4549ed0fb78fSIlya Dryomov 	 */
4550ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4551ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4552ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
4553ed0fb78fSIlya Dryomov 		if (!atomic_read(&fs_info->balance_running)) {
4554ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4555ed0fb78fSIlya Dryomov 			if (!mutex_trylock(&fs_info->volume_mutex))
4556ed0fb78fSIlya Dryomov 				goto again;
4557ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4558ed0fb78fSIlya Dryomov 
4559ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
4560ed0fb78fSIlya Dryomov 			    !atomic_read(&fs_info->balance_running)) {
4561ed0fb78fSIlya Dryomov 				/* this is (3) */
4562ed0fb78fSIlya Dryomov 				need_unlock = false;
4563ed0fb78fSIlya Dryomov 				goto locked;
4564ed0fb78fSIlya Dryomov 			}
4565ed0fb78fSIlya Dryomov 
4566ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4567ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->volume_mutex);
4568ed0fb78fSIlya Dryomov 			goto again;
4569ed0fb78fSIlya Dryomov 		} else {
4570ed0fb78fSIlya Dryomov 			/* this is (2) */
4571ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4572ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4573ed0fb78fSIlya Dryomov 			goto out;
4574ed0fb78fSIlya Dryomov 		}
4575ed0fb78fSIlya Dryomov 	} else {
4576ed0fb78fSIlya Dryomov 		/* this is (1) */
4577ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4578e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4579ed0fb78fSIlya Dryomov 		goto out;
4580ed0fb78fSIlya Dryomov 	}
4581ed0fb78fSIlya Dryomov 
4582ed0fb78fSIlya Dryomov locked:
4583171938e5SDavid Sterba 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4584c9e9f97bSIlya Dryomov 
4585c9e9f97bSIlya Dryomov 	if (arg) {
4586c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4587c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4588c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4589ed0fb78fSIlya Dryomov 			goto out_unlock;
4590c9e9f97bSIlya Dryomov 		}
4591de322263SIlya Dryomov 
4592de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4593de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4594de322263SIlya Dryomov 				ret = -ENOTCONN;
4595de322263SIlya Dryomov 				goto out_bargs;
4596de322263SIlya Dryomov 			}
4597de322263SIlya Dryomov 
4598de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4599de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4600de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4601de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4602de322263SIlya Dryomov 
4603de322263SIlya Dryomov 			goto do_balance;
4604de322263SIlya Dryomov 		}
4605c9e9f97bSIlya Dryomov 	} else {
4606c9e9f97bSIlya Dryomov 		bargs = NULL;
4607c9e9f97bSIlya Dryomov 	}
4608c9e9f97bSIlya Dryomov 
4609ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4610837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4611837d5b6eSIlya Dryomov 		goto out_bargs;
4612837d5b6eSIlya Dryomov 	}
4613837d5b6eSIlya Dryomov 
46148d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4615c9e9f97bSIlya Dryomov 	if (!bctl) {
4616c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4617c9e9f97bSIlya Dryomov 		goto out_bargs;
4618c9e9f97bSIlya Dryomov 	}
4619c9e9f97bSIlya Dryomov 
4620c9e9f97bSIlya Dryomov 	bctl->fs_info = fs_info;
4621c9e9f97bSIlya Dryomov 	if (arg) {
4622c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4623c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4624c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4625c9e9f97bSIlya Dryomov 
4626c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4627f43ffb60SIlya Dryomov 	} else {
4628f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4629f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4630c9e9f97bSIlya Dryomov 	}
4631c9e9f97bSIlya Dryomov 
46328eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
46338eb93459SDavid Sterba 		ret = -EINVAL;
46340f89abf5SChristian Engelmayer 		goto out_bctl;
46358eb93459SDavid Sterba 	}
46368eb93459SDavid Sterba 
4637de322263SIlya Dryomov do_balance:
4638c9e9f97bSIlya Dryomov 	/*
4639171938e5SDavid Sterba 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP
4640ed0fb78fSIlya Dryomov 	 * goes to to btrfs_balance.  bctl is freed in __cancel_balance,
4641ed0fb78fSIlya Dryomov 	 * or, if restriper was paused all the way until unmount, in
4642171938e5SDavid Sterba 	 * free_fs_info.  The flag is cleared in __cancel_balance.
4643c9e9f97bSIlya Dryomov 	 */
4644ed0fb78fSIlya Dryomov 	need_unlock = false;
4645ed0fb78fSIlya Dryomov 
4646ed0fb78fSIlya Dryomov 	ret = btrfs_balance(bctl, bargs);
46470f89abf5SChristian Engelmayer 	bctl = NULL;
4648ed0fb78fSIlya Dryomov 
4649c9e9f97bSIlya Dryomov 	if (arg) {
4650c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4651c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4652c9e9f97bSIlya Dryomov 	}
4653c9e9f97bSIlya Dryomov 
46540f89abf5SChristian Engelmayer out_bctl:
46550f89abf5SChristian Engelmayer 	kfree(bctl);
4656c9e9f97bSIlya Dryomov out_bargs:
4657c9e9f97bSIlya Dryomov 	kfree(bargs);
4658ed0fb78fSIlya Dryomov out_unlock:
4659c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4660c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->volume_mutex);
4661ed0fb78fSIlya Dryomov 	if (need_unlock)
4662171938e5SDavid Sterba 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4663ed0fb78fSIlya Dryomov out:
4664e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4665c9e9f97bSIlya Dryomov 	return ret;
4666c9e9f97bSIlya Dryomov }
4667c9e9f97bSIlya Dryomov 
46682ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4669837d5b6eSIlya Dryomov {
4670837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4671837d5b6eSIlya Dryomov 		return -EPERM;
4672837d5b6eSIlya Dryomov 
4673837d5b6eSIlya Dryomov 	switch (cmd) {
4674837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
46750b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4676a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
46770b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4678837d5b6eSIlya Dryomov 	}
4679837d5b6eSIlya Dryomov 
4680837d5b6eSIlya Dryomov 	return -EINVAL;
4681837d5b6eSIlya Dryomov }
4682837d5b6eSIlya Dryomov 
46832ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
468419a39dceSIlya Dryomov 					 void __user *arg)
468519a39dceSIlya Dryomov {
468619a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
468719a39dceSIlya Dryomov 	int ret = 0;
468819a39dceSIlya Dryomov 
468919a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
469019a39dceSIlya Dryomov 		return -EPERM;
469119a39dceSIlya Dryomov 
469219a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
469319a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
469419a39dceSIlya Dryomov 		ret = -ENOTCONN;
469519a39dceSIlya Dryomov 		goto out;
469619a39dceSIlya Dryomov 	}
469719a39dceSIlya Dryomov 
46988d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
469919a39dceSIlya Dryomov 	if (!bargs) {
470019a39dceSIlya Dryomov 		ret = -ENOMEM;
470119a39dceSIlya Dryomov 		goto out;
470219a39dceSIlya Dryomov 	}
470319a39dceSIlya Dryomov 
470419a39dceSIlya Dryomov 	update_ioctl_balance_args(fs_info, 1, bargs);
470519a39dceSIlya Dryomov 
470619a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
470719a39dceSIlya Dryomov 		ret = -EFAULT;
470819a39dceSIlya Dryomov 
470919a39dceSIlya Dryomov 	kfree(bargs);
471019a39dceSIlya Dryomov out:
471119a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
471219a39dceSIlya Dryomov 	return ret;
471319a39dceSIlya Dryomov }
471419a39dceSIlya Dryomov 
4715905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
47165d13a37bSArne Jansen {
47170b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47180b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47195d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
47205d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
47215d13a37bSArne Jansen 	int ret;
47225d13a37bSArne Jansen 	int err;
47235d13a37bSArne Jansen 
47245d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
47255d13a37bSArne Jansen 		return -EPERM;
47265d13a37bSArne Jansen 
4727905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4728905b0ddaSMiao Xie 	if (ret)
4729905b0ddaSMiao Xie 		return ret;
47305d13a37bSArne Jansen 
47315d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4732905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4733905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4734905b0ddaSMiao Xie 		goto drop_write;
4735905b0ddaSMiao Xie 	}
47365d13a37bSArne Jansen 
47370b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
47380b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 2);
47395d13a37bSArne Jansen 	if (IS_ERR(trans)) {
47405d13a37bSArne Jansen 		ret = PTR_ERR(trans);
47415d13a37bSArne Jansen 		goto out;
47425d13a37bSArne Jansen 	}
47435d13a37bSArne Jansen 
47445d13a37bSArne Jansen 	switch (sa->cmd) {
47455d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
47460b246afaSJeff Mahoney 		ret = btrfs_quota_enable(trans, fs_info);
47475d13a37bSArne Jansen 		break;
47485d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
47490b246afaSJeff Mahoney 		ret = btrfs_quota_disable(trans, fs_info);
47505d13a37bSArne Jansen 		break;
47515d13a37bSArne Jansen 	default:
47525d13a37bSArne Jansen 		ret = -EINVAL;
47535d13a37bSArne Jansen 		break;
47545d13a37bSArne Jansen 	}
47555d13a37bSArne Jansen 
47563a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
47575d13a37bSArne Jansen 	if (err && !ret)
47585d13a37bSArne Jansen 		ret = err;
47595d13a37bSArne Jansen out:
47605d13a37bSArne Jansen 	kfree(sa);
47610b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4762905b0ddaSMiao Xie drop_write:
4763905b0ddaSMiao Xie 	mnt_drop_write_file(file);
47645d13a37bSArne Jansen 	return ret;
47655d13a37bSArne Jansen }
47665d13a37bSArne Jansen 
4767905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
47685d13a37bSArne Jansen {
47690b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
47700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
47710b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
47725d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
47735d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
47745d13a37bSArne Jansen 	int ret;
47755d13a37bSArne Jansen 	int err;
47765d13a37bSArne Jansen 
47775d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
47785d13a37bSArne Jansen 		return -EPERM;
47795d13a37bSArne Jansen 
4780905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4781905b0ddaSMiao Xie 	if (ret)
4782905b0ddaSMiao Xie 		return ret;
47835d13a37bSArne Jansen 
47845d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4785905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4786905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4787905b0ddaSMiao Xie 		goto drop_write;
4788905b0ddaSMiao Xie 	}
47895d13a37bSArne Jansen 
47905d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
47915d13a37bSArne Jansen 	if (IS_ERR(trans)) {
47925d13a37bSArne Jansen 		ret = PTR_ERR(trans);
47935d13a37bSArne Jansen 		goto out;
47945d13a37bSArne Jansen 	}
47955d13a37bSArne Jansen 
47965d13a37bSArne Jansen 	if (sa->assign) {
47970b246afaSJeff Mahoney 		ret = btrfs_add_qgroup_relation(trans, fs_info,
47985d13a37bSArne Jansen 						sa->src, sa->dst);
47995d13a37bSArne Jansen 	} else {
48000b246afaSJeff Mahoney 		ret = btrfs_del_qgroup_relation(trans, fs_info,
48015d13a37bSArne Jansen 						sa->src, sa->dst);
48025d13a37bSArne Jansen 	}
48035d13a37bSArne Jansen 
4804e082f563SQu Wenruo 	/* update qgroup status and info */
48050b246afaSJeff Mahoney 	err = btrfs_run_qgroups(trans, fs_info);
4806e082f563SQu Wenruo 	if (err < 0)
48070b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4808ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
48093a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
48105d13a37bSArne Jansen 	if (err && !ret)
48115d13a37bSArne Jansen 		ret = err;
48125d13a37bSArne Jansen 
48135d13a37bSArne Jansen out:
48145d13a37bSArne Jansen 	kfree(sa);
4815905b0ddaSMiao Xie drop_write:
4816905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48175d13a37bSArne Jansen 	return ret;
48185d13a37bSArne Jansen }
48195d13a37bSArne Jansen 
4820905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
48215d13a37bSArne Jansen {
48220b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48240b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
48255d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
48265d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48275d13a37bSArne Jansen 	int ret;
48285d13a37bSArne Jansen 	int err;
48295d13a37bSArne Jansen 
48305d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48315d13a37bSArne Jansen 		return -EPERM;
48325d13a37bSArne Jansen 
4833905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4834905b0ddaSMiao Xie 	if (ret)
4835905b0ddaSMiao Xie 		return ret;
48365d13a37bSArne Jansen 
48375d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4838905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4839905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4840905b0ddaSMiao Xie 		goto drop_write;
4841905b0ddaSMiao Xie 	}
48425d13a37bSArne Jansen 
4843d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4844d86e56cfSMiao Xie 		ret = -EINVAL;
4845d86e56cfSMiao Xie 		goto out;
4846d86e56cfSMiao Xie 	}
4847d86e56cfSMiao Xie 
48485d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
48495d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48505d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48515d13a37bSArne Jansen 		goto out;
48525d13a37bSArne Jansen 	}
48535d13a37bSArne Jansen 
48545d13a37bSArne Jansen 	if (sa->create) {
48550b246afaSJeff Mahoney 		ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
48565d13a37bSArne Jansen 	} else {
48570b246afaSJeff Mahoney 		ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
48585d13a37bSArne Jansen 	}
48595d13a37bSArne Jansen 
48603a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
48615d13a37bSArne Jansen 	if (err && !ret)
48625d13a37bSArne Jansen 		ret = err;
48635d13a37bSArne Jansen 
48645d13a37bSArne Jansen out:
48655d13a37bSArne Jansen 	kfree(sa);
4866905b0ddaSMiao Xie drop_write:
4867905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48685d13a37bSArne Jansen 	return ret;
48695d13a37bSArne Jansen }
48705d13a37bSArne Jansen 
4871905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
48725d13a37bSArne Jansen {
48730b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48740b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48750b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
48765d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
48775d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48785d13a37bSArne Jansen 	int ret;
48795d13a37bSArne Jansen 	int err;
48805d13a37bSArne Jansen 	u64 qgroupid;
48815d13a37bSArne Jansen 
48825d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48835d13a37bSArne Jansen 		return -EPERM;
48845d13a37bSArne Jansen 
4885905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4886905b0ddaSMiao Xie 	if (ret)
4887905b0ddaSMiao Xie 		return ret;
48885d13a37bSArne Jansen 
48895d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4890905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4891905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4892905b0ddaSMiao Xie 		goto drop_write;
4893905b0ddaSMiao Xie 	}
48945d13a37bSArne Jansen 
48955d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
48965d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48975d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48985d13a37bSArne Jansen 		goto out;
48995d13a37bSArne Jansen 	}
49005d13a37bSArne Jansen 
49015d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
49025d13a37bSArne Jansen 	if (!qgroupid) {
49035d13a37bSArne Jansen 		/* take the current subvol as qgroup */
49045d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
49055d13a37bSArne Jansen 	}
49065d13a37bSArne Jansen 
49070b246afaSJeff Mahoney 	ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
49085d13a37bSArne Jansen 
49093a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
49105d13a37bSArne Jansen 	if (err && !ret)
49115d13a37bSArne Jansen 		ret = err;
49125d13a37bSArne Jansen 
49135d13a37bSArne Jansen out:
49145d13a37bSArne Jansen 	kfree(sa);
4915905b0ddaSMiao Xie drop_write:
4916905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49175d13a37bSArne Jansen 	return ret;
49185d13a37bSArne Jansen }
49195d13a37bSArne Jansen 
49202f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
49212f232036SJan Schmidt {
49220b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49242f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
49252f232036SJan Schmidt 	int ret;
49262f232036SJan Schmidt 
49272f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
49282f232036SJan Schmidt 		return -EPERM;
49292f232036SJan Schmidt 
49302f232036SJan Schmidt 	ret = mnt_want_write_file(file);
49312f232036SJan Schmidt 	if (ret)
49322f232036SJan Schmidt 		return ret;
49332f232036SJan Schmidt 
49342f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
49352f232036SJan Schmidt 	if (IS_ERR(qsa)) {
49362f232036SJan Schmidt 		ret = PTR_ERR(qsa);
49372f232036SJan Schmidt 		goto drop_write;
49382f232036SJan Schmidt 	}
49392f232036SJan Schmidt 
49402f232036SJan Schmidt 	if (qsa->flags) {
49412f232036SJan Schmidt 		ret = -EINVAL;
49422f232036SJan Schmidt 		goto out;
49432f232036SJan Schmidt 	}
49442f232036SJan Schmidt 
49450b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
49462f232036SJan Schmidt 
49472f232036SJan Schmidt out:
49482f232036SJan Schmidt 	kfree(qsa);
49492f232036SJan Schmidt drop_write:
49502f232036SJan Schmidt 	mnt_drop_write_file(file);
49512f232036SJan Schmidt 	return ret;
49522f232036SJan Schmidt }
49532f232036SJan Schmidt 
49542f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
49552f232036SJan Schmidt {
49560b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49582f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
49592f232036SJan Schmidt 	int ret = 0;
49602f232036SJan Schmidt 
49612f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
49622f232036SJan Schmidt 		return -EPERM;
49632f232036SJan Schmidt 
49648d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
49652f232036SJan Schmidt 	if (!qsa)
49662f232036SJan Schmidt 		return -ENOMEM;
49672f232036SJan Schmidt 
49680b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
49692f232036SJan Schmidt 		qsa->flags = 1;
49700b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
49712f232036SJan Schmidt 	}
49722f232036SJan Schmidt 
49732f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
49742f232036SJan Schmidt 		ret = -EFAULT;
49752f232036SJan Schmidt 
49762f232036SJan Schmidt 	kfree(qsa);
49772f232036SJan Schmidt 	return ret;
49782f232036SJan Schmidt }
49792f232036SJan Schmidt 
498057254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
498157254b6eSJan Schmidt {
49820b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49830b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
498457254b6eSJan Schmidt 
498557254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
498657254b6eSJan Schmidt 		return -EPERM;
498757254b6eSJan Schmidt 
49880b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
498957254b6eSJan Schmidt }
499057254b6eSJan Schmidt 
4991abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
4992abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
49938ea05e3aSAlexander Block {
4994496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
49950b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49968ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
49978ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
49988ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
4999c2050a45SDeepa Dinamani 	struct timespec ct = current_time(inode);
50008ea05e3aSAlexander Block 	int ret = 0;
5001dd5f9615SStefan Behrens 	int received_uuid_changed;
50028ea05e3aSAlexander Block 
5003bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
5004bd60ea0fSDavid Sterba 		return -EPERM;
5005bd60ea0fSDavid Sterba 
50068ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
50078ea05e3aSAlexander Block 	if (ret < 0)
50088ea05e3aSAlexander Block 		return ret;
50098ea05e3aSAlexander Block 
50100b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
50118ea05e3aSAlexander Block 
50124a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
50138ea05e3aSAlexander Block 		ret = -EINVAL;
50148ea05e3aSAlexander Block 		goto out;
50158ea05e3aSAlexander Block 	}
50168ea05e3aSAlexander Block 
50178ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
50188ea05e3aSAlexander Block 		ret = -EROFS;
50198ea05e3aSAlexander Block 		goto out;
50208ea05e3aSAlexander Block 	}
50218ea05e3aSAlexander Block 
5022dd5f9615SStefan Behrens 	/*
5023dd5f9615SStefan Behrens 	 * 1 - root item
5024dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5025dd5f9615SStefan Behrens 	 */
5026dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
50278ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
50288ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
50298ea05e3aSAlexander Block 		trans = NULL;
50308ea05e3aSAlexander Block 		goto out;
50318ea05e3aSAlexander Block 	}
50328ea05e3aSAlexander Block 
50338ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
50348ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
50358ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
50368ea05e3aSAlexander Block 
5037dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5038dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5039dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5040d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
5041d87ff758SNikolay Borisov 		ret = btrfs_uuid_tree_rem(trans, fs_info,
5042d87ff758SNikolay Borisov 					  root_item->received_uuid,
5043dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5044dd5f9615SStefan Behrens 					  root->root_key.objectid);
5045d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
5046d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
5047d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
5048d87ff758SNikolay Borisov 		        goto out;
5049d87ff758SNikolay Borisov 		}
5050d87ff758SNikolay Borisov 	}
50518ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
50528ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
50538ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
50543cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
50553cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
50563cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
50573cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
50588ea05e3aSAlexander Block 
50590b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
50608ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
50618ea05e3aSAlexander Block 	if (ret < 0) {
50623a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
50638ea05e3aSAlexander Block 		goto out;
5064dd5f9615SStefan Behrens 	}
5065dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
50660b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_add(trans, fs_info, sa->uuid,
5067dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5068dd5f9615SStefan Behrens 					  root->root_key.objectid);
5069dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
507066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
5071efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
5072dd5f9615SStefan Behrens 			goto out;
5073dd5f9615SStefan Behrens 		}
5074dd5f9615SStefan Behrens 	}
50753a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5076abccd00fSHugo Mills out:
50770b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5078abccd00fSHugo Mills 	mnt_drop_write_file(file);
5079abccd00fSHugo Mills 	return ret;
5080abccd00fSHugo Mills }
5081abccd00fSHugo Mills 
5082abccd00fSHugo Mills #ifdef CONFIG_64BIT
5083abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5084abccd00fSHugo Mills 						void __user *arg)
5085abccd00fSHugo Mills {
5086abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5087abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5088abccd00fSHugo Mills 	int ret = 0;
5089abccd00fSHugo Mills 
5090abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
50917b9ea627SShailendra Verma 	if (IS_ERR(args32))
50927b9ea627SShailendra Verma 		return PTR_ERR(args32);
5093abccd00fSHugo Mills 
50948d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
509584dbeb87SDan Carpenter 	if (!args64) {
509684dbeb87SDan Carpenter 		ret = -ENOMEM;
5097abccd00fSHugo Mills 		goto out;
5098abccd00fSHugo Mills 	}
5099abccd00fSHugo Mills 
5100abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5101abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5102abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5103abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5104abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5105abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5106abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5107abccd00fSHugo Mills 	args64->flags = args32->flags;
5108abccd00fSHugo Mills 
5109abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5110abccd00fSHugo Mills 	if (ret)
5111abccd00fSHugo Mills 		goto out;
5112abccd00fSHugo Mills 
5113abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5114abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5115abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5116abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5117abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5118abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5119abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5120abccd00fSHugo Mills 	args32->flags = args64->flags;
5121abccd00fSHugo Mills 
5122abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5123abccd00fSHugo Mills 	if (ret)
5124abccd00fSHugo Mills 		ret = -EFAULT;
5125abccd00fSHugo Mills 
5126abccd00fSHugo Mills out:
5127abccd00fSHugo Mills 	kfree(args32);
5128abccd00fSHugo Mills 	kfree(args64);
5129abccd00fSHugo Mills 	return ret;
5130abccd00fSHugo Mills }
5131abccd00fSHugo Mills #endif
5132abccd00fSHugo Mills 
5133abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5134abccd00fSHugo Mills 					    void __user *arg)
5135abccd00fSHugo Mills {
5136abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5137abccd00fSHugo Mills 	int ret = 0;
5138abccd00fSHugo Mills 
5139abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
51407b9ea627SShailendra Verma 	if (IS_ERR(sa))
51417b9ea627SShailendra Verma 		return PTR_ERR(sa);
5142abccd00fSHugo Mills 
5143abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5144abccd00fSHugo Mills 
5145abccd00fSHugo Mills 	if (ret)
5146abccd00fSHugo Mills 		goto out;
5147abccd00fSHugo Mills 
51488ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
51498ea05e3aSAlexander Block 	if (ret)
51508ea05e3aSAlexander Block 		ret = -EFAULT;
51518ea05e3aSAlexander Block 
51528ea05e3aSAlexander Block out:
51538ea05e3aSAlexander Block 	kfree(sa);
51548ea05e3aSAlexander Block 	return ret;
51558ea05e3aSAlexander Block }
51568ea05e3aSAlexander Block 
5157867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5158867ab667Sjeff.liu {
51590b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5161a1b83ac5SAnand Jain 	size_t len;
5162867ab667Sjeff.liu 	int ret;
5163a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5164a1b83ac5SAnand Jain 
51650b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
51660b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
51670b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
5168a1b83ac5SAnand Jain 
5169a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5170867ab667Sjeff.liu 
5171867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
51720b246afaSJeff Mahoney 		btrfs_warn(fs_info,
51730b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
51740b246afaSJeff Mahoney 			   --len);
5175867ab667Sjeff.liu 	}
5176867ab667Sjeff.liu 
5177867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5178867ab667Sjeff.liu 
5179867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5180867ab667Sjeff.liu }
5181867ab667Sjeff.liu 
5182a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5183a8bfd4abSjeff.liu {
51840b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51860b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
51870b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
5188a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5189a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5190a8bfd4abSjeff.liu 	int ret;
5191a8bfd4abSjeff.liu 
5192a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5193a8bfd4abSjeff.liu 		return -EPERM;
5194a8bfd4abSjeff.liu 
5195a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5196a8bfd4abSjeff.liu 		return -EFAULT;
5197a8bfd4abSjeff.liu 
5198a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
51990b246afaSJeff Mahoney 		btrfs_err(fs_info,
52005d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5201a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5202a8bfd4abSjeff.liu 		return -EINVAL;
5203a8bfd4abSjeff.liu 	}
5204a8bfd4abSjeff.liu 
5205a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5206a8bfd4abSjeff.liu 	if (ret)
5207a8bfd4abSjeff.liu 		return ret;
5208a8bfd4abSjeff.liu 
5209a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5210a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5211a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5212a8bfd4abSjeff.liu 		goto out_unlock;
5213a8bfd4abSjeff.liu 	}
5214a8bfd4abSjeff.liu 
52150b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5216a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
52170b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
52183a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5219a8bfd4abSjeff.liu 
5220a8bfd4abSjeff.liu out_unlock:
5221a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5222a8bfd4abSjeff.liu 	return ret;
5223a8bfd4abSjeff.liu }
5224a8bfd4abSjeff.liu 
52252eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
52262eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
52272eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
52282eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
52292eaa055fSJeff Mahoney 
5230d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
52312eaa055fSJeff Mahoney {
52324d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
52332eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
52342eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
52352eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
52362eaa055fSJeff Mahoney 	};
52372eaa055fSJeff Mahoney 
52382eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
52392eaa055fSJeff Mahoney 		return -EFAULT;
52402eaa055fSJeff Mahoney 
52412eaa055fSJeff Mahoney 	return 0;
52422eaa055fSJeff Mahoney }
52432eaa055fSJeff Mahoney 
52442eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
52452eaa055fSJeff Mahoney {
52460b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52480b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
52492eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
52502eaa055fSJeff Mahoney 
52512eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
52522eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
52532eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
52542eaa055fSJeff Mahoney 
52552eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
52562eaa055fSJeff Mahoney 		return -EFAULT;
52572eaa055fSJeff Mahoney 
52582eaa055fSJeff Mahoney 	return 0;
52592eaa055fSJeff Mahoney }
52602eaa055fSJeff Mahoney 
52612ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
52623b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
52632eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
52642eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
52652eaa055fSJeff Mahoney {
52663b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
52673b02a68aSJeff Mahoney 	char *names;
52682eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
52692eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
52702eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
52712eaa055fSJeff Mahoney 
52722eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
52732eaa055fSJeff Mahoney 	if (unsupported) {
52743b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
52753b02a68aSJeff Mahoney 		if (names) {
52760b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52773b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
52783b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
52793b02a68aSJeff Mahoney 			kfree(names);
52803b02a68aSJeff Mahoney 		} else
52810b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52822eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
52832eaa055fSJeff Mahoney 				   type, unsupported);
52842eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
52852eaa055fSJeff Mahoney 	}
52862eaa055fSJeff Mahoney 
52872eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
52882eaa055fSJeff Mahoney 	if (disallowed) {
52893b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
52903b02a68aSJeff Mahoney 		if (names) {
52910b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52923b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
52933b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
52943b02a68aSJeff Mahoney 			kfree(names);
52953b02a68aSJeff Mahoney 		} else
52960b246afaSJeff Mahoney 			btrfs_warn(fs_info,
52972eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
52982eaa055fSJeff Mahoney 				   type, disallowed);
52992eaa055fSJeff Mahoney 		return -EPERM;
53002eaa055fSJeff Mahoney 	}
53012eaa055fSJeff Mahoney 
53022eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
53032eaa055fSJeff Mahoney 	if (disallowed) {
53043b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
53053b02a68aSJeff Mahoney 		if (names) {
53060b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53073b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
53083b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
53093b02a68aSJeff Mahoney 			kfree(names);
53103b02a68aSJeff Mahoney 		} else
53110b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53122eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
53132eaa055fSJeff Mahoney 				   type, disallowed);
53142eaa055fSJeff Mahoney 		return -EPERM;
53152eaa055fSJeff Mahoney 	}
53162eaa055fSJeff Mahoney 
53172eaa055fSJeff Mahoney 	return 0;
53182eaa055fSJeff Mahoney }
53192eaa055fSJeff Mahoney 
53202ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
53212ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
53222eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
53232eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
53242eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
53252eaa055fSJeff Mahoney 
53262eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
53272eaa055fSJeff Mahoney {
53280b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53290b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53300b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
53310b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
53322eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
53332eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
53342eaa055fSJeff Mahoney 	u64 newflags;
53352eaa055fSJeff Mahoney 	int ret;
53362eaa055fSJeff Mahoney 
53372eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
53382eaa055fSJeff Mahoney 		return -EPERM;
53392eaa055fSJeff Mahoney 
53402eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
53412eaa055fSJeff Mahoney 		return -EFAULT;
53422eaa055fSJeff Mahoney 
53432eaa055fSJeff Mahoney 	/* Nothing to do */
53442eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
53452eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
53462eaa055fSJeff Mahoney 		return 0;
53472eaa055fSJeff Mahoney 
53482ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
53492eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
53502eaa055fSJeff Mahoney 	if (ret)
53512eaa055fSJeff Mahoney 		return ret;
53522eaa055fSJeff Mahoney 
53532ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
53542eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
53552eaa055fSJeff Mahoney 	if (ret)
53562eaa055fSJeff Mahoney 		return ret;
53572eaa055fSJeff Mahoney 
53582ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
53592eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
53602eaa055fSJeff Mahoney 	if (ret)
53612eaa055fSJeff Mahoney 		return ret;
53622eaa055fSJeff Mahoney 
53637ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
53647ab19625SDavid Sterba 	if (ret)
53657ab19625SDavid Sterba 		return ret;
53667ab19625SDavid Sterba 
53678051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
53687ab19625SDavid Sterba 	if (IS_ERR(trans)) {
53697ab19625SDavid Sterba 		ret = PTR_ERR(trans);
53707ab19625SDavid Sterba 		goto out_drop_write;
53717ab19625SDavid Sterba 	}
53722eaa055fSJeff Mahoney 
53730b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
53742eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
53752eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
53762eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
53772eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
53782eaa055fSJeff Mahoney 
53792eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
53802eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
53812eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
53822eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
53832eaa055fSJeff Mahoney 
53842eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
53852eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
53862eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
53872eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
53880b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
53892eaa055fSJeff Mahoney 
53903a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
53917ab19625SDavid Sterba out_drop_write:
53927ab19625SDavid Sterba 	mnt_drop_write_file(file);
53937ab19625SDavid Sterba 
53947ab19625SDavid Sterba 	return ret;
53952eaa055fSJeff Mahoney }
53962eaa055fSJeff Mahoney 
53972351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
53982351f431SJosef Bacik {
53992351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
54002351f431SJosef Bacik 	int ret;
54012351f431SJosef Bacik 
54022351f431SJosef Bacik 	if (compat) {
54032351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
54042351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
54052351f431SJosef Bacik 
54062351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
54072351f431SJosef Bacik 		if (ret)
54082351f431SJosef Bacik 			return -EFAULT;
54092351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
54102351f431SJosef Bacik 		if (!arg)
54112351f431SJosef Bacik 			return -ENOMEM;
54122351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
54132351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
54142351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
54152351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
54162351f431SJosef Bacik 		arg->flags = args32.flags;
54172351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
54182351f431SJosef Bacik 		       sizeof(args32.reserved));
54192351f431SJosef Bacik #else
54202351f431SJosef Bacik 		return -ENOTTY;
54212351f431SJosef Bacik #endif
54222351f431SJosef Bacik 	} else {
54232351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
54242351f431SJosef Bacik 		if (IS_ERR(arg))
54252351f431SJosef Bacik 			return PTR_ERR(arg);
54262351f431SJosef Bacik 	}
54272351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
54282351f431SJosef Bacik 	kfree(arg);
54292351f431SJosef Bacik 	return ret;
54302351f431SJosef Bacik }
54312351f431SJosef Bacik 
5432f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5433f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5434f46b5a66SChristoph Hellwig {
54350b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
54360b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
54370b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
54384bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5439f46b5a66SChristoph Hellwig 
5440f46b5a66SChristoph Hellwig 	switch (cmd) {
54416cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
54426cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
54436cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
54446cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
54456cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
54466cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5447f7039b1dSLi Dongyang 	case FITRIM:
5448f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5449f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5450fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5451fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5452fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
54533de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5454fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
54556f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
54566f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
545776dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
545876dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
54590caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
54600caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
54610caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
54620caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
54636ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
54646ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5465f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
54661e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
54671e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
54681e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5469f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5470198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5471f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
54722ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5473f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5474da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
54756b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
54766b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5477475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
54782ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5479475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
54802ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5481f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
54829ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5483ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5484ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5485cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5486cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5487ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5488ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5489d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5490d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5491d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5492d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5493d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
5494d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
54951406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
54962ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
54979b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
54989b199859SFilipe David Borba Manana 		int ret;
54999b199859SFilipe David Borba Manana 
55000b246afaSJeff Mahoney 		ret = btrfs_start_delalloc_roots(fs_info, 0, -1);
55019b199859SFilipe David Borba Manana 		if (ret)
55029b199859SFilipe David Borba Manana 			return ret;
55030b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
55042fad4e83SDavid Sterba 		/*
55052fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
550601327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
55072fad4e83SDavid Sterba 		 * processing uncleaned subvols.
55082fad4e83SDavid Sterba 		 */
55090b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
55109b199859SFilipe David Borba Manana 		return ret;
55119b199859SFilipe David Borba Manana 	}
551246204592SSage Weil 	case BTRFS_IOC_START_SYNC:
55139a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
551446204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
55152ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5516475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5517b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5518475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
55192ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5520475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
55212ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5522c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
55239ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5524837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
55252ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
552619a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
55272ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
55288ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
55298ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5530abccd00fSHugo Mills #ifdef CONFIG_64BIT
5531abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5532abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5533abccd00fSHugo Mills #endif
553431db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
55352351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
55362351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
55372351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
55382351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
55392351f431SJosef Bacik #endif
5540c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
55412ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
55425d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5543905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
55445d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5545905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
55465d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5547905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
55485d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5549905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
55502f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
55512f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
55522f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
55532f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
555457254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
555557254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
55563f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
55572ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5558867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5559867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5560a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5561a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
55622eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5563d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
55642eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
55652eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
55662eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
55672eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5568f46b5a66SChristoph Hellwig 	}
5569f46b5a66SChristoph Hellwig 
5570f46b5a66SChristoph Hellwig 	return -ENOTTY;
5571f46b5a66SChristoph Hellwig }
55724c63c245SLuke Dashjr 
55734c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
55744c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
55754c63c245SLuke Dashjr {
55762a362249SJeff Mahoney 	/*
55772a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
55782a362249SJeff Mahoney 	 * handling is necessary.
55792a362249SJeff Mahoney 	 */
55804c63c245SLuke Dashjr 	switch (cmd) {
55814c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
55824c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
55834c63c245SLuke Dashjr 		break;
55844c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
55854c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
55864c63c245SLuke Dashjr 		break;
55874c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
55884c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
55894c63c245SLuke Dashjr 		break;
55904c63c245SLuke Dashjr 	}
55914c63c245SLuke Dashjr 
55924c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
55934c63c245SLuke Dashjr }
55944c63c245SLuke Dashjr #endif
5595