xref: /openbmc/linux/fs/btrfs/ioctl.c (revision 8d2db785)
1f46b5a66SChristoph Hellwig /*
2f46b5a66SChristoph Hellwig  * Copyright (C) 2007 Oracle.  All rights reserved.
3f46b5a66SChristoph Hellwig  *
4f46b5a66SChristoph Hellwig  * This program is free software; you can redistribute it and/or
5f46b5a66SChristoph Hellwig  * modify it under the terms of the GNU General Public
6f46b5a66SChristoph Hellwig  * License v2 as published by the Free Software Foundation.
7f46b5a66SChristoph Hellwig  *
8f46b5a66SChristoph Hellwig  * This program is distributed in the hope that it will be useful,
9f46b5a66SChristoph Hellwig  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10f46b5a66SChristoph Hellwig  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11f46b5a66SChristoph Hellwig  * General Public License for more details.
12f46b5a66SChristoph Hellwig  *
13f46b5a66SChristoph Hellwig  * You should have received a copy of the GNU General Public
14f46b5a66SChristoph Hellwig  * License along with this program; if not, write to the
15f46b5a66SChristoph Hellwig  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16f46b5a66SChristoph Hellwig  * Boston, MA 021110-1307, USA.
17f46b5a66SChristoph Hellwig  */
18f46b5a66SChristoph Hellwig 
19f46b5a66SChristoph Hellwig #include <linux/kernel.h>
20f46b5a66SChristoph Hellwig #include <linux/bio.h>
21f46b5a66SChristoph Hellwig #include <linux/buffer_head.h>
22f46b5a66SChristoph Hellwig #include <linux/file.h>
23f46b5a66SChristoph Hellwig #include <linux/fs.h>
24cb8e7090SChristoph Hellwig #include <linux/fsnotify.h>
25f46b5a66SChristoph Hellwig #include <linux/pagemap.h>
26f46b5a66SChristoph Hellwig #include <linux/highmem.h>
27f46b5a66SChristoph Hellwig #include <linux/time.h>
28f46b5a66SChristoph Hellwig #include <linux/init.h>
29f46b5a66SChristoph Hellwig #include <linux/string.h>
30f46b5a66SChristoph Hellwig #include <linux/backing-dev.h>
31cb8e7090SChristoph Hellwig #include <linux/mount.h>
32f46b5a66SChristoph Hellwig #include <linux/mpage.h>
33cb8e7090SChristoph Hellwig #include <linux/namei.h>
34f46b5a66SChristoph Hellwig #include <linux/swap.h>
35f46b5a66SChristoph Hellwig #include <linux/writeback.h>
36f46b5a66SChristoph Hellwig #include <linux/statfs.h>
37f46b5a66SChristoph Hellwig #include <linux/compat.h>
38f46b5a66SChristoph Hellwig #include <linux/bit_spinlock.h>
39cb8e7090SChristoph Hellwig #include <linux/security.h>
40f46b5a66SChristoph Hellwig #include <linux/xattr.h>
417ea394f1SYan Zheng #include <linux/vmalloc.h>
425a0e3ad6STejun Heo #include <linux/slab.h>
43f7039b1dSLi Dongyang #include <linux/blkdev.h>
448ea05e3aSAlexander Block #include <linux/uuid.h>
4555e301fdSFilipe Brandenburger #include <linux/btrfs.h>
46416161dbSMark Fasheh #include <linux/uaccess.h>
47f46b5a66SChristoph Hellwig #include "ctree.h"
48f46b5a66SChristoph Hellwig #include "disk-io.h"
49f46b5a66SChristoph Hellwig #include "transaction.h"
50f46b5a66SChristoph Hellwig #include "btrfs_inode.h"
51f46b5a66SChristoph Hellwig #include "print-tree.h"
52f46b5a66SChristoph Hellwig #include "volumes.h"
53925baeddSChris Mason #include "locking.h"
54581bb050SLi Zefan #include "inode-map.h"
55d7728c96SJan Schmidt #include "backref.h"
56606686eeSJosef Bacik #include "rcu-string.h"
5731db9f7cSAlexander Block #include "send.h"
583f6bcfbdSStefan Behrens #include "dev-replace.h"
5963541927SFilipe David Borba Manana #include "props.h"
603b02a68aSJeff Mahoney #include "sysfs.h"
61fcebe456SJosef Bacik #include "qgroup.h"
62f46b5a66SChristoph Hellwig 
63abccd00fSHugo Mills #ifdef CONFIG_64BIT
64abccd00fSHugo Mills /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
65abccd00fSHugo Mills  * structures are incorrect, as the timespec structure from userspace
66abccd00fSHugo Mills  * is 4 bytes too small. We define these alternatives here to teach
67abccd00fSHugo Mills  * the kernel about the 32-bit struct packing.
68abccd00fSHugo Mills  */
69abccd00fSHugo Mills struct btrfs_ioctl_timespec_32 {
70abccd00fSHugo Mills 	__u64 sec;
71abccd00fSHugo Mills 	__u32 nsec;
72abccd00fSHugo Mills } __attribute__ ((__packed__));
73abccd00fSHugo Mills 
74abccd00fSHugo Mills struct btrfs_ioctl_received_subvol_args_32 {
75abccd00fSHugo Mills 	char	uuid[BTRFS_UUID_SIZE];	/* in */
76abccd00fSHugo Mills 	__u64	stransid;		/* in */
77abccd00fSHugo Mills 	__u64	rtransid;		/* out */
78abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 stime; /* in */
79abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 rtime; /* out */
80abccd00fSHugo Mills 	__u64	flags;			/* in */
81abccd00fSHugo Mills 	__u64	reserved[16];		/* in */
82abccd00fSHugo Mills } __attribute__ ((__packed__));
83abccd00fSHugo Mills 
84abccd00fSHugo Mills #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
85abccd00fSHugo Mills 				struct btrfs_ioctl_received_subvol_args_32)
86abccd00fSHugo Mills #endif
87abccd00fSHugo Mills 
88abccd00fSHugo Mills 
89416161dbSMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
901c919a5eSMark Fasheh 		       u64 off, u64 olen, u64 olen_aligned, u64 destoff,
911c919a5eSMark Fasheh 		       int no_time_update);
92416161dbSMark Fasheh 
936cbff00fSChristoph Hellwig /* Mask out flags that are inappropriate for the given type of inode. */
946cbff00fSChristoph Hellwig static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
956cbff00fSChristoph Hellwig {
966cbff00fSChristoph Hellwig 	if (S_ISDIR(mode))
976cbff00fSChristoph Hellwig 		return flags;
986cbff00fSChristoph Hellwig 	else if (S_ISREG(mode))
996cbff00fSChristoph Hellwig 		return flags & ~FS_DIRSYNC_FL;
1006cbff00fSChristoph Hellwig 	else
1016cbff00fSChristoph Hellwig 		return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
1026cbff00fSChristoph Hellwig }
103f46b5a66SChristoph Hellwig 
1046cbff00fSChristoph Hellwig /*
1056cbff00fSChristoph Hellwig  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
1066cbff00fSChristoph Hellwig  */
1076cbff00fSChristoph Hellwig static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
1086cbff00fSChristoph Hellwig {
1096cbff00fSChristoph Hellwig 	unsigned int iflags = 0;
1106cbff00fSChristoph Hellwig 
1116cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_SYNC)
1126cbff00fSChristoph Hellwig 		iflags |= FS_SYNC_FL;
1136cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_IMMUTABLE)
1146cbff00fSChristoph Hellwig 		iflags |= FS_IMMUTABLE_FL;
1156cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_APPEND)
1166cbff00fSChristoph Hellwig 		iflags |= FS_APPEND_FL;
1176cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NODUMP)
1186cbff00fSChristoph Hellwig 		iflags |= FS_NODUMP_FL;
1196cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NOATIME)
1206cbff00fSChristoph Hellwig 		iflags |= FS_NOATIME_FL;
1216cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_DIRSYNC)
1226cbff00fSChristoph Hellwig 		iflags |= FS_DIRSYNC_FL;
123d0092bddSLi Zefan 	if (flags & BTRFS_INODE_NODATACOW)
124d0092bddSLi Zefan 		iflags |= FS_NOCOW_FL;
125d0092bddSLi Zefan 
126d0092bddSLi Zefan 	if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
127d0092bddSLi Zefan 		iflags |= FS_COMPR_FL;
128d0092bddSLi Zefan 	else if (flags & BTRFS_INODE_NOCOMPRESS)
129d0092bddSLi Zefan 		iflags |= FS_NOCOMP_FL;
1306cbff00fSChristoph Hellwig 
1316cbff00fSChristoph Hellwig 	return iflags;
1326cbff00fSChristoph Hellwig }
1336cbff00fSChristoph Hellwig 
1346cbff00fSChristoph Hellwig /*
1356cbff00fSChristoph Hellwig  * Update inode->i_flags based on the btrfs internal flags.
1366cbff00fSChristoph Hellwig  */
1376cbff00fSChristoph Hellwig void btrfs_update_iflags(struct inode *inode)
1386cbff00fSChristoph Hellwig {
1396cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
1403cc79392SFilipe Manana 	unsigned int new_fl = 0;
1416cbff00fSChristoph Hellwig 
1426cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_SYNC)
1433cc79392SFilipe Manana 		new_fl |= S_SYNC;
1446cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_IMMUTABLE)
1453cc79392SFilipe Manana 		new_fl |= S_IMMUTABLE;
1466cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_APPEND)
1473cc79392SFilipe Manana 		new_fl |= S_APPEND;
1486cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_NOATIME)
1493cc79392SFilipe Manana 		new_fl |= S_NOATIME;
1506cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_DIRSYNC)
1513cc79392SFilipe Manana 		new_fl |= S_DIRSYNC;
1523cc79392SFilipe Manana 
1533cc79392SFilipe Manana 	set_mask_bits(&inode->i_flags,
1543cc79392SFilipe Manana 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
1553cc79392SFilipe Manana 		      new_fl);
1566cbff00fSChristoph Hellwig }
1576cbff00fSChristoph Hellwig 
1586cbff00fSChristoph Hellwig /*
1596cbff00fSChristoph Hellwig  * Inherit flags from the parent inode.
1606cbff00fSChristoph Hellwig  *
161e27425d6SJosef Bacik  * Currently only the compression flags and the cow flags are inherited.
1626cbff00fSChristoph Hellwig  */
1636cbff00fSChristoph Hellwig void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
1646cbff00fSChristoph Hellwig {
1650b4dcea5SChris Mason 	unsigned int flags;
1660b4dcea5SChris Mason 
1670b4dcea5SChris Mason 	if (!dir)
1680b4dcea5SChris Mason 		return;
1690b4dcea5SChris Mason 
1700b4dcea5SChris Mason 	flags = BTRFS_I(dir)->flags;
1716cbff00fSChristoph Hellwig 
172e27425d6SJosef Bacik 	if (flags & BTRFS_INODE_NOCOMPRESS) {
173e27425d6SJosef Bacik 		BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
174e27425d6SJosef Bacik 		BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
175e27425d6SJosef Bacik 	} else if (flags & BTRFS_INODE_COMPRESS) {
176e27425d6SJosef Bacik 		BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
177e27425d6SJosef Bacik 		BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
178e27425d6SJosef Bacik 	}
1796cbff00fSChristoph Hellwig 
180213490b3SLiu Bo 	if (flags & BTRFS_INODE_NODATACOW) {
181e27425d6SJosef Bacik 		BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
182213490b3SLiu Bo 		if (S_ISREG(inode->i_mode))
183213490b3SLiu Bo 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
184213490b3SLiu Bo 	}
185e27425d6SJosef Bacik 
1866cbff00fSChristoph Hellwig 	btrfs_update_iflags(inode);
1876cbff00fSChristoph Hellwig }
1886cbff00fSChristoph Hellwig 
1896cbff00fSChristoph Hellwig static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
1906cbff00fSChristoph Hellwig {
191496ad9aaSAl Viro 	struct btrfs_inode *ip = BTRFS_I(file_inode(file));
1926cbff00fSChristoph Hellwig 	unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
1936cbff00fSChristoph Hellwig 
1946cbff00fSChristoph Hellwig 	if (copy_to_user(arg, &flags, sizeof(flags)))
1956cbff00fSChristoph Hellwig 		return -EFAULT;
1966cbff00fSChristoph Hellwig 	return 0;
1976cbff00fSChristoph Hellwig }
1986cbff00fSChristoph Hellwig 
19975e7cb7fSLiu Bo static int check_flags(unsigned int flags)
20075e7cb7fSLiu Bo {
20175e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
20275e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
20375e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
204e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
205e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
20675e7cb7fSLiu Bo 		return -EOPNOTSUPP;
20775e7cb7fSLiu Bo 
20875e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
20975e7cb7fSLiu Bo 		return -EINVAL;
21075e7cb7fSLiu Bo 
21175e7cb7fSLiu Bo 	return 0;
21275e7cb7fSLiu Bo }
21375e7cb7fSLiu Bo 
2146cbff00fSChristoph Hellwig static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
2156cbff00fSChristoph Hellwig {
216496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2176cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
2186cbff00fSChristoph Hellwig 	struct btrfs_root *root = ip->root;
2196cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
2206cbff00fSChristoph Hellwig 	unsigned int flags, oldflags;
2216cbff00fSChristoph Hellwig 	int ret;
222f062abf0SLi Zefan 	u64 ip_oldflags;
223f062abf0SLi Zefan 	unsigned int i_oldflags;
2247e97b8daSDavid Sterba 	umode_t mode;
2256cbff00fSChristoph Hellwig 
226bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
227bd60ea0fSDavid Sterba 		return -EPERM;
228bd60ea0fSDavid Sterba 
229b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
230b83cc969SLi Zefan 		return -EROFS;
231b83cc969SLi Zefan 
2326cbff00fSChristoph Hellwig 	if (copy_from_user(&flags, arg, sizeof(flags)))
2336cbff00fSChristoph Hellwig 		return -EFAULT;
2346cbff00fSChristoph Hellwig 
23575e7cb7fSLiu Bo 	ret = check_flags(flags);
23675e7cb7fSLiu Bo 	if (ret)
23775e7cb7fSLiu Bo 		return ret;
2386cbff00fSChristoph Hellwig 
239e7848683SJan Kara 	ret = mnt_want_write_file(file);
240e7848683SJan Kara 	if (ret)
241e7848683SJan Kara 		return ret;
242e7848683SJan Kara 
2436cbff00fSChristoph Hellwig 	mutex_lock(&inode->i_mutex);
2446cbff00fSChristoph Hellwig 
245f062abf0SLi Zefan 	ip_oldflags = ip->flags;
246f062abf0SLi Zefan 	i_oldflags = inode->i_flags;
2477e97b8daSDavid Sterba 	mode = inode->i_mode;
248f062abf0SLi Zefan 
2496cbff00fSChristoph Hellwig 	flags = btrfs_mask_flags(inode->i_mode, flags);
2506cbff00fSChristoph Hellwig 	oldflags = btrfs_flags_to_ioctl(ip->flags);
2516cbff00fSChristoph Hellwig 	if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
2526cbff00fSChristoph Hellwig 		if (!capable(CAP_LINUX_IMMUTABLE)) {
2536cbff00fSChristoph Hellwig 			ret = -EPERM;
2546cbff00fSChristoph Hellwig 			goto out_unlock;
2556cbff00fSChristoph Hellwig 		}
2566cbff00fSChristoph Hellwig 	}
2576cbff00fSChristoph Hellwig 
2586cbff00fSChristoph Hellwig 	if (flags & FS_SYNC_FL)
2596cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_SYNC;
2606cbff00fSChristoph Hellwig 	else
2616cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_SYNC;
2626cbff00fSChristoph Hellwig 	if (flags & FS_IMMUTABLE_FL)
2636cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_IMMUTABLE;
2646cbff00fSChristoph Hellwig 	else
2656cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_IMMUTABLE;
2666cbff00fSChristoph Hellwig 	if (flags & FS_APPEND_FL)
2676cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_APPEND;
2686cbff00fSChristoph Hellwig 	else
2696cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_APPEND;
2706cbff00fSChristoph Hellwig 	if (flags & FS_NODUMP_FL)
2716cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NODUMP;
2726cbff00fSChristoph Hellwig 	else
2736cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NODUMP;
2746cbff00fSChristoph Hellwig 	if (flags & FS_NOATIME_FL)
2756cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NOATIME;
2766cbff00fSChristoph Hellwig 	else
2776cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NOATIME;
2786cbff00fSChristoph Hellwig 	if (flags & FS_DIRSYNC_FL)
2796cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_DIRSYNC;
2806cbff00fSChristoph Hellwig 	else
2816cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_DIRSYNC;
2827e97b8daSDavid Sterba 	if (flags & FS_NOCOW_FL) {
2837e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2847e97b8daSDavid Sterba 			/*
2857e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2867e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2877e97b8daSDavid Sterba 			 * status of the file and will not set it.
2887e97b8daSDavid Sterba 			 */
2897e97b8daSDavid Sterba 			if (inode->i_size == 0)
2907e97b8daSDavid Sterba 				ip->flags |= BTRFS_INODE_NODATACOW
2917e97b8daSDavid Sterba 					   | BTRFS_INODE_NODATASUM;
2927e97b8daSDavid Sterba 		} else {
293e1e8fb6aSLi Zefan 			ip->flags |= BTRFS_INODE_NODATACOW;
2947e97b8daSDavid Sterba 		}
2957e97b8daSDavid Sterba 	} else {
2967e97b8daSDavid Sterba 		/*
2977e97b8daSDavid Sterba 		 * Revert back under same assuptions as above
2987e97b8daSDavid Sterba 		 */
2997e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
3007e97b8daSDavid Sterba 			if (inode->i_size == 0)
3017e97b8daSDavid Sterba 				ip->flags &= ~(BTRFS_INODE_NODATACOW
3027e97b8daSDavid Sterba 				             | BTRFS_INODE_NODATASUM);
3037e97b8daSDavid Sterba 		} else {
304e1e8fb6aSLi Zefan 			ip->flags &= ~BTRFS_INODE_NODATACOW;
3057e97b8daSDavid Sterba 		}
3067e97b8daSDavid Sterba 	}
3076cbff00fSChristoph Hellwig 
30875e7cb7fSLiu Bo 	/*
30975e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
31075e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
31175e7cb7fSLiu Bo 	 * things smaller.
31275e7cb7fSLiu Bo 	 */
31375e7cb7fSLiu Bo 	if (flags & FS_NOCOMP_FL) {
31475e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_COMPRESS;
31575e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_NOCOMPRESS;
31663541927SFilipe David Borba Manana 
31763541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
31863541927SFilipe David Borba Manana 		if (ret && ret != -ENODATA)
31963541927SFilipe David Borba Manana 			goto out_drop;
32075e7cb7fSLiu Bo 	} else if (flags & FS_COMPR_FL) {
32163541927SFilipe David Borba Manana 		const char *comp;
32263541927SFilipe David Borba Manana 
32375e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_COMPRESS;
32475e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
32563541927SFilipe David Borba Manana 
32663541927SFilipe David Borba Manana 		if (root->fs_info->compress_type == BTRFS_COMPRESS_LZO)
32763541927SFilipe David Borba Manana 			comp = "lzo";
32863541927SFilipe David Borba Manana 		else
32963541927SFilipe David Borba Manana 			comp = "zlib";
33063541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression",
33163541927SFilipe David Borba Manana 				     comp, strlen(comp), 0);
33263541927SFilipe David Borba Manana 		if (ret)
33363541927SFilipe David Borba Manana 			goto out_drop;
33463541927SFilipe David Borba Manana 
335ebcb904dSLi Zefan 	} else {
33678a017a2SFilipe Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
33778a017a2SFilipe Manana 		if (ret && ret != -ENODATA)
33878a017a2SFilipe Manana 			goto out_drop;
339ebcb904dSLi Zefan 		ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
34075e7cb7fSLiu Bo 	}
3416cbff00fSChristoph Hellwig 
3424da6f1a3SLi Zefan 	trans = btrfs_start_transaction(root, 1);
343f062abf0SLi Zefan 	if (IS_ERR(trans)) {
344f062abf0SLi Zefan 		ret = PTR_ERR(trans);
345f062abf0SLi Zefan 		goto out_drop;
346f062abf0SLi Zefan 	}
3476cbff00fSChristoph Hellwig 
348306424ccSLi Zefan 	btrfs_update_iflags(inode);
3490c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
350306424ccSLi Zefan 	inode->i_ctime = CURRENT_TIME;
3516cbff00fSChristoph Hellwig 	ret = btrfs_update_inode(trans, root, inode);
3526cbff00fSChristoph Hellwig 
3536cbff00fSChristoph Hellwig 	btrfs_end_transaction(trans, root);
354f062abf0SLi Zefan  out_drop:
355f062abf0SLi Zefan 	if (ret) {
356f062abf0SLi Zefan 		ip->flags = ip_oldflags;
357f062abf0SLi Zefan 		inode->i_flags = i_oldflags;
358f062abf0SLi Zefan 	}
3596cbff00fSChristoph Hellwig 
3606cbff00fSChristoph Hellwig  out_unlock:
3616cbff00fSChristoph Hellwig 	mutex_unlock(&inode->i_mutex);
362e7848683SJan Kara 	mnt_drop_write_file(file);
3632d4e6f6aSliubo 	return ret;
3646cbff00fSChristoph Hellwig }
3656cbff00fSChristoph Hellwig 
3666cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
3676cbff00fSChristoph Hellwig {
368496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3696cbff00fSChristoph Hellwig 
3706cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
3716cbff00fSChristoph Hellwig }
372f46b5a66SChristoph Hellwig 
373f7039b1dSLi Dongyang static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
374f7039b1dSLi Dongyang {
37554563d41SAl Viro 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
376f7039b1dSLi Dongyang 	struct btrfs_device *device;
377f7039b1dSLi Dongyang 	struct request_queue *q;
378f7039b1dSLi Dongyang 	struct fstrim_range range;
379f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
380f7039b1dSLi Dongyang 	u64 num_devices = 0;
381815745cfSAl Viro 	u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
382f7039b1dSLi Dongyang 	int ret;
383f7039b1dSLi Dongyang 
384f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
385f7039b1dSLi Dongyang 		return -EPERM;
386f7039b1dSLi Dongyang 
3871f78160cSXiao Guangrong 	rcu_read_lock();
3881f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
3891f78160cSXiao Guangrong 				dev_list) {
390f7039b1dSLi Dongyang 		if (!device->bdev)
391f7039b1dSLi Dongyang 			continue;
392f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
393f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
394f7039b1dSLi Dongyang 			num_devices++;
395f7039b1dSLi Dongyang 			minlen = min((u64)q->limits.discard_granularity,
396f7039b1dSLi Dongyang 				     minlen);
397f7039b1dSLi Dongyang 		}
398f7039b1dSLi Dongyang 	}
3991f78160cSXiao Guangrong 	rcu_read_unlock();
400f4c697e6SLukas Czerner 
401f7039b1dSLi Dongyang 	if (!num_devices)
402f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
403f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
404f7039b1dSLi Dongyang 		return -EFAULT;
405e515c18bSLukas Czerner 	if (range.start > total_bytes ||
406e515c18bSLukas Czerner 	    range.len < fs_info->sb->s_blocksize)
407f4c697e6SLukas Czerner 		return -EINVAL;
408f7039b1dSLi Dongyang 
409f4c697e6SLukas Czerner 	range.len = min(range.len, total_bytes - range.start);
410f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
411815745cfSAl Viro 	ret = btrfs_trim_fs(fs_info->tree_root, &range);
412f7039b1dSLi Dongyang 	if (ret < 0)
413f7039b1dSLi Dongyang 		return ret;
414f7039b1dSLi Dongyang 
415f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
416f7039b1dSLi Dongyang 		return -EFAULT;
417f7039b1dSLi Dongyang 
418f7039b1dSLi Dongyang 	return 0;
419f7039b1dSLi Dongyang }
420f7039b1dSLi Dongyang 
421dd5f9615SStefan Behrens int btrfs_is_empty_uuid(u8 *uuid)
422dd5f9615SStefan Behrens {
42346e0f66aSChris Mason 	int i;
42446e0f66aSChris Mason 
42546e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
42646e0f66aSChris Mason 		if (uuid[i])
42746e0f66aSChris Mason 			return 0;
42846e0f66aSChris Mason 	}
42946e0f66aSChris Mason 	return 1;
430dd5f9615SStefan Behrens }
431dd5f9615SStefan Behrens 
432d5c12070SMiao Xie static noinline int create_subvol(struct inode *dir,
433cb8e7090SChristoph Hellwig 				  struct dentry *dentry,
43472fd032eSSage Weil 				  char *name, int namelen,
4356f72c7e2SArne Jansen 				  u64 *async_transid,
4368696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
437f46b5a66SChristoph Hellwig {
438f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
439f46b5a66SChristoph Hellwig 	struct btrfs_key key;
440f46b5a66SChristoph Hellwig 	struct btrfs_root_item root_item;
441f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
442f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
443d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
44476dda93cSYan, Zheng 	struct btrfs_root *new_root;
445d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
4468ea05e3aSAlexander Block 	struct timespec cur_time = CURRENT_TIME;
4475662344bSTsutomu Itoh 	struct inode *inode;
448f46b5a66SChristoph Hellwig 	int ret;
449f46b5a66SChristoph Hellwig 	int err;
450f46b5a66SChristoph Hellwig 	u64 objectid;
451f46b5a66SChristoph Hellwig 	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
4523de4586cSChris Mason 	u64 index = 0;
453d5c12070SMiao Xie 	u64 qgroup_reserved;
4548ea05e3aSAlexander Block 	uuid_le new_uuid;
455f46b5a66SChristoph Hellwig 
456581bb050SLi Zefan 	ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
4572fbe8c8aSAl Viro 	if (ret)
458a22285a6SYan, Zheng 		return ret;
4596a912213SJosef Bacik 
460e09fe2d2SQu Wenruo 	/*
461e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
462e09fe2d2SQu Wenruo 	 * screwed up since it assume subvolme qgroup's level to be 0.
463e09fe2d2SQu Wenruo 	 */
464e09fe2d2SQu Wenruo 	if (btrfs_qgroup_level(objectid))
465e09fe2d2SQu Wenruo 		return -ENOSPC;
466e09fe2d2SQu Wenruo 
467d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4689ed74f2dSJosef Bacik 	/*
469d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
470d5c12070SMiao Xie 	 * of create_snapshot().
4719ed74f2dSJosef Bacik 	 */
472d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
473dd5f9615SStefan Behrens 					       8, &qgroup_reserved, false);
474d5c12070SMiao Xie 	if (ret)
475d5c12070SMiao Xie 		return ret;
476f46b5a66SChristoph Hellwig 
477d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
478d5c12070SMiao Xie 	if (IS_ERR(trans)) {
479d5c12070SMiao Xie 		ret = PTR_ERR(trans);
480de6e8200SLiu Bo 		btrfs_subvolume_release_metadata(root, &block_rsv,
481de6e8200SLiu Bo 						 qgroup_reserved);
482de6e8200SLiu Bo 		return ret;
483d5c12070SMiao Xie 	}
484d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
485d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
486f46b5a66SChristoph Hellwig 
4878696c533SMiao Xie 	ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit);
4886f72c7e2SArne Jansen 	if (ret)
4896f72c7e2SArne Jansen 		goto fail;
4906f72c7e2SArne Jansen 
4914d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
4928e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
4938e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
4948e8a1e31SJosef Bacik 		goto fail;
4958e8a1e31SJosef Bacik 	}
496f46b5a66SChristoph Hellwig 
4975d4f98a2SYan Zheng 	memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
498f46b5a66SChristoph Hellwig 	btrfs_set_header_bytenr(leaf, leaf->start);
499f46b5a66SChristoph Hellwig 	btrfs_set_header_generation(leaf, trans->transid);
5005d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
501f46b5a66SChristoph Hellwig 	btrfs_set_header_owner(leaf, objectid);
502f46b5a66SChristoph Hellwig 
5030a4e5586SRoss Kirk 	write_extent_buffer(leaf, root->fs_info->fsid, btrfs_header_fsid(),
504f46b5a66SChristoph Hellwig 			    BTRFS_FSID_SIZE);
5055d4f98a2SYan Zheng 	write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
506b308bc2fSGeert Uytterhoeven 			    btrfs_header_chunk_tree_uuid(leaf),
5075d4f98a2SYan Zheng 			    BTRFS_UUID_SIZE);
508f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
509f46b5a66SChristoph Hellwig 
5108ea05e3aSAlexander Block 	memset(&root_item, 0, sizeof(root_item));
5118ea05e3aSAlexander Block 
512f46b5a66SChristoph Hellwig 	inode_item = &root_item.inode;
5133cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
5143cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
5153cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
516707e8a07SDavid Sterba 	btrfs_set_stack_inode_nbytes(inode_item, root->nodesize);
5173cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
518f46b5a66SChristoph Hellwig 
5193cae210fSQu Wenruo 	btrfs_set_root_flags(&root_item, 0);
5203cae210fSQu Wenruo 	btrfs_set_root_limit(&root_item, 0);
5213cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
52208fe4db1SLi Zefan 
523f46b5a66SChristoph Hellwig 	btrfs_set_root_bytenr(&root_item, leaf->start);
52484234f3aSYan Zheng 	btrfs_set_root_generation(&root_item, trans->transid);
525f46b5a66SChristoph Hellwig 	btrfs_set_root_level(&root_item, 0);
526f46b5a66SChristoph Hellwig 	btrfs_set_root_refs(&root_item, 1);
52786b9f2ecSYan, Zheng 	btrfs_set_root_used(&root_item, leaf->len);
52880ff3856SYan Zheng 	btrfs_set_root_last_snapshot(&root_item, 0);
529f46b5a66SChristoph Hellwig 
5308ea05e3aSAlexander Block 	btrfs_set_root_generation_v2(&root_item,
5318ea05e3aSAlexander Block 			btrfs_root_generation(&root_item));
5328ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
5338ea05e3aSAlexander Block 	memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE);
5343cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item.otime, cur_time.tv_sec);
5353cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item.otime, cur_time.tv_nsec);
5368ea05e3aSAlexander Block 	root_item.ctime = root_item.otime;
5378ea05e3aSAlexander Block 	btrfs_set_root_ctransid(&root_item, trans->transid);
5388ea05e3aSAlexander Block 	btrfs_set_root_otransid(&root_item, trans->transid);
539f46b5a66SChristoph Hellwig 
540925baeddSChris Mason 	btrfs_tree_unlock(leaf);
541f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
542f46b5a66SChristoph Hellwig 	leaf = NULL;
543f46b5a66SChristoph Hellwig 
544f46b5a66SChristoph Hellwig 	btrfs_set_root_dirid(&root_item, new_dirid);
545f46b5a66SChristoph Hellwig 
546f46b5a66SChristoph Hellwig 	key.objectid = objectid;
5475d4f98a2SYan Zheng 	key.offset = 0;
548962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
549f46b5a66SChristoph Hellwig 	ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
550f46b5a66SChristoph Hellwig 				&root_item);
551f46b5a66SChristoph Hellwig 	if (ret)
552f46b5a66SChristoph Hellwig 		goto fail;
553f46b5a66SChristoph Hellwig 
55476dda93cSYan, Zheng 	key.offset = (u64)-1;
55576dda93cSYan, Zheng 	new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
55679787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
55779787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
5586d13f549SDavid Sterba 		btrfs_abort_transaction(trans, root, ret);
55979787eaaSJeff Mahoney 		goto fail;
56079787eaaSJeff Mahoney 	}
56176dda93cSYan, Zheng 
56276dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
56376dda93cSYan, Zheng 
56463541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
565ce598979SMark Fasheh 	if (ret) {
566ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
56779787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
568ce598979SMark Fasheh 		goto fail;
569ce598979SMark Fasheh 	}
570ce598979SMark Fasheh 
571f46b5a66SChristoph Hellwig 	/*
572f46b5a66SChristoph Hellwig 	 * insert the directory item
573f46b5a66SChristoph Hellwig 	 */
5743de4586cSChris Mason 	ret = btrfs_set_inode_index(dir, &index);
57579787eaaSJeff Mahoney 	if (ret) {
57679787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
57779787eaaSJeff Mahoney 		goto fail;
57879787eaaSJeff Mahoney 	}
5793de4586cSChris Mason 
5803de4586cSChris Mason 	ret = btrfs_insert_dir_item(trans, root,
58116cdcec7SMiao Xie 				    name, namelen, dir, &key,
5823de4586cSChris Mason 				    BTRFS_FT_DIR, index);
58379787eaaSJeff Mahoney 	if (ret) {
58479787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
585f46b5a66SChristoph Hellwig 		goto fail;
58679787eaaSJeff Mahoney 	}
5870660b5afSChris Mason 
58852c26179SYan Zheng 	btrfs_i_size_write(dir, dir->i_size + namelen * 2);
58952c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
59052c26179SYan Zheng 	BUG_ON(ret);
59152c26179SYan Zheng 
5920660b5afSChris Mason 	ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5934df27c4dSYan, Zheng 				 objectid, root->root_key.objectid,
59433345d01SLi Zefan 				 btrfs_ino(dir), index, name, namelen);
5950660b5afSChris Mason 	BUG_ON(ret);
5960660b5afSChris Mason 
597dd5f9615SStefan Behrens 	ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
598dd5f9615SStefan Behrens 				  root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
599dd5f9615SStefan Behrens 				  objectid);
600dd5f9615SStefan Behrens 	if (ret)
601dd5f9615SStefan Behrens 		btrfs_abort_transaction(trans, root, ret);
602dd5f9615SStefan Behrens 
603f46b5a66SChristoph Hellwig fail:
604d5c12070SMiao Xie 	trans->block_rsv = NULL;
605d5c12070SMiao Xie 	trans->bytes_reserved = 0;
606de6e8200SLiu Bo 	btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
607de6e8200SLiu Bo 
60872fd032eSSage Weil 	if (async_transid) {
60972fd032eSSage Weil 		*async_transid = trans->transid;
61072fd032eSSage Weil 		err = btrfs_commit_transaction_async(trans, root, 1);
61100d71c9cSMiao Xie 		if (err)
61200d71c9cSMiao Xie 			err = btrfs_commit_transaction(trans, root);
61372fd032eSSage Weil 	} else {
61476dda93cSYan, Zheng 		err = btrfs_commit_transaction(trans, root);
61572fd032eSSage Weil 	}
616f46b5a66SChristoph Hellwig 	if (err && !ret)
617f46b5a66SChristoph Hellwig 		ret = err;
6181a65e24bSChris Mason 
6195662344bSTsutomu Itoh 	if (!ret) {
6205662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
621de6e8200SLiu Bo 		if (IS_ERR(inode))
622de6e8200SLiu Bo 			return PTR_ERR(inode);
6235662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
6245662344bSTsutomu Itoh 	}
625f46b5a66SChristoph Hellwig 	return ret;
626f46b5a66SChristoph Hellwig }
627f46b5a66SChristoph Hellwig 
6289ea24bbeSFilipe Manana static void btrfs_wait_for_no_snapshoting_writes(struct btrfs_root *root)
6298257b2dcSMiao Xie {
6308257b2dcSMiao Xie 	s64 writers;
6318257b2dcSMiao Xie 	DEFINE_WAIT(wait);
6328257b2dcSMiao Xie 
6338257b2dcSMiao Xie 	do {
6348257b2dcSMiao Xie 		prepare_to_wait(&root->subv_writers->wait, &wait,
6358257b2dcSMiao Xie 				TASK_UNINTERRUPTIBLE);
6368257b2dcSMiao Xie 
6378257b2dcSMiao Xie 		writers = percpu_counter_sum(&root->subv_writers->counter);
6388257b2dcSMiao Xie 		if (writers)
6398257b2dcSMiao Xie 			schedule();
6408257b2dcSMiao Xie 
6418257b2dcSMiao Xie 		finish_wait(&root->subv_writers->wait, &wait);
6428257b2dcSMiao Xie 	} while (writers);
6438257b2dcSMiao Xie }
6448257b2dcSMiao Xie 
645e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
646e9662f70SMiao Xie 			   struct dentry *dentry, char *name, int namelen,
647e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
648e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
649f46b5a66SChristoph Hellwig {
6502e4bfab9SYan, Zheng 	struct inode *inode;
651f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
652f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
6532e4bfab9SYan, Zheng 	int ret;
654f46b5a66SChristoph Hellwig 
65527cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
656f46b5a66SChristoph Hellwig 		return -EINVAL;
657f46b5a66SChristoph Hellwig 
6588257b2dcSMiao Xie 	atomic_inc(&root->will_be_snapshoted);
6594e857c58SPeter Zijlstra 	smp_mb__after_atomic();
6609ea24bbeSFilipe Manana 	btrfs_wait_for_no_snapshoting_writes(root);
6618257b2dcSMiao Xie 
6626a03843dSMiao Xie 	ret = btrfs_start_delalloc_inodes(root, 0);
6636a03843dSMiao Xie 	if (ret)
6648257b2dcSMiao Xie 		goto out;
6656a03843dSMiao Xie 
666b0244199SMiao Xie 	btrfs_wait_ordered_extents(root, -1);
6676a03843dSMiao Xie 
668a22285a6SYan, Zheng 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
6698257b2dcSMiao Xie 	if (!pending_snapshot) {
6708257b2dcSMiao Xie 		ret = -ENOMEM;
6718257b2dcSMiao Xie 		goto out;
6728257b2dcSMiao Xie 	}
673a22285a6SYan, Zheng 
67466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
67566d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
676d5c12070SMiao Xie 	/*
677d5c12070SMiao Xie 	 * 1 - parent dir inode
678d5c12070SMiao Xie 	 * 2 - dir entries
679d5c12070SMiao Xie 	 * 1 - root item
680d5c12070SMiao Xie 	 * 2 - root ref/backref
681d5c12070SMiao Xie 	 * 1 - root of snapshot
682dd5f9615SStefan Behrens 	 * 1 - UUID item
683d5c12070SMiao Xie 	 */
684d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
685dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
686ee3441b4SJeff Mahoney 					&pending_snapshot->qgroup_reserved,
687ee3441b4SJeff Mahoney 					false);
688d5c12070SMiao Xie 	if (ret)
6898257b2dcSMiao Xie 		goto free;
690d5c12070SMiao Xie 
691a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
692a22285a6SYan, Zheng 	pending_snapshot->root = root;
693b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
694e9662f70SMiao Xie 	pending_snapshot->dir = dir;
6958696c533SMiao Xie 	pending_snapshot->inherit = inherit;
696a22285a6SYan, Zheng 
697d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
698a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
699a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
700a22285a6SYan, Zheng 		goto fail;
701a22285a6SYan, Zheng 	}
702a22285a6SYan, Zheng 
7038351583eSJosef Bacik 	spin_lock(&root->fs_info->trans_lock);
704a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
705a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
7068351583eSJosef Bacik 	spin_unlock(&root->fs_info->trans_lock);
70772fd032eSSage Weil 	if (async_transid) {
70872fd032eSSage Weil 		*async_transid = trans->transid;
70972fd032eSSage Weil 		ret = btrfs_commit_transaction_async(trans,
71072fd032eSSage Weil 				     root->fs_info->extent_root, 1);
71100d71c9cSMiao Xie 		if (ret)
71200d71c9cSMiao Xie 			ret = btrfs_commit_transaction(trans, root);
71372fd032eSSage Weil 	} else {
71472fd032eSSage Weil 		ret = btrfs_commit_transaction(trans,
71572fd032eSSage Weil 					       root->fs_info->extent_root);
71672fd032eSSage Weil 	}
717aec8030aSMiao Xie 	if (ret)
718c37b2b62SJosef Bacik 		goto fail;
719a22285a6SYan, Zheng 
720a22285a6SYan, Zheng 	ret = pending_snapshot->error;
721f46b5a66SChristoph Hellwig 	if (ret)
7222e4bfab9SYan, Zheng 		goto fail;
723f46b5a66SChristoph Hellwig 
724d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
725d3797308SChris Mason 	if (ret)
726d3797308SChris Mason 		goto fail;
727d3797308SChris Mason 
7282b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
7292e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
7302e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
7312e4bfab9SYan, Zheng 		goto fail;
7322e4bfab9SYan, Zheng 	}
7335662344bSTsutomu Itoh 
7342e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
7352e4bfab9SYan, Zheng 	ret = 0;
7362e4bfab9SYan, Zheng fail:
737d5c12070SMiao Xie 	btrfs_subvolume_release_metadata(BTRFS_I(dir)->root,
738d5c12070SMiao Xie 					 &pending_snapshot->block_rsv,
739d5c12070SMiao Xie 					 pending_snapshot->qgroup_reserved);
7408257b2dcSMiao Xie free:
741a22285a6SYan, Zheng 	kfree(pending_snapshot);
7428257b2dcSMiao Xie out:
7439ea24bbeSFilipe Manana 	if (atomic_dec_and_test(&root->will_be_snapshoted))
7449ea24bbeSFilipe Manana 		wake_up_atomic_t(&root->will_be_snapshoted);
745f46b5a66SChristoph Hellwig 	return ret;
746f46b5a66SChristoph Hellwig }
747f46b5a66SChristoph Hellwig 
7484260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
7494260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
7504260f7c7SSage Weil  *  whether the type of victim is right.
7514260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
7524260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
7534260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
7544260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
7554260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
7564260f7c7SSage Weil  *	a. be owner of dir, or
7574260f7c7SSage Weil  *	b. be owner of victim, or
7584260f7c7SSage Weil  *	c. have CAP_FOWNER capability
7594260f7c7SSage Weil  *  6. If the victim is append-only or immutable we can't do antyhing with
7604260f7c7SSage Weil  *     links pointing to it.
7614260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
7624260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
7634260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
7644260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
7654260f7c7SSage Weil  *     nfs_async_unlink().
7664260f7c7SSage Weil  */
7674260f7c7SSage Weil 
7684260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
7694260f7c7SSage Weil {
7704260f7c7SSage Weil 	int error;
7714260f7c7SSage Weil 
7722b0143b5SDavid Howells 	if (d_really_is_negative(victim))
7734260f7c7SSage Weil 		return -ENOENT;
7744260f7c7SSage Weil 
7752b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
7764fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
7774260f7c7SSage Weil 
7784260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
7794260f7c7SSage Weil 	if (error)
7804260f7c7SSage Weil 		return error;
7814260f7c7SSage Weil 	if (IS_APPEND(dir))
7824260f7c7SSage Weil 		return -EPERM;
7832b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
7842b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
7854260f7c7SSage Weil 		return -EPERM;
7864260f7c7SSage Weil 	if (isdir) {
787e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
7884260f7c7SSage Weil 			return -ENOTDIR;
7894260f7c7SSage Weil 		if (IS_ROOT(victim))
7904260f7c7SSage Weil 			return -EBUSY;
791e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
7924260f7c7SSage Weil 		return -EISDIR;
7934260f7c7SSage Weil 	if (IS_DEADDIR(dir))
7944260f7c7SSage Weil 		return -ENOENT;
7954260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
7964260f7c7SSage Weil 		return -EBUSY;
7974260f7c7SSage Weil 	return 0;
7984260f7c7SSage Weil }
7994260f7c7SSage Weil 
800cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
801cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
802cb8e7090SChristoph Hellwig {
8032b0143b5SDavid Howells 	if (d_really_is_positive(child))
804cb8e7090SChristoph Hellwig 		return -EEXIST;
805cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
806cb8e7090SChristoph Hellwig 		return -ENOENT;
807cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
808cb8e7090SChristoph Hellwig }
809cb8e7090SChristoph Hellwig 
810cb8e7090SChristoph Hellwig /*
811cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
812cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
813cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
814cb8e7090SChristoph Hellwig  */
81576dda93cSYan, Zheng static noinline int btrfs_mksubvol(struct path *parent,
81676dda93cSYan, Zheng 				   char *name, int namelen,
81772fd032eSSage Weil 				   struct btrfs_root *snap_src,
8186f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
8198696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
820cb8e7090SChristoph Hellwig {
8212b0143b5SDavid Howells 	struct inode *dir  = d_inode(parent->dentry);
822cb8e7090SChristoph Hellwig 	struct dentry *dentry;
823cb8e7090SChristoph Hellwig 	int error;
824cb8e7090SChristoph Hellwig 
8255c50c9b8SDavid Sterba 	error = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
8265c50c9b8SDavid Sterba 	if (error == -EINTR)
8275c50c9b8SDavid Sterba 		return error;
828cb8e7090SChristoph Hellwig 
829cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
830cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
831cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
832cb8e7090SChristoph Hellwig 		goto out_unlock;
833cb8e7090SChristoph Hellwig 
834cb8e7090SChristoph Hellwig 	error = -EEXIST;
8352b0143b5SDavid Howells 	if (d_really_is_positive(dentry))
836cb8e7090SChristoph Hellwig 		goto out_dput;
837cb8e7090SChristoph Hellwig 
83876dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
839cb8e7090SChristoph Hellwig 	if (error)
840a874a63eSLiu Bo 		goto out_dput;
841cb8e7090SChristoph Hellwig 
8429c52057cSChris Mason 	/*
8439c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
8449c52057cSChris Mason 	 * check for them now when we can safely fail
8459c52057cSChris Mason 	 */
8469c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
8479c52057cSChris Mason 					       dir->i_ino, name,
8489c52057cSChris Mason 					       namelen);
8499c52057cSChris Mason 	if (error)
8509c52057cSChris Mason 		goto out_dput;
8519c52057cSChris Mason 
85276dda93cSYan, Zheng 	down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
85376dda93cSYan, Zheng 
85476dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
85576dda93cSYan, Zheng 		goto out_up_read;
85676dda93cSYan, Zheng 
8573de4586cSChris Mason 	if (snap_src) {
858e9662f70SMiao Xie 		error = create_snapshot(snap_src, dir, dentry, name, namelen,
8596f72c7e2SArne Jansen 					async_transid, readonly, inherit);
8603de4586cSChris Mason 	} else {
861d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
862d5c12070SMiao Xie 				      async_transid, inherit);
8633de4586cSChris Mason 	}
86476dda93cSYan, Zheng 	if (!error)
86576dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
86676dda93cSYan, Zheng out_up_read:
86776dda93cSYan, Zheng 	up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
868cb8e7090SChristoph Hellwig out_dput:
869cb8e7090SChristoph Hellwig 	dput(dentry);
870cb8e7090SChristoph Hellwig out_unlock:
87176dda93cSYan, Zheng 	mutex_unlock(&dir->i_mutex);
872cb8e7090SChristoph Hellwig 	return error;
873cb8e7090SChristoph Hellwig }
874cb8e7090SChristoph Hellwig 
8754cb5300bSChris Mason /*
8764cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
8774cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
8784cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
8794cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
8804cb5300bSChris Mason  * part of the file
8814cb5300bSChris Mason  */
882aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
8834cb5300bSChris Mason {
8844cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8854cb5300bSChris Mason 	struct extent_map *em = NULL;
8864cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8874cb5300bSChris Mason 	u64 end;
8884cb5300bSChris Mason 
8894cb5300bSChris Mason 	read_lock(&em_tree->lock);
8904cb5300bSChris Mason 	em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
8914cb5300bSChris Mason 	read_unlock(&em_tree->lock);
8924cb5300bSChris Mason 
8934cb5300bSChris Mason 	if (em) {
8944cb5300bSChris Mason 		end = extent_map_end(em);
8954cb5300bSChris Mason 		free_extent_map(em);
8964cb5300bSChris Mason 		if (end - offset > thresh)
8974cb5300bSChris Mason 			return 0;
8984cb5300bSChris Mason 	}
8994cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
9004cb5300bSChris Mason 	thresh /= 2;
9014cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
9024cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
9034cb5300bSChris Mason 	if (end >= thresh)
9044cb5300bSChris Mason 		return 0;
9054cb5300bSChris Mason 	return 1;
9064cb5300bSChris Mason }
9074cb5300bSChris Mason 
9084cb5300bSChris Mason /*
9094cb5300bSChris Mason  * helper function to walk through a file and find extents
9104cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
9114cb5300bSChris Mason  *
9124cb5300bSChris Mason  * This is used by the defragging code to find new and small
9134cb5300bSChris Mason  * extents
9144cb5300bSChris Mason  */
9154cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
9164cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
917aab110abSDavid Sterba 			    u64 *off, u32 thresh)
9184cb5300bSChris Mason {
9194cb5300bSChris Mason 	struct btrfs_path *path;
9204cb5300bSChris Mason 	struct btrfs_key min_key;
9214cb5300bSChris Mason 	struct extent_buffer *leaf;
9224cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
9234cb5300bSChris Mason 	int type;
9244cb5300bSChris Mason 	int ret;
925a4689d2bSDavid Sterba 	u64 ino = btrfs_ino(inode);
9264cb5300bSChris Mason 
9274cb5300bSChris Mason 	path = btrfs_alloc_path();
9284cb5300bSChris Mason 	if (!path)
9294cb5300bSChris Mason 		return -ENOMEM;
9304cb5300bSChris Mason 
931a4689d2bSDavid Sterba 	min_key.objectid = ino;
9324cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
9334cb5300bSChris Mason 	min_key.offset = *off;
9344cb5300bSChris Mason 
9354cb5300bSChris Mason 	while (1) {
9366174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
9374cb5300bSChris Mason 		if (ret != 0)
9384cb5300bSChris Mason 			goto none;
939f094c9bdSFilipe Manana process_slot:
940a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
9414cb5300bSChris Mason 			goto none;
9424cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
9434cb5300bSChris Mason 			goto none;
9444cb5300bSChris Mason 
9454cb5300bSChris Mason 		leaf = path->nodes[0];
9464cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
9474cb5300bSChris Mason 					struct btrfs_file_extent_item);
9484cb5300bSChris Mason 
9494cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
9504cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
9514cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
9524cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
9534cb5300bSChris Mason 			*off = min_key.offset;
9544cb5300bSChris Mason 			btrfs_free_path(path);
9554cb5300bSChris Mason 			return 0;
9564cb5300bSChris Mason 		}
9574cb5300bSChris Mason 
958f094c9bdSFilipe Manana 		path->slots[0]++;
959f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
960f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
961f094c9bdSFilipe Manana 			goto process_slot;
962f094c9bdSFilipe Manana 		}
963f094c9bdSFilipe Manana 
9644cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
9654cb5300bSChris Mason 			goto none;
9664cb5300bSChris Mason 
9674cb5300bSChris Mason 		min_key.offset++;
9684cb5300bSChris Mason 		btrfs_release_path(path);
9694cb5300bSChris Mason 	}
9704cb5300bSChris Mason none:
9714cb5300bSChris Mason 	btrfs_free_path(path);
9724cb5300bSChris Mason 	return -ENOENT;
9734cb5300bSChris Mason }
9744cb5300bSChris Mason 
9756c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
97617ce6ef8SLiu Bo {
97717ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
978940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9796c282eb4SLi Zefan 	struct extent_map *em;
9806c282eb4SLi Zefan 	u64 len = PAGE_CACHE_SIZE;
981940100a4SChris Mason 
982940100a4SChris Mason 	/*
983940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
984940100a4SChris Mason 	 * the full extent lock
985940100a4SChris Mason 	 */
986940100a4SChris Mason 	read_lock(&em_tree->lock);
987940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
988940100a4SChris Mason 	read_unlock(&em_tree->lock);
989940100a4SChris Mason 
990940100a4SChris Mason 	if (!em) {
991308d9800SFilipe Manana 		struct extent_state *cached = NULL;
992308d9800SFilipe Manana 		u64 end = start + len - 1;
993308d9800SFilipe Manana 
994940100a4SChris Mason 		/* get the big lock and read metadata off disk */
995308d9800SFilipe Manana 		lock_extent_bits(io_tree, start, end, 0, &cached);
996940100a4SChris Mason 		em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
997308d9800SFilipe Manana 		unlock_extent_cached(io_tree, start, end, &cached, GFP_NOFS);
998940100a4SChris Mason 
9996cf8bfbfSDan Carpenter 		if (IS_ERR(em))
10006c282eb4SLi Zefan 			return NULL;
1001940100a4SChris Mason 	}
1002940100a4SChris Mason 
10036c282eb4SLi Zefan 	return em;
10046c282eb4SLi Zefan }
10056c282eb4SLi Zefan 
10066c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
10076c282eb4SLi Zefan {
10086c282eb4SLi Zefan 	struct extent_map *next;
10096c282eb4SLi Zefan 	bool ret = true;
10106c282eb4SLi Zefan 
10116c282eb4SLi Zefan 	/* this is the last extent */
10126c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
10136c282eb4SLi Zefan 		return false;
10146c282eb4SLi Zefan 
10156c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
1016e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1017e9512d72SChris Mason 		ret = false;
1018e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1019e9512d72SChris Mason 		 (em->block_len > 128 * 1024 && next->block_len > 128 * 1024))
10206c282eb4SLi Zefan 		ret = false;
10216c282eb4SLi Zefan 
10226c282eb4SLi Zefan 	free_extent_map(next);
10236c282eb4SLi Zefan 	return ret;
10246c282eb4SLi Zefan }
10256c282eb4SLi Zefan 
1026aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1027a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
1028a43a2111SAndrew Mahone 			       int compress)
10296c282eb4SLi Zefan {
10306c282eb4SLi Zefan 	struct extent_map *em;
10316c282eb4SLi Zefan 	int ret = 1;
10326c282eb4SLi Zefan 	bool next_mergeable = true;
10334a3560c4SLiu Bo 	bool prev_mergeable = true;
10346c282eb4SLi Zefan 
10356c282eb4SLi Zefan 	/*
10366c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
10376c282eb4SLi Zefan 	 * defragging it
10386c282eb4SLi Zefan 	 */
10396c282eb4SLi Zefan 	if (start < *defrag_end)
10406c282eb4SLi Zefan 		return 1;
10416c282eb4SLi Zefan 
10426c282eb4SLi Zefan 	*skip = 0;
10436c282eb4SLi Zefan 
10446c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
10456c282eb4SLi Zefan 	if (!em)
10466c282eb4SLi Zefan 		return 0;
10476c282eb4SLi Zefan 
1048940100a4SChris Mason 	/* this will cover holes, and inline extents */
104917ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1050940100a4SChris Mason 		ret = 0;
105117ce6ef8SLiu Bo 		goto out;
105217ce6ef8SLiu Bo 	}
105317ce6ef8SLiu Bo 
10544a3560c4SLiu Bo 	if (!*defrag_end)
10554a3560c4SLiu Bo 		prev_mergeable = false;
10564a3560c4SLiu Bo 
10576c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1058940100a4SChris Mason 	/*
10596c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
10606c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1061940100a4SChris Mason 	 */
1062a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
10634a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1064940100a4SChris Mason 		ret = 0;
106517ce6ef8SLiu Bo out:
1066940100a4SChris Mason 	/*
1067940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1068940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1069940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1070940100a4SChris Mason 	 *
1071940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1072940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1073940100a4SChris Mason 	 */
1074940100a4SChris Mason 	if (ret) {
1075940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1076940100a4SChris Mason 	} else {
1077940100a4SChris Mason 		*last_len = 0;
1078940100a4SChris Mason 		*skip = extent_map_end(em);
1079940100a4SChris Mason 		*defrag_end = 0;
1080940100a4SChris Mason 	}
1081940100a4SChris Mason 
1082940100a4SChris Mason 	free_extent_map(em);
1083940100a4SChris Mason 	return ret;
1084940100a4SChris Mason }
1085940100a4SChris Mason 
10864cb5300bSChris Mason /*
10874cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
10884cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
10894cb5300bSChris Mason  * to COW and defrag.
10904cb5300bSChris Mason  *
10914cb5300bSChris Mason  * It also makes sure the delalloc code has enough
10924cb5300bSChris Mason  * dirty data to avoid making new small extents as part
10934cb5300bSChris Mason  * of the defrag
10944cb5300bSChris Mason  *
10954cb5300bSChris Mason  * It's a good idea to start RA on this range
10964cb5300bSChris Mason  * before calling this.
10974cb5300bSChris Mason  */
10984cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
10994cb5300bSChris Mason 				    struct page **pages,
11004cb5300bSChris Mason 				    unsigned long start_index,
1101c41570c9SJustin Maggard 				    unsigned long num_pages)
1102f46b5a66SChristoph Hellwig {
11034cb5300bSChris Mason 	unsigned long file_end;
11044cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1105f46b5a66SChristoph Hellwig 	u64 page_start;
1106f46b5a66SChristoph Hellwig 	u64 page_end;
11071f12bd06SLiu Bo 	u64 page_cnt;
11084cb5300bSChris Mason 	int ret;
11094cb5300bSChris Mason 	int i;
11104cb5300bSChris Mason 	int i_done;
11114cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
11124cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1113600a45e1SMiao Xie 	struct extent_io_tree *tree;
11143b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
11154cb5300bSChris Mason 
11164cb5300bSChris Mason 	file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
11171f12bd06SLiu Bo 	if (!isize || start_index > file_end)
11181f12bd06SLiu Bo 		return 0;
11191f12bd06SLiu Bo 
11201f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
11214cb5300bSChris Mason 
11224cb5300bSChris Mason 	ret = btrfs_delalloc_reserve_space(inode,
1123df480633SQu Wenruo 			start_index << PAGE_CACHE_SHIFT,
11241f12bd06SLiu Bo 			page_cnt << PAGE_CACHE_SHIFT);
11254cb5300bSChris Mason 	if (ret)
11264cb5300bSChris Mason 		return ret;
11274cb5300bSChris Mason 	i_done = 0;
1128600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
11294cb5300bSChris Mason 
11304cb5300bSChris Mason 	/* step one, lock all the pages */
11311f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
11324cb5300bSChris Mason 		struct page *page;
1133600a45e1SMiao Xie again:
1134a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
11353b16a4e3SJosef Bacik 					   start_index + i, mask);
11364cb5300bSChris Mason 		if (!page)
11374cb5300bSChris Mason 			break;
11384cb5300bSChris Mason 
1139600a45e1SMiao Xie 		page_start = page_offset(page);
1140600a45e1SMiao Xie 		page_end = page_start + PAGE_CACHE_SIZE - 1;
1141600a45e1SMiao Xie 		while (1) {
1142308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1143308d9800SFilipe Manana 					 0, &cached_state);
1144600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1145600a45e1SMiao Xie 							      page_start);
1146308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1147308d9800SFilipe Manana 					     &cached_state, GFP_NOFS);
1148600a45e1SMiao Xie 			if (!ordered)
1149600a45e1SMiao Xie 				break;
1150600a45e1SMiao Xie 
1151600a45e1SMiao Xie 			unlock_page(page);
1152600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1153600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1154600a45e1SMiao Xie 			lock_page(page);
11551f12bd06SLiu Bo 			/*
11561f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
11571f12bd06SLiu Bo 			 * it was released or not.
11581f12bd06SLiu Bo 			 */
11591f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
11601f12bd06SLiu Bo 				unlock_page(page);
11611f12bd06SLiu Bo 				page_cache_release(page);
11621f12bd06SLiu Bo 				goto again;
11631f12bd06SLiu Bo 			}
1164600a45e1SMiao Xie 		}
1165600a45e1SMiao Xie 
11664cb5300bSChris Mason 		if (!PageUptodate(page)) {
11674cb5300bSChris Mason 			btrfs_readpage(NULL, page);
11684cb5300bSChris Mason 			lock_page(page);
11694cb5300bSChris Mason 			if (!PageUptodate(page)) {
11704cb5300bSChris Mason 				unlock_page(page);
11714cb5300bSChris Mason 				page_cache_release(page);
11724cb5300bSChris Mason 				ret = -EIO;
11734cb5300bSChris Mason 				break;
11744cb5300bSChris Mason 			}
11754cb5300bSChris Mason 		}
1176600a45e1SMiao Xie 
1177600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1178600a45e1SMiao Xie 			unlock_page(page);
1179600a45e1SMiao Xie 			page_cache_release(page);
1180600a45e1SMiao Xie 			goto again;
1181600a45e1SMiao Xie 		}
1182600a45e1SMiao Xie 
11834cb5300bSChris Mason 		pages[i] = page;
11844cb5300bSChris Mason 		i_done++;
11854cb5300bSChris Mason 	}
11864cb5300bSChris Mason 	if (!i_done || ret)
11874cb5300bSChris Mason 		goto out;
11884cb5300bSChris Mason 
11894cb5300bSChris Mason 	if (!(inode->i_sb->s_flags & MS_ACTIVE))
11904cb5300bSChris Mason 		goto out;
11914cb5300bSChris Mason 
11924cb5300bSChris Mason 	/*
11934cb5300bSChris Mason 	 * so now we have a nice long stream of locked
11944cb5300bSChris Mason 	 * and up to date pages, lets wait on them
11954cb5300bSChris Mason 	 */
11964cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
11974cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
11984cb5300bSChris Mason 
11994cb5300bSChris Mason 	page_start = page_offset(pages[0]);
12004cb5300bSChris Mason 	page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
12014cb5300bSChris Mason 
12024cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1203d0082371SJeff Mahoney 			 page_start, page_end - 1, 0, &cached_state);
12044cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
12054cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
12069e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
12079e8a4a8bSLiu Bo 			  &cached_state, GFP_NOFS);
12084cb5300bSChris Mason 
12091f12bd06SLiu Bo 	if (i_done != page_cnt) {
12109e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
12119e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
12129e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
12134cb5300bSChris Mason 		btrfs_delalloc_release_space(inode,
1214df480633SQu Wenruo 				start_index << PAGE_CACHE_SHIFT,
12151f12bd06SLiu Bo 				(page_cnt - i_done) << PAGE_CACHE_SHIFT);
12164cb5300bSChris Mason 	}
12174cb5300bSChris Mason 
12184cb5300bSChris Mason 
12199e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
12209e8a4a8bSLiu Bo 			  &cached_state, GFP_NOFS);
12214cb5300bSChris Mason 
12224cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
12234cb5300bSChris Mason 			     page_start, page_end - 1, &cached_state,
12244cb5300bSChris Mason 			     GFP_NOFS);
12254cb5300bSChris Mason 
12264cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12274cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
12284cb5300bSChris Mason 		ClearPageChecked(pages[i]);
12294cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
12304cb5300bSChris Mason 		set_page_dirty(pages[i]);
12314cb5300bSChris Mason 		unlock_page(pages[i]);
12324cb5300bSChris Mason 		page_cache_release(pages[i]);
12334cb5300bSChris Mason 	}
12344cb5300bSChris Mason 	return i_done;
12354cb5300bSChris Mason out:
12364cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12374cb5300bSChris Mason 		unlock_page(pages[i]);
12384cb5300bSChris Mason 		page_cache_release(pages[i]);
12394cb5300bSChris Mason 	}
12407cf5b976SQu Wenruo 	btrfs_delalloc_release_space(inode,
1241df480633SQu Wenruo 			start_index << PAGE_CACHE_SHIFT,
1242df480633SQu Wenruo 			page_cnt << PAGE_CACHE_SHIFT);
12434cb5300bSChris Mason 	return ret;
12444cb5300bSChris Mason 
12454cb5300bSChris Mason }
12464cb5300bSChris Mason 
12474cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
12484cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
12494cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
12504cb5300bSChris Mason {
12514cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
12524cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
12534cb5300bSChris Mason 	unsigned long last_index;
1254151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1255940100a4SChris Mason 	u64 last_len = 0;
1256940100a4SChris Mason 	u64 skip = 0;
1257940100a4SChris Mason 	u64 defrag_end = 0;
12584cb5300bSChris Mason 	u64 newer_off = range->start;
1259f46b5a66SChristoph Hellwig 	unsigned long i;
1260008873eaSLi Zefan 	unsigned long ra_index = 0;
1261f46b5a66SChristoph Hellwig 	int ret;
12624cb5300bSChris Mason 	int defrag_count = 0;
12631a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1264aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
1265c41570c9SJustin Maggard 	unsigned long max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1266c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
12674cb5300bSChris Mason 	u64 new_align = ~((u64)128 * 1024 - 1);
12684cb5300bSChris Mason 	struct page **pages = NULL;
12694cb5300bSChris Mason 
12700abd5b17SLiu Bo 	if (isize == 0)
12710abd5b17SLiu Bo 		return 0;
12720abd5b17SLiu Bo 
12730abd5b17SLiu Bo 	if (range->start >= isize)
12740abd5b17SLiu Bo 		return -EINVAL;
12751a419d85SLi Zefan 
12761a419d85SLi Zefan 	if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
12771a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
12781a419d85SLi Zefan 			return -EINVAL;
12791a419d85SLi Zefan 		if (range->compress_type)
12801a419d85SLi Zefan 			compress_type = range->compress_type;
12811a419d85SLi Zefan 	}
1282f46b5a66SChristoph Hellwig 
12830abd5b17SLiu Bo 	if (extent_thresh == 0)
12840abd5b17SLiu Bo 		extent_thresh = 256 * 1024;
1285f46b5a66SChristoph Hellwig 
12864cb5300bSChris Mason 	/*
12874cb5300bSChris Mason 	 * if we were not given a file, allocate a readahead
12884cb5300bSChris Mason 	 * context
12894cb5300bSChris Mason 	 */
12904cb5300bSChris Mason 	if (!file) {
12914cb5300bSChris Mason 		ra = kzalloc(sizeof(*ra), GFP_NOFS);
12924cb5300bSChris Mason 		if (!ra)
12934cb5300bSChris Mason 			return -ENOMEM;
12944cb5300bSChris Mason 		file_ra_state_init(ra, inode->i_mapping);
12954cb5300bSChris Mason 	} else {
12964cb5300bSChris Mason 		ra = &file->f_ra;
12974cb5300bSChris Mason 	}
12984cb5300bSChris Mason 
1299d9b0d9baSDulshani Gunawardhana 	pages = kmalloc_array(max_cluster, sizeof(struct page *),
13004cb5300bSChris Mason 			GFP_NOFS);
13014cb5300bSChris Mason 	if (!pages) {
13024cb5300bSChris Mason 		ret = -ENOMEM;
13034cb5300bSChris Mason 		goto out_ra;
13044cb5300bSChris Mason 	}
13054cb5300bSChris Mason 
13064cb5300bSChris Mason 	/* find the last page to defrag */
13071e701a32SChris Mason 	if (range->start + range->len > range->start) {
1308151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
13091e701a32SChris Mason 			 range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
13101e701a32SChris Mason 	} else {
1311151a31b2SLi Zefan 		last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
13121e701a32SChris Mason 	}
13131e701a32SChris Mason 
13144cb5300bSChris Mason 	if (newer_than) {
13154cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
13164cb5300bSChris Mason 				       &newer_off, 64 * 1024);
13174cb5300bSChris Mason 		if (!ret) {
13184cb5300bSChris Mason 			range->start = newer_off;
13194cb5300bSChris Mason 			/*
13204cb5300bSChris Mason 			 * we always align our defrag to help keep
13214cb5300bSChris Mason 			 * the extents in the file evenly spaced
13224cb5300bSChris Mason 			 */
13234cb5300bSChris Mason 			i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
13244cb5300bSChris Mason 		} else
13254cb5300bSChris Mason 			goto out_ra;
13264cb5300bSChris Mason 	} else {
13271e701a32SChris Mason 		i = range->start >> PAGE_CACHE_SHIFT;
13284cb5300bSChris Mason 	}
13294cb5300bSChris Mason 	if (!max_to_defrag)
1330070034bdSchandan 		max_to_defrag = last_index - i + 1;
13314cb5300bSChris Mason 
13322a0f7f57SLi Zefan 	/*
13332a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
13342a0f7f57SLi Zefan 	 * written sequentially.
13352a0f7f57SLi Zefan 	 */
13362a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
13372a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
13382a0f7f57SLi Zefan 
1339f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
1340ed6078f7SDavid Sterba 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_CACHE_SIZE))) {
13414cb5300bSChris Mason 		/*
13424cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
13434cb5300bSChris Mason 		 * the FS
13444cb5300bSChris Mason 		 */
13454cb5300bSChris Mason 		if (!(inode->i_sb->s_flags & MS_ACTIVE))
13464cb5300bSChris Mason 			break;
13474cb5300bSChris Mason 
1348210549ebSDavid Sterba 		if (btrfs_defrag_cancelled(root->fs_info)) {
1349f14d104dSDavid Sterba 			btrfs_debug(root->fs_info, "defrag_file cancelled");
1350210549ebSDavid Sterba 			ret = -EAGAIN;
1351210549ebSDavid Sterba 			break;
1352210549ebSDavid Sterba 		}
1353210549ebSDavid Sterba 
135466c26892SLiu Bo 		if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
13556c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
1356a43a2111SAndrew Mahone 					 &defrag_end, range->flags &
1357a43a2111SAndrew Mahone 					 BTRFS_DEFRAG_RANGE_COMPRESS)) {
1358940100a4SChris Mason 			unsigned long next;
1359940100a4SChris Mason 			/*
1360940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1361940100a4SChris Mason 			 * bump our counter by the suggested amount
1362940100a4SChris Mason 			 */
1363ed6078f7SDavid Sterba 			next = DIV_ROUND_UP(skip, PAGE_CACHE_SIZE);
1364940100a4SChris Mason 			i = max(i + 1, next);
1365940100a4SChris Mason 			continue;
1366940100a4SChris Mason 		}
1367008873eaSLi Zefan 
1368008873eaSLi Zefan 		if (!newer_than) {
1369008873eaSLi Zefan 			cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1370008873eaSLi Zefan 				   PAGE_CACHE_SHIFT) - i;
1371008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1372008873eaSLi Zefan 		} else {
1373008873eaSLi Zefan 			cluster = max_cluster;
1374008873eaSLi Zefan 		}
1375008873eaSLi Zefan 
1376008873eaSLi Zefan 		if (i + cluster > ra_index) {
1377008873eaSLi Zefan 			ra_index = max(i, ra_index);
1378008873eaSLi Zefan 			btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1379008873eaSLi Zefan 				       cluster);
1380e4826a5bSchandan 			ra_index += cluster;
1381008873eaSLi Zefan 		}
13824cb5300bSChris Mason 
1383ecb8bea8SLiu Bo 		mutex_lock(&inode->i_mutex);
1384633085c7SFilipe David Borba Manana 		if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1385633085c7SFilipe David Borba Manana 			BTRFS_I(inode)->force_compress = compress_type;
1386008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1387ecb8bea8SLiu Bo 		if (ret < 0) {
1388ecb8bea8SLiu Bo 			mutex_unlock(&inode->i_mutex);
13894cb5300bSChris Mason 			goto out_ra;
1390ecb8bea8SLiu Bo 		}
13914cb5300bSChris Mason 
13924cb5300bSChris Mason 		defrag_count += ret;
1393d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
1394ecb8bea8SLiu Bo 		mutex_unlock(&inode->i_mutex);
13954cb5300bSChris Mason 
13964cb5300bSChris Mason 		if (newer_than) {
13974cb5300bSChris Mason 			if (newer_off == (u64)-1)
13984cb5300bSChris Mason 				break;
13994cb5300bSChris Mason 
1400e1f041e1SLiu Bo 			if (ret > 0)
1401e1f041e1SLiu Bo 				i += ret;
1402e1f041e1SLiu Bo 
14034cb5300bSChris Mason 			newer_off = max(newer_off + 1,
14044cb5300bSChris Mason 					(u64)i << PAGE_CACHE_SHIFT);
14054cb5300bSChris Mason 
14064cb5300bSChris Mason 			ret = find_new_extents(root, inode,
14074cb5300bSChris Mason 					       newer_than, &newer_off,
14084cb5300bSChris Mason 					       64 * 1024);
14094cb5300bSChris Mason 			if (!ret) {
14104cb5300bSChris Mason 				range->start = newer_off;
14114cb5300bSChris Mason 				i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
14124cb5300bSChris Mason 			} else {
14134cb5300bSChris Mason 				break;
1414940100a4SChris Mason 			}
14154cb5300bSChris Mason 		} else {
1416008873eaSLi Zefan 			if (ret > 0) {
1417cbcc8326SLi Zefan 				i += ret;
1418008873eaSLi Zefan 				last_len += ret << PAGE_CACHE_SHIFT;
1419008873eaSLi Zefan 			} else {
1420940100a4SChris Mason 				i++;
1421008873eaSLi Zefan 				last_len = 0;
1422008873eaSLi Zefan 			}
1423f46b5a66SChristoph Hellwig 		}
14244cb5300bSChris Mason 	}
1425f46b5a66SChristoph Hellwig 
1426dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
14271e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1428dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1429dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1430dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1431dec8ef90SFilipe Manana 	}
14321e701a32SChris Mason 
14331e701a32SChris Mason 	if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
14341e701a32SChris Mason 		/* the filemap_flush will queue IO into the worker threads, but
14351e701a32SChris Mason 		 * we have to make sure the IO is actually started and that
14361e701a32SChris Mason 		 * ordered extents get created before we return
14371e701a32SChris Mason 		 */
14381e701a32SChris Mason 		atomic_inc(&root->fs_info->async_submit_draining);
14391e701a32SChris Mason 		while (atomic_read(&root->fs_info->nr_async_submits) ||
14401e701a32SChris Mason 		      atomic_read(&root->fs_info->async_delalloc_pages)) {
14411e701a32SChris Mason 			wait_event(root->fs_info->async_submit_wait,
14421e701a32SChris Mason 			   (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
14431e701a32SChris Mason 			    atomic_read(&root->fs_info->async_delalloc_pages) == 0));
14441e701a32SChris Mason 		}
14451e701a32SChris Mason 		atomic_dec(&root->fs_info->async_submit_draining);
14461e701a32SChris Mason 	}
14471e701a32SChris Mason 
14481a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
14492b0ce2c2SMitch Harder 		btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
14501a419d85SLi Zefan 	}
14511a419d85SLi Zefan 
145260ccf82fSDiego Calleja 	ret = defrag_count;
1453940100a4SChris Mason 
14544cb5300bSChris Mason out_ra:
1455633085c7SFilipe David Borba Manana 	if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1456633085c7SFilipe David Borba Manana 		mutex_lock(&inode->i_mutex);
1457633085c7SFilipe David Borba Manana 		BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1458633085c7SFilipe David Borba Manana 		mutex_unlock(&inode->i_mutex);
1459633085c7SFilipe David Borba Manana 	}
14604cb5300bSChris Mason 	if (!file)
14614cb5300bSChris Mason 		kfree(ra);
14624cb5300bSChris Mason 	kfree(pages);
1463940100a4SChris Mason 	return ret;
1464f46b5a66SChristoph Hellwig }
1465f46b5a66SChristoph Hellwig 
1466198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
146776dda93cSYan, Zheng 					void __user *arg)
1468f46b5a66SChristoph Hellwig {
1469f46b5a66SChristoph Hellwig 	u64 new_size;
1470f46b5a66SChristoph Hellwig 	u64 old_size;
1471f46b5a66SChristoph Hellwig 	u64 devid = 1;
1472496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1473f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1474f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1475f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1476f46b5a66SChristoph Hellwig 	char *sizestr;
14779a40f122SGui Hecheng 	char *retptr;
1478f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1479f46b5a66SChristoph Hellwig 	int ret = 0;
1480f46b5a66SChristoph Hellwig 	int mod = 0;
1481f46b5a66SChristoph Hellwig 
1482e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1483e441d54dSChris Mason 		return -EPERM;
1484e441d54dSChris Mason 
1485198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1486198605a8SMiao Xie 	if (ret)
1487198605a8SMiao Xie 		return ret;
1488198605a8SMiao Xie 
14895ac00addSStefan Behrens 	if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
14905ac00addSStefan Behrens 			1)) {
149197547676SMiao Xie 		mnt_drop_write_file(file);
1492e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1493c9e9f97bSIlya Dryomov 	}
1494c9e9f97bSIlya Dryomov 
14955ac00addSStefan Behrens 	mutex_lock(&root->fs_info->volume_mutex);
1496dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1497c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1498c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1499c9e9f97bSIlya Dryomov 		goto out;
1500c9e9f97bSIlya Dryomov 	}
15015516e595SMark Fasheh 
15025516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1503f46b5a66SChristoph Hellwig 
1504f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1505f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1506f46b5a66SChristoph Hellwig 	if (devstr) {
1507f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1508f46b5a66SChristoph Hellwig 		*devstr = '\0';
1509f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
151058dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
151158dfae63SZhangZhen 		if (ret)
151258dfae63SZhangZhen 			goto out_free;
1513dfd79829SMiao Xie 		if (!devid) {
1514dfd79829SMiao Xie 			ret = -EINVAL;
1515dfd79829SMiao Xie 			goto out_free;
1516dfd79829SMiao Xie 		}
1517efe120a0SFrank Holton 		btrfs_info(root->fs_info, "resizing devid %llu", devid);
1518f46b5a66SChristoph Hellwig 	}
1519dba60f3fSMiao Xie 
1520aa1b8cd4SStefan Behrens 	device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1521f46b5a66SChristoph Hellwig 	if (!device) {
1522efe120a0SFrank Holton 		btrfs_info(root->fs_info, "resizer unable to find device %llu",
1523c1c9ff7cSGeert Uytterhoeven 		       devid);
1524dfd79829SMiao Xie 		ret = -ENODEV;
1525c9e9f97bSIlya Dryomov 		goto out_free;
1526f46b5a66SChristoph Hellwig 	}
1527dba60f3fSMiao Xie 
1528dba60f3fSMiao Xie 	if (!device->writeable) {
1529efe120a0SFrank Holton 		btrfs_info(root->fs_info,
1530efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1531c1c9ff7cSGeert Uytterhoeven 		       devid);
1532dfd79829SMiao Xie 		ret = -EPERM;
15334e42ae1bSLiu Bo 		goto out_free;
15344e42ae1bSLiu Bo 	}
15354e42ae1bSLiu Bo 
1536f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1537f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1538f46b5a66SChristoph Hellwig 	else {
1539f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1540f46b5a66SChristoph Hellwig 			mod = -1;
1541f46b5a66SChristoph Hellwig 			sizestr++;
1542f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1543f46b5a66SChristoph Hellwig 			mod = 1;
1544f46b5a66SChristoph Hellwig 			sizestr++;
1545f46b5a66SChristoph Hellwig 		}
15469a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
15479a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1548f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1549c9e9f97bSIlya Dryomov 			goto out_free;
1550f46b5a66SChristoph Hellwig 		}
1551f46b5a66SChristoph Hellwig 	}
1552f46b5a66SChristoph Hellwig 
155363a212abSStefan Behrens 	if (device->is_tgtdev_for_dev_replace) {
1554dfd79829SMiao Xie 		ret = -EPERM;
155563a212abSStefan Behrens 		goto out_free;
155663a212abSStefan Behrens 	}
155763a212abSStefan Behrens 
15587cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1559f46b5a66SChristoph Hellwig 
1560f46b5a66SChristoph Hellwig 	if (mod < 0) {
1561f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1562f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1563c9e9f97bSIlya Dryomov 			goto out_free;
1564f46b5a66SChristoph Hellwig 		}
1565f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1566f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1567eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1568902c68a4SGui Hecheng 			ret = -ERANGE;
1569eb8052e0SWenliang Fan 			goto out_free;
1570eb8052e0SWenliang Fan 		}
1571f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1572f46b5a66SChristoph Hellwig 	}
1573f46b5a66SChristoph Hellwig 
1574f46b5a66SChristoph Hellwig 	if (new_size < 256 * 1024 * 1024) {
1575f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1576c9e9f97bSIlya Dryomov 		goto out_free;
1577f46b5a66SChristoph Hellwig 	}
1578f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1579f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1580c9e9f97bSIlya Dryomov 		goto out_free;
1581f46b5a66SChristoph Hellwig 	}
1582f46b5a66SChristoph Hellwig 
1583b8b93addSDavid Sterba 	new_size = div_u64(new_size, root->sectorsize);
1584f46b5a66SChristoph Hellwig 	new_size *= root->sectorsize;
1585f46b5a66SChristoph Hellwig 
1586ecaeb14bSDavid Sterba 	btrfs_info_in_rcu(root->fs_info, "new size for %s is %llu",
1587c1c9ff7cSGeert Uytterhoeven 		      rcu_str_deref(device->name), new_size);
1588f46b5a66SChristoph Hellwig 
1589f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1590a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
159198d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
159298d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1593c9e9f97bSIlya Dryomov 			goto out_free;
159498d5dc13STsutomu Itoh 		}
1595f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
1596f46b5a66SChristoph Hellwig 		btrfs_commit_transaction(trans, root);
1597ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1598f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
15990253f40eSjeff.liu 	} /* equal, nothing need to do */
1600f46b5a66SChristoph Hellwig 
1601c9e9f97bSIlya Dryomov out_free:
1602f46b5a66SChristoph Hellwig 	kfree(vol_args);
1603c9e9f97bSIlya Dryomov out:
1604c9e9f97bSIlya Dryomov 	mutex_unlock(&root->fs_info->volume_mutex);
16055ac00addSStefan Behrens 	atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
160618f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1607f46b5a66SChristoph Hellwig 	return ret;
1608f46b5a66SChristoph Hellwig }
1609f46b5a66SChristoph Hellwig 
161072fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
16116f72c7e2SArne Jansen 				char *name, unsigned long fd, int subvol,
16126f72c7e2SArne Jansen 				u64 *transid, bool readonly,
16138696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1614f46b5a66SChristoph Hellwig {
1615f46b5a66SChristoph Hellwig 	int namelen;
16163de4586cSChris Mason 	int ret = 0;
1617f46b5a66SChristoph Hellwig 
1618a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1619a874a63eSLiu Bo 	if (ret)
1620a874a63eSLiu Bo 		goto out;
1621a874a63eSLiu Bo 
162272fd032eSSage Weil 	namelen = strlen(name);
162372fd032eSSage Weil 	if (strchr(name, '/')) {
1624f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1625a874a63eSLiu Bo 		goto out_drop_write;
1626f46b5a66SChristoph Hellwig 	}
1627f46b5a66SChristoph Hellwig 
162816780cabSChris Mason 	if (name[0] == '.' &&
162916780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
163016780cabSChris Mason 		ret = -EEXIST;
1631a874a63eSLiu Bo 		goto out_drop_write;
163216780cabSChris Mason 	}
163316780cabSChris Mason 
16343de4586cSChris Mason 	if (subvol) {
163572fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
16366f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1637cb8e7090SChristoph Hellwig 	} else {
16382903ff01SAl Viro 		struct fd src = fdget(fd);
16393de4586cSChris Mason 		struct inode *src_inode;
16402903ff01SAl Viro 		if (!src.file) {
16413de4586cSChris Mason 			ret = -EINVAL;
1642a874a63eSLiu Bo 			goto out_drop_write;
16433de4586cSChris Mason 		}
16443de4586cSChris Mason 
1645496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1646496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1647efe120a0SFrank Holton 			btrfs_info(BTRFS_I(src_inode)->root->fs_info,
1648efe120a0SFrank Holton 				   "Snapshot src from another FS");
164923ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1650d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1651d0242061SDavid Sterba 			/*
1652d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1653d0242061SDavid Sterba 			 * are limited to own subvolumes only
1654d0242061SDavid Sterba 			 */
1655d0242061SDavid Sterba 			ret = -EPERM;
1656ecd18815SAl Viro 		} else {
165772fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
165872fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
16596f72c7e2SArne Jansen 					     transid, readonly, inherit);
1660ecd18815SAl Viro 		}
16612903ff01SAl Viro 		fdput(src);
1662cb8e7090SChristoph Hellwig 	}
1663a874a63eSLiu Bo out_drop_write:
1664a874a63eSLiu Bo 	mnt_drop_write_file(file);
1665f46b5a66SChristoph Hellwig out:
166672fd032eSSage Weil 	return ret;
166772fd032eSSage Weil }
166872fd032eSSage Weil 
166972fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1670fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
167172fd032eSSage Weil {
1672fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
167372fd032eSSage Weil 	int ret;
167472fd032eSSage Weil 
1675fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1676fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1677fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1678fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1679fa0d2b9bSLi Zefan 
1680fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1681b83cc969SLi Zefan 					      vol_args->fd, subvol,
16826f72c7e2SArne Jansen 					      NULL, false, NULL);
1683fa0d2b9bSLi Zefan 
1684fa0d2b9bSLi Zefan 	kfree(vol_args);
1685fa0d2b9bSLi Zefan 	return ret;
1686fa0d2b9bSLi Zefan }
1687fa0d2b9bSLi Zefan 
1688fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1689fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1690fa0d2b9bSLi Zefan {
1691fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1692fa0d2b9bSLi Zefan 	int ret;
1693fdfb1e4fSLi Zefan 	u64 transid = 0;
1694fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1695b83cc969SLi Zefan 	bool readonly = false;
16966f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
169772fd032eSSage Weil 
1698fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1699fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1700fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1701fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1702fdfb1e4fSLi Zefan 
1703b83cc969SLi Zefan 	if (vol_args->flags &
17046f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
17056f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1706b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1707c47ca32dSDan Carpenter 		goto free_args;
1708fdfb1e4fSLi Zefan 	}
1709fdfb1e4fSLi Zefan 
1710fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1711fdfb1e4fSLi Zefan 		ptr = &transid;
1712b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1713b83cc969SLi Zefan 		readonly = true;
17146f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
17156f72c7e2SArne Jansen 		if (vol_args->size > PAGE_CACHE_SIZE) {
17166f72c7e2SArne Jansen 			ret = -EINVAL;
1717c47ca32dSDan Carpenter 			goto free_args;
17186f72c7e2SArne Jansen 		}
17196f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
17206f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
17216f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1722c47ca32dSDan Carpenter 			goto free_args;
17236f72c7e2SArne Jansen 		}
17246f72c7e2SArne Jansen 	}
172575eaa0e2SSage Weil 
1726fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
17276f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
17288696c533SMiao Xie 					      readonly, inherit);
1729c47ca32dSDan Carpenter 	if (ret)
1730c47ca32dSDan Carpenter 		goto free_inherit;
173175eaa0e2SSage Weil 
1732c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1733fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1734c47ca32dSDan Carpenter 					transid),
1735c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
173675eaa0e2SSage Weil 		ret = -EFAULT;
1737c47ca32dSDan Carpenter 
1738c47ca32dSDan Carpenter free_inherit:
17396f72c7e2SArne Jansen 	kfree(inherit);
1740c47ca32dSDan Carpenter free_args:
1741c47ca32dSDan Carpenter 	kfree(vol_args);
1742f46b5a66SChristoph Hellwig 	return ret;
1743f46b5a66SChristoph Hellwig }
1744f46b5a66SChristoph Hellwig 
17450caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
17460caa102dSLi Zefan 						void __user *arg)
17470caa102dSLi Zefan {
1748496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17490caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17500caa102dSLi Zefan 	int ret = 0;
17510caa102dSLi Zefan 	u64 flags = 0;
17520caa102dSLi Zefan 
175333345d01SLi Zefan 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
17540caa102dSLi Zefan 		return -EINVAL;
17550caa102dSLi Zefan 
17560caa102dSLi Zefan 	down_read(&root->fs_info->subvol_sem);
17570caa102dSLi Zefan 	if (btrfs_root_readonly(root))
17580caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
17590caa102dSLi Zefan 	up_read(&root->fs_info->subvol_sem);
17600caa102dSLi Zefan 
17610caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
17620caa102dSLi Zefan 		ret = -EFAULT;
17630caa102dSLi Zefan 
17640caa102dSLi Zefan 	return ret;
17650caa102dSLi Zefan }
17660caa102dSLi Zefan 
17670caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
17680caa102dSLi Zefan 					      void __user *arg)
17690caa102dSLi Zefan {
1770496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17710caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17720caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
17730caa102dSLi Zefan 	u64 root_flags;
17740caa102dSLi Zefan 	u64 flags;
17750caa102dSLi Zefan 	int ret = 0;
17760caa102dSLi Zefan 
1777bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1778bd60ea0fSDavid Sterba 		return -EPERM;
1779bd60ea0fSDavid Sterba 
1780b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1781b9ca0664SLiu Bo 	if (ret)
1782b9ca0664SLiu Bo 		goto out;
17830caa102dSLi Zefan 
1784b9ca0664SLiu Bo 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1785b9ca0664SLiu Bo 		ret = -EINVAL;
1786b9ca0664SLiu Bo 		goto out_drop_write;
1787b9ca0664SLiu Bo 	}
17880caa102dSLi Zefan 
1789b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1790b9ca0664SLiu Bo 		ret = -EFAULT;
1791b9ca0664SLiu Bo 		goto out_drop_write;
1792b9ca0664SLiu Bo 	}
17930caa102dSLi Zefan 
1794b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1795b9ca0664SLiu Bo 		ret = -EINVAL;
1796b9ca0664SLiu Bo 		goto out_drop_write;
1797b9ca0664SLiu Bo 	}
17980caa102dSLi Zefan 
1799b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1800b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1801b9ca0664SLiu Bo 		goto out_drop_write;
1802b9ca0664SLiu Bo 	}
18030caa102dSLi Zefan 
18040caa102dSLi Zefan 	down_write(&root->fs_info->subvol_sem);
18050caa102dSLi Zefan 
18060caa102dSLi Zefan 	/* nothing to do */
18070caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1808b9ca0664SLiu Bo 		goto out_drop_sem;
18090caa102dSLi Zefan 
18100caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
18112c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
18120caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
18130caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
18142c686537SDavid Sterba 	} else {
18152c686537SDavid Sterba 		/*
18162c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
18172c686537SDavid Sterba 		 * send
18182c686537SDavid Sterba 		 */
18192c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
18202c686537SDavid Sterba 		if (root->send_in_progress == 0) {
18210caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
18220caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
18232c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18242c686537SDavid Sterba 		} else {
18252c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18262c686537SDavid Sterba 			btrfs_warn(root->fs_info,
18272c686537SDavid Sterba 			"Attempt to set subvolume %llu read-write during send",
18282c686537SDavid Sterba 					root->root_key.objectid);
18292c686537SDavid Sterba 			ret = -EPERM;
18302c686537SDavid Sterba 			goto out_drop_sem;
18312c686537SDavid Sterba 		}
18322c686537SDavid Sterba 	}
18330caa102dSLi Zefan 
18340caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
18350caa102dSLi Zefan 	if (IS_ERR(trans)) {
18360caa102dSLi Zefan 		ret = PTR_ERR(trans);
18370caa102dSLi Zefan 		goto out_reset;
18380caa102dSLi Zefan 	}
18390caa102dSLi Zefan 
1840b4dc2b8cSLi Zefan 	ret = btrfs_update_root(trans, root->fs_info->tree_root,
18410caa102dSLi Zefan 				&root->root_key, &root->root_item);
18420caa102dSLi Zefan 
18430caa102dSLi Zefan 	btrfs_commit_transaction(trans, root);
18440caa102dSLi Zefan out_reset:
18450caa102dSLi Zefan 	if (ret)
18460caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1847b9ca0664SLiu Bo out_drop_sem:
18480caa102dSLi Zefan 	up_write(&root->fs_info->subvol_sem);
1849b9ca0664SLiu Bo out_drop_write:
1850b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1851b9ca0664SLiu Bo out:
18520caa102dSLi Zefan 	return ret;
18530caa102dSLi Zefan }
18540caa102dSLi Zefan 
185576dda93cSYan, Zheng /*
185676dda93cSYan, Zheng  * helper to check if the subvolume references other subvolumes
185776dda93cSYan, Zheng  */
185876dda93cSYan, Zheng static noinline int may_destroy_subvol(struct btrfs_root *root)
185976dda93cSYan, Zheng {
186076dda93cSYan, Zheng 	struct btrfs_path *path;
1861175a2b87SJosef Bacik 	struct btrfs_dir_item *di;
186276dda93cSYan, Zheng 	struct btrfs_key key;
1863175a2b87SJosef Bacik 	u64 dir_id;
186476dda93cSYan, Zheng 	int ret;
186576dda93cSYan, Zheng 
186676dda93cSYan, Zheng 	path = btrfs_alloc_path();
186776dda93cSYan, Zheng 	if (!path)
186876dda93cSYan, Zheng 		return -ENOMEM;
186976dda93cSYan, Zheng 
1870175a2b87SJosef Bacik 	/* Make sure this root isn't set as the default subvol */
1871175a2b87SJosef Bacik 	dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1872175a2b87SJosef Bacik 	di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1873175a2b87SJosef Bacik 				   dir_id, "default", 7, 0);
1874175a2b87SJosef Bacik 	if (di && !IS_ERR(di)) {
1875175a2b87SJosef Bacik 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1876175a2b87SJosef Bacik 		if (key.objectid == root->root_key.objectid) {
187772de6b53SGuangyu Sun 			ret = -EPERM;
187872de6b53SGuangyu Sun 			btrfs_err(root->fs_info, "deleting default subvolume "
187972de6b53SGuangyu Sun 				  "%llu is not allowed", key.objectid);
1880175a2b87SJosef Bacik 			goto out;
1881175a2b87SJosef Bacik 		}
1882175a2b87SJosef Bacik 		btrfs_release_path(path);
1883175a2b87SJosef Bacik 	}
1884175a2b87SJosef Bacik 
188576dda93cSYan, Zheng 	key.objectid = root->root_key.objectid;
188676dda93cSYan, Zheng 	key.type = BTRFS_ROOT_REF_KEY;
188776dda93cSYan, Zheng 	key.offset = (u64)-1;
188876dda93cSYan, Zheng 
188976dda93cSYan, Zheng 	ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
189076dda93cSYan, Zheng 				&key, path, 0, 0);
189176dda93cSYan, Zheng 	if (ret < 0)
189276dda93cSYan, Zheng 		goto out;
189376dda93cSYan, Zheng 	BUG_ON(ret == 0);
189476dda93cSYan, Zheng 
189576dda93cSYan, Zheng 	ret = 0;
189676dda93cSYan, Zheng 	if (path->slots[0] > 0) {
189776dda93cSYan, Zheng 		path->slots[0]--;
189876dda93cSYan, Zheng 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
189976dda93cSYan, Zheng 		if (key.objectid == root->root_key.objectid &&
190076dda93cSYan, Zheng 		    key.type == BTRFS_ROOT_REF_KEY)
190176dda93cSYan, Zheng 			ret = -ENOTEMPTY;
190276dda93cSYan, Zheng 	}
190376dda93cSYan, Zheng out:
190476dda93cSYan, Zheng 	btrfs_free_path(path);
190576dda93cSYan, Zheng 	return ret;
190676dda93cSYan, Zheng }
190776dda93cSYan, Zheng 
1908ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1909ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1910ac8e9819SChris Mason {
1911abc6e134SChris Mason 	struct btrfs_key test;
1912abc6e134SChris Mason 	int ret;
1913abc6e134SChris Mason 
1914abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1915abc6e134SChris Mason 	test.type = sk->min_type;
1916abc6e134SChris Mason 	test.offset = sk->min_offset;
1917abc6e134SChris Mason 
1918abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1919abc6e134SChris Mason 	if (ret < 0)
1920ac8e9819SChris Mason 		return 0;
1921abc6e134SChris Mason 
1922abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1923abc6e134SChris Mason 	test.type = sk->max_type;
1924abc6e134SChris Mason 	test.offset = sk->max_offset;
1925abc6e134SChris Mason 
1926abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1927abc6e134SChris Mason 	if (ret > 0)
1928ac8e9819SChris Mason 		return 0;
1929ac8e9819SChris Mason 	return 1;
1930ac8e9819SChris Mason }
1931ac8e9819SChris Mason 
1932ac8e9819SChris Mason static noinline int copy_to_sk(struct btrfs_root *root,
1933ac8e9819SChris Mason 			       struct btrfs_path *path,
1934ac8e9819SChris Mason 			       struct btrfs_key *key,
1935ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
19369b6e817dSGerhard Heift 			       size_t *buf_size,
1937ba346b35SGerhard Heift 			       char __user *ubuf,
1938ac8e9819SChris Mason 			       unsigned long *sk_offset,
1939ac8e9819SChris Mason 			       int *num_found)
1940ac8e9819SChris Mason {
1941ac8e9819SChris Mason 	u64 found_transid;
1942ac8e9819SChris Mason 	struct extent_buffer *leaf;
1943ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
1944dd81d459SNaohiro Aota 	struct btrfs_key test;
1945ac8e9819SChris Mason 	unsigned long item_off;
1946ac8e9819SChris Mason 	unsigned long item_len;
1947ac8e9819SChris Mason 	int nritems;
1948ac8e9819SChris Mason 	int i;
1949ac8e9819SChris Mason 	int slot;
1950ac8e9819SChris Mason 	int ret = 0;
1951ac8e9819SChris Mason 
1952ac8e9819SChris Mason 	leaf = path->nodes[0];
1953ac8e9819SChris Mason 	slot = path->slots[0];
1954ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
1955ac8e9819SChris Mason 
1956ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
1957ac8e9819SChris Mason 		i = nritems;
1958ac8e9819SChris Mason 		goto advance_key;
1959ac8e9819SChris Mason 	}
1960ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
1961ac8e9819SChris Mason 
1962ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
1963ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
1964ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
1965ac8e9819SChris Mason 
196603b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
196703b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
196803b71c6cSGabriel de Perthuis 			continue;
196903b71c6cSGabriel de Perthuis 
19709b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
19718f5f6178SGerhard Heift 			if (*num_found) {
1972ac8e9819SChris Mason 				ret = 1;
19738f5f6178SGerhard Heift 				goto out;
19748f5f6178SGerhard Heift 			}
19758f5f6178SGerhard Heift 
19768f5f6178SGerhard Heift 			/*
19778f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
19788f5f6178SGerhard Heift 			 * handle -EOVERFLOW
19798f5f6178SGerhard Heift 			 */
19808f5f6178SGerhard Heift 
19819b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
1982ac8e9819SChris Mason 			item_len = 0;
19838f5f6178SGerhard Heift 			ret = -EOVERFLOW;
19848f5f6178SGerhard Heift 		}
1985ac8e9819SChris Mason 
19869b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
1987ac8e9819SChris Mason 			ret = 1;
198825c9bc2eSGerhard Heift 			goto out;
1989ac8e9819SChris Mason 		}
1990ac8e9819SChris Mason 
1991ac8e9819SChris Mason 		sh.objectid = key->objectid;
1992ac8e9819SChris Mason 		sh.offset = key->offset;
1993ac8e9819SChris Mason 		sh.type = key->type;
1994ac8e9819SChris Mason 		sh.len = item_len;
1995ac8e9819SChris Mason 		sh.transid = found_transid;
1996ac8e9819SChris Mason 
1997ac8e9819SChris Mason 		/* copy search result header */
1998ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
1999ba346b35SGerhard Heift 			ret = -EFAULT;
2000ba346b35SGerhard Heift 			goto out;
2001ba346b35SGerhard Heift 		}
2002ba346b35SGerhard Heift 
2003ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2004ac8e9819SChris Mason 
2005ac8e9819SChris Mason 		if (item_len) {
2006ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2007ac8e9819SChris Mason 			/* copy the item */
2008ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
2009ba346b35SGerhard Heift 						       item_off, item_len)) {
2010ba346b35SGerhard Heift 				ret = -EFAULT;
2011ba346b35SGerhard Heift 				goto out;
2012ba346b35SGerhard Heift 			}
2013ba346b35SGerhard Heift 
2014ac8e9819SChris Mason 			*sk_offset += item_len;
2015ac8e9819SChris Mason 		}
2016e2156867SHugo Mills 		(*num_found)++;
2017ac8e9819SChris Mason 
20188f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
20198f5f6178SGerhard Heift 			goto out;
20208f5f6178SGerhard Heift 
202125c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
202225c9bc2eSGerhard Heift 			ret = 1;
202325c9bc2eSGerhard Heift 			goto out;
202425c9bc2eSGerhard Heift 		}
2025ac8e9819SChris Mason 	}
2026ac8e9819SChris Mason advance_key:
2027ac8e9819SChris Mason 	ret = 0;
2028dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2029dd81d459SNaohiro Aota 	test.type = sk->max_type;
2030dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2031dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2032dd81d459SNaohiro Aota 		ret = 1;
2033dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2034abc6e134SChris Mason 		key->offset++;
2035dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2036abc6e134SChris Mason 		key->offset = 0;
2037abc6e134SChris Mason 		key->type++;
2038dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2039abc6e134SChris Mason 		key->offset = 0;
2040abc6e134SChris Mason 		key->type = 0;
2041abc6e134SChris Mason 		key->objectid++;
2042abc6e134SChris Mason 	} else
2043abc6e134SChris Mason 		ret = 1;
204425c9bc2eSGerhard Heift out:
2045ba346b35SGerhard Heift 	/*
2046ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2047ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2048ba346b35SGerhard Heift 	 *     * all items were found
2049ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2050ba346b35SGerhard Heift 	 *     leaf
2051ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2052ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2053ba346b35SGerhard Heift 	 */
2054ac8e9819SChris Mason 	return ret;
2055ac8e9819SChris Mason }
2056ac8e9819SChris Mason 
2057ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
205812544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
20599b6e817dSGerhard Heift 				 size_t *buf_size,
2060ba346b35SGerhard Heift 				 char __user *ubuf)
2061ac8e9819SChris Mason {
2062ac8e9819SChris Mason 	struct btrfs_root *root;
2063ac8e9819SChris Mason 	struct btrfs_key key;
2064ac8e9819SChris Mason 	struct btrfs_path *path;
2065ac8e9819SChris Mason 	struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
2066ac8e9819SChris Mason 	int ret;
2067ac8e9819SChris Mason 	int num_found = 0;
2068ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2069ac8e9819SChris Mason 
20709b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
20719b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
207212544442SGerhard Heift 		return -EOVERFLOW;
20739b6e817dSGerhard Heift 	}
207412544442SGerhard Heift 
2075ac8e9819SChris Mason 	path = btrfs_alloc_path();
2076ac8e9819SChris Mason 	if (!path)
2077ac8e9819SChris Mason 		return -ENOMEM;
2078ac8e9819SChris Mason 
2079ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2080ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2081ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2082ac8e9819SChris Mason 	} else {
2083ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2084ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2085ac8e9819SChris Mason 		key.offset = (u64)-1;
2086ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2087ac8e9819SChris Mason 		if (IS_ERR(root)) {
2088f14d104dSDavid Sterba 			btrfs_err(info, "could not find root %llu",
2089ac8e9819SChris Mason 			       sk->tree_id);
2090ac8e9819SChris Mason 			btrfs_free_path(path);
2091ac8e9819SChris Mason 			return -ENOENT;
2092ac8e9819SChris Mason 		}
2093ac8e9819SChris Mason 	}
2094ac8e9819SChris Mason 
2095ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2096ac8e9819SChris Mason 	key.type = sk->min_type;
2097ac8e9819SChris Mason 	key.offset = sk->min_offset;
2098ac8e9819SChris Mason 
2099ac8e9819SChris Mason 	while (1) {
21006174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2101ac8e9819SChris Mason 		if (ret != 0) {
2102ac8e9819SChris Mason 			if (ret > 0)
2103ac8e9819SChris Mason 				ret = 0;
2104ac8e9819SChris Mason 			goto err;
2105ac8e9819SChris Mason 		}
2106ba346b35SGerhard Heift 		ret = copy_to_sk(root, path, &key, sk, buf_size, ubuf,
2107ac8e9819SChris Mason 				 &sk_offset, &num_found);
2108b3b4aa74SDavid Sterba 		btrfs_release_path(path);
210925c9bc2eSGerhard Heift 		if (ret)
2110ac8e9819SChris Mason 			break;
2111ac8e9819SChris Mason 
2112ac8e9819SChris Mason 	}
21138f5f6178SGerhard Heift 	if (ret > 0)
2114ac8e9819SChris Mason 		ret = 0;
2115ac8e9819SChris Mason err:
2116ac8e9819SChris Mason 	sk->nr_items = num_found;
2117ac8e9819SChris Mason 	btrfs_free_path(path);
2118ac8e9819SChris Mason 	return ret;
2119ac8e9819SChris Mason }
2120ac8e9819SChris Mason 
2121ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2122ac8e9819SChris Mason 					   void __user *argp)
2123ac8e9819SChris Mason {
2124ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2125ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2126ac8e9819SChris Mason 	struct inode *inode;
2127ac8e9819SChris Mason 	int ret;
21289b6e817dSGerhard Heift 	size_t buf_size;
2129ac8e9819SChris Mason 
2130ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2131ac8e9819SChris Mason 		return -EPERM;
2132ac8e9819SChris Mason 
2133ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2134ac8e9819SChris Mason 
2135ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2136ba346b35SGerhard Heift 		return -EFAULT;
2137ba346b35SGerhard Heift 
2138ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2139ac8e9819SChris Mason 
2140496ad9aaSAl Viro 	inode = file_inode(file);
2141ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
21428f5f6178SGerhard Heift 
21438f5f6178SGerhard Heift 	/*
21448f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
21458f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
21468f5f6178SGerhard Heift 	 */
21478f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
21488f5f6178SGerhard Heift 		ret = 0;
21498f5f6178SGerhard Heift 
2150ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2151ac8e9819SChris Mason 		ret = -EFAULT;
2152ac8e9819SChris Mason 	return ret;
2153ac8e9819SChris Mason }
2154ac8e9819SChris Mason 
2155cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2156cc68a8a5SGerhard Heift 					       void __user *argp)
2157cc68a8a5SGerhard Heift {
2158cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2159cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2160cc68a8a5SGerhard Heift 	struct inode *inode;
2161cc68a8a5SGerhard Heift 	int ret;
2162cc68a8a5SGerhard Heift 	size_t buf_size;
2163cc68a8a5SGerhard Heift 	const size_t buf_limit = 16 * 1024 * 1024;
2164cc68a8a5SGerhard Heift 
2165cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2166cc68a8a5SGerhard Heift 		return -EPERM;
2167cc68a8a5SGerhard Heift 
2168cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2169cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2170cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2171cc68a8a5SGerhard Heift 		return -EFAULT;
2172cc68a8a5SGerhard Heift 
2173cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2174cc68a8a5SGerhard Heift 
2175cc68a8a5SGerhard Heift 	if (buf_size < sizeof(struct btrfs_ioctl_search_header))
2176cc68a8a5SGerhard Heift 		return -EOVERFLOW;
2177cc68a8a5SGerhard Heift 
2178cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2179cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2180cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2181cc68a8a5SGerhard Heift 
2182cc68a8a5SGerhard Heift 	inode = file_inode(file);
2183cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2184cc68a8a5SGerhard Heift 			   (char *)(&uarg->buf[0]));
2185cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2186cc68a8a5SGerhard Heift 		ret = -EFAULT;
2187cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2188cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2189cc68a8a5SGerhard Heift 		ret = -EFAULT;
2190cc68a8a5SGerhard Heift 
219176dda93cSYan, Zheng 	return ret;
219276dda93cSYan, Zheng }
219376dda93cSYan, Zheng 
219498d377a0STARUISI Hiroaki /*
2195ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2196ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
219798d377a0STARUISI Hiroaki  */
219898d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
219998d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
220098d377a0STARUISI Hiroaki {
220198d377a0STARUISI Hiroaki 	struct btrfs_root *root;
220298d377a0STARUISI Hiroaki 	struct btrfs_key key;
2203ac8e9819SChris Mason 	char *ptr;
220498d377a0STARUISI Hiroaki 	int ret = -1;
220598d377a0STARUISI Hiroaki 	int slot;
220698d377a0STARUISI Hiroaki 	int len;
220798d377a0STARUISI Hiroaki 	int total_len = 0;
220898d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
220998d377a0STARUISI Hiroaki 	struct extent_buffer *l;
221098d377a0STARUISI Hiroaki 	struct btrfs_path *path;
221198d377a0STARUISI Hiroaki 
221298d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
221398d377a0STARUISI Hiroaki 		name[0]='\0';
221498d377a0STARUISI Hiroaki 		return 0;
221598d377a0STARUISI Hiroaki 	}
221698d377a0STARUISI Hiroaki 
221798d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
221898d377a0STARUISI Hiroaki 	if (!path)
221998d377a0STARUISI Hiroaki 		return -ENOMEM;
222098d377a0STARUISI Hiroaki 
2221ac8e9819SChris Mason 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
222298d377a0STARUISI Hiroaki 
222398d377a0STARUISI Hiroaki 	key.objectid = tree_id;
222498d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
222598d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
222698d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
222798d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2228f14d104dSDavid Sterba 		btrfs_err(info, "could not find root %llu", tree_id);
22298ad6fcabSChris Mason 		ret = -ENOENT;
22308ad6fcabSChris Mason 		goto out;
223198d377a0STARUISI Hiroaki 	}
223298d377a0STARUISI Hiroaki 
223398d377a0STARUISI Hiroaki 	key.objectid = dirid;
223498d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
22358ad6fcabSChris Mason 	key.offset = (u64)-1;
223698d377a0STARUISI Hiroaki 
223798d377a0STARUISI Hiroaki 	while (1) {
223898d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
223998d377a0STARUISI Hiroaki 		if (ret < 0)
224098d377a0STARUISI Hiroaki 			goto out;
224118674c6cSFilipe David Borba Manana 		else if (ret > 0) {
224218674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
224318674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
224418674c6cSFilipe David Borba Manana 			if (ret < 0)
224518674c6cSFilipe David Borba Manana 				goto out;
224618674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2247ac8e9819SChris Mason 				ret = -ENOENT;
224898d377a0STARUISI Hiroaki 				goto out;
2249ac8e9819SChris Mason 			}
225018674c6cSFilipe David Borba Manana 		}
225118674c6cSFilipe David Borba Manana 
225218674c6cSFilipe David Borba Manana 		l = path->nodes[0];
225318674c6cSFilipe David Borba Manana 		slot = path->slots[0];
225418674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
225598d377a0STARUISI Hiroaki 
225698d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
225798d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
225898d377a0STARUISI Hiroaki 		ptr -= len + 1;
225998d377a0STARUISI Hiroaki 		total_len += len + 1;
2260a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2261a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
226298d377a0STARUISI Hiroaki 			goto out;
2263a696cf35SFilipe David Borba Manana 		}
226498d377a0STARUISI Hiroaki 
226598d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
226698d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
226798d377a0STARUISI Hiroaki 
226898d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
226998d377a0STARUISI Hiroaki 			break;
227098d377a0STARUISI Hiroaki 
2271b3b4aa74SDavid Sterba 		btrfs_release_path(path);
227298d377a0STARUISI Hiroaki 		key.objectid = key.offset;
22738ad6fcabSChris Mason 		key.offset = (u64)-1;
227498d377a0STARUISI Hiroaki 		dirid = key.objectid;
227598d377a0STARUISI Hiroaki 	}
227677906a50SLi Zefan 	memmove(name, ptr, total_len);
227798d377a0STARUISI Hiroaki 	name[total_len] = '\0';
227898d377a0STARUISI Hiroaki 	ret = 0;
227998d377a0STARUISI Hiroaki out:
228098d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2281ac8e9819SChris Mason 	return ret;
2282ac8e9819SChris Mason }
2283ac8e9819SChris Mason 
2284ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2285ac8e9819SChris Mason 					   void __user *argp)
2286ac8e9819SChris Mason {
2287ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2288ac8e9819SChris Mason 	 struct inode *inode;
228901b810b8SDavid Sterba 	int ret = 0;
2290ac8e9819SChris Mason 
22912354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
22922354d08fSJulia Lawall 	if (IS_ERR(args))
22932354d08fSJulia Lawall 		return PTR_ERR(args);
2294c2b96929SDan Carpenter 
2295496ad9aaSAl Viro 	inode = file_inode(file);
2296ac8e9819SChris Mason 
229701b810b8SDavid Sterba 	/*
229801b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
229901b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
230001b810b8SDavid Sterba 	 */
23011b53ac4dSChris Mason 	if (args->treeid == 0)
23021b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
23031b53ac4dSChris Mason 
230401b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
230501b810b8SDavid Sterba 		args->name[0] = 0;
230601b810b8SDavid Sterba 		goto out;
230701b810b8SDavid Sterba 	}
230801b810b8SDavid Sterba 
230901b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
231001b810b8SDavid Sterba 		ret = -EPERM;
231101b810b8SDavid Sterba 		goto out;
231201b810b8SDavid Sterba 	}
231301b810b8SDavid Sterba 
2314ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2315ac8e9819SChris Mason 					args->treeid, args->objectid,
2316ac8e9819SChris Mason 					args->name);
2317ac8e9819SChris Mason 
231801b810b8SDavid Sterba out:
2319ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2320ac8e9819SChris Mason 		ret = -EFAULT;
2321ac8e9819SChris Mason 
2322ac8e9819SChris Mason 	kfree(args);
232398d377a0STARUISI Hiroaki 	return ret;
232498d377a0STARUISI Hiroaki }
232598d377a0STARUISI Hiroaki 
232676dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
232776dda93cSYan, Zheng 					     void __user *arg)
232876dda93cSYan, Zheng {
232954563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
233076dda93cSYan, Zheng 	struct dentry *dentry;
23312b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
233276dda93cSYan, Zheng 	struct inode *inode;
233376dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
233476dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
233576dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
233676dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
2337c58aaad2SMiao Xie 	struct btrfs_block_rsv block_rsv;
2338521e0546SDavid Sterba 	u64 root_flags;
2339c58aaad2SMiao Xie 	u64 qgroup_reserved;
234076dda93cSYan, Zheng 	int namelen;
234176dda93cSYan, Zheng 	int ret;
234276dda93cSYan, Zheng 	int err = 0;
234376dda93cSYan, Zheng 
234476dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
234576dda93cSYan, Zheng 	if (IS_ERR(vol_args))
234676dda93cSYan, Zheng 		return PTR_ERR(vol_args);
234776dda93cSYan, Zheng 
234876dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
234976dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
235076dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
235176dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
235276dda93cSYan, Zheng 		err = -EINVAL;
235376dda93cSYan, Zheng 		goto out;
235476dda93cSYan, Zheng 	}
235576dda93cSYan, Zheng 
2356a561be71SAl Viro 	err = mnt_want_write_file(file);
235776dda93cSYan, Zheng 	if (err)
235876dda93cSYan, Zheng 		goto out;
235976dda93cSYan, Zheng 
2360521e0546SDavid Sterba 
23615c50c9b8SDavid Sterba 	err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
23625c50c9b8SDavid Sterba 	if (err == -EINTR)
2363e43f998eSDavid Sterba 		goto out_drop_write;
236476dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
236576dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
236676dda93cSYan, Zheng 		err = PTR_ERR(dentry);
236776dda93cSYan, Zheng 		goto out_unlock_dir;
236876dda93cSYan, Zheng 	}
236976dda93cSYan, Zheng 
23702b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
237176dda93cSYan, Zheng 		err = -ENOENT;
237276dda93cSYan, Zheng 		goto out_dput;
237376dda93cSYan, Zheng 	}
237476dda93cSYan, Zheng 
23752b0143b5SDavid Howells 	inode = d_inode(dentry);
23764260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
23774260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
23784260f7c7SSage Weil 		/*
23794260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
23804260f7c7SSage Weil 		 * option, when the user has write+exec access to the
23814260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
23824260f7c7SSage Weil 		 * allowed.
23834260f7c7SSage Weil 		 *
23844260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
23854260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
23864260f7c7SSage Weil 		 * otherwise be able to delete.
23874260f7c7SSage Weil 		 *
23884260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
23894260f7c7SSage Weil 		 * rmdir(2).
23904260f7c7SSage Weil 		 */
23914260f7c7SSage Weil 		err = -EPERM;
23924260f7c7SSage Weil 		if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
23934260f7c7SSage Weil 			goto out_dput;
23944260f7c7SSage Weil 
23954260f7c7SSage Weil 		/*
23964260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
23974260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
23984260f7c7SSage Weil 		 * must be called on the dentry referencing the root
23994260f7c7SSage Weil 		 * of the subvol, not a random directory contained
24004260f7c7SSage Weil 		 * within it.
24014260f7c7SSage Weil 		 */
24024260f7c7SSage Weil 		err = -EINVAL;
24034260f7c7SSage Weil 		if (root == dest)
24044260f7c7SSage Weil 			goto out_dput;
24054260f7c7SSage Weil 
24064260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
24074260f7c7SSage Weil 		if (err)
24084260f7c7SSage Weil 			goto out_dput;
24095c39da5bSMiao Xie 	}
24104260f7c7SSage Weil 
24115c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
24124260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
24134260f7c7SSage Weil 	if (err)
24144260f7c7SSage Weil 		goto out_dput;
24154260f7c7SSage Weil 
241633345d01SLi Zefan 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
241776dda93cSYan, Zheng 		err = -EINVAL;
241876dda93cSYan, Zheng 		goto out_dput;
241976dda93cSYan, Zheng 	}
242076dda93cSYan, Zheng 
242176dda93cSYan, Zheng 	mutex_lock(&inode->i_mutex);
2422521e0546SDavid Sterba 
2423521e0546SDavid Sterba 	/*
2424521e0546SDavid Sterba 	 * Don't allow to delete a subvolume with send in progress. This is
2425521e0546SDavid Sterba 	 * inside the i_mutex so the error handling that has to drop the bit
2426521e0546SDavid Sterba 	 * again is not run concurrently.
2427521e0546SDavid Sterba 	 */
2428521e0546SDavid Sterba 	spin_lock(&dest->root_item_lock);
2429c55bfa67SFilipe Manana 	root_flags = btrfs_root_flags(&dest->root_item);
2430c55bfa67SFilipe Manana 	if (dest->send_in_progress == 0) {
2431c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2432521e0546SDavid Sterba 				root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2433521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2434521e0546SDavid Sterba 	} else {
2435521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2436521e0546SDavid Sterba 		btrfs_warn(root->fs_info,
2437521e0546SDavid Sterba 			"Attempt to delete subvolume %llu during send",
2438c55bfa67SFilipe Manana 			dest->root_key.objectid);
2439521e0546SDavid Sterba 		err = -EPERM;
2440909e26dcSOmar Sandoval 		goto out_unlock_inode;
2441521e0546SDavid Sterba 	}
2442521e0546SDavid Sterba 
244376dda93cSYan, Zheng 	down_write(&root->fs_info->subvol_sem);
244476dda93cSYan, Zheng 
244576dda93cSYan, Zheng 	err = may_destroy_subvol(dest);
244676dda93cSYan, Zheng 	if (err)
244776dda93cSYan, Zheng 		goto out_up_write;
244876dda93cSYan, Zheng 
2449c58aaad2SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2450c58aaad2SMiao Xie 	/*
2451c58aaad2SMiao Xie 	 * One for dir inode, two for dir entries, two for root
2452c58aaad2SMiao Xie 	 * ref/backref.
2453c58aaad2SMiao Xie 	 */
2454c58aaad2SMiao Xie 	err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2455ee3441b4SJeff Mahoney 					       5, &qgroup_reserved, true);
2456c58aaad2SMiao Xie 	if (err)
2457c58aaad2SMiao Xie 		goto out_up_write;
2458c58aaad2SMiao Xie 
2459a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 0);
2460a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
2461a22285a6SYan, Zheng 		err = PTR_ERR(trans);
2462c58aaad2SMiao Xie 		goto out_release;
2463a22285a6SYan, Zheng 	}
2464c58aaad2SMiao Xie 	trans->block_rsv = &block_rsv;
2465c58aaad2SMiao Xie 	trans->bytes_reserved = block_rsv.size;
2466a22285a6SYan, Zheng 
246776dda93cSYan, Zheng 	ret = btrfs_unlink_subvol(trans, root, dir,
246876dda93cSYan, Zheng 				dest->root_key.objectid,
246976dda93cSYan, Zheng 				dentry->d_name.name,
247076dda93cSYan, Zheng 				dentry->d_name.len);
247179787eaaSJeff Mahoney 	if (ret) {
247279787eaaSJeff Mahoney 		err = ret;
247379787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
247479787eaaSJeff Mahoney 		goto out_end_trans;
247579787eaaSJeff Mahoney 	}
247676dda93cSYan, Zheng 
247776dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, dest);
247876dda93cSYan, Zheng 
247976dda93cSYan, Zheng 	memset(&dest->root_item.drop_progress, 0,
248076dda93cSYan, Zheng 		sizeof(dest->root_item.drop_progress));
248176dda93cSYan, Zheng 	dest->root_item.drop_level = 0;
248276dda93cSYan, Zheng 	btrfs_set_root_refs(&dest->root_item, 0);
248376dda93cSYan, Zheng 
248427cdeb70SMiao Xie 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
248576dda93cSYan, Zheng 		ret = btrfs_insert_orphan_item(trans,
248676dda93cSYan, Zheng 					root->fs_info->tree_root,
248776dda93cSYan, Zheng 					dest->root_key.objectid);
248879787eaaSJeff Mahoney 		if (ret) {
248979787eaaSJeff Mahoney 			btrfs_abort_transaction(trans, root, ret);
249079787eaaSJeff Mahoney 			err = ret;
249179787eaaSJeff Mahoney 			goto out_end_trans;
2492d68fc57bSYan, Zheng 		}
249379787eaaSJeff Mahoney 	}
2494dd5f9615SStefan Behrens 
2495dd5f9615SStefan Behrens 	ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2496dd5f9615SStefan Behrens 				  dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2497dd5f9615SStefan Behrens 				  dest->root_key.objectid);
2498dd5f9615SStefan Behrens 	if (ret && ret != -ENOENT) {
2499dd5f9615SStefan Behrens 		btrfs_abort_transaction(trans, root, ret);
2500dd5f9615SStefan Behrens 		err = ret;
2501dd5f9615SStefan Behrens 		goto out_end_trans;
2502dd5f9615SStefan Behrens 	}
2503dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2504dd5f9615SStefan Behrens 		ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2505dd5f9615SStefan Behrens 					  dest->root_item.received_uuid,
2506dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2507dd5f9615SStefan Behrens 					  dest->root_key.objectid);
2508dd5f9615SStefan Behrens 		if (ret && ret != -ENOENT) {
2509dd5f9615SStefan Behrens 			btrfs_abort_transaction(trans, root, ret);
2510dd5f9615SStefan Behrens 			err = ret;
2511dd5f9615SStefan Behrens 			goto out_end_trans;
2512dd5f9615SStefan Behrens 		}
2513dd5f9615SStefan Behrens 	}
2514dd5f9615SStefan Behrens 
251579787eaaSJeff Mahoney out_end_trans:
2516c58aaad2SMiao Xie 	trans->block_rsv = NULL;
2517c58aaad2SMiao Xie 	trans->bytes_reserved = 0;
2518531cb13fSSage Weil 	ret = btrfs_end_transaction(trans, root);
251979787eaaSJeff Mahoney 	if (ret && !err)
252079787eaaSJeff Mahoney 		err = ret;
252176dda93cSYan, Zheng 	inode->i_flags |= S_DEAD;
2522c58aaad2SMiao Xie out_release:
2523c58aaad2SMiao Xie 	btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
252476dda93cSYan, Zheng out_up_write:
252576dda93cSYan, Zheng 	up_write(&root->fs_info->subvol_sem);
2526521e0546SDavid Sterba 	if (err) {
2527521e0546SDavid Sterba 		spin_lock(&dest->root_item_lock);
2528c55bfa67SFilipe Manana 		root_flags = btrfs_root_flags(&dest->root_item);
2529c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2530521e0546SDavid Sterba 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2531521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2532521e0546SDavid Sterba 	}
2533909e26dcSOmar Sandoval out_unlock_inode:
253476dda93cSYan, Zheng 	mutex_unlock(&inode->i_mutex);
253576dda93cSYan, Zheng 	if (!err) {
253664ad6c48SOmar Sandoval 		d_invalidate(dentry);
253776dda93cSYan, Zheng 		btrfs_invalidate_inodes(dest);
253876dda93cSYan, Zheng 		d_delete(dentry);
253961155aa0SDavid Sterba 		ASSERT(dest->send_in_progress == 0);
2540fa6ac876SLiu Bo 
2541fa6ac876SLiu Bo 		/* the last ref */
254257cdc8dbSDavid Sterba 		if (dest->ino_cache_inode) {
254357cdc8dbSDavid Sterba 			iput(dest->ino_cache_inode);
254457cdc8dbSDavid Sterba 			dest->ino_cache_inode = NULL;
2545fa6ac876SLiu Bo 		}
254676dda93cSYan, Zheng 	}
254776dda93cSYan, Zheng out_dput:
254876dda93cSYan, Zheng 	dput(dentry);
254976dda93cSYan, Zheng out_unlock_dir:
255076dda93cSYan, Zheng 	mutex_unlock(&dir->i_mutex);
2551e43f998eSDavid Sterba out_drop_write:
25522a79f17eSAl Viro 	mnt_drop_write_file(file);
255376dda93cSYan, Zheng out:
255476dda93cSYan, Zheng 	kfree(vol_args);
255576dda93cSYan, Zheng 	return err;
255676dda93cSYan, Zheng }
255776dda93cSYan, Zheng 
25581e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2559f46b5a66SChristoph Hellwig {
2560496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2561f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
25621e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2563c146afadSYan Zheng 	int ret;
2564c146afadSYan Zheng 
256525122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
256625122d15SIlya Dryomov 	if (ret)
256725122d15SIlya Dryomov 		return ret;
2568b83cc969SLi Zefan 
256925122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
257025122d15SIlya Dryomov 		ret = -EROFS;
257125122d15SIlya Dryomov 		goto out;
25725ac00addSStefan Behrens 	}
2573f46b5a66SChristoph Hellwig 
2574f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2575f46b5a66SChristoph Hellwig 	case S_IFDIR:
2576e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2577e441d54dSChris Mason 			ret = -EPERM;
2578e441d54dSChris Mason 			goto out;
2579e441d54dSChris Mason 		}
2580de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
25818929ecfaSYan, Zheng 		if (ret)
25828929ecfaSYan, Zheng 			goto out;
2583de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root->fs_info->extent_root);
2584f46b5a66SChristoph Hellwig 		break;
2585f46b5a66SChristoph Hellwig 	case S_IFREG:
2586e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2587e441d54dSChris Mason 			ret = -EINVAL;
2588e441d54dSChris Mason 			goto out;
2589e441d54dSChris Mason 		}
25901e701a32SChris Mason 
25911e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
25921e701a32SChris Mason 		if (!range) {
25931e701a32SChris Mason 			ret = -ENOMEM;
25941e701a32SChris Mason 			goto out;
25951e701a32SChris Mason 		}
25961e701a32SChris Mason 
25971e701a32SChris Mason 		if (argp) {
25981e701a32SChris Mason 			if (copy_from_user(range, argp,
25991e701a32SChris Mason 					   sizeof(*range))) {
26001e701a32SChris Mason 				ret = -EFAULT;
26011e701a32SChris Mason 				kfree(range);
2602683be16eSDan Carpenter 				goto out;
26031e701a32SChris Mason 			}
26041e701a32SChris Mason 			/* compression requires us to start the IO */
26051e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
26061e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
26071e701a32SChris Mason 				range->extent_thresh = (u32)-1;
26081e701a32SChris Mason 			}
26091e701a32SChris Mason 		} else {
26101e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
26111e701a32SChris Mason 			range->len = (u64)-1;
26121e701a32SChris Mason 		}
2613496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
26144cb5300bSChris Mason 					range, 0, 0);
26154cb5300bSChris Mason 		if (ret > 0)
26164cb5300bSChris Mason 			ret = 0;
26171e701a32SChris Mason 		kfree(range);
2618f46b5a66SChristoph Hellwig 		break;
26198929ecfaSYan, Zheng 	default:
26208929ecfaSYan, Zheng 		ret = -EINVAL;
2621f46b5a66SChristoph Hellwig 	}
2622e441d54dSChris Mason out:
262325122d15SIlya Dryomov 	mnt_drop_write_file(file);
2624e441d54dSChris Mason 	return ret;
2625f46b5a66SChristoph Hellwig }
2626f46b5a66SChristoph Hellwig 
2627b2950863SChristoph Hellwig static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2628f46b5a66SChristoph Hellwig {
2629f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2630f46b5a66SChristoph Hellwig 	int ret;
2631f46b5a66SChristoph Hellwig 
2632e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2633e441d54dSChris Mason 		return -EPERM;
2634e441d54dSChris Mason 
26355ac00addSStefan Behrens 	if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
26365ac00addSStefan Behrens 			1)) {
2637e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2638c9e9f97bSIlya Dryomov 	}
2639c9e9f97bSIlya Dryomov 
26405ac00addSStefan Behrens 	mutex_lock(&root->fs_info->volume_mutex);
2641dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2642c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2643c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2644c9e9f97bSIlya Dryomov 		goto out;
2645c9e9f97bSIlya Dryomov 	}
2646f46b5a66SChristoph Hellwig 
26475516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2648f46b5a66SChristoph Hellwig 	ret = btrfs_init_new_device(root, vol_args->name);
2649f46b5a66SChristoph Hellwig 
265043d20761SAnand Jain 	if (!ret)
265143d20761SAnand Jain 		btrfs_info(root->fs_info, "disk added %s",vol_args->name);
265243d20761SAnand Jain 
2653f46b5a66SChristoph Hellwig 	kfree(vol_args);
2654c9e9f97bSIlya Dryomov out:
2655c9e9f97bSIlya Dryomov 	mutex_unlock(&root->fs_info->volume_mutex);
26565ac00addSStefan Behrens 	atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2657f46b5a66SChristoph Hellwig 	return ret;
2658f46b5a66SChristoph Hellwig }
2659f46b5a66SChristoph Hellwig 
2660da24927bSMiao Xie static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2661f46b5a66SChristoph Hellwig {
2662496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2663f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2664f46b5a66SChristoph Hellwig 	int ret;
2665f46b5a66SChristoph Hellwig 
2666e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2667e441d54dSChris Mason 		return -EPERM;
2668e441d54dSChris Mason 
2669da24927bSMiao Xie 	ret = mnt_want_write_file(file);
2670da24927bSMiao Xie 	if (ret)
2671da24927bSMiao Xie 		return ret;
2672c146afadSYan Zheng 
2673dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2674c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2675c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2676c47ca32dSDan Carpenter 		goto err_drop;
2677c9e9f97bSIlya Dryomov 	}
2678f46b5a66SChristoph Hellwig 
26795516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2680f46b5a66SChristoph Hellwig 
2681183860f6SAnand Jain 	if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2682183860f6SAnand Jain 			1)) {
2683183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2684183860f6SAnand Jain 		goto out;
2685183860f6SAnand Jain 	}
2686183860f6SAnand Jain 
2687183860f6SAnand Jain 	mutex_lock(&root->fs_info->volume_mutex);
2688183860f6SAnand Jain 	ret = btrfs_rm_device(root, vol_args->name);
2689c9e9f97bSIlya Dryomov 	mutex_unlock(&root->fs_info->volume_mutex);
26905ac00addSStefan Behrens 	atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2691183860f6SAnand Jain 
2692ec95d491SAnand Jain 	if (!ret)
2693ec95d491SAnand Jain 		btrfs_info(root->fs_info, "disk deleted %s",vol_args->name);
2694ec95d491SAnand Jain 
2695183860f6SAnand Jain out:
2696183860f6SAnand Jain 	kfree(vol_args);
2697c47ca32dSDan Carpenter err_drop:
26984ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
2699f46b5a66SChristoph Hellwig 	return ret;
2700f46b5a66SChristoph Hellwig }
2701f46b5a66SChristoph Hellwig 
2702475f6387SJan Schmidt static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2703475f6387SJan Schmidt {
2704027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
2705475f6387SJan Schmidt 	struct btrfs_device *device;
2706475f6387SJan Schmidt 	struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2707027ed2f0SLi Zefan 	int ret = 0;
2708475f6387SJan Schmidt 
2709027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2710027ed2f0SLi Zefan 	if (!fi_args)
2711027ed2f0SLi Zefan 		return -ENOMEM;
2712027ed2f0SLi Zefan 
2713f7171750SFilipe David Borba Manana 	mutex_lock(&fs_devices->device_list_mutex);
2714027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
2715027ed2f0SLi Zefan 	memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2716475f6387SJan Schmidt 
2717d7641a49SByongho Lee 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
2718027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
2719027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
2720475f6387SJan Schmidt 	}
2721475f6387SJan Schmidt 	mutex_unlock(&fs_devices->device_list_mutex);
2722475f6387SJan Schmidt 
272380a773fbSDavid Sterba 	fi_args->nodesize = root->fs_info->super_copy->nodesize;
272480a773fbSDavid Sterba 	fi_args->sectorsize = root->fs_info->super_copy->sectorsize;
272580a773fbSDavid Sterba 	fi_args->clone_alignment = root->fs_info->super_copy->sectorsize;
272680a773fbSDavid Sterba 
2727027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2728027ed2f0SLi Zefan 		ret = -EFAULT;
2729475f6387SJan Schmidt 
2730027ed2f0SLi Zefan 	kfree(fi_args);
2731027ed2f0SLi Zefan 	return ret;
2732475f6387SJan Schmidt }
2733475f6387SJan Schmidt 
2734475f6387SJan Schmidt static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2735475f6387SJan Schmidt {
2736475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
2737475f6387SJan Schmidt 	struct btrfs_device *dev;
2738475f6387SJan Schmidt 	struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2739475f6387SJan Schmidt 	int ret = 0;
2740475f6387SJan Schmidt 	char *s_uuid = NULL;
2741475f6387SJan Schmidt 
2742475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
2743475f6387SJan Schmidt 	if (IS_ERR(di_args))
2744475f6387SJan Schmidt 		return PTR_ERR(di_args);
2745475f6387SJan Schmidt 
2746dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
2747475f6387SJan Schmidt 		s_uuid = di_args->uuid;
2748475f6387SJan Schmidt 
2749475f6387SJan Schmidt 	mutex_lock(&fs_devices->device_list_mutex);
2750aa1b8cd4SStefan Behrens 	dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2751475f6387SJan Schmidt 
2752475f6387SJan Schmidt 	if (!dev) {
2753475f6387SJan Schmidt 		ret = -ENODEV;
2754475f6387SJan Schmidt 		goto out;
2755475f6387SJan Schmidt 	}
2756475f6387SJan Schmidt 
2757475f6387SJan Schmidt 	di_args->devid = dev->devid;
27587cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
27597cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2760475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2761a27202fbSJim Meyering 	if (dev->name) {
2762606686eeSJosef Bacik 		struct rcu_string *name;
2763606686eeSJosef Bacik 
2764606686eeSJosef Bacik 		rcu_read_lock();
2765606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
2766606686eeSJosef Bacik 		strncpy(di_args->path, name->str, sizeof(di_args->path));
2767606686eeSJosef Bacik 		rcu_read_unlock();
2768a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
2769a27202fbSJim Meyering 	} else {
277099ba55adSStefan Behrens 		di_args->path[0] = '\0';
2771a27202fbSJim Meyering 	}
2772475f6387SJan Schmidt 
2773475f6387SJan Schmidt out:
277455793c0dSDavid Sterba 	mutex_unlock(&fs_devices->device_list_mutex);
2775475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2776475f6387SJan Schmidt 		ret = -EFAULT;
2777475f6387SJan Schmidt 
2778475f6387SJan Schmidt 	kfree(di_args);
2779475f6387SJan Schmidt 	return ret;
2780475f6387SJan Schmidt }
2781475f6387SJan Schmidt 
2782f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2783416161dbSMark Fasheh {
2784416161dbSMark Fasheh 	struct page *page;
2785416161dbSMark Fasheh 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2786416161dbSMark Fasheh 
2787416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
2788416161dbSMark Fasheh 	if (!page)
2789416161dbSMark Fasheh 		return NULL;
2790416161dbSMark Fasheh 
2791416161dbSMark Fasheh 	if (!PageUptodate(page)) {
2792416161dbSMark Fasheh 		if (extent_read_full_page_nolock(tree, page, btrfs_get_extent,
2793416161dbSMark Fasheh 						 0))
2794416161dbSMark Fasheh 			return NULL;
2795416161dbSMark Fasheh 		lock_page(page);
2796416161dbSMark Fasheh 		if (!PageUptodate(page)) {
2797416161dbSMark Fasheh 			unlock_page(page);
2798416161dbSMark Fasheh 			page_cache_release(page);
2799416161dbSMark Fasheh 			return NULL;
2800416161dbSMark Fasheh 		}
2801416161dbSMark Fasheh 	}
2802416161dbSMark Fasheh 	unlock_page(page);
2803416161dbSMark Fasheh 
2804416161dbSMark Fasheh 	return page;
2805416161dbSMark Fasheh }
2806416161dbSMark Fasheh 
2807f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
2808f4414602SMark Fasheh 			       int num_pages, u64 off)
2809f4414602SMark Fasheh {
2810f4414602SMark Fasheh 	int i;
2811f4414602SMark Fasheh 	pgoff_t index = off >> PAGE_CACHE_SHIFT;
2812f4414602SMark Fasheh 
2813f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
2814f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
2815f4414602SMark Fasheh 		if (!pages[i])
2816f4414602SMark Fasheh 			return -ENOMEM;
2817f4414602SMark Fasheh 	}
2818f4414602SMark Fasheh 	return 0;
2819f4414602SMark Fasheh }
2820f4414602SMark Fasheh 
282177fe20dcSMark Fasheh static inline void lock_extent_range(struct inode *inode, u64 off, u64 len)
282277fe20dcSMark Fasheh {
282377fe20dcSMark Fasheh 	/* do any pending delalloc/csum calc on src, one way or
282477fe20dcSMark Fasheh 	   another, and lock file content */
282577fe20dcSMark Fasheh 	while (1) {
282677fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
282777fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
282877fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
282977fe20dcSMark Fasheh 							    off + len - 1);
2830ff5df9b8SFilipe Manana 		if ((!ordered ||
2831ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
2832ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
283377fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2834ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2835ff5df9b8SFilipe Manana 			if (ordered)
2836ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
283777fe20dcSMark Fasheh 			break;
2838ff5df9b8SFilipe Manana 		}
283977fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
284077fe20dcSMark Fasheh 		if (ordered)
284177fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
284277fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
284377fe20dcSMark Fasheh 	}
284477fe20dcSMark Fasheh }
284577fe20dcSMark Fasheh 
2846f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2847416161dbSMark Fasheh {
2848416161dbSMark Fasheh 	mutex_unlock(&inode1->i_mutex);
2849416161dbSMark Fasheh 	mutex_unlock(&inode2->i_mutex);
2850416161dbSMark Fasheh }
2851416161dbSMark Fasheh 
2852f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2853f4414602SMark Fasheh {
2854f4414602SMark Fasheh 	if (inode1 < inode2)
2855f4414602SMark Fasheh 		swap(inode1, inode2);
2856f4414602SMark Fasheh 
2857f4414602SMark Fasheh 	mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2858f4414602SMark Fasheh 	mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2859f4414602SMark Fasheh }
2860f4414602SMark Fasheh 
2861f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2862f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
2863f4414602SMark Fasheh {
2864f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2865f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2866f4414602SMark Fasheh }
2867f4414602SMark Fasheh 
2868f4414602SMark Fasheh static void btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2869416161dbSMark Fasheh 				     struct inode *inode2, u64 loff2, u64 len)
2870416161dbSMark Fasheh {
2871416161dbSMark Fasheh 	if (inode1 < inode2) {
2872416161dbSMark Fasheh 		swap(inode1, inode2);
2873416161dbSMark Fasheh 		swap(loff1, loff2);
2874416161dbSMark Fasheh 	}
2875416161dbSMark Fasheh 	lock_extent_range(inode1, loff1, len);
2876416161dbSMark Fasheh 	lock_extent_range(inode2, loff2, len);
2877416161dbSMark Fasheh }
2878f4414602SMark Fasheh 
2879f4414602SMark Fasheh struct cmp_pages {
2880f4414602SMark Fasheh 	int		num_pages;
2881f4414602SMark Fasheh 	struct page	**src_pages;
2882f4414602SMark Fasheh 	struct page	**dst_pages;
2883f4414602SMark Fasheh };
2884f4414602SMark Fasheh 
2885f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2886f4414602SMark Fasheh {
2887f4414602SMark Fasheh 	int i;
2888f4414602SMark Fasheh 	struct page *pg;
2889f4414602SMark Fasheh 
2890f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
2891f4414602SMark Fasheh 		pg = cmp->src_pages[i];
2892f4414602SMark Fasheh 		if (pg)
2893f4414602SMark Fasheh 			page_cache_release(pg);
2894f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
2895f4414602SMark Fasheh 		if (pg)
2896f4414602SMark Fasheh 			page_cache_release(pg);
2897f4414602SMark Fasheh 	}
2898f4414602SMark Fasheh 	kfree(cmp->src_pages);
2899f4414602SMark Fasheh 	kfree(cmp->dst_pages);
2900f4414602SMark Fasheh }
2901f4414602SMark Fasheh 
2902f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2903f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
2904f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
2905f4414602SMark Fasheh {
2906f4414602SMark Fasheh 	int ret;
2907f4414602SMark Fasheh 	int num_pages = PAGE_CACHE_ALIGN(len) >> PAGE_CACHE_SHIFT;
2908f4414602SMark Fasheh 	struct page **src_pgarr, **dst_pgarr;
2909f4414602SMark Fasheh 
2910f4414602SMark Fasheh 	/*
2911f4414602SMark Fasheh 	 * We must gather up all the pages before we initiate our
2912f4414602SMark Fasheh 	 * extent locking. We use an array for the page pointers. Size
2913f4414602SMark Fasheh 	 * of the array is bounded by len, which is in turn bounded by
2914f4414602SMark Fasheh 	 * BTRFS_MAX_DEDUPE_LEN.
2915f4414602SMark Fasheh 	 */
2916f4414602SMark Fasheh 	src_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2917f4414602SMark Fasheh 	dst_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2918f4414602SMark Fasheh 	if (!src_pgarr || !dst_pgarr) {
2919f4414602SMark Fasheh 		kfree(src_pgarr);
2920f4414602SMark Fasheh 		kfree(dst_pgarr);
2921f4414602SMark Fasheh 		return -ENOMEM;
2922f4414602SMark Fasheh 	}
2923f4414602SMark Fasheh 	cmp->num_pages = num_pages;
2924f4414602SMark Fasheh 	cmp->src_pages = src_pgarr;
2925f4414602SMark Fasheh 	cmp->dst_pages = dst_pgarr;
2926f4414602SMark Fasheh 
2927f4414602SMark Fasheh 	ret = gather_extent_pages(src, cmp->src_pages, cmp->num_pages, loff);
2928f4414602SMark Fasheh 	if (ret)
2929f4414602SMark Fasheh 		goto out;
2930f4414602SMark Fasheh 
2931f4414602SMark Fasheh 	ret = gather_extent_pages(dst, cmp->dst_pages, cmp->num_pages, dst_loff);
2932f4414602SMark Fasheh 
2933f4414602SMark Fasheh out:
2934f4414602SMark Fasheh 	if (ret)
2935f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
2936f4414602SMark Fasheh 	return 0;
2937416161dbSMark Fasheh }
2938416161dbSMark Fasheh 
2939416161dbSMark Fasheh static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2940f4414602SMark Fasheh 			  u64 dst_loff, u64 len, struct cmp_pages *cmp)
2941416161dbSMark Fasheh {
2942416161dbSMark Fasheh 	int ret = 0;
2943f4414602SMark Fasheh 	int i;
2944416161dbSMark Fasheh 	struct page *src_page, *dst_page;
2945416161dbSMark Fasheh 	unsigned int cmp_len = PAGE_CACHE_SIZE;
2946416161dbSMark Fasheh 	void *addr, *dst_addr;
2947416161dbSMark Fasheh 
2948f4414602SMark Fasheh 	i = 0;
2949416161dbSMark Fasheh 	while (len) {
2950416161dbSMark Fasheh 		if (len < PAGE_CACHE_SIZE)
2951416161dbSMark Fasheh 			cmp_len = len;
2952416161dbSMark Fasheh 
2953f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
2954f4414602SMark Fasheh 
2955f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
2956f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
2957f4414602SMark Fasheh 
2958416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
2959416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
2960416161dbSMark Fasheh 
2961416161dbSMark Fasheh 		flush_dcache_page(src_page);
2962416161dbSMark Fasheh 		flush_dcache_page(dst_page);
2963416161dbSMark Fasheh 
2964416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
2965416161dbSMark Fasheh 			ret = BTRFS_SAME_DATA_DIFFERS;
2966416161dbSMark Fasheh 
2967416161dbSMark Fasheh 		kunmap_atomic(addr);
2968416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
2969416161dbSMark Fasheh 
2970416161dbSMark Fasheh 		if (ret)
2971416161dbSMark Fasheh 			break;
2972416161dbSMark Fasheh 
2973416161dbSMark Fasheh 		len -= cmp_len;
2974f4414602SMark Fasheh 		i++;
2975416161dbSMark Fasheh 	}
2976416161dbSMark Fasheh 
2977416161dbSMark Fasheh 	return ret;
2978416161dbSMark Fasheh }
2979416161dbSMark Fasheh 
2980e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
2981e1d227a4SMark Fasheh 				     u64 olen)
2982416161dbSMark Fasheh {
2983e1d227a4SMark Fasheh 	u64 len = *plen;
2984416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2985416161dbSMark Fasheh 
2986e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
2987416161dbSMark Fasheh 		return -EINVAL;
2988e1d227a4SMark Fasheh 
2989e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
2990e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
2991e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
2992e1d227a4SMark Fasheh 
2993416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
2994416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2995416161dbSMark Fasheh 		return -EINVAL;
2996416161dbSMark Fasheh 
2997416161dbSMark Fasheh 	return 0;
2998416161dbSMark Fasheh }
2999416161dbSMark Fasheh 
3000e1d227a4SMark Fasheh static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3001416161dbSMark Fasheh 			     struct inode *dst, u64 dst_loff)
3002416161dbSMark Fasheh {
3003416161dbSMark Fasheh 	int ret;
3004e1d227a4SMark Fasheh 	u64 len = olen;
3005f4414602SMark Fasheh 	struct cmp_pages cmp;
30060efa9f48SMark Fasheh 	int same_inode = 0;
30070efa9f48SMark Fasheh 	u64 same_lock_start = 0;
30080efa9f48SMark Fasheh 	u64 same_lock_len = 0;
3009416161dbSMark Fasheh 
3010416161dbSMark Fasheh 	if (src == dst)
30110efa9f48SMark Fasheh 		same_inode = 1;
3012416161dbSMark Fasheh 
3013113e8283SFilipe Manana 	if (len == 0)
3014113e8283SFilipe Manana 		return 0;
3015113e8283SFilipe Manana 
30160efa9f48SMark Fasheh 	if (same_inode) {
30170efa9f48SMark Fasheh 		mutex_lock(&src->i_mutex);
30180efa9f48SMark Fasheh 
30190efa9f48SMark Fasheh 		ret = extent_same_check_offsets(src, loff, &len, olen);
30200efa9f48SMark Fasheh 		if (ret)
30210efa9f48SMark Fasheh 			goto out_unlock;
30220efa9f48SMark Fasheh 
30230efa9f48SMark Fasheh 		/*
30240efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
30250efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
30260efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
30270efa9f48SMark Fasheh 		 *
30280efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
30290efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
30300efa9f48SMark Fasheh 		 * reject the request.
30310efa9f48SMark Fasheh 		 *
30320efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
30330efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
30340efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
30350efa9f48SMark Fasheh 		 * i_size.
30360efa9f48SMark Fasheh 		 */
30370efa9f48SMark Fasheh 		if (len != olen) {
30380efa9f48SMark Fasheh 			ret = -EINVAL;
30390efa9f48SMark Fasheh 			goto out_unlock;
30400efa9f48SMark Fasheh 		}
30410efa9f48SMark Fasheh 
30420efa9f48SMark Fasheh 		/* Check for overlapping ranges */
30430efa9f48SMark Fasheh 		if (dst_loff + len > loff && dst_loff < loff + len) {
30440efa9f48SMark Fasheh 			ret = -EINVAL;
30450efa9f48SMark Fasheh 			goto out_unlock;
30460efa9f48SMark Fasheh 		}
30470efa9f48SMark Fasheh 
30480efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
30490efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
30500efa9f48SMark Fasheh 	} else {
3051f4414602SMark Fasheh 		btrfs_double_inode_lock(src, dst);
3052416161dbSMark Fasheh 
3053e1d227a4SMark Fasheh 		ret = extent_same_check_offsets(src, loff, &len, olen);
3054416161dbSMark Fasheh 		if (ret)
3055416161dbSMark Fasheh 			goto out_unlock;
3056416161dbSMark Fasheh 
3057e1d227a4SMark Fasheh 		ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3058416161dbSMark Fasheh 		if (ret)
3059416161dbSMark Fasheh 			goto out_unlock;
30600efa9f48SMark Fasheh 	}
3061416161dbSMark Fasheh 
3062416161dbSMark Fasheh 	/* don't make the dst file partly checksummed */
3063416161dbSMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3064416161dbSMark Fasheh 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3065416161dbSMark Fasheh 		ret = -EINVAL;
3066416161dbSMark Fasheh 		goto out_unlock;
3067416161dbSMark Fasheh 	}
3068416161dbSMark Fasheh 
3069f4414602SMark Fasheh 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3070f4414602SMark Fasheh 	if (ret)
3071f4414602SMark Fasheh 		goto out_unlock;
3072f4414602SMark Fasheh 
30730efa9f48SMark Fasheh 	if (same_inode)
30740efa9f48SMark Fasheh 		lock_extent_range(src, same_lock_start, same_lock_len);
30750efa9f48SMark Fasheh 	else
3076f4414602SMark Fasheh 		btrfs_double_extent_lock(src, loff, dst, dst_loff, len);
3077f4414602SMark Fasheh 
3078207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
3079f4414602SMark Fasheh 	ret = btrfs_cmp_data(src, loff, dst, dst_loff, olen, &cmp);
3080416161dbSMark Fasheh 	if (ret == 0)
30811c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3082416161dbSMark Fasheh 
30830efa9f48SMark Fasheh 	if (same_inode)
30840efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
30850efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
30860efa9f48SMark Fasheh 	else
3087f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3088f4414602SMark Fasheh 
3089f4414602SMark Fasheh 	btrfs_cmp_data_free(&cmp);
3090416161dbSMark Fasheh out_unlock:
30910efa9f48SMark Fasheh 	if (same_inode)
30920efa9f48SMark Fasheh 		mutex_unlock(&src->i_mutex);
30930efa9f48SMark Fasheh 	else
3094f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3095416161dbSMark Fasheh 
3096416161dbSMark Fasheh 	return ret;
3097416161dbSMark Fasheh }
3098416161dbSMark Fasheh 
3099416161dbSMark Fasheh #define BTRFS_MAX_DEDUPE_LEN	(16 * 1024 * 1024)
3100416161dbSMark Fasheh 
3101416161dbSMark Fasheh static long btrfs_ioctl_file_extent_same(struct file *file,
31021c1c8747SAl Viro 			struct btrfs_ioctl_same_args __user *argp)
3103416161dbSMark Fasheh {
3104497b4050SFilipe Manana 	struct btrfs_ioctl_same_args *same = NULL;
3105cbf8b8caSMark Fasheh 	struct btrfs_ioctl_same_extent_info *info;
31061c1c8747SAl Viro 	struct inode *src = file_inode(file);
3107416161dbSMark Fasheh 	u64 off;
3108416161dbSMark Fasheh 	u64 len;
3109416161dbSMark Fasheh 	int i;
3110416161dbSMark Fasheh 	int ret;
3111cbf8b8caSMark Fasheh 	unsigned long size;
3112416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3113416161dbSMark Fasheh 	bool is_admin = capable(CAP_SYS_ADMIN);
31141c1c8747SAl Viro 	u16 count;
3115416161dbSMark Fasheh 
3116416161dbSMark Fasheh 	if (!(file->f_mode & FMODE_READ))
3117416161dbSMark Fasheh 		return -EINVAL;
3118416161dbSMark Fasheh 
3119416161dbSMark Fasheh 	ret = mnt_want_write_file(file);
3120416161dbSMark Fasheh 	if (ret)
3121416161dbSMark Fasheh 		return ret;
3122416161dbSMark Fasheh 
31231c1c8747SAl Viro 	if (get_user(count, &argp->dest_count)) {
3124416161dbSMark Fasheh 		ret = -EFAULT;
3125416161dbSMark Fasheh 		goto out;
3126416161dbSMark Fasheh 	}
3127416161dbSMark Fasheh 
31281c1c8747SAl Viro 	size = offsetof(struct btrfs_ioctl_same_args __user, info[count]);
3129cbf8b8caSMark Fasheh 
31301c1c8747SAl Viro 	same = memdup_user(argp, size);
3131cbf8b8caSMark Fasheh 
3132229eed43SGeyslan G. Bem 	if (IS_ERR(same)) {
3133229eed43SGeyslan G. Bem 		ret = PTR_ERR(same);
3134497b4050SFilipe Manana 		same = NULL;
3135cbf8b8caSMark Fasheh 		goto out;
3136cbf8b8caSMark Fasheh 	}
3137cbf8b8caSMark Fasheh 
3138cbf8b8caSMark Fasheh 	off = same->logical_offset;
3139cbf8b8caSMark Fasheh 	len = same->length;
3140416161dbSMark Fasheh 
3141416161dbSMark Fasheh 	/*
3142416161dbSMark Fasheh 	 * Limit the total length we will dedupe for each operation.
3143416161dbSMark Fasheh 	 * This is intended to bound the total time spent in this
3144416161dbSMark Fasheh 	 * ioctl to something sane.
3145416161dbSMark Fasheh 	 */
3146416161dbSMark Fasheh 	if (len > BTRFS_MAX_DEDUPE_LEN)
3147416161dbSMark Fasheh 		len = BTRFS_MAX_DEDUPE_LEN;
3148416161dbSMark Fasheh 
3149416161dbSMark Fasheh 	if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
3150416161dbSMark Fasheh 		/*
3151416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3152416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3153416161dbSMark Fasheh 		 * this situation without an update.
3154416161dbSMark Fasheh 		 */
3155416161dbSMark Fasheh 		ret = -EINVAL;
3156416161dbSMark Fasheh 		goto out;
3157416161dbSMark Fasheh 	}
3158416161dbSMark Fasheh 
3159416161dbSMark Fasheh 	ret = -EISDIR;
3160416161dbSMark Fasheh 	if (S_ISDIR(src->i_mode))
3161416161dbSMark Fasheh 		goto out;
3162416161dbSMark Fasheh 
3163416161dbSMark Fasheh 	ret = -EACCES;
3164416161dbSMark Fasheh 	if (!S_ISREG(src->i_mode))
3165416161dbSMark Fasheh 		goto out;
3166416161dbSMark Fasheh 
3167cbf8b8caSMark Fasheh 	/* pre-format output fields to sane values */
31681c1c8747SAl Viro 	for (i = 0; i < count; i++) {
3169cbf8b8caSMark Fasheh 		same->info[i].bytes_deduped = 0ULL;
3170cbf8b8caSMark Fasheh 		same->info[i].status = 0;
3171416161dbSMark Fasheh 	}
3172416161dbSMark Fasheh 
31731c1c8747SAl Viro 	for (i = 0, info = same->info; i < count; i++, info++) {
31741c1c8747SAl Viro 		struct inode *dst;
31751c1c8747SAl Viro 		struct fd dst_file = fdget(info->fd);
31761c1c8747SAl Viro 		if (!dst_file.file) {
3177cbf8b8caSMark Fasheh 			info->status = -EBADF;
31781c1c8747SAl Viro 			continue;
3179416161dbSMark Fasheh 		}
31801c1c8747SAl Viro 		dst = file_inode(dst_file.file);
3181416161dbSMark Fasheh 
31821c1c8747SAl Viro 		if (!(is_admin || (dst_file.file->f_mode & FMODE_WRITE))) {
3183cbf8b8caSMark Fasheh 			info->status = -EINVAL;
31841c1c8747SAl Viro 		} else if (file->f_path.mnt != dst_file.file->f_path.mnt) {
3185cbf8b8caSMark Fasheh 			info->status = -EXDEV;
31861c1c8747SAl Viro 		} else if (S_ISDIR(dst->i_mode)) {
3187cbf8b8caSMark Fasheh 			info->status = -EISDIR;
31881c1c8747SAl Viro 		} else if (!S_ISREG(dst->i_mode)) {
3189cbf8b8caSMark Fasheh 			info->status = -EACCES;
31901c1c8747SAl Viro 		} else {
3191cbf8b8caSMark Fasheh 			info->status = btrfs_extent_same(src, off, len, dst,
3192cbf8b8caSMark Fasheh 							info->logical_offset);
3193cbf8b8caSMark Fasheh 			if (info->status == 0)
3194cbf8b8caSMark Fasheh 				info->bytes_deduped += len;
31951c1c8747SAl Viro 		}
31961c1c8747SAl Viro 		fdput(dst_file);
3197cbf8b8caSMark Fasheh 	}
3198416161dbSMark Fasheh 
3199cbf8b8caSMark Fasheh 	ret = copy_to_user(argp, same, size);
3200cbf8b8caSMark Fasheh 	if (ret)
3201416161dbSMark Fasheh 		ret = -EFAULT;
3202416161dbSMark Fasheh 
3203416161dbSMark Fasheh out:
3204416161dbSMark Fasheh 	mnt_drop_write_file(file);
3205497b4050SFilipe Manana 	kfree(same);
3206416161dbSMark Fasheh 	return ret;
3207416161dbSMark Fasheh }
3208416161dbSMark Fasheh 
3209f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3210f82a9901SFilipe Manana 				     struct inode *inode,
3211f82a9901SFilipe Manana 				     u64 endoff,
3212f82a9901SFilipe Manana 				     const u64 destoff,
32131c919a5eSMark Fasheh 				     const u64 olen,
32141c919a5eSMark Fasheh 				     int no_time_update)
3215f82a9901SFilipe Manana {
3216f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3217f82a9901SFilipe Manana 	int ret;
3218f82a9901SFilipe Manana 
3219f82a9901SFilipe Manana 	inode_inc_iversion(inode);
32201c919a5eSMark Fasheh 	if (!no_time_update)
3221f82a9901SFilipe Manana 		inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3222f82a9901SFilipe Manana 	/*
3223f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3224f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3225f82a9901SFilipe Manana 	 */
3226f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3227f82a9901SFilipe Manana 		endoff = destoff + olen;
3228f82a9901SFilipe Manana 	if (endoff > inode->i_size)
3229f82a9901SFilipe Manana 		btrfs_i_size_write(inode, endoff);
3230f82a9901SFilipe Manana 
3231f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3232f82a9901SFilipe Manana 	if (ret) {
3233f82a9901SFilipe Manana 		btrfs_abort_transaction(trans, root, ret);
3234f82a9901SFilipe Manana 		btrfs_end_transaction(trans, root);
3235f82a9901SFilipe Manana 		goto out;
3236f82a9901SFilipe Manana 	}
3237f82a9901SFilipe Manana 	ret = btrfs_end_transaction(trans, root);
3238f82a9901SFilipe Manana out:
3239f82a9901SFilipe Manana 	return ret;
3240f82a9901SFilipe Manana }
3241f82a9901SFilipe Manana 
32427ffbb598SFilipe Manana static void clone_update_extent_map(struct inode *inode,
32437ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
32447ffbb598SFilipe Manana 				    const struct btrfs_path *path,
32457ffbb598SFilipe Manana 				    const u64 hole_offset,
32467ffbb598SFilipe Manana 				    const u64 hole_len)
32477ffbb598SFilipe Manana {
32487ffbb598SFilipe Manana 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
32497ffbb598SFilipe Manana 	struct extent_map *em;
32507ffbb598SFilipe Manana 	int ret;
32517ffbb598SFilipe Manana 
32527ffbb598SFilipe Manana 	em = alloc_extent_map();
32537ffbb598SFilipe Manana 	if (!em) {
32547ffbb598SFilipe Manana 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
32557ffbb598SFilipe Manana 			&BTRFS_I(inode)->runtime_flags);
32567ffbb598SFilipe Manana 		return;
32577ffbb598SFilipe Manana 	}
32587ffbb598SFilipe Manana 
325914f59796SFilipe Manana 	if (path) {
326014f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
326114f59796SFilipe Manana 
326214f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
326314f59796SFilipe Manana 				    struct btrfs_file_extent_item);
32647ffbb598SFilipe Manana 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
32657ffbb598SFilipe Manana 		em->generation = -1;
32667ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
32677ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
32687ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
32697ffbb598SFilipe Manana 				&BTRFS_I(inode)->runtime_flags);
32707ffbb598SFilipe Manana 	} else {
32717ffbb598SFilipe Manana 		em->start = hole_offset;
32727ffbb598SFilipe Manana 		em->len = hole_len;
32737ffbb598SFilipe Manana 		em->ram_bytes = em->len;
32747ffbb598SFilipe Manana 		em->orig_start = hole_offset;
32757ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
32767ffbb598SFilipe Manana 		em->block_len = 0;
32777ffbb598SFilipe Manana 		em->orig_block_len = 0;
32787ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
32797ffbb598SFilipe Manana 		em->generation = trans->transid;
32807ffbb598SFilipe Manana 	}
32817ffbb598SFilipe Manana 
32827ffbb598SFilipe Manana 	while (1) {
32837ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
32847ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
32857ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
32867ffbb598SFilipe Manana 		if (ret != -EEXIST) {
32877ffbb598SFilipe Manana 			free_extent_map(em);
32887ffbb598SFilipe Manana 			break;
32897ffbb598SFilipe Manana 		}
32907ffbb598SFilipe Manana 		btrfs_drop_extent_cache(inode, em->start,
32917ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
32927ffbb598SFilipe Manana 	}
32937ffbb598SFilipe Manana 
3294ee39b432SDavid Sterba 	if (ret)
32957ffbb598SFilipe Manana 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
32967ffbb598SFilipe Manana 			&BTRFS_I(inode)->runtime_flags);
32977ffbb598SFilipe Manana }
32987ffbb598SFilipe Manana 
32998039d87dSFilipe Manana /*
33008039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
33018039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
33028039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
33038039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
33048039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
33058039d87dSFilipe Manana  *
33068039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
33078039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
33088039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
33098039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
33108039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
33118039d87dSFilipe Manana  * i_mutex, which we are holding here).
33128039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
33138039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
33148039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
33158039d87dSFilipe Manana  *
33168039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
33178039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
33188039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
33198039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
33208039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
33218039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
33228039d87dSFilipe Manana  * the former.
33238039d87dSFilipe Manana  */
33248039d87dSFilipe Manana static int clone_copy_inline_extent(struct inode *src,
33258039d87dSFilipe Manana 				    struct inode *dst,
33268039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
33278039d87dSFilipe Manana 				    struct btrfs_path *path,
33288039d87dSFilipe Manana 				    struct btrfs_key *new_key,
33298039d87dSFilipe Manana 				    const u64 drop_start,
33308039d87dSFilipe Manana 				    const u64 datal,
33318039d87dSFilipe Manana 				    const u64 skip,
33328039d87dSFilipe Manana 				    const u64 size,
33338039d87dSFilipe Manana 				    char *inline_data)
33348039d87dSFilipe Manana {
33358039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
33368039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
33378039d87dSFilipe Manana 				      root->sectorsize);
33388039d87dSFilipe Manana 	int ret;
33398039d87dSFilipe Manana 	struct btrfs_key key;
33408039d87dSFilipe Manana 
33418039d87dSFilipe Manana 	if (new_key->offset > 0)
33428039d87dSFilipe Manana 		return -EOPNOTSUPP;
33438039d87dSFilipe Manana 
33448039d87dSFilipe Manana 	key.objectid = btrfs_ino(dst);
33458039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
33468039d87dSFilipe Manana 	key.offset = 0;
33478039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
33488039d87dSFilipe Manana 	if (ret < 0) {
33498039d87dSFilipe Manana 		return ret;
33508039d87dSFilipe Manana 	} else if (ret > 0) {
33518039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
33528039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
33538039d87dSFilipe Manana 			if (ret < 0)
33548039d87dSFilipe Manana 				return ret;
33558039d87dSFilipe Manana 			else if (ret > 0)
33568039d87dSFilipe Manana 				goto copy_inline_extent;
33578039d87dSFilipe Manana 		}
33588039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
33598039d87dSFilipe Manana 		if (key.objectid == btrfs_ino(dst) &&
33608039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
33618039d87dSFilipe Manana 			ASSERT(key.offset > 0);
33628039d87dSFilipe Manana 			return -EOPNOTSUPP;
33638039d87dSFilipe Manana 		}
33648039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
33658039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
33668039d87dSFilipe Manana 		u64 ext_len;
33678039d87dSFilipe Manana 
33688039d87dSFilipe Manana 		/*
33698039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
33708039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
33718039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
33728039d87dSFilipe Manana 		 */
33738039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
33748039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
33758039d87dSFilipe Manana 		/*
33768039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
33778039d87dSFilipe Manana 		 * following it.
33788039d87dSFilipe Manana 		 */
33798039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
33808039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
33818039d87dSFilipe Manana 			goto copy_inline_extent;
33828039d87dSFilipe Manana 
33838039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
33848039d87dSFilipe Manana 		if (ext_len > aligned_end)
33858039d87dSFilipe Manana 			return -EOPNOTSUPP;
33868039d87dSFilipe Manana 
33878039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
33888039d87dSFilipe Manana 		if (ret < 0) {
33898039d87dSFilipe Manana 			return ret;
33908039d87dSFilipe Manana 		} else if (ret == 0) {
33918039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
33928039d87dSFilipe Manana 					      path->slots[0]);
33938039d87dSFilipe Manana 			if (key.objectid == btrfs_ino(dst) &&
33948039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
33958039d87dSFilipe Manana 				return -EOPNOTSUPP;
33968039d87dSFilipe Manana 		}
33978039d87dSFilipe Manana 	}
33988039d87dSFilipe Manana 
33998039d87dSFilipe Manana copy_inline_extent:
34008039d87dSFilipe Manana 	/*
34018039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
34028039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
34038039d87dSFilipe Manana 	 */
34048039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
34058039d87dSFilipe Manana 		/*
34068039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
34078039d87dSFilipe Manana 		 * This would require copying the data from the source inline
34088039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
34098039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
34108039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
34118039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
34128039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
34138039d87dSFilipe Manana 		 * inline extent).
34148039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
34158039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
34168039d87dSFilipe Manana 		 */
34178039d87dSFilipe Manana 		return -EOPNOTSUPP;
34188039d87dSFilipe Manana 	}
34198039d87dSFilipe Manana 
34208039d87dSFilipe Manana 	btrfs_release_path(path);
34218039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
34228039d87dSFilipe Manana 	if (ret)
34238039d87dSFilipe Manana 		return ret;
34248039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
34258039d87dSFilipe Manana 	if (ret)
34268039d87dSFilipe Manana 		return ret;
34278039d87dSFilipe Manana 
34288039d87dSFilipe Manana 	if (skip) {
34298039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
34308039d87dSFilipe Manana 
34318039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
34328039d87dSFilipe Manana 	}
34338039d87dSFilipe Manana 
34348039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
34358039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
34368039d87dSFilipe Manana 						  path->slots[0]),
34378039d87dSFilipe Manana 			    size);
34388039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
34398039d87dSFilipe Manana 
34408039d87dSFilipe Manana 	return 0;
34418039d87dSFilipe Manana }
34428039d87dSFilipe Manana 
344332b7c687SMark Fasheh /**
344432b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
344532b7c687SMark Fasheh  *
344632b7c687SMark Fasheh  * @src: Inode to clone from
344732b7c687SMark Fasheh  * @inode: Inode to clone to
344832b7c687SMark Fasheh  * @off: Offset within source to start clone from
344932b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
34501c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
345132b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
34521c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
345332b7c687SMark Fasheh  */
345432b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3455f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
34561c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3457f46b5a66SChristoph Hellwig {
3458f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
345932b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3460f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
346132b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
346232b7c687SMark Fasheh 	char *buf = NULL;
3463ae01a0abSYan Zheng 	struct btrfs_key key;
3464f46b5a66SChristoph Hellwig 	u32 nritems;
3465f46b5a66SChristoph Hellwig 	int slot;
3466ae01a0abSYan Zheng 	int ret;
3467f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3468f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3469ae01a0abSYan Zheng 
3470ae01a0abSYan Zheng 	ret = -ENOMEM;
3471707e8a07SDavid Sterba 	buf = vmalloc(root->nodesize);
3472ae01a0abSYan Zheng 	if (!buf)
347332b7c687SMark Fasheh 		return ret;
3474ae01a0abSYan Zheng 
3475ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3476ae01a0abSYan Zheng 	if (!path) {
3477ae01a0abSYan Zheng 		vfree(buf);
347832b7c687SMark Fasheh 		return ret;
3479ae01a0abSYan Zheng 	}
348032b7c687SMark Fasheh 
3481ae01a0abSYan Zheng 	path->reada = 2;
3482c5c9cd4dSSage Weil 	/* clone data */
348333345d01SLi Zefan 	key.objectid = btrfs_ino(src);
3484ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
34852c463823SFilipe Manana 	key.offset = off;
3486f46b5a66SChristoph Hellwig 
3487f46b5a66SChristoph Hellwig 	while (1) {
3488de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3489df858e76SFilipe Manana 
3490f46b5a66SChristoph Hellwig 		/*
3491f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3492f46b5a66SChristoph Hellwig 		 * tree.
3493f46b5a66SChristoph Hellwig 		 */
3494e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3495362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3496362a20c5SDavid Sterba 				0, 0);
3497f46b5a66SChristoph Hellwig 		if (ret < 0)
3498f46b5a66SChristoph Hellwig 			goto out;
34992c463823SFilipe Manana 		/*
35002c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
35012c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
35022c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
35032c463823SFilipe Manana 		 */
35042c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
35052c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
35062c463823SFilipe Manana 					      path->slots[0] - 1);
35072c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
35082c463823SFilipe Manana 				path->slots[0]--;
35092c463823SFilipe Manana 		}
3510f46b5a66SChristoph Hellwig 
3511ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3512e4355f34SFilipe David Borba Manana process_slot:
3513ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3514362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3515f46b5a66SChristoph Hellwig 			if (ret < 0)
3516f46b5a66SChristoph Hellwig 				goto out;
3517f46b5a66SChristoph Hellwig 			if (ret > 0)
3518f46b5a66SChristoph Hellwig 				break;
3519ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3520f46b5a66SChristoph Hellwig 		}
3521f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3522f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3523f46b5a66SChristoph Hellwig 
3524ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3525962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
352633345d01SLi Zefan 		    key.objectid != btrfs_ino(src))
3527f46b5a66SChristoph Hellwig 			break;
3528f46b5a66SChristoph Hellwig 
3529962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3530c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3531c5c9cd4dSSage Weil 			int type;
353231840ae1SZheng Yan 			u32 size;
353331840ae1SZheng Yan 			struct btrfs_key new_key;
3534c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3535c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3536c5c9cd4dSSage Weil 			u8 comp;
3537f82a9901SFilipe Manana 			u64 drop_start;
353831840ae1SZheng Yan 
3539c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3540c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3541c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3542c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3543c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3544c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3545d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3546d397712bSChris Mason 								      extent);
3547d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3548d397712bSChris Mason 								 extent);
3549c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3550d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3551d397712bSChris Mason 								    extent);
3552c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3553c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3554c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3555c5c9cd4dSSage Weil 								    extent);
3556c5c9cd4dSSage Weil 			}
355731840ae1SZheng Yan 
35582c463823SFilipe Manana 			/*
35592c463823SFilipe Manana 			 * The first search might have left us at an extent
35602c463823SFilipe Manana 			 * item that ends before our target range's start, can
35612c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
35622c463823SFilipe Manana 			 */
35632c463823SFilipe Manana 			if (key.offset + datal <= off) {
3564e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3565e4355f34SFilipe David Borba Manana 				goto process_slot;
35662c463823SFilipe Manana 			} else if (key.offset >= off + len) {
35672c463823SFilipe Manana 				break;
3568e4355f34SFilipe David Borba Manana 			}
3569df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3570e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3571e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3572e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3573e4355f34SFilipe David Borba Manana 					   size);
3574e4355f34SFilipe David Borba Manana 
3575e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3576e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3577c5c9cd4dSSage Weil 
357831840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
357933345d01SLi Zefan 			new_key.objectid = btrfs_ino(inode);
35804d728ec7SLi Zefan 			if (off <= key.offset)
3581c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
35824d728ec7SLi Zefan 			else
35834d728ec7SLi Zefan 				new_key.offset = destoff;
3584c5c9cd4dSSage Weil 
3585b6f3409bSSage Weil 			/*
3586f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3587f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3588f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3589f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3590f82a9901SFilipe Manana 			 * partially overlaps it).
3591f82a9901SFilipe Manana 			 */
3592f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3593f82a9901SFilipe Manana 				drop_start = last_dest_end;
3594f82a9901SFilipe Manana 			else
3595f82a9901SFilipe Manana 				drop_start = new_key.offset;
3596f82a9901SFilipe Manana 
3597f82a9901SFilipe Manana 			/*
3598b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3599b6f3409bSSage Weil 			 * 1 - add new extent
3600b6f3409bSSage Weil 			 * 1 - inode update
3601b6f3409bSSage Weil 			 */
3602b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3603a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3604a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3605a22285a6SYan, Zheng 				goto out;
3606a22285a6SYan, Zheng 			}
3607a22285a6SYan, Zheng 
3608c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3609c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3610d72c0842SLi Zefan 				/*
3611d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3612d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3613d72c0842SLi Zefan 				 */
3614d72c0842SLi Zefan 
361593915584SAntonio Ospite 				/* subtract range b */
3616d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3617d72c0842SLi Zefan 					datal = off + len - key.offset;
3618d72c0842SLi Zefan 
361993915584SAntonio Ospite 				/* subtract range a */
3620a22285a6SYan, Zheng 				if (off > key.offset) {
3621a22285a6SYan, Zheng 					datao += off - key.offset;
3622a22285a6SYan, Zheng 					datal -= off - key.offset;
3623a22285a6SYan, Zheng 				}
3624a22285a6SYan, Zheng 
36255dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3626f82a9901SFilipe Manana 							 drop_start,
3627a22285a6SYan, Zheng 							 new_key.offset + datal,
36282671485dSJosef Bacik 							 1);
362979787eaaSJeff Mahoney 				if (ret) {
36303f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
363100fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
363200fdf13aSLiu Bo 								root, ret);
363379787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
363479787eaaSJeff Mahoney 					goto out;
363579787eaaSJeff Mahoney 				}
3636a22285a6SYan, Zheng 
363731840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
363831840ae1SZheng Yan 							      &new_key, size);
363979787eaaSJeff Mahoney 				if (ret) {
364079787eaaSJeff Mahoney 					btrfs_abort_transaction(trans, root,
364179787eaaSJeff Mahoney 								ret);
364279787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
364379787eaaSJeff Mahoney 					goto out;
364479787eaaSJeff Mahoney 				}
364531840ae1SZheng Yan 
364631840ae1SZheng Yan 				leaf = path->nodes[0];
364731840ae1SZheng Yan 				slot = path->slots[0];
364831840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
364931840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
365031840ae1SZheng Yan 					    size);
3651ae01a0abSYan Zheng 
3652f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3653f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3654c5c9cd4dSSage Weil 
3655c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3656c5c9cd4dSSage Weil 				if (!disko)
3657c5c9cd4dSSage Weil 					datao = 0;
3658c5c9cd4dSSage Weil 
3659c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3660c5c9cd4dSSage Weil 							     datao);
3661c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3662c5c9cd4dSSage Weil 								datal);
3663fcebe456SJosef Bacik 
3664c5c9cd4dSSage Weil 				if (disko) {
3665c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
3666ae01a0abSYan Zheng 					ret = btrfs_inc_extent_ref(trans, root,
36675d4f98a2SYan Zheng 							disko, diskl, 0,
3668f46b5a66SChristoph Hellwig 							root->root_key.objectid,
366933345d01SLi Zefan 							btrfs_ino(inode),
3670b06c4bf5SFilipe Manana 							new_key.offset - datao);
367179787eaaSJeff Mahoney 					if (ret) {
367279787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
367379787eaaSJeff Mahoney 									root,
367479787eaaSJeff Mahoney 									ret);
367579787eaaSJeff Mahoney 						btrfs_end_transaction(trans,
367679787eaaSJeff Mahoney 								      root);
367779787eaaSJeff Mahoney 						goto out;
367879787eaaSJeff Mahoney 
367979787eaaSJeff Mahoney 					}
3680f46b5a66SChristoph Hellwig 				}
3681c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3682c5c9cd4dSSage Weil 				u64 skip = 0;
3683c5c9cd4dSSage Weil 				u64 trim = 0;
3684ed958762SFilipe Manana 
3685c5c9cd4dSSage Weil 				if (off > key.offset) {
3686c5c9cd4dSSage Weil 					skip = off - key.offset;
3687c5c9cd4dSSage Weil 					new_key.offset += skip;
368831840ae1SZheng Yan 				}
3689d397712bSChris Mason 
3690c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3691c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3692d397712bSChris Mason 
3693c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3694c5c9cd4dSSage Weil 					ret = -EINVAL;
3695a22285a6SYan, Zheng 					btrfs_end_transaction(trans, root);
3696c5c9cd4dSSage Weil 					goto out;
369731840ae1SZheng Yan 				}
3698c5c9cd4dSSage Weil 				size -= skip + trim;
3699c5c9cd4dSSage Weil 				datal -= skip + trim;
3700a22285a6SYan, Zheng 
37018039d87dSFilipe Manana 				ret = clone_copy_inline_extent(src, inode,
37028039d87dSFilipe Manana 							       trans, path,
37038039d87dSFilipe Manana 							       &new_key,
3704f82a9901SFilipe Manana 							       drop_start,
37058039d87dSFilipe Manana 							       datal,
37068039d87dSFilipe Manana 							       skip, size, buf);
370779787eaaSJeff Mahoney 				if (ret) {
37083f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
37093a29bc09SChris Mason 						btrfs_abort_transaction(trans,
37108039d87dSFilipe Manana 									root,
371179787eaaSJeff Mahoney 									ret);
371279787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
371379787eaaSJeff Mahoney 					goto out;
371479787eaaSJeff Mahoney 				}
3715c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3716c5c9cd4dSSage Weil 				slot = path->slots[0];
3717c5c9cd4dSSage Weil 			}
3718c5c9cd4dSSage Weil 
37197ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
37207ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
37217ffbb598SFilipe Manana 				clone_update_extent_map(inode, trans,
372214f59796SFilipe Manana 						NULL, drop_start,
37237ffbb598SFilipe Manana 						new_key.offset - drop_start);
37247ffbb598SFilipe Manana 
372514f59796SFilipe Manana 			clone_update_extent_map(inode, trans, path, 0, 0);
37267ffbb598SFilipe Manana 
3727c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3728b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3729c5c9cd4dSSage Weil 
373062e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
373162e2390eSFilipe Manana 					      root->sectorsize);
3732f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3733f82a9901SFilipe Manana 							last_dest_end,
37341c919a5eSMark Fasheh 							destoff, olen,
37351c919a5eSMark Fasheh 							no_time_update);
3736f82a9901SFilipe Manana 			if (ret)
373779787eaaSJeff Mahoney 				goto out;
37382c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
37392c463823SFilipe Manana 				break;
3740a22285a6SYan, Zheng 		}
3741b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3742df858e76SFilipe Manana 		key.offset = next_key_min_offset;
3743ae01a0abSYan Zheng 	}
3744f46b5a66SChristoph Hellwig 	ret = 0;
374532b7c687SMark Fasheh 
3746f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3747f82a9901SFilipe Manana 		/*
3748f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3749f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3750f82a9901SFilipe Manana 		 */
3751b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3752f82a9901SFilipe Manana 
3753f82a9901SFilipe Manana 		/*
3754f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3755f82a9901SFilipe Manana 		 * 1 - inode update
3756f82a9901SFilipe Manana 		 */
3757f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3758f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3759f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3760f82a9901SFilipe Manana 			goto out;
3761f82a9901SFilipe Manana 		}
3762f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3763f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3764f82a9901SFilipe Manana 		if (ret) {
3765f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
3766f82a9901SFilipe Manana 				btrfs_abort_transaction(trans, root, ret);
3767f82a9901SFilipe Manana 			btrfs_end_transaction(trans, root);
3768f82a9901SFilipe Manana 			goto out;
3769f82a9901SFilipe Manana 		}
377014f59796SFilipe Manana 		clone_update_extent_map(inode, trans, NULL, last_dest_end,
377114f59796SFilipe Manana 					destoff + len - last_dest_end);
3772f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
37731c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3774f82a9901SFilipe Manana 	}
3775f82a9901SFilipe Manana 
3776f46b5a66SChristoph Hellwig out:
377732b7c687SMark Fasheh 	btrfs_free_path(path);
377832b7c687SMark Fasheh 	vfree(buf);
377932b7c687SMark Fasheh 	return ret;
378032b7c687SMark Fasheh }
378132b7c687SMark Fasheh 
378232b7c687SMark Fasheh static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
378332b7c687SMark Fasheh 				       u64 off, u64 olen, u64 destoff)
378432b7c687SMark Fasheh {
378554563d41SAl Viro 	struct inode *inode = file_inode(file);
378632b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
378732b7c687SMark Fasheh 	struct fd src_file;
378832b7c687SMark Fasheh 	struct inode *src;
378932b7c687SMark Fasheh 	int ret;
379032b7c687SMark Fasheh 	u64 len = olen;
379132b7c687SMark Fasheh 	u64 bs = root->fs_info->sb->s_blocksize;
379232b7c687SMark Fasheh 	int same_inode = 0;
379332b7c687SMark Fasheh 
379432b7c687SMark Fasheh 	/*
379532b7c687SMark Fasheh 	 * TODO:
379632b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
379732b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
379832b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
379932b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
380000fdf13aSLiu Bo 	 *
380100fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
380200fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
380332b7c687SMark Fasheh 	 */
380432b7c687SMark Fasheh 
380532b7c687SMark Fasheh 	/* the destination must be opened for writing */
380632b7c687SMark Fasheh 	if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
380732b7c687SMark Fasheh 		return -EINVAL;
380832b7c687SMark Fasheh 
380932b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
381032b7c687SMark Fasheh 		return -EROFS;
381132b7c687SMark Fasheh 
381232b7c687SMark Fasheh 	ret = mnt_want_write_file(file);
381332b7c687SMark Fasheh 	if (ret)
381432b7c687SMark Fasheh 		return ret;
381532b7c687SMark Fasheh 
381632b7c687SMark Fasheh 	src_file = fdget(srcfd);
381732b7c687SMark Fasheh 	if (!src_file.file) {
381832b7c687SMark Fasheh 		ret = -EBADF;
381932b7c687SMark Fasheh 		goto out_drop_write;
382032b7c687SMark Fasheh 	}
382132b7c687SMark Fasheh 
382232b7c687SMark Fasheh 	ret = -EXDEV;
382332b7c687SMark Fasheh 	if (src_file.file->f_path.mnt != file->f_path.mnt)
382432b7c687SMark Fasheh 		goto out_fput;
382532b7c687SMark Fasheh 
382632b7c687SMark Fasheh 	src = file_inode(src_file.file);
382732b7c687SMark Fasheh 
382832b7c687SMark Fasheh 	ret = -EINVAL;
382932b7c687SMark Fasheh 	if (src == inode)
383032b7c687SMark Fasheh 		same_inode = 1;
383132b7c687SMark Fasheh 
383232b7c687SMark Fasheh 	/* the src must be open for reading */
383332b7c687SMark Fasheh 	if (!(src_file.file->f_mode & FMODE_READ))
383432b7c687SMark Fasheh 		goto out_fput;
383532b7c687SMark Fasheh 
383632b7c687SMark Fasheh 	/* don't make the dst file partly checksummed */
383732b7c687SMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
383832b7c687SMark Fasheh 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
383932b7c687SMark Fasheh 		goto out_fput;
384032b7c687SMark Fasheh 
384132b7c687SMark Fasheh 	ret = -EISDIR;
384232b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
384332b7c687SMark Fasheh 		goto out_fput;
384432b7c687SMark Fasheh 
384532b7c687SMark Fasheh 	ret = -EXDEV;
384632b7c687SMark Fasheh 	if (src->i_sb != inode->i_sb)
384732b7c687SMark Fasheh 		goto out_fput;
384832b7c687SMark Fasheh 
384932b7c687SMark Fasheh 	if (!same_inode) {
3850293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
385132b7c687SMark Fasheh 	} else {
385232b7c687SMark Fasheh 		mutex_lock(&src->i_mutex);
385332b7c687SMark Fasheh 	}
385432b7c687SMark Fasheh 
385532b7c687SMark Fasheh 	/* determine range to clone */
385632b7c687SMark Fasheh 	ret = -EINVAL;
385732b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
385832b7c687SMark Fasheh 		goto out_unlock;
385932b7c687SMark Fasheh 	if (len == 0)
386032b7c687SMark Fasheh 		olen = len = src->i_size - off;
386132b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
386232b7c687SMark Fasheh 	if (off + len == src->i_size)
386332b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
386432b7c687SMark Fasheh 
3865ccccf3d6SFilipe Manana 	if (len == 0) {
3866ccccf3d6SFilipe Manana 		ret = 0;
3867ccccf3d6SFilipe Manana 		goto out_unlock;
3868ccccf3d6SFilipe Manana 	}
3869ccccf3d6SFilipe Manana 
387032b7c687SMark Fasheh 	/* verify the end result is block aligned */
387132b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
387232b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
387332b7c687SMark Fasheh 		goto out_unlock;
387432b7c687SMark Fasheh 
387532b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
387632b7c687SMark Fasheh 	if (same_inode) {
387732b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
387832b7c687SMark Fasheh 			goto out_unlock;
387932b7c687SMark Fasheh 	}
388032b7c687SMark Fasheh 
388132b7c687SMark Fasheh 	if (destoff > inode->i_size) {
388232b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
388332b7c687SMark Fasheh 		if (ret)
388432b7c687SMark Fasheh 			goto out_unlock;
388532b7c687SMark Fasheh 	}
388632b7c687SMark Fasheh 
3887c125b8bfSFilipe Manana 	/*
3888c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
3889c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
3890c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
3891c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
3892c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
3893c125b8bfSFilipe Manana 	 */
3894c125b8bfSFilipe Manana 	if (same_inode) {
3895c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3896c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
389732b7c687SMark Fasheh 
3898c125b8bfSFilipe Manana 		lock_extent_range(src, lock_start, lock_len);
3899c125b8bfSFilipe Manana 	} else {
3900293a8489SMark Fasheh 		btrfs_double_extent_lock(src, off, inode, destoff, len);
3901c125b8bfSFilipe Manana 	}
390232b7c687SMark Fasheh 
39031c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
390432b7c687SMark Fasheh 
3905c125b8bfSFilipe Manana 	if (same_inode) {
3906c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3907c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
3908c125b8bfSFilipe Manana 
3909c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3910c125b8bfSFilipe Manana 	} else {
3911293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
3912c125b8bfSFilipe Manana 	}
3913c125b8bfSFilipe Manana 	/*
3914c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3915c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3916c125b8bfSFilipe Manana 	 */
3917c125b8bfSFilipe Manana 	truncate_inode_pages_range(&inode->i_data, destoff,
3918c125b8bfSFilipe Manana 				   PAGE_CACHE_ALIGN(destoff + len) - 1);
3919f46b5a66SChristoph Hellwig out_unlock:
3920293a8489SMark Fasheh 	if (!same_inode)
3921293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
3922293a8489SMark Fasheh 	else
3923f46b5a66SChristoph Hellwig 		mutex_unlock(&src->i_mutex);
3924f46b5a66SChristoph Hellwig out_fput:
39252903ff01SAl Viro 	fdput(src_file);
3926ab67b7c1SYan Zheng out_drop_write:
39272a79f17eSAl Viro 	mnt_drop_write_file(file);
3928f46b5a66SChristoph Hellwig 	return ret;
3929f46b5a66SChristoph Hellwig }
3930f46b5a66SChristoph Hellwig 
39317a865e8aSChristoph Hellwig static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
3932c5c9cd4dSSage Weil {
3933c5c9cd4dSSage Weil 	struct btrfs_ioctl_clone_range_args args;
3934c5c9cd4dSSage Weil 
39357a865e8aSChristoph Hellwig 	if (copy_from_user(&args, argp, sizeof(args)))
3936c5c9cd4dSSage Weil 		return -EFAULT;
3937c5c9cd4dSSage Weil 	return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
3938c5c9cd4dSSage Weil 				 args.src_length, args.dest_offset);
3939c5c9cd4dSSage Weil }
3940c5c9cd4dSSage Weil 
3941f46b5a66SChristoph Hellwig /*
3942f46b5a66SChristoph Hellwig  * there are many ways the trans_start and trans_end ioctls can lead
3943f46b5a66SChristoph Hellwig  * to deadlocks.  They should only be used by applications that
3944f46b5a66SChristoph Hellwig  * basically own the machine, and have a very in depth understanding
3945f46b5a66SChristoph Hellwig  * of all the possible deadlocks and enospc problems.
3946f46b5a66SChristoph Hellwig  */
3947b2950863SChristoph Hellwig static long btrfs_ioctl_trans_start(struct file *file)
3948f46b5a66SChristoph Hellwig {
3949496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3950f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
3951f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
39521ab86aedSSage Weil 	int ret;
3953f46b5a66SChristoph Hellwig 
39541ab86aedSSage Weil 	ret = -EPERM;
3955df5b5520SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
3956f46b5a66SChristoph Hellwig 		goto out;
39571ab86aedSSage Weil 
39581ab86aedSSage Weil 	ret = -EINPROGRESS;
39591ab86aedSSage Weil 	if (file->private_data)
39601ab86aedSSage Weil 		goto out;
39619ca9ee09SSage Weil 
3962b83cc969SLi Zefan 	ret = -EROFS;
3963b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
3964b83cc969SLi Zefan 		goto out;
3965b83cc969SLi Zefan 
3966a561be71SAl Viro 	ret = mnt_want_write_file(file);
3967c146afadSYan Zheng 	if (ret)
3968c146afadSYan Zheng 		goto out;
3969c146afadSYan Zheng 
3970a4abeea4SJosef Bacik 	atomic_inc(&root->fs_info->open_ioctl_trans);
39719ca9ee09SSage Weil 
3972f46b5a66SChristoph Hellwig 	ret = -ENOMEM;
39737a7eaa40SJosef Bacik 	trans = btrfs_start_ioctl_transaction(root);
3974abd30bb0STsutomu Itoh 	if (IS_ERR(trans))
39751ab86aedSSage Weil 		goto out_drop;
39761ab86aedSSage Weil 
39771ab86aedSSage Weil 	file->private_data = trans;
39781ab86aedSSage Weil 	return 0;
39791ab86aedSSage Weil 
39801ab86aedSSage Weil out_drop:
3981a4abeea4SJosef Bacik 	atomic_dec(&root->fs_info->open_ioctl_trans);
39822a79f17eSAl Viro 	mnt_drop_write_file(file);
3983f46b5a66SChristoph Hellwig out:
3984f46b5a66SChristoph Hellwig 	return ret;
3985f46b5a66SChristoph Hellwig }
3986f46b5a66SChristoph Hellwig 
39876ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
39886ef5ed0dSJosef Bacik {
3989496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
39906ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
39916ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
39926ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
39936ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
39946ef5ed0dSJosef Bacik 	struct btrfs_path *path;
39956ef5ed0dSJosef Bacik 	struct btrfs_key location;
39966ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
39976ef5ed0dSJosef Bacik 	u64 objectid = 0;
39986ef5ed0dSJosef Bacik 	u64 dir_id;
39993c04ce01SMiao Xie 	int ret;
40006ef5ed0dSJosef Bacik 
40016ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
40026ef5ed0dSJosef Bacik 		return -EPERM;
40036ef5ed0dSJosef Bacik 
40043c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
40053c04ce01SMiao Xie 	if (ret)
40063c04ce01SMiao Xie 		return ret;
40073c04ce01SMiao Xie 
40083c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
40093c04ce01SMiao Xie 		ret = -EFAULT;
40103c04ce01SMiao Xie 		goto out;
40113c04ce01SMiao Xie 	}
40126ef5ed0dSJosef Bacik 
40136ef5ed0dSJosef Bacik 	if (!objectid)
40141cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
40156ef5ed0dSJosef Bacik 
40166ef5ed0dSJosef Bacik 	location.objectid = objectid;
40176ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
40186ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
40196ef5ed0dSJosef Bacik 
40206ef5ed0dSJosef Bacik 	new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
40213c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
40223c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
40233c04ce01SMiao Xie 		goto out;
40243c04ce01SMiao Xie 	}
40256ef5ed0dSJosef Bacik 
40266ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
40273c04ce01SMiao Xie 	if (!path) {
40283c04ce01SMiao Xie 		ret = -ENOMEM;
40293c04ce01SMiao Xie 		goto out;
40303c04ce01SMiao Xie 	}
40316ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
40326ef5ed0dSJosef Bacik 
40336ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
403498d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
40356ef5ed0dSJosef Bacik 		btrfs_free_path(path);
40363c04ce01SMiao Xie 		ret = PTR_ERR(trans);
40373c04ce01SMiao Xie 		goto out;
40386ef5ed0dSJosef Bacik 	}
40396ef5ed0dSJosef Bacik 
40406c41761fSDavid Sterba 	dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
40416ef5ed0dSJosef Bacik 	di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
40426ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
4043cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
40446ef5ed0dSJosef Bacik 		btrfs_free_path(path);
40456ef5ed0dSJosef Bacik 		btrfs_end_transaction(trans, root);
4046efe120a0SFrank Holton 		btrfs_err(new_root->fs_info, "Umm, you don't have the default dir"
4047efe120a0SFrank Holton 			   "item, this isn't going to work");
40483c04ce01SMiao Xie 		ret = -ENOENT;
40493c04ce01SMiao Xie 		goto out;
40506ef5ed0dSJosef Bacik 	}
40516ef5ed0dSJosef Bacik 
40526ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
40536ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
40546ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
40556ef5ed0dSJosef Bacik 	btrfs_free_path(path);
40566ef5ed0dSJosef Bacik 
40572b0ce2c2SMitch Harder 	btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
40586ef5ed0dSJosef Bacik 	btrfs_end_transaction(trans, root);
40593c04ce01SMiao Xie out:
40603c04ce01SMiao Xie 	mnt_drop_write_file(file);
40613c04ce01SMiao Xie 	return ret;
40626ef5ed0dSJosef Bacik }
40636ef5ed0dSJosef Bacik 
40645af3e8ccSStefan Behrens void btrfs_get_block_group_info(struct list_head *groups_list,
4065bf5fc093SJosef Bacik 				struct btrfs_ioctl_space_info *space)
4066bf5fc093SJosef Bacik {
4067bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4068bf5fc093SJosef Bacik 
4069bf5fc093SJosef Bacik 	space->total_bytes = 0;
4070bf5fc093SJosef Bacik 	space->used_bytes = 0;
4071bf5fc093SJosef Bacik 	space->flags = 0;
4072bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4073bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4074bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4075bf5fc093SJosef Bacik 		space->used_bytes +=
4076bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4077bf5fc093SJosef Bacik 	}
4078bf5fc093SJosef Bacik }
4079bf5fc093SJosef Bacik 
408048a3b636SEric Sandeen static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
40811406e432SJosef Bacik {
40821406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
40831406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
40841406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
40857fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
408613f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
40871406e432SJosef Bacik 	struct btrfs_space_info *info;
4088bf5fc093SJosef Bacik 	u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
4089bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_SYSTEM,
4090bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_METADATA,
4091bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
4092bf5fc093SJosef Bacik 	int num_types = 4;
40937fde62bfSChris Mason 	int alloc_size;
40941406e432SJosef Bacik 	int ret = 0;
409551788b1bSDan Rosenberg 	u64 slot_count = 0;
4096bf5fc093SJosef Bacik 	int i, c;
40971406e432SJosef Bacik 
40981406e432SJosef Bacik 	if (copy_from_user(&space_args,
40991406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
41001406e432SJosef Bacik 			   sizeof(space_args)))
41011406e432SJosef Bacik 		return -EFAULT;
41021406e432SJosef Bacik 
4103bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4104bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4105bf5fc093SJosef Bacik 
4106bf5fc093SJosef Bacik 		info = NULL;
41077fde62bfSChris Mason 		rcu_read_lock();
4108bf5fc093SJosef Bacik 		list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
4109bf5fc093SJosef Bacik 					list) {
4110bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4111bf5fc093SJosef Bacik 				info = tmp;
4112bf5fc093SJosef Bacik 				break;
4113bf5fc093SJosef Bacik 			}
4114bf5fc093SJosef Bacik 		}
41157fde62bfSChris Mason 		rcu_read_unlock();
41161406e432SJosef Bacik 
4117bf5fc093SJosef Bacik 		if (!info)
4118bf5fc093SJosef Bacik 			continue;
4119bf5fc093SJosef Bacik 
4120bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4121bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4122bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4123bf5fc093SJosef Bacik 				slot_count++;
4124bf5fc093SJosef Bacik 		}
4125bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4126bf5fc093SJosef Bacik 	}
4127bf5fc093SJosef Bacik 
412836523e95SDavid Sterba 	/*
412936523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
413036523e95SDavid Sterba 	 */
413136523e95SDavid Sterba 	slot_count++;
413236523e95SDavid Sterba 
41337fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
41347fde62bfSChris Mason 	if (space_args.space_slots == 0) {
41357fde62bfSChris Mason 		space_args.total_spaces = slot_count;
41367fde62bfSChris Mason 		goto out;
41377fde62bfSChris Mason 	}
4138bf5fc093SJosef Bacik 
413951788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4140bf5fc093SJosef Bacik 
41417fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4142bf5fc093SJosef Bacik 
41437fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
41447fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
41457fde62bfSChris Mason 	 */
41467fde62bfSChris Mason 	if (alloc_size > PAGE_CACHE_SIZE)
41477fde62bfSChris Mason 		return -ENOMEM;
41487fde62bfSChris Mason 
41497fde62bfSChris Mason 	space_args.total_spaces = 0;
41508d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
41517fde62bfSChris Mason 	if (!dest)
41527fde62bfSChris Mason 		return -ENOMEM;
41537fde62bfSChris Mason 	dest_orig = dest;
41547fde62bfSChris Mason 
41557fde62bfSChris Mason 	/* now we have a buffer to copy into */
4156bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4157bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4158bf5fc093SJosef Bacik 
415951788b1bSDan Rosenberg 		if (!slot_count)
416051788b1bSDan Rosenberg 			break;
416151788b1bSDan Rosenberg 
4162bf5fc093SJosef Bacik 		info = NULL;
41631406e432SJosef Bacik 		rcu_read_lock();
4164bf5fc093SJosef Bacik 		list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
4165bf5fc093SJosef Bacik 					list) {
4166bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4167bf5fc093SJosef Bacik 				info = tmp;
41687fde62bfSChris Mason 				break;
4169bf5fc093SJosef Bacik 			}
4170bf5fc093SJosef Bacik 		}
4171bf5fc093SJosef Bacik 		rcu_read_unlock();
41727fde62bfSChris Mason 
4173bf5fc093SJosef Bacik 		if (!info)
4174bf5fc093SJosef Bacik 			continue;
4175bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4176bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4177bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
41785af3e8ccSStefan Behrens 				btrfs_get_block_group_info(
41795af3e8ccSStefan Behrens 					&info->block_groups[c], &space);
41807fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
41811406e432SJosef Bacik 				dest++;
41821406e432SJosef Bacik 				space_args.total_spaces++;
418351788b1bSDan Rosenberg 				slot_count--;
41841406e432SJosef Bacik 			}
418551788b1bSDan Rosenberg 			if (!slot_count)
418651788b1bSDan Rosenberg 				break;
4187bf5fc093SJosef Bacik 		}
4188bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4189bf5fc093SJosef Bacik 	}
41901406e432SJosef Bacik 
419136523e95SDavid Sterba 	/*
419236523e95SDavid Sterba 	 * Add global block reserve
419336523e95SDavid Sterba 	 */
419436523e95SDavid Sterba 	if (slot_count) {
419536523e95SDavid Sterba 		struct btrfs_block_rsv *block_rsv = &root->fs_info->global_block_rsv;
419636523e95SDavid Sterba 
419736523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
419836523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
419936523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
420036523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
420136523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
420236523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
420336523e95SDavid Sterba 		space_args.total_spaces++;
420436523e95SDavid Sterba 	}
420536523e95SDavid Sterba 
42062eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
42077fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
42087fde62bfSChris Mason 
42097fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
42107fde62bfSChris Mason 		ret = -EFAULT;
42117fde62bfSChris Mason 
42127fde62bfSChris Mason 	kfree(dest_orig);
42137fde62bfSChris Mason out:
42147fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
42151406e432SJosef Bacik 		ret = -EFAULT;
42161406e432SJosef Bacik 
42171406e432SJosef Bacik 	return ret;
42181406e432SJosef Bacik }
42191406e432SJosef Bacik 
4220f46b5a66SChristoph Hellwig /*
4221f46b5a66SChristoph Hellwig  * there are many ways the trans_start and trans_end ioctls can lead
4222f46b5a66SChristoph Hellwig  * to deadlocks.  They should only be used by applications that
4223f46b5a66SChristoph Hellwig  * basically own the machine, and have a very in depth understanding
4224f46b5a66SChristoph Hellwig  * of all the possible deadlocks and enospc problems.
4225f46b5a66SChristoph Hellwig  */
4226f46b5a66SChristoph Hellwig long btrfs_ioctl_trans_end(struct file *file)
4227f46b5a66SChristoph Hellwig {
4228496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4229f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
4230f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
4231f46b5a66SChristoph Hellwig 
4232f46b5a66SChristoph Hellwig 	trans = file->private_data;
42331ab86aedSSage Weil 	if (!trans)
42341ab86aedSSage Weil 		return -EINVAL;
4235b214107eSChristoph Hellwig 	file->private_data = NULL;
42369ca9ee09SSage Weil 
42371ab86aedSSage Weil 	btrfs_end_transaction(trans, root);
42381ab86aedSSage Weil 
4239a4abeea4SJosef Bacik 	atomic_dec(&root->fs_info->open_ioctl_trans);
42409ca9ee09SSage Weil 
42412a79f17eSAl Viro 	mnt_drop_write_file(file);
42421ab86aedSSage Weil 	return 0;
4243f46b5a66SChristoph Hellwig }
4244f46b5a66SChristoph Hellwig 
42459a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
42469a8c28beSMiao Xie 					    void __user *argp)
424746204592SSage Weil {
424846204592SSage Weil 	struct btrfs_trans_handle *trans;
424946204592SSage Weil 	u64 transid;
4250db5b493aSTsutomu Itoh 	int ret;
425146204592SSage Weil 
4252d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4253ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4254ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
425598d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4256ff7c1d33SMiao Xie 
4257ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4258ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4259ff7c1d33SMiao Xie 		goto out;
4260ff7c1d33SMiao Xie 	}
426146204592SSage Weil 	transid = trans->transid;
4262db5b493aSTsutomu Itoh 	ret = btrfs_commit_transaction_async(trans, root, 0);
42638b2b2d3cSTsutomu Itoh 	if (ret) {
42648b2b2d3cSTsutomu Itoh 		btrfs_end_transaction(trans, root);
4265db5b493aSTsutomu Itoh 		return ret;
42668b2b2d3cSTsutomu Itoh 	}
4267ff7c1d33SMiao Xie out:
426846204592SSage Weil 	if (argp)
426946204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
427046204592SSage Weil 			return -EFAULT;
427146204592SSage Weil 	return 0;
427246204592SSage Weil }
427346204592SSage Weil 
42749a8c28beSMiao Xie static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
42759a8c28beSMiao Xie 					   void __user *argp)
427646204592SSage Weil {
427746204592SSage Weil 	u64 transid;
427846204592SSage Weil 
427946204592SSage Weil 	if (argp) {
428046204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
428146204592SSage Weil 			return -EFAULT;
428246204592SSage Weil 	} else {
428346204592SSage Weil 		transid = 0;  /* current trans */
428446204592SSage Weil 	}
428546204592SSage Weil 	return btrfs_wait_for_commit(root, transid);
428646204592SSage Weil }
428746204592SSage Weil 
4288b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4289475f6387SJan Schmidt {
4290496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4291475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4292b8e95489SMiao Xie 	int ret;
4293475f6387SJan Schmidt 
4294475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4295475f6387SJan Schmidt 		return -EPERM;
4296475f6387SJan Schmidt 
4297475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4298475f6387SJan Schmidt 	if (IS_ERR(sa))
4299475f6387SJan Schmidt 		return PTR_ERR(sa);
4300475f6387SJan Schmidt 
4301b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4302b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4303b8e95489SMiao Xie 		if (ret)
4304b8e95489SMiao Xie 			goto out;
4305b8e95489SMiao Xie 	}
4306b8e95489SMiao Xie 
4307aa1b8cd4SStefan Behrens 	ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
430863a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
430963a212abSStefan Behrens 			      0);
4310475f6387SJan Schmidt 
4311475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4312475f6387SJan Schmidt 		ret = -EFAULT;
4313475f6387SJan Schmidt 
4314b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4315b8e95489SMiao Xie 		mnt_drop_write_file(file);
4316b8e95489SMiao Xie out:
4317475f6387SJan Schmidt 	kfree(sa);
4318475f6387SJan Schmidt 	return ret;
4319475f6387SJan Schmidt }
4320475f6387SJan Schmidt 
4321475f6387SJan Schmidt static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
4322475f6387SJan Schmidt {
4323475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4324475f6387SJan Schmidt 		return -EPERM;
4325475f6387SJan Schmidt 
4326aa1b8cd4SStefan Behrens 	return btrfs_scrub_cancel(root->fs_info);
4327475f6387SJan Schmidt }
4328475f6387SJan Schmidt 
4329475f6387SJan Schmidt static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
4330475f6387SJan Schmidt 				       void __user *arg)
4331475f6387SJan Schmidt {
4332475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4333475f6387SJan Schmidt 	int ret;
4334475f6387SJan Schmidt 
4335475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4336475f6387SJan Schmidt 		return -EPERM;
4337475f6387SJan Schmidt 
4338475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4339475f6387SJan Schmidt 	if (IS_ERR(sa))
4340475f6387SJan Schmidt 		return PTR_ERR(sa);
4341475f6387SJan Schmidt 
4342475f6387SJan Schmidt 	ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
4343475f6387SJan Schmidt 
4344475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4345475f6387SJan Schmidt 		ret = -EFAULT;
4346475f6387SJan Schmidt 
4347475f6387SJan Schmidt 	kfree(sa);
4348475f6387SJan Schmidt 	return ret;
4349475f6387SJan Schmidt }
4350475f6387SJan Schmidt 
4351c11d2c23SStefan Behrens static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
4352b27f7c0cSDavid Sterba 				      void __user *arg)
4353c11d2c23SStefan Behrens {
4354c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4355c11d2c23SStefan Behrens 	int ret;
4356c11d2c23SStefan Behrens 
4357c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4358c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4359c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4360c11d2c23SStefan Behrens 
4361b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4362b27f7c0cSDavid Sterba 		kfree(sa);
4363b27f7c0cSDavid Sterba 		return -EPERM;
4364b27f7c0cSDavid Sterba 	}
4365b27f7c0cSDavid Sterba 
4366b27f7c0cSDavid Sterba 	ret = btrfs_get_dev_stats(root, sa);
4367c11d2c23SStefan Behrens 
4368c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4369c11d2c23SStefan Behrens 		ret = -EFAULT;
4370c11d2c23SStefan Behrens 
4371c11d2c23SStefan Behrens 	kfree(sa);
4372c11d2c23SStefan Behrens 	return ret;
4373c11d2c23SStefan Behrens }
4374c11d2c23SStefan Behrens 
43753f6bcfbdSStefan Behrens static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
43763f6bcfbdSStefan Behrens {
43773f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
43783f6bcfbdSStefan Behrens 	int ret;
43793f6bcfbdSStefan Behrens 
43803f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
43813f6bcfbdSStefan Behrens 		return -EPERM;
43823f6bcfbdSStefan Behrens 
43833f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
43843f6bcfbdSStefan Behrens 	if (IS_ERR(p))
43853f6bcfbdSStefan Behrens 		return PTR_ERR(p);
43863f6bcfbdSStefan Behrens 
43873f6bcfbdSStefan Behrens 	switch (p->cmd) {
43883f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4389adfa97cbSIlya Dryomov 		if (root->fs_info->sb->s_flags & MS_RDONLY) {
4390adfa97cbSIlya Dryomov 			ret = -EROFS;
4391adfa97cbSIlya Dryomov 			goto out;
4392adfa97cbSIlya Dryomov 		}
43933f6bcfbdSStefan Behrens 		if (atomic_xchg(
43943f6bcfbdSStefan Behrens 			&root->fs_info->mutually_exclusive_operation_running,
43953f6bcfbdSStefan Behrens 			1)) {
4396e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
43973f6bcfbdSStefan Behrens 		} else {
43983f6bcfbdSStefan Behrens 			ret = btrfs_dev_replace_start(root, p);
43993f6bcfbdSStefan Behrens 			atomic_set(
44003f6bcfbdSStefan Behrens 			 &root->fs_info->mutually_exclusive_operation_running,
44013f6bcfbdSStefan Behrens 			 0);
44023f6bcfbdSStefan Behrens 		}
44033f6bcfbdSStefan Behrens 		break;
44043f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
44053f6bcfbdSStefan Behrens 		btrfs_dev_replace_status(root->fs_info, p);
44063f6bcfbdSStefan Behrens 		ret = 0;
44073f6bcfbdSStefan Behrens 		break;
44083f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
44093f6bcfbdSStefan Behrens 		ret = btrfs_dev_replace_cancel(root->fs_info, p);
44103f6bcfbdSStefan Behrens 		break;
44113f6bcfbdSStefan Behrens 	default:
44123f6bcfbdSStefan Behrens 		ret = -EINVAL;
44133f6bcfbdSStefan Behrens 		break;
44143f6bcfbdSStefan Behrens 	}
44153f6bcfbdSStefan Behrens 
44163f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
44173f6bcfbdSStefan Behrens 		ret = -EFAULT;
4418adfa97cbSIlya Dryomov out:
44193f6bcfbdSStefan Behrens 	kfree(p);
44203f6bcfbdSStefan Behrens 	return ret;
44213f6bcfbdSStefan Behrens }
44223f6bcfbdSStefan Behrens 
4423d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4424d7728c96SJan Schmidt {
4425d7728c96SJan Schmidt 	int ret = 0;
4426d7728c96SJan Schmidt 	int i;
4427740c3d22SChris Mason 	u64 rel_ptr;
4428d7728c96SJan Schmidt 	int size;
4429806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4430d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4431d7728c96SJan Schmidt 	struct btrfs_path *path;
4432d7728c96SJan Schmidt 
443382b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4434d7728c96SJan Schmidt 		return -EPERM;
4435d7728c96SJan Schmidt 
4436d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4437d7728c96SJan Schmidt 	if (!path) {
4438d7728c96SJan Schmidt 		ret = -ENOMEM;
4439d7728c96SJan Schmidt 		goto out;
4440d7728c96SJan Schmidt 	}
4441d7728c96SJan Schmidt 
4442d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4443d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4444d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4445d7728c96SJan Schmidt 		ipa = NULL;
4446d7728c96SJan Schmidt 		goto out;
4447d7728c96SJan Schmidt 	}
4448d7728c96SJan Schmidt 
4449d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4450d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4451d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4452d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4453d7728c96SJan Schmidt 		ipath = NULL;
4454d7728c96SJan Schmidt 		goto out;
4455d7728c96SJan Schmidt 	}
4456d7728c96SJan Schmidt 
4457d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4458d7728c96SJan Schmidt 	if (ret < 0)
4459d7728c96SJan Schmidt 		goto out;
4460d7728c96SJan Schmidt 
4461d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4462745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4463745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4464740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4465d7728c96SJan Schmidt 	}
4466d7728c96SJan Schmidt 
4467745c4d8eSJeff Mahoney 	ret = copy_to_user((void *)(unsigned long)ipa->fspath,
4468745c4d8eSJeff Mahoney 			   (void *)(unsigned long)ipath->fspath, size);
4469d7728c96SJan Schmidt 	if (ret) {
4470d7728c96SJan Schmidt 		ret = -EFAULT;
4471d7728c96SJan Schmidt 		goto out;
4472d7728c96SJan Schmidt 	}
4473d7728c96SJan Schmidt 
4474d7728c96SJan Schmidt out:
4475d7728c96SJan Schmidt 	btrfs_free_path(path);
4476d7728c96SJan Schmidt 	free_ipath(ipath);
4477d7728c96SJan Schmidt 	kfree(ipa);
4478d7728c96SJan Schmidt 
4479d7728c96SJan Schmidt 	return ret;
4480d7728c96SJan Schmidt }
4481d7728c96SJan Schmidt 
4482d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4483d7728c96SJan Schmidt {
4484d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4485d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4486d7728c96SJan Schmidt 
4487d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4488d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4489d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4490d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4491d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4492d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4493d7728c96SJan Schmidt 	} else {
4494d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4495d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4496d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4497d7728c96SJan Schmidt 	}
4498d7728c96SJan Schmidt 
4499d7728c96SJan Schmidt 	return 0;
4500d7728c96SJan Schmidt }
4501d7728c96SJan Schmidt 
4502d7728c96SJan Schmidt static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
4503d7728c96SJan Schmidt 					void __user *arg)
4504d7728c96SJan Schmidt {
4505d7728c96SJan Schmidt 	int ret = 0;
4506d7728c96SJan Schmidt 	int size;
4507d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4508d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4509d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4510d7728c96SJan Schmidt 
4511d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4512d7728c96SJan Schmidt 		return -EPERM;
4513d7728c96SJan Schmidt 
4514d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
4515d7728c96SJan Schmidt 	if (IS_ERR(loi)) {
4516d7728c96SJan Schmidt 		ret = PTR_ERR(loi);
4517d7728c96SJan Schmidt 		loi = NULL;
4518d7728c96SJan Schmidt 		goto out;
4519d7728c96SJan Schmidt 	}
4520d7728c96SJan Schmidt 
4521d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4522d7728c96SJan Schmidt 	if (!path) {
4523d7728c96SJan Schmidt 		ret = -ENOMEM;
4524d7728c96SJan Schmidt 		goto out;
4525d7728c96SJan Schmidt 	}
4526d7728c96SJan Schmidt 
4527425d17a2SLiu Bo 	size = min_t(u32, loi->size, 64 * 1024);
4528d7728c96SJan Schmidt 	inodes = init_data_container(size);
4529d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4530d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4531d7728c96SJan Schmidt 		inodes = NULL;
4532d7728c96SJan Schmidt 		goto out;
4533d7728c96SJan Schmidt 	}
4534d7728c96SJan Schmidt 
4535df031f07SLiu Bo 	ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
4536df031f07SLiu Bo 					  build_ino_list, inodes);
4537df031f07SLiu Bo 	if (ret == -EINVAL)
4538d7728c96SJan Schmidt 		ret = -ENOENT;
4539d7728c96SJan Schmidt 	if (ret < 0)
4540d7728c96SJan Schmidt 		goto out;
4541d7728c96SJan Schmidt 
4542745c4d8eSJeff Mahoney 	ret = copy_to_user((void *)(unsigned long)loi->inodes,
4543745c4d8eSJeff Mahoney 			   (void *)(unsigned long)inodes, size);
4544d7728c96SJan Schmidt 	if (ret)
4545d7728c96SJan Schmidt 		ret = -EFAULT;
4546d7728c96SJan Schmidt 
4547d7728c96SJan Schmidt out:
4548d7728c96SJan Schmidt 	btrfs_free_path(path);
4549425d17a2SLiu Bo 	vfree(inodes);
4550d7728c96SJan Schmidt 	kfree(loi);
4551d7728c96SJan Schmidt 
4552d7728c96SJan Schmidt 	return ret;
4553d7728c96SJan Schmidt }
4554d7728c96SJan Schmidt 
455519a39dceSIlya Dryomov void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
4556c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4557c9e9f97bSIlya Dryomov {
4558c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4559c9e9f97bSIlya Dryomov 
4560c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4561c9e9f97bSIlya Dryomov 
4562837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_running))
4563837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4564837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4565837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4566a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4567a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4568837d5b6eSIlya Dryomov 
4569c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4570c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4571c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
457219a39dceSIlya Dryomov 
457319a39dceSIlya Dryomov 	if (lock) {
457419a39dceSIlya Dryomov 		spin_lock(&fs_info->balance_lock);
457519a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
457619a39dceSIlya Dryomov 		spin_unlock(&fs_info->balance_lock);
457719a39dceSIlya Dryomov 	} else {
457819a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
457919a39dceSIlya Dryomov 	}
4580c9e9f97bSIlya Dryomov }
4581c9e9f97bSIlya Dryomov 
45829ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4583c9e9f97bSIlya Dryomov {
4584496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4585c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4586c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4587c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4588ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4589c9e9f97bSIlya Dryomov 	int ret;
4590c9e9f97bSIlya Dryomov 
4591c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4592c9e9f97bSIlya Dryomov 		return -EPERM;
4593c9e9f97bSIlya Dryomov 
4594e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
45959ba1f6e4SLiu Bo 	if (ret)
45969ba1f6e4SLiu Bo 		return ret;
45979ba1f6e4SLiu Bo 
4598ed0fb78fSIlya Dryomov again:
4599ed0fb78fSIlya Dryomov 	if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
4600c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->volume_mutex);
4601c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4602ed0fb78fSIlya Dryomov 		need_unlock = true;
4603ed0fb78fSIlya Dryomov 		goto locked;
4604ed0fb78fSIlya Dryomov 	}
4605ed0fb78fSIlya Dryomov 
4606ed0fb78fSIlya Dryomov 	/*
4607ed0fb78fSIlya Dryomov 	 * mut. excl. ops lock is locked.  Three possibilites:
4608ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4609ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4610ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4611ed0fb78fSIlya Dryomov 	 */
4612ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4613ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4614ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
4615ed0fb78fSIlya Dryomov 		if (!atomic_read(&fs_info->balance_running)) {
4616ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4617ed0fb78fSIlya Dryomov 			if (!mutex_trylock(&fs_info->volume_mutex))
4618ed0fb78fSIlya Dryomov 				goto again;
4619ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4620ed0fb78fSIlya Dryomov 
4621ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
4622ed0fb78fSIlya Dryomov 			    !atomic_read(&fs_info->balance_running)) {
4623ed0fb78fSIlya Dryomov 				/* this is (3) */
4624ed0fb78fSIlya Dryomov 				need_unlock = false;
4625ed0fb78fSIlya Dryomov 				goto locked;
4626ed0fb78fSIlya Dryomov 			}
4627ed0fb78fSIlya Dryomov 
4628ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4629ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->volume_mutex);
4630ed0fb78fSIlya Dryomov 			goto again;
4631ed0fb78fSIlya Dryomov 		} else {
4632ed0fb78fSIlya Dryomov 			/* this is (2) */
4633ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4634ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4635ed0fb78fSIlya Dryomov 			goto out;
4636ed0fb78fSIlya Dryomov 		}
4637ed0fb78fSIlya Dryomov 	} else {
4638ed0fb78fSIlya Dryomov 		/* this is (1) */
4639ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4640e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4641ed0fb78fSIlya Dryomov 		goto out;
4642ed0fb78fSIlya Dryomov 	}
4643ed0fb78fSIlya Dryomov 
4644ed0fb78fSIlya Dryomov locked:
4645ed0fb78fSIlya Dryomov 	BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
4646c9e9f97bSIlya Dryomov 
4647c9e9f97bSIlya Dryomov 	if (arg) {
4648c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4649c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4650c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4651ed0fb78fSIlya Dryomov 			goto out_unlock;
4652c9e9f97bSIlya Dryomov 		}
4653de322263SIlya Dryomov 
4654de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4655de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4656de322263SIlya Dryomov 				ret = -ENOTCONN;
4657de322263SIlya Dryomov 				goto out_bargs;
4658de322263SIlya Dryomov 			}
4659de322263SIlya Dryomov 
4660de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4661de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4662de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4663de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4664de322263SIlya Dryomov 
4665de322263SIlya Dryomov 			goto do_balance;
4666de322263SIlya Dryomov 		}
4667c9e9f97bSIlya Dryomov 	} else {
4668c9e9f97bSIlya Dryomov 		bargs = NULL;
4669c9e9f97bSIlya Dryomov 	}
4670c9e9f97bSIlya Dryomov 
4671ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4672837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4673837d5b6eSIlya Dryomov 		goto out_bargs;
4674837d5b6eSIlya Dryomov 	}
4675837d5b6eSIlya Dryomov 
46768d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4677c9e9f97bSIlya Dryomov 	if (!bctl) {
4678c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4679c9e9f97bSIlya Dryomov 		goto out_bargs;
4680c9e9f97bSIlya Dryomov 	}
4681c9e9f97bSIlya Dryomov 
4682c9e9f97bSIlya Dryomov 	bctl->fs_info = fs_info;
4683c9e9f97bSIlya Dryomov 	if (arg) {
4684c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4685c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4686c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4687c9e9f97bSIlya Dryomov 
4688c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4689f43ffb60SIlya Dryomov 	} else {
4690f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4691f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4692c9e9f97bSIlya Dryomov 	}
4693c9e9f97bSIlya Dryomov 
46948eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
46958eb93459SDavid Sterba 		ret = -EINVAL;
46960f89abf5SChristian Engelmayer 		goto out_bctl;
46978eb93459SDavid Sterba 	}
46988eb93459SDavid Sterba 
4699de322263SIlya Dryomov do_balance:
4700c9e9f97bSIlya Dryomov 	/*
4701ed0fb78fSIlya Dryomov 	 * Ownership of bctl and mutually_exclusive_operation_running
4702ed0fb78fSIlya Dryomov 	 * goes to to btrfs_balance.  bctl is freed in __cancel_balance,
4703ed0fb78fSIlya Dryomov 	 * or, if restriper was paused all the way until unmount, in
4704ed0fb78fSIlya Dryomov 	 * free_fs_info.  mutually_exclusive_operation_running is
4705ed0fb78fSIlya Dryomov 	 * cleared in __cancel_balance.
4706c9e9f97bSIlya Dryomov 	 */
4707ed0fb78fSIlya Dryomov 	need_unlock = false;
4708ed0fb78fSIlya Dryomov 
4709ed0fb78fSIlya Dryomov 	ret = btrfs_balance(bctl, bargs);
47100f89abf5SChristian Engelmayer 	bctl = NULL;
4711ed0fb78fSIlya Dryomov 
4712c9e9f97bSIlya Dryomov 	if (arg) {
4713c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4714c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4715c9e9f97bSIlya Dryomov 	}
4716c9e9f97bSIlya Dryomov 
47170f89abf5SChristian Engelmayer out_bctl:
47180f89abf5SChristian Engelmayer 	kfree(bctl);
4719c9e9f97bSIlya Dryomov out_bargs:
4720c9e9f97bSIlya Dryomov 	kfree(bargs);
4721ed0fb78fSIlya Dryomov out_unlock:
4722c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4723c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->volume_mutex);
4724ed0fb78fSIlya Dryomov 	if (need_unlock)
4725ed0fb78fSIlya Dryomov 		atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
4726ed0fb78fSIlya Dryomov out:
4727e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4728c9e9f97bSIlya Dryomov 	return ret;
4729c9e9f97bSIlya Dryomov }
4730c9e9f97bSIlya Dryomov 
4731837d5b6eSIlya Dryomov static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
4732837d5b6eSIlya Dryomov {
4733837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4734837d5b6eSIlya Dryomov 		return -EPERM;
4735837d5b6eSIlya Dryomov 
4736837d5b6eSIlya Dryomov 	switch (cmd) {
4737837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
4738837d5b6eSIlya Dryomov 		return btrfs_pause_balance(root->fs_info);
4739a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
4740a7e99c69SIlya Dryomov 		return btrfs_cancel_balance(root->fs_info);
4741837d5b6eSIlya Dryomov 	}
4742837d5b6eSIlya Dryomov 
4743837d5b6eSIlya Dryomov 	return -EINVAL;
4744837d5b6eSIlya Dryomov }
4745837d5b6eSIlya Dryomov 
474619a39dceSIlya Dryomov static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
474719a39dceSIlya Dryomov 					 void __user *arg)
474819a39dceSIlya Dryomov {
474919a39dceSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
475019a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
475119a39dceSIlya Dryomov 	int ret = 0;
475219a39dceSIlya Dryomov 
475319a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
475419a39dceSIlya Dryomov 		return -EPERM;
475519a39dceSIlya Dryomov 
475619a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
475719a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
475819a39dceSIlya Dryomov 		ret = -ENOTCONN;
475919a39dceSIlya Dryomov 		goto out;
476019a39dceSIlya Dryomov 	}
476119a39dceSIlya Dryomov 
47628d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
476319a39dceSIlya Dryomov 	if (!bargs) {
476419a39dceSIlya Dryomov 		ret = -ENOMEM;
476519a39dceSIlya Dryomov 		goto out;
476619a39dceSIlya Dryomov 	}
476719a39dceSIlya Dryomov 
476819a39dceSIlya Dryomov 	update_ioctl_balance_args(fs_info, 1, bargs);
476919a39dceSIlya Dryomov 
477019a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
477119a39dceSIlya Dryomov 		ret = -EFAULT;
477219a39dceSIlya Dryomov 
477319a39dceSIlya Dryomov 	kfree(bargs);
477419a39dceSIlya Dryomov out:
477519a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
477619a39dceSIlya Dryomov 	return ret;
477719a39dceSIlya Dryomov }
477819a39dceSIlya Dryomov 
4779905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
47805d13a37bSArne Jansen {
4781496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
47825d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
47835d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
47845d13a37bSArne Jansen 	int ret;
47855d13a37bSArne Jansen 	int err;
47865d13a37bSArne Jansen 
47875d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
47885d13a37bSArne Jansen 		return -EPERM;
47895d13a37bSArne Jansen 
4790905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4791905b0ddaSMiao Xie 	if (ret)
4792905b0ddaSMiao Xie 		return ret;
47935d13a37bSArne Jansen 
47945d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4795905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4796905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4797905b0ddaSMiao Xie 		goto drop_write;
4798905b0ddaSMiao Xie 	}
47995d13a37bSArne Jansen 
48007708f029SWang Shilong 	down_write(&root->fs_info->subvol_sem);
480192f183aaSWang Shilong 	trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
48025d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48035d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48045d13a37bSArne Jansen 		goto out;
48055d13a37bSArne Jansen 	}
48065d13a37bSArne Jansen 
48075d13a37bSArne Jansen 	switch (sa->cmd) {
48085d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
48095d13a37bSArne Jansen 		ret = btrfs_quota_enable(trans, root->fs_info);
48105d13a37bSArne Jansen 		break;
48115d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
48125d13a37bSArne Jansen 		ret = btrfs_quota_disable(trans, root->fs_info);
48135d13a37bSArne Jansen 		break;
48145d13a37bSArne Jansen 	default:
48155d13a37bSArne Jansen 		ret = -EINVAL;
48165d13a37bSArne Jansen 		break;
48175d13a37bSArne Jansen 	}
48185d13a37bSArne Jansen 
481992f183aaSWang Shilong 	err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
48205d13a37bSArne Jansen 	if (err && !ret)
48215d13a37bSArne Jansen 		ret = err;
48225d13a37bSArne Jansen out:
48235d13a37bSArne Jansen 	kfree(sa);
48247708f029SWang Shilong 	up_write(&root->fs_info->subvol_sem);
4825905b0ddaSMiao Xie drop_write:
4826905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48275d13a37bSArne Jansen 	return ret;
48285d13a37bSArne Jansen }
48295d13a37bSArne Jansen 
4830905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
48315d13a37bSArne Jansen {
4832496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
48335d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
48345d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48355d13a37bSArne Jansen 	int ret;
48365d13a37bSArne Jansen 	int err;
48375d13a37bSArne Jansen 
48385d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48395d13a37bSArne Jansen 		return -EPERM;
48405d13a37bSArne Jansen 
4841905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4842905b0ddaSMiao Xie 	if (ret)
4843905b0ddaSMiao Xie 		return ret;
48445d13a37bSArne Jansen 
48455d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4846905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4847905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4848905b0ddaSMiao Xie 		goto drop_write;
4849905b0ddaSMiao Xie 	}
48505d13a37bSArne Jansen 
48515d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
48525d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48535d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48545d13a37bSArne Jansen 		goto out;
48555d13a37bSArne Jansen 	}
48565d13a37bSArne Jansen 
48575d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
48585d13a37bSArne Jansen 	if (sa->assign) {
48595d13a37bSArne Jansen 		ret = btrfs_add_qgroup_relation(trans, root->fs_info,
48605d13a37bSArne Jansen 						sa->src, sa->dst);
48615d13a37bSArne Jansen 	} else {
48625d13a37bSArne Jansen 		ret = btrfs_del_qgroup_relation(trans, root->fs_info,
48635d13a37bSArne Jansen 						sa->src, sa->dst);
48645d13a37bSArne Jansen 	}
48655d13a37bSArne Jansen 
4866e082f563SQu Wenruo 	/* update qgroup status and info */
4867e082f563SQu Wenruo 	err = btrfs_run_qgroups(trans, root->fs_info);
4868e082f563SQu Wenruo 	if (err < 0)
4869a4553fefSAnand Jain 		btrfs_std_error(root->fs_info, ret,
4870e082f563SQu Wenruo 			    "failed to update qgroup status and info\n");
48715d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
48725d13a37bSArne Jansen 	if (err && !ret)
48735d13a37bSArne Jansen 		ret = err;
48745d13a37bSArne Jansen 
48755d13a37bSArne Jansen out:
48765d13a37bSArne Jansen 	kfree(sa);
4877905b0ddaSMiao Xie drop_write:
4878905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48795d13a37bSArne Jansen 	return ret;
48805d13a37bSArne Jansen }
48815d13a37bSArne Jansen 
4882905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
48835d13a37bSArne Jansen {
4884496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
48855d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
48865d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48875d13a37bSArne Jansen 	int ret;
48885d13a37bSArne Jansen 	int err;
48895d13a37bSArne Jansen 
48905d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48915d13a37bSArne Jansen 		return -EPERM;
48925d13a37bSArne Jansen 
4893905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4894905b0ddaSMiao Xie 	if (ret)
4895905b0ddaSMiao Xie 		return ret;
48965d13a37bSArne Jansen 
48975d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4898905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4899905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4900905b0ddaSMiao Xie 		goto drop_write;
4901905b0ddaSMiao Xie 	}
49025d13a37bSArne Jansen 
4903d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4904d86e56cfSMiao Xie 		ret = -EINVAL;
4905d86e56cfSMiao Xie 		goto out;
4906d86e56cfSMiao Xie 	}
4907d86e56cfSMiao Xie 
49085d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
49095d13a37bSArne Jansen 	if (IS_ERR(trans)) {
49105d13a37bSArne Jansen 		ret = PTR_ERR(trans);
49115d13a37bSArne Jansen 		goto out;
49125d13a37bSArne Jansen 	}
49135d13a37bSArne Jansen 
49145d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
49155d13a37bSArne Jansen 	if (sa->create) {
49164087cf24SDongsheng Yang 		ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid);
49175d13a37bSArne Jansen 	} else {
49185d13a37bSArne Jansen 		ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
49195d13a37bSArne Jansen 	}
49205d13a37bSArne Jansen 
49215d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
49225d13a37bSArne Jansen 	if (err && !ret)
49235d13a37bSArne Jansen 		ret = err;
49245d13a37bSArne Jansen 
49255d13a37bSArne Jansen out:
49265d13a37bSArne Jansen 	kfree(sa);
4927905b0ddaSMiao Xie drop_write:
4928905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49295d13a37bSArne Jansen 	return ret;
49305d13a37bSArne Jansen }
49315d13a37bSArne Jansen 
4932905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
49335d13a37bSArne Jansen {
4934496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
49355d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
49365d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
49375d13a37bSArne Jansen 	int ret;
49385d13a37bSArne Jansen 	int err;
49395d13a37bSArne Jansen 	u64 qgroupid;
49405d13a37bSArne Jansen 
49415d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
49425d13a37bSArne Jansen 		return -EPERM;
49435d13a37bSArne Jansen 
4944905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4945905b0ddaSMiao Xie 	if (ret)
4946905b0ddaSMiao Xie 		return ret;
49475d13a37bSArne Jansen 
49485d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4949905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4950905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4951905b0ddaSMiao Xie 		goto drop_write;
4952905b0ddaSMiao Xie 	}
49535d13a37bSArne Jansen 
49545d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
49555d13a37bSArne Jansen 	if (IS_ERR(trans)) {
49565d13a37bSArne Jansen 		ret = PTR_ERR(trans);
49575d13a37bSArne Jansen 		goto out;
49585d13a37bSArne Jansen 	}
49595d13a37bSArne Jansen 
49605d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
49615d13a37bSArne Jansen 	if (!qgroupid) {
49625d13a37bSArne Jansen 		/* take the current subvol as qgroup */
49635d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
49645d13a37bSArne Jansen 	}
49655d13a37bSArne Jansen 
49665d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
49675d13a37bSArne Jansen 	ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
49685d13a37bSArne Jansen 
49695d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
49705d13a37bSArne Jansen 	if (err && !ret)
49715d13a37bSArne Jansen 		ret = err;
49725d13a37bSArne Jansen 
49735d13a37bSArne Jansen out:
49745d13a37bSArne Jansen 	kfree(sa);
4975905b0ddaSMiao Xie drop_write:
4976905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49775d13a37bSArne Jansen 	return ret;
49785d13a37bSArne Jansen }
49795d13a37bSArne Jansen 
49802f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
49812f232036SJan Schmidt {
49826d0379ecSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
49832f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
49842f232036SJan Schmidt 	int ret;
49852f232036SJan Schmidt 
49862f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
49872f232036SJan Schmidt 		return -EPERM;
49882f232036SJan Schmidt 
49892f232036SJan Schmidt 	ret = mnt_want_write_file(file);
49902f232036SJan Schmidt 	if (ret)
49912f232036SJan Schmidt 		return ret;
49922f232036SJan Schmidt 
49932f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
49942f232036SJan Schmidt 	if (IS_ERR(qsa)) {
49952f232036SJan Schmidt 		ret = PTR_ERR(qsa);
49962f232036SJan Schmidt 		goto drop_write;
49972f232036SJan Schmidt 	}
49982f232036SJan Schmidt 
49992f232036SJan Schmidt 	if (qsa->flags) {
50002f232036SJan Schmidt 		ret = -EINVAL;
50012f232036SJan Schmidt 		goto out;
50022f232036SJan Schmidt 	}
50032f232036SJan Schmidt 
50042f232036SJan Schmidt 	ret = btrfs_qgroup_rescan(root->fs_info);
50052f232036SJan Schmidt 
50062f232036SJan Schmidt out:
50072f232036SJan Schmidt 	kfree(qsa);
50082f232036SJan Schmidt drop_write:
50092f232036SJan Schmidt 	mnt_drop_write_file(file);
50102f232036SJan Schmidt 	return ret;
50112f232036SJan Schmidt }
50122f232036SJan Schmidt 
50132f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
50142f232036SJan Schmidt {
50156d0379ecSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
50162f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
50172f232036SJan Schmidt 	int ret = 0;
50182f232036SJan Schmidt 
50192f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
50202f232036SJan Schmidt 		return -EPERM;
50212f232036SJan Schmidt 
50228d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
50232f232036SJan Schmidt 	if (!qsa)
50242f232036SJan Schmidt 		return -ENOMEM;
50252f232036SJan Schmidt 
50262f232036SJan Schmidt 	if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
50272f232036SJan Schmidt 		qsa->flags = 1;
50282f232036SJan Schmidt 		qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
50292f232036SJan Schmidt 	}
50302f232036SJan Schmidt 
50312f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
50322f232036SJan Schmidt 		ret = -EFAULT;
50332f232036SJan Schmidt 
50342f232036SJan Schmidt 	kfree(qsa);
50352f232036SJan Schmidt 	return ret;
50362f232036SJan Schmidt }
50372f232036SJan Schmidt 
503857254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
503957254b6eSJan Schmidt {
504054563d41SAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
504157254b6eSJan Schmidt 
504257254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
504357254b6eSJan Schmidt 		return -EPERM;
504457254b6eSJan Schmidt 
504557254b6eSJan Schmidt 	return btrfs_qgroup_wait_for_completion(root->fs_info);
504657254b6eSJan Schmidt }
504757254b6eSJan Schmidt 
5048abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
5049abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
50508ea05e3aSAlexander Block {
5051496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
50528ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
50538ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
50548ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
50558ea05e3aSAlexander Block 	struct timespec ct = CURRENT_TIME;
50568ea05e3aSAlexander Block 	int ret = 0;
5057dd5f9615SStefan Behrens 	int received_uuid_changed;
50588ea05e3aSAlexander Block 
5059bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
5060bd60ea0fSDavid Sterba 		return -EPERM;
5061bd60ea0fSDavid Sterba 
50628ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
50638ea05e3aSAlexander Block 	if (ret < 0)
50648ea05e3aSAlexander Block 		return ret;
50658ea05e3aSAlexander Block 
50668ea05e3aSAlexander Block 	down_write(&root->fs_info->subvol_sem);
50678ea05e3aSAlexander Block 
50688ea05e3aSAlexander Block 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
50698ea05e3aSAlexander Block 		ret = -EINVAL;
50708ea05e3aSAlexander Block 		goto out;
50718ea05e3aSAlexander Block 	}
50728ea05e3aSAlexander Block 
50738ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
50748ea05e3aSAlexander Block 		ret = -EROFS;
50758ea05e3aSAlexander Block 		goto out;
50768ea05e3aSAlexander Block 	}
50778ea05e3aSAlexander Block 
5078dd5f9615SStefan Behrens 	/*
5079dd5f9615SStefan Behrens 	 * 1 - root item
5080dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5081dd5f9615SStefan Behrens 	 */
5082dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
50838ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
50848ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
50858ea05e3aSAlexander Block 		trans = NULL;
50868ea05e3aSAlexander Block 		goto out;
50878ea05e3aSAlexander Block 	}
50888ea05e3aSAlexander Block 
50898ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
50908ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
50918ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
50928ea05e3aSAlexander Block 
5093dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5094dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5095dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5096dd5f9615SStefan Behrens 	    !btrfs_is_empty_uuid(root_item->received_uuid))
5097dd5f9615SStefan Behrens 		btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
5098dd5f9615SStefan Behrens 				    root_item->received_uuid,
5099dd5f9615SStefan Behrens 				    BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5100dd5f9615SStefan Behrens 				    root->root_key.objectid);
51018ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
51028ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
51038ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
51043cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
51053cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
51063cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
51073cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
51088ea05e3aSAlexander Block 
51098ea05e3aSAlexander Block 	ret = btrfs_update_root(trans, root->fs_info->tree_root,
51108ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
51118ea05e3aSAlexander Block 	if (ret < 0) {
51128ea05e3aSAlexander Block 		btrfs_end_transaction(trans, root);
51138ea05e3aSAlexander Block 		goto out;
5114dd5f9615SStefan Behrens 	}
5115dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5116dd5f9615SStefan Behrens 		ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
5117dd5f9615SStefan Behrens 					  sa->uuid,
5118dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5119dd5f9615SStefan Behrens 					  root->root_key.objectid);
5120dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
5121dd5f9615SStefan Behrens 			btrfs_abort_transaction(trans, root, ret);
5122dd5f9615SStefan Behrens 			goto out;
5123dd5f9615SStefan Behrens 		}
5124dd5f9615SStefan Behrens 	}
51258ea05e3aSAlexander Block 	ret = btrfs_commit_transaction(trans, root);
5126dd5f9615SStefan Behrens 	if (ret < 0) {
5127dd5f9615SStefan Behrens 		btrfs_abort_transaction(trans, root, ret);
51288ea05e3aSAlexander Block 		goto out;
51298ea05e3aSAlexander Block 	}
51308ea05e3aSAlexander Block 
5131abccd00fSHugo Mills out:
5132abccd00fSHugo Mills 	up_write(&root->fs_info->subvol_sem);
5133abccd00fSHugo Mills 	mnt_drop_write_file(file);
5134abccd00fSHugo Mills 	return ret;
5135abccd00fSHugo Mills }
5136abccd00fSHugo Mills 
5137abccd00fSHugo Mills #ifdef CONFIG_64BIT
5138abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5139abccd00fSHugo Mills 						void __user *arg)
5140abccd00fSHugo Mills {
5141abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5142abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5143abccd00fSHugo Mills 	int ret = 0;
5144abccd00fSHugo Mills 
5145abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
5146abccd00fSHugo Mills 	if (IS_ERR(args32)) {
5147abccd00fSHugo Mills 		ret = PTR_ERR(args32);
5148abccd00fSHugo Mills 		args32 = NULL;
5149abccd00fSHugo Mills 		goto out;
5150abccd00fSHugo Mills 	}
5151abccd00fSHugo Mills 
51528d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
515384dbeb87SDan Carpenter 	if (!args64) {
515484dbeb87SDan Carpenter 		ret = -ENOMEM;
5155abccd00fSHugo Mills 		goto out;
5156abccd00fSHugo Mills 	}
5157abccd00fSHugo Mills 
5158abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5159abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5160abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5161abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5162abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5163abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5164abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5165abccd00fSHugo Mills 	args64->flags = args32->flags;
5166abccd00fSHugo Mills 
5167abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5168abccd00fSHugo Mills 	if (ret)
5169abccd00fSHugo Mills 		goto out;
5170abccd00fSHugo Mills 
5171abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5172abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5173abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5174abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5175abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5176abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5177abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5178abccd00fSHugo Mills 	args32->flags = args64->flags;
5179abccd00fSHugo Mills 
5180abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5181abccd00fSHugo Mills 	if (ret)
5182abccd00fSHugo Mills 		ret = -EFAULT;
5183abccd00fSHugo Mills 
5184abccd00fSHugo Mills out:
5185abccd00fSHugo Mills 	kfree(args32);
5186abccd00fSHugo Mills 	kfree(args64);
5187abccd00fSHugo Mills 	return ret;
5188abccd00fSHugo Mills }
5189abccd00fSHugo Mills #endif
5190abccd00fSHugo Mills 
5191abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5192abccd00fSHugo Mills 					    void __user *arg)
5193abccd00fSHugo Mills {
5194abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5195abccd00fSHugo Mills 	int ret = 0;
5196abccd00fSHugo Mills 
5197abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
5198abccd00fSHugo Mills 	if (IS_ERR(sa)) {
5199abccd00fSHugo Mills 		ret = PTR_ERR(sa);
5200abccd00fSHugo Mills 		sa = NULL;
5201abccd00fSHugo Mills 		goto out;
5202abccd00fSHugo Mills 	}
5203abccd00fSHugo Mills 
5204abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5205abccd00fSHugo Mills 
5206abccd00fSHugo Mills 	if (ret)
5207abccd00fSHugo Mills 		goto out;
5208abccd00fSHugo Mills 
52098ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
52108ea05e3aSAlexander Block 	if (ret)
52118ea05e3aSAlexander Block 		ret = -EFAULT;
52128ea05e3aSAlexander Block 
52138ea05e3aSAlexander Block out:
52148ea05e3aSAlexander Block 	kfree(sa);
52158ea05e3aSAlexander Block 	return ret;
52168ea05e3aSAlexander Block }
52178ea05e3aSAlexander Block 
5218867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5219867ab667Sjeff.liu {
52206d0379ecSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5221a1b83ac5SAnand Jain 	size_t len;
5222867ab667Sjeff.liu 	int ret;
5223a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5224a1b83ac5SAnand Jain 
5225a1b83ac5SAnand Jain 	spin_lock(&root->fs_info->super_lock);
5226a1b83ac5SAnand Jain 	memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5227a1b83ac5SAnand Jain 	spin_unlock(&root->fs_info->super_lock);
5228a1b83ac5SAnand Jain 
5229a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5230867ab667Sjeff.liu 
5231867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
5232efe120a0SFrank Holton 		btrfs_warn(root->fs_info,
5233efe120a0SFrank Holton 			"label is too long, return the first %zu bytes", --len);
5234867ab667Sjeff.liu 	}
5235867ab667Sjeff.liu 
5236867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5237867ab667Sjeff.liu 
5238867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5239867ab667Sjeff.liu }
5240867ab667Sjeff.liu 
5241a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5242a8bfd4abSjeff.liu {
52436d0379ecSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5244a8bfd4abSjeff.liu 	struct btrfs_super_block *super_block = root->fs_info->super_copy;
5245a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5246a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5247a8bfd4abSjeff.liu 	int ret;
5248a8bfd4abSjeff.liu 
5249a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5250a8bfd4abSjeff.liu 		return -EPERM;
5251a8bfd4abSjeff.liu 
5252a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5253a8bfd4abSjeff.liu 		return -EFAULT;
5254a8bfd4abSjeff.liu 
5255a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
5256efe120a0SFrank Holton 		btrfs_err(root->fs_info, "unable to set label with more than %d bytes",
5257a8bfd4abSjeff.liu 		       BTRFS_LABEL_SIZE - 1);
5258a8bfd4abSjeff.liu 		return -EINVAL;
5259a8bfd4abSjeff.liu 	}
5260a8bfd4abSjeff.liu 
5261a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5262a8bfd4abSjeff.liu 	if (ret)
5263a8bfd4abSjeff.liu 		return ret;
5264a8bfd4abSjeff.liu 
5265a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5266a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5267a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5268a8bfd4abSjeff.liu 		goto out_unlock;
5269a8bfd4abSjeff.liu 	}
5270a8bfd4abSjeff.liu 
5271a1b83ac5SAnand Jain 	spin_lock(&root->fs_info->super_lock);
5272a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
5273a1b83ac5SAnand Jain 	spin_unlock(&root->fs_info->super_lock);
5274d0270acaSJeff Mahoney 	ret = btrfs_commit_transaction(trans, root);
5275a8bfd4abSjeff.liu 
5276a8bfd4abSjeff.liu out_unlock:
5277a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5278a8bfd4abSjeff.liu 	return ret;
5279a8bfd4abSjeff.liu }
5280a8bfd4abSjeff.liu 
52812eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
52822eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
52832eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
52842eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
52852eaa055fSJeff Mahoney 
52862eaa055fSJeff Mahoney static int btrfs_ioctl_get_supported_features(struct file *file,
52872eaa055fSJeff Mahoney 					      void __user *arg)
52882eaa055fSJeff Mahoney {
52892eaa055fSJeff Mahoney 	static struct btrfs_ioctl_feature_flags features[3] = {
52902eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
52912eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
52922eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
52932eaa055fSJeff Mahoney 	};
52942eaa055fSJeff Mahoney 
52952eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
52962eaa055fSJeff Mahoney 		return -EFAULT;
52972eaa055fSJeff Mahoney 
52982eaa055fSJeff Mahoney 	return 0;
52992eaa055fSJeff Mahoney }
53002eaa055fSJeff Mahoney 
53012eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
53022eaa055fSJeff Mahoney {
53032eaa055fSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
53042eaa055fSJeff Mahoney 	struct btrfs_super_block *super_block = root->fs_info->super_copy;
53052eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
53062eaa055fSJeff Mahoney 
53072eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
53082eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
53092eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
53102eaa055fSJeff Mahoney 
53112eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
53122eaa055fSJeff Mahoney 		return -EFAULT;
53132eaa055fSJeff Mahoney 
53142eaa055fSJeff Mahoney 	return 0;
53152eaa055fSJeff Mahoney }
53162eaa055fSJeff Mahoney 
53173b02a68aSJeff Mahoney static int check_feature_bits(struct btrfs_root *root,
53183b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
53192eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
53202eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
53212eaa055fSJeff Mahoney {
53223b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
53233b02a68aSJeff Mahoney 	char *names;
53242eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
53252eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
53262eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
53272eaa055fSJeff Mahoney 
53282eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
53292eaa055fSJeff Mahoney 	if (unsupported) {
53303b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
53313b02a68aSJeff Mahoney 		if (names) {
53323b02a68aSJeff Mahoney 			btrfs_warn(root->fs_info,
53333b02a68aSJeff Mahoney 			   "this kernel does not support the %s feature bit%s",
53343b02a68aSJeff Mahoney 			   names, strchr(names, ',') ? "s" : "");
53353b02a68aSJeff Mahoney 			kfree(names);
53363b02a68aSJeff Mahoney 		} else
53372eaa055fSJeff Mahoney 			btrfs_warn(root->fs_info,
53382eaa055fSJeff Mahoney 			   "this kernel does not support %s bits 0x%llx",
53392eaa055fSJeff Mahoney 			   type, unsupported);
53402eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
53412eaa055fSJeff Mahoney 	}
53422eaa055fSJeff Mahoney 
53432eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
53442eaa055fSJeff Mahoney 	if (disallowed) {
53453b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
53463b02a68aSJeff Mahoney 		if (names) {
53473b02a68aSJeff Mahoney 			btrfs_warn(root->fs_info,
53483b02a68aSJeff Mahoney 			   "can't set the %s feature bit%s while mounted",
53493b02a68aSJeff Mahoney 			   names, strchr(names, ',') ? "s" : "");
53503b02a68aSJeff Mahoney 			kfree(names);
53513b02a68aSJeff Mahoney 		} else
53522eaa055fSJeff Mahoney 			btrfs_warn(root->fs_info,
53532eaa055fSJeff Mahoney 			   "can't set %s bits 0x%llx while mounted",
53542eaa055fSJeff Mahoney 			   type, disallowed);
53552eaa055fSJeff Mahoney 		return -EPERM;
53562eaa055fSJeff Mahoney 	}
53572eaa055fSJeff Mahoney 
53582eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
53592eaa055fSJeff Mahoney 	if (disallowed) {
53603b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
53613b02a68aSJeff Mahoney 		if (names) {
53623b02a68aSJeff Mahoney 			btrfs_warn(root->fs_info,
53633b02a68aSJeff Mahoney 			   "can't clear the %s feature bit%s while mounted",
53643b02a68aSJeff Mahoney 			   names, strchr(names, ',') ? "s" : "");
53653b02a68aSJeff Mahoney 			kfree(names);
53663b02a68aSJeff Mahoney 		} else
53672eaa055fSJeff Mahoney 			btrfs_warn(root->fs_info,
53682eaa055fSJeff Mahoney 			   "can't clear %s bits 0x%llx while mounted",
53692eaa055fSJeff Mahoney 			   type, disallowed);
53702eaa055fSJeff Mahoney 		return -EPERM;
53712eaa055fSJeff Mahoney 	}
53722eaa055fSJeff Mahoney 
53732eaa055fSJeff Mahoney 	return 0;
53742eaa055fSJeff Mahoney }
53752eaa055fSJeff Mahoney 
53762eaa055fSJeff Mahoney #define check_feature(root, change_mask, flags, mask_base)	\
53773b02a68aSJeff Mahoney check_feature_bits(root, FEAT_##mask_base, change_mask, flags,	\
53782eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
53792eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
53802eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
53812eaa055fSJeff Mahoney 
53822eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
53832eaa055fSJeff Mahoney {
53842eaa055fSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
53852eaa055fSJeff Mahoney 	struct btrfs_super_block *super_block = root->fs_info->super_copy;
53862eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
53872eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
53882eaa055fSJeff Mahoney 	u64 newflags;
53892eaa055fSJeff Mahoney 	int ret;
53902eaa055fSJeff Mahoney 
53912eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
53922eaa055fSJeff Mahoney 		return -EPERM;
53932eaa055fSJeff Mahoney 
53942eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
53952eaa055fSJeff Mahoney 		return -EFAULT;
53962eaa055fSJeff Mahoney 
53972eaa055fSJeff Mahoney 	/* Nothing to do */
53982eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
53992eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
54002eaa055fSJeff Mahoney 		return 0;
54012eaa055fSJeff Mahoney 
54022eaa055fSJeff Mahoney 	ret = check_feature(root, flags[0].compat_flags,
54032eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
54042eaa055fSJeff Mahoney 	if (ret)
54052eaa055fSJeff Mahoney 		return ret;
54062eaa055fSJeff Mahoney 
54072eaa055fSJeff Mahoney 	ret = check_feature(root, flags[0].compat_ro_flags,
54082eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
54092eaa055fSJeff Mahoney 	if (ret)
54102eaa055fSJeff Mahoney 		return ret;
54112eaa055fSJeff Mahoney 
54122eaa055fSJeff Mahoney 	ret = check_feature(root, flags[0].incompat_flags,
54132eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
54142eaa055fSJeff Mahoney 	if (ret)
54152eaa055fSJeff Mahoney 		return ret;
54162eaa055fSJeff Mahoney 
54178051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
54182eaa055fSJeff Mahoney 	if (IS_ERR(trans))
54192eaa055fSJeff Mahoney 		return PTR_ERR(trans);
54202eaa055fSJeff Mahoney 
54212eaa055fSJeff Mahoney 	spin_lock(&root->fs_info->super_lock);
54222eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
54232eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
54242eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
54252eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
54262eaa055fSJeff Mahoney 
54272eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
54282eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
54292eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
54302eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
54312eaa055fSJeff Mahoney 
54322eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
54332eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
54342eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
54352eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
54362eaa055fSJeff Mahoney 	spin_unlock(&root->fs_info->super_lock);
54372eaa055fSJeff Mahoney 
5438d0270acaSJeff Mahoney 	return btrfs_commit_transaction(trans, root);
54392eaa055fSJeff Mahoney }
54402eaa055fSJeff Mahoney 
5441f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5442f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5443f46b5a66SChristoph Hellwig {
5444496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
54454bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5446f46b5a66SChristoph Hellwig 
5447f46b5a66SChristoph Hellwig 	switch (cmd) {
54486cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
54496cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
54506cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
54516cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
54526cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
54536cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5454f7039b1dSLi Dongyang 	case FITRIM:
5455f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5456f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5457fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5458fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5459fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
54603de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5461fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
54626f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
54636f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
546476dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
546576dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
54660caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
54670caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
54680caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
54690caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
54706ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
54716ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5472f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
54731e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
54741e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
54751e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5476f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5477198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5478f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
54794bcabaa3SChristoph Hellwig 		return btrfs_ioctl_add_dev(root, argp);
5480f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5481da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
5482475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
5483475f6387SJan Schmidt 		return btrfs_ioctl_fs_info(root, argp);
5484475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
5485475f6387SJan Schmidt 		return btrfs_ioctl_dev_info(root, argp);
5486f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
54879ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5488f46b5a66SChristoph Hellwig 	case BTRFS_IOC_CLONE:
5489c5c9cd4dSSage Weil 		return btrfs_ioctl_clone(file, arg, 0, 0, 0);
5490c5c9cd4dSSage Weil 	case BTRFS_IOC_CLONE_RANGE:
54917a865e8aSChristoph Hellwig 		return btrfs_ioctl_clone_range(file, argp);
5492f46b5a66SChristoph Hellwig 	case BTRFS_IOC_TRANS_START:
5493f46b5a66SChristoph Hellwig 		return btrfs_ioctl_trans_start(file);
5494f46b5a66SChristoph Hellwig 	case BTRFS_IOC_TRANS_END:
5495f46b5a66SChristoph Hellwig 		return btrfs_ioctl_trans_end(file);
5496ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5497ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5498cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5499cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5500ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5501ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5502d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5503d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5504d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5505d7728c96SJan Schmidt 		return btrfs_ioctl_logical_to_ino(root, argp);
55061406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
55071406e432SJosef Bacik 		return btrfs_ioctl_space_info(root, argp);
55089b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
55099b199859SFilipe David Borba Manana 		int ret;
55109b199859SFilipe David Borba Manana 
55116c255e67SMiao Xie 		ret = btrfs_start_delalloc_roots(root->fs_info, 0, -1);
55129b199859SFilipe David Borba Manana 		if (ret)
55139b199859SFilipe David Borba Manana 			return ret;
5514ddb52f4fSAl Viro 		ret = btrfs_sync_fs(file_inode(file)->i_sb, 1);
55152fad4e83SDavid Sterba 		/*
55162fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
55172fad4e83SDavid Sterba 		 * namely it pokes the cleaner ktread that will start
55182fad4e83SDavid Sterba 		 * processing uncleaned subvols.
55192fad4e83SDavid Sterba 		 */
55202fad4e83SDavid Sterba 		wake_up_process(root->fs_info->transaction_kthread);
55219b199859SFilipe David Borba Manana 		return ret;
55229b199859SFilipe David Borba Manana 	}
552346204592SSage Weil 	case BTRFS_IOC_START_SYNC:
55249a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
552546204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
55269a8c28beSMiao Xie 		return btrfs_ioctl_wait_sync(root, argp);
5527475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5528b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5529475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
5530475f6387SJan Schmidt 		return btrfs_ioctl_scrub_cancel(root, argp);
5531475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
5532475f6387SJan Schmidt 		return btrfs_ioctl_scrub_progress(root, argp);
5533c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
55349ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5535837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
5536837d5b6eSIlya Dryomov 		return btrfs_ioctl_balance_ctl(root, arg);
553719a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
553819a39dceSIlya Dryomov 		return btrfs_ioctl_balance_progress(root, argp);
55398ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
55408ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5541abccd00fSHugo Mills #ifdef CONFIG_64BIT
5542abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5543abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5544abccd00fSHugo Mills #endif
554531db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
554631db9f7cSAlexander Block 		return btrfs_ioctl_send(file, argp);
5547c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
5548b27f7c0cSDavid Sterba 		return btrfs_ioctl_get_dev_stats(root, argp);
55495d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5550905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
55515d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5552905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
55535d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5554905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
55555d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5556905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
55572f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
55582f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
55592f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
55602f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
556157254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
556257254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
55633f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
55643f6bcfbdSStefan Behrens 		return btrfs_ioctl_dev_replace(root, argp);
5565867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5566867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5567a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5568a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
5569416161dbSMark Fasheh 	case BTRFS_IOC_FILE_EXTENT_SAME:
5570416161dbSMark Fasheh 		return btrfs_ioctl_file_extent_same(file, argp);
55712eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
55722eaa055fSJeff Mahoney 		return btrfs_ioctl_get_supported_features(file, argp);
55732eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
55742eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
55752eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
55762eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5577f46b5a66SChristoph Hellwig 	}
5578f46b5a66SChristoph Hellwig 
5579f46b5a66SChristoph Hellwig 	return -ENOTTY;
5580f46b5a66SChristoph Hellwig }
5581