xref: /openbmc/linux/fs/btrfs/ioctl.c (revision dd81d459)
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;
10336c282eb4SLi Zefan 
10346c282eb4SLi Zefan 	/*
10356c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
10366c282eb4SLi Zefan 	 * defragging it
10376c282eb4SLi Zefan 	 */
10386c282eb4SLi Zefan 	if (start < *defrag_end)
10396c282eb4SLi Zefan 		return 1;
10406c282eb4SLi Zefan 
10416c282eb4SLi Zefan 	*skip = 0;
10426c282eb4SLi Zefan 
10436c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
10446c282eb4SLi Zefan 	if (!em)
10456c282eb4SLi Zefan 		return 0;
10466c282eb4SLi Zefan 
1047940100a4SChris Mason 	/* this will cover holes, and inline extents */
104817ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1049940100a4SChris Mason 		ret = 0;
105017ce6ef8SLiu Bo 		goto out;
105117ce6ef8SLiu Bo 	}
105217ce6ef8SLiu Bo 
10536c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1054940100a4SChris Mason 	/*
10556c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
10566c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1057940100a4SChris Mason 	 */
1058a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
10596c282eb4SLi Zefan 	    (em->len >= thresh || !next_mergeable))
1060940100a4SChris Mason 		ret = 0;
106117ce6ef8SLiu Bo out:
1062940100a4SChris Mason 	/*
1063940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1064940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1065940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1066940100a4SChris Mason 	 *
1067940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1068940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1069940100a4SChris Mason 	 */
1070940100a4SChris Mason 	if (ret) {
1071940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1072940100a4SChris Mason 	} else {
1073940100a4SChris Mason 		*last_len = 0;
1074940100a4SChris Mason 		*skip = extent_map_end(em);
1075940100a4SChris Mason 		*defrag_end = 0;
1076940100a4SChris Mason 	}
1077940100a4SChris Mason 
1078940100a4SChris Mason 	free_extent_map(em);
1079940100a4SChris Mason 	return ret;
1080940100a4SChris Mason }
1081940100a4SChris Mason 
10824cb5300bSChris Mason /*
10834cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
10844cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
10854cb5300bSChris Mason  * to COW and defrag.
10864cb5300bSChris Mason  *
10874cb5300bSChris Mason  * It also makes sure the delalloc code has enough
10884cb5300bSChris Mason  * dirty data to avoid making new small extents as part
10894cb5300bSChris Mason  * of the defrag
10904cb5300bSChris Mason  *
10914cb5300bSChris Mason  * It's a good idea to start RA on this range
10924cb5300bSChris Mason  * before calling this.
10934cb5300bSChris Mason  */
10944cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
10954cb5300bSChris Mason 				    struct page **pages,
10964cb5300bSChris Mason 				    unsigned long start_index,
1097c41570c9SJustin Maggard 				    unsigned long num_pages)
1098f46b5a66SChristoph Hellwig {
10994cb5300bSChris Mason 	unsigned long file_end;
11004cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1101f46b5a66SChristoph Hellwig 	u64 page_start;
1102f46b5a66SChristoph Hellwig 	u64 page_end;
11031f12bd06SLiu Bo 	u64 page_cnt;
11044cb5300bSChris Mason 	int ret;
11054cb5300bSChris Mason 	int i;
11064cb5300bSChris Mason 	int i_done;
11074cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
11084cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1109600a45e1SMiao Xie 	struct extent_io_tree *tree;
11103b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
11114cb5300bSChris Mason 
11124cb5300bSChris Mason 	file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
11131f12bd06SLiu Bo 	if (!isize || start_index > file_end)
11141f12bd06SLiu Bo 		return 0;
11151f12bd06SLiu Bo 
11161f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
11174cb5300bSChris Mason 
11184cb5300bSChris Mason 	ret = btrfs_delalloc_reserve_space(inode,
11191f12bd06SLiu Bo 					   page_cnt << PAGE_CACHE_SHIFT);
11204cb5300bSChris Mason 	if (ret)
11214cb5300bSChris Mason 		return ret;
11224cb5300bSChris Mason 	i_done = 0;
1123600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
11244cb5300bSChris Mason 
11254cb5300bSChris Mason 	/* step one, lock all the pages */
11261f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
11274cb5300bSChris Mason 		struct page *page;
1128600a45e1SMiao Xie again:
1129a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
11303b16a4e3SJosef Bacik 					   start_index + i, mask);
11314cb5300bSChris Mason 		if (!page)
11324cb5300bSChris Mason 			break;
11334cb5300bSChris Mason 
1134600a45e1SMiao Xie 		page_start = page_offset(page);
1135600a45e1SMiao Xie 		page_end = page_start + PAGE_CACHE_SIZE - 1;
1136600a45e1SMiao Xie 		while (1) {
1137308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1138308d9800SFilipe Manana 					 0, &cached_state);
1139600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1140600a45e1SMiao Xie 							      page_start);
1141308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1142308d9800SFilipe Manana 					     &cached_state, GFP_NOFS);
1143600a45e1SMiao Xie 			if (!ordered)
1144600a45e1SMiao Xie 				break;
1145600a45e1SMiao Xie 
1146600a45e1SMiao Xie 			unlock_page(page);
1147600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1148600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1149600a45e1SMiao Xie 			lock_page(page);
11501f12bd06SLiu Bo 			/*
11511f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
11521f12bd06SLiu Bo 			 * it was released or not.
11531f12bd06SLiu Bo 			 */
11541f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
11551f12bd06SLiu Bo 				unlock_page(page);
11561f12bd06SLiu Bo 				page_cache_release(page);
11571f12bd06SLiu Bo 				goto again;
11581f12bd06SLiu Bo 			}
1159600a45e1SMiao Xie 		}
1160600a45e1SMiao Xie 
11614cb5300bSChris Mason 		if (!PageUptodate(page)) {
11624cb5300bSChris Mason 			btrfs_readpage(NULL, page);
11634cb5300bSChris Mason 			lock_page(page);
11644cb5300bSChris Mason 			if (!PageUptodate(page)) {
11654cb5300bSChris Mason 				unlock_page(page);
11664cb5300bSChris Mason 				page_cache_release(page);
11674cb5300bSChris Mason 				ret = -EIO;
11684cb5300bSChris Mason 				break;
11694cb5300bSChris Mason 			}
11704cb5300bSChris Mason 		}
1171600a45e1SMiao Xie 
1172600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1173600a45e1SMiao Xie 			unlock_page(page);
1174600a45e1SMiao Xie 			page_cache_release(page);
1175600a45e1SMiao Xie 			goto again;
1176600a45e1SMiao Xie 		}
1177600a45e1SMiao Xie 
11784cb5300bSChris Mason 		pages[i] = page;
11794cb5300bSChris Mason 		i_done++;
11804cb5300bSChris Mason 	}
11814cb5300bSChris Mason 	if (!i_done || ret)
11824cb5300bSChris Mason 		goto out;
11834cb5300bSChris Mason 
11844cb5300bSChris Mason 	if (!(inode->i_sb->s_flags & MS_ACTIVE))
11854cb5300bSChris Mason 		goto out;
11864cb5300bSChris Mason 
11874cb5300bSChris Mason 	/*
11884cb5300bSChris Mason 	 * so now we have a nice long stream of locked
11894cb5300bSChris Mason 	 * and up to date pages, lets wait on them
11904cb5300bSChris Mason 	 */
11914cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
11924cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
11934cb5300bSChris Mason 
11944cb5300bSChris Mason 	page_start = page_offset(pages[0]);
11954cb5300bSChris Mason 	page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
11964cb5300bSChris Mason 
11974cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1198d0082371SJeff Mahoney 			 page_start, page_end - 1, 0, &cached_state);
11994cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
12004cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
12019e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
12029e8a4a8bSLiu Bo 			  &cached_state, GFP_NOFS);
12034cb5300bSChris Mason 
12041f12bd06SLiu Bo 	if (i_done != page_cnt) {
12059e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
12069e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
12079e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
12084cb5300bSChris Mason 		btrfs_delalloc_release_space(inode,
12091f12bd06SLiu Bo 				     (page_cnt - i_done) << PAGE_CACHE_SHIFT);
12104cb5300bSChris Mason 	}
12114cb5300bSChris Mason 
12124cb5300bSChris Mason 
12139e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
12149e8a4a8bSLiu Bo 			  &cached_state, GFP_NOFS);
12154cb5300bSChris Mason 
12164cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
12174cb5300bSChris Mason 			     page_start, page_end - 1, &cached_state,
12184cb5300bSChris Mason 			     GFP_NOFS);
12194cb5300bSChris Mason 
12204cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12214cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
12224cb5300bSChris Mason 		ClearPageChecked(pages[i]);
12234cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
12244cb5300bSChris Mason 		set_page_dirty(pages[i]);
12254cb5300bSChris Mason 		unlock_page(pages[i]);
12264cb5300bSChris Mason 		page_cache_release(pages[i]);
12274cb5300bSChris Mason 	}
12284cb5300bSChris Mason 	return i_done;
12294cb5300bSChris Mason out:
12304cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12314cb5300bSChris Mason 		unlock_page(pages[i]);
12324cb5300bSChris Mason 		page_cache_release(pages[i]);
12334cb5300bSChris Mason 	}
12341f12bd06SLiu Bo 	btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
12354cb5300bSChris Mason 	return ret;
12364cb5300bSChris Mason 
12374cb5300bSChris Mason }
12384cb5300bSChris Mason 
12394cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
12404cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
12414cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
12424cb5300bSChris Mason {
12434cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
12444cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
12454cb5300bSChris Mason 	unsigned long last_index;
1246151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1247940100a4SChris Mason 	u64 last_len = 0;
1248940100a4SChris Mason 	u64 skip = 0;
1249940100a4SChris Mason 	u64 defrag_end = 0;
12504cb5300bSChris Mason 	u64 newer_off = range->start;
1251f46b5a66SChristoph Hellwig 	unsigned long i;
1252008873eaSLi Zefan 	unsigned long ra_index = 0;
1253f46b5a66SChristoph Hellwig 	int ret;
12544cb5300bSChris Mason 	int defrag_count = 0;
12551a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1256aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
1257c41570c9SJustin Maggard 	unsigned long max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1258c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
12594cb5300bSChris Mason 	u64 new_align = ~((u64)128 * 1024 - 1);
12604cb5300bSChris Mason 	struct page **pages = NULL;
12614cb5300bSChris Mason 
12620abd5b17SLiu Bo 	if (isize == 0)
12630abd5b17SLiu Bo 		return 0;
12640abd5b17SLiu Bo 
12650abd5b17SLiu Bo 	if (range->start >= isize)
12660abd5b17SLiu Bo 		return -EINVAL;
12671a419d85SLi Zefan 
12681a419d85SLi Zefan 	if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
12691a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
12701a419d85SLi Zefan 			return -EINVAL;
12711a419d85SLi Zefan 		if (range->compress_type)
12721a419d85SLi Zefan 			compress_type = range->compress_type;
12731a419d85SLi Zefan 	}
1274f46b5a66SChristoph Hellwig 
12750abd5b17SLiu Bo 	if (extent_thresh == 0)
12760abd5b17SLiu Bo 		extent_thresh = 256 * 1024;
1277f46b5a66SChristoph Hellwig 
12784cb5300bSChris Mason 	/*
12794cb5300bSChris Mason 	 * if we were not given a file, allocate a readahead
12804cb5300bSChris Mason 	 * context
12814cb5300bSChris Mason 	 */
12824cb5300bSChris Mason 	if (!file) {
12834cb5300bSChris Mason 		ra = kzalloc(sizeof(*ra), GFP_NOFS);
12844cb5300bSChris Mason 		if (!ra)
12854cb5300bSChris Mason 			return -ENOMEM;
12864cb5300bSChris Mason 		file_ra_state_init(ra, inode->i_mapping);
12874cb5300bSChris Mason 	} else {
12884cb5300bSChris Mason 		ra = &file->f_ra;
12894cb5300bSChris Mason 	}
12904cb5300bSChris Mason 
1291d9b0d9baSDulshani Gunawardhana 	pages = kmalloc_array(max_cluster, sizeof(struct page *),
12924cb5300bSChris Mason 			GFP_NOFS);
12934cb5300bSChris Mason 	if (!pages) {
12944cb5300bSChris Mason 		ret = -ENOMEM;
12954cb5300bSChris Mason 		goto out_ra;
12964cb5300bSChris Mason 	}
12974cb5300bSChris Mason 
12984cb5300bSChris Mason 	/* find the last page to defrag */
12991e701a32SChris Mason 	if (range->start + range->len > range->start) {
1300151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
13011e701a32SChris Mason 			 range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
13021e701a32SChris Mason 	} else {
1303151a31b2SLi Zefan 		last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
13041e701a32SChris Mason 	}
13051e701a32SChris Mason 
13064cb5300bSChris Mason 	if (newer_than) {
13074cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
13084cb5300bSChris Mason 				       &newer_off, 64 * 1024);
13094cb5300bSChris Mason 		if (!ret) {
13104cb5300bSChris Mason 			range->start = newer_off;
13114cb5300bSChris Mason 			/*
13124cb5300bSChris Mason 			 * we always align our defrag to help keep
13134cb5300bSChris Mason 			 * the extents in the file evenly spaced
13144cb5300bSChris Mason 			 */
13154cb5300bSChris Mason 			i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
13164cb5300bSChris Mason 		} else
13174cb5300bSChris Mason 			goto out_ra;
13184cb5300bSChris Mason 	} else {
13191e701a32SChris Mason 		i = range->start >> PAGE_CACHE_SHIFT;
13204cb5300bSChris Mason 	}
13214cb5300bSChris Mason 	if (!max_to_defrag)
1322070034bdSchandan 		max_to_defrag = last_index - i + 1;
13234cb5300bSChris Mason 
13242a0f7f57SLi Zefan 	/*
13252a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
13262a0f7f57SLi Zefan 	 * written sequentially.
13272a0f7f57SLi Zefan 	 */
13282a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
13292a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
13302a0f7f57SLi Zefan 
1331f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
1332ed6078f7SDavid Sterba 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_CACHE_SIZE))) {
13334cb5300bSChris Mason 		/*
13344cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
13354cb5300bSChris Mason 		 * the FS
13364cb5300bSChris Mason 		 */
13374cb5300bSChris Mason 		if (!(inode->i_sb->s_flags & MS_ACTIVE))
13384cb5300bSChris Mason 			break;
13394cb5300bSChris Mason 
1340210549ebSDavid Sterba 		if (btrfs_defrag_cancelled(root->fs_info)) {
1341efe120a0SFrank Holton 			printk(KERN_DEBUG "BTRFS: defrag_file cancelled\n");
1342210549ebSDavid Sterba 			ret = -EAGAIN;
1343210549ebSDavid Sterba 			break;
1344210549ebSDavid Sterba 		}
1345210549ebSDavid Sterba 
134666c26892SLiu Bo 		if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
13476c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
1348a43a2111SAndrew Mahone 					 &defrag_end, range->flags &
1349a43a2111SAndrew Mahone 					 BTRFS_DEFRAG_RANGE_COMPRESS)) {
1350940100a4SChris Mason 			unsigned long next;
1351940100a4SChris Mason 			/*
1352940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1353940100a4SChris Mason 			 * bump our counter by the suggested amount
1354940100a4SChris Mason 			 */
1355ed6078f7SDavid Sterba 			next = DIV_ROUND_UP(skip, PAGE_CACHE_SIZE);
1356940100a4SChris Mason 			i = max(i + 1, next);
1357940100a4SChris Mason 			continue;
1358940100a4SChris Mason 		}
1359008873eaSLi Zefan 
1360008873eaSLi Zefan 		if (!newer_than) {
1361008873eaSLi Zefan 			cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1362008873eaSLi Zefan 				   PAGE_CACHE_SHIFT) - i;
1363008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1364008873eaSLi Zefan 		} else {
1365008873eaSLi Zefan 			cluster = max_cluster;
1366008873eaSLi Zefan 		}
1367008873eaSLi Zefan 
1368008873eaSLi Zefan 		if (i + cluster > ra_index) {
1369008873eaSLi Zefan 			ra_index = max(i, ra_index);
1370008873eaSLi Zefan 			btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1371008873eaSLi Zefan 				       cluster);
1372e4826a5bSchandan 			ra_index += cluster;
1373008873eaSLi Zefan 		}
13744cb5300bSChris Mason 
1375ecb8bea8SLiu Bo 		mutex_lock(&inode->i_mutex);
1376633085c7SFilipe David Borba Manana 		if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1377633085c7SFilipe David Borba Manana 			BTRFS_I(inode)->force_compress = compress_type;
1378008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1379ecb8bea8SLiu Bo 		if (ret < 0) {
1380ecb8bea8SLiu Bo 			mutex_unlock(&inode->i_mutex);
13814cb5300bSChris Mason 			goto out_ra;
1382ecb8bea8SLiu Bo 		}
13834cb5300bSChris Mason 
13844cb5300bSChris Mason 		defrag_count += ret;
1385d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
1386ecb8bea8SLiu Bo 		mutex_unlock(&inode->i_mutex);
13874cb5300bSChris Mason 
13884cb5300bSChris Mason 		if (newer_than) {
13894cb5300bSChris Mason 			if (newer_off == (u64)-1)
13904cb5300bSChris Mason 				break;
13914cb5300bSChris Mason 
1392e1f041e1SLiu Bo 			if (ret > 0)
1393e1f041e1SLiu Bo 				i += ret;
1394e1f041e1SLiu Bo 
13954cb5300bSChris Mason 			newer_off = max(newer_off + 1,
13964cb5300bSChris Mason 					(u64)i << PAGE_CACHE_SHIFT);
13974cb5300bSChris Mason 
13984cb5300bSChris Mason 			ret = find_new_extents(root, inode,
13994cb5300bSChris Mason 					       newer_than, &newer_off,
14004cb5300bSChris Mason 					       64 * 1024);
14014cb5300bSChris Mason 			if (!ret) {
14024cb5300bSChris Mason 				range->start = newer_off;
14034cb5300bSChris Mason 				i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
14044cb5300bSChris Mason 			} else {
14054cb5300bSChris Mason 				break;
1406940100a4SChris Mason 			}
14074cb5300bSChris Mason 		} else {
1408008873eaSLi Zefan 			if (ret > 0) {
1409cbcc8326SLi Zefan 				i += ret;
1410008873eaSLi Zefan 				last_len += ret << PAGE_CACHE_SHIFT;
1411008873eaSLi Zefan 			} else {
1412940100a4SChris Mason 				i++;
1413008873eaSLi Zefan 				last_len = 0;
1414008873eaSLi Zefan 			}
1415f46b5a66SChristoph Hellwig 		}
14164cb5300bSChris Mason 	}
1417f46b5a66SChristoph Hellwig 
1418dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
14191e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1420dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1421dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1422dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1423dec8ef90SFilipe Manana 	}
14241e701a32SChris Mason 
14251e701a32SChris Mason 	if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
14261e701a32SChris Mason 		/* the filemap_flush will queue IO into the worker threads, but
14271e701a32SChris Mason 		 * we have to make sure the IO is actually started and that
14281e701a32SChris Mason 		 * ordered extents get created before we return
14291e701a32SChris Mason 		 */
14301e701a32SChris Mason 		atomic_inc(&root->fs_info->async_submit_draining);
14311e701a32SChris Mason 		while (atomic_read(&root->fs_info->nr_async_submits) ||
14321e701a32SChris Mason 		      atomic_read(&root->fs_info->async_delalloc_pages)) {
14331e701a32SChris Mason 			wait_event(root->fs_info->async_submit_wait,
14341e701a32SChris Mason 			   (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
14351e701a32SChris Mason 			    atomic_read(&root->fs_info->async_delalloc_pages) == 0));
14361e701a32SChris Mason 		}
14371e701a32SChris Mason 		atomic_dec(&root->fs_info->async_submit_draining);
14381e701a32SChris Mason 	}
14391e701a32SChris Mason 
14401a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
14412b0ce2c2SMitch Harder 		btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
14421a419d85SLi Zefan 	}
14431a419d85SLi Zefan 
144460ccf82fSDiego Calleja 	ret = defrag_count;
1445940100a4SChris Mason 
14464cb5300bSChris Mason out_ra:
1447633085c7SFilipe David Borba Manana 	if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1448633085c7SFilipe David Borba Manana 		mutex_lock(&inode->i_mutex);
1449633085c7SFilipe David Borba Manana 		BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1450633085c7SFilipe David Borba Manana 		mutex_unlock(&inode->i_mutex);
1451633085c7SFilipe David Borba Manana 	}
14524cb5300bSChris Mason 	if (!file)
14534cb5300bSChris Mason 		kfree(ra);
14544cb5300bSChris Mason 	kfree(pages);
1455940100a4SChris Mason 	return ret;
1456f46b5a66SChristoph Hellwig }
1457f46b5a66SChristoph Hellwig 
1458198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
145976dda93cSYan, Zheng 					void __user *arg)
1460f46b5a66SChristoph Hellwig {
1461f46b5a66SChristoph Hellwig 	u64 new_size;
1462f46b5a66SChristoph Hellwig 	u64 old_size;
1463f46b5a66SChristoph Hellwig 	u64 devid = 1;
1464496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1465f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1466f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1467f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1468f46b5a66SChristoph Hellwig 	char *sizestr;
14699a40f122SGui Hecheng 	char *retptr;
1470f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1471f46b5a66SChristoph Hellwig 	int ret = 0;
1472f46b5a66SChristoph Hellwig 	int mod = 0;
1473f46b5a66SChristoph Hellwig 
1474e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1475e441d54dSChris Mason 		return -EPERM;
1476e441d54dSChris Mason 
1477198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1478198605a8SMiao Xie 	if (ret)
1479198605a8SMiao Xie 		return ret;
1480198605a8SMiao Xie 
14815ac00addSStefan Behrens 	if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
14825ac00addSStefan Behrens 			1)) {
148397547676SMiao Xie 		mnt_drop_write_file(file);
1484e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1485c9e9f97bSIlya Dryomov 	}
1486c9e9f97bSIlya Dryomov 
14875ac00addSStefan Behrens 	mutex_lock(&root->fs_info->volume_mutex);
1488dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1489c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1490c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1491c9e9f97bSIlya Dryomov 		goto out;
1492c9e9f97bSIlya Dryomov 	}
14935516e595SMark Fasheh 
14945516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1495f46b5a66SChristoph Hellwig 
1496f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1497f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1498f46b5a66SChristoph Hellwig 	if (devstr) {
1499f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1500f46b5a66SChristoph Hellwig 		*devstr = '\0';
1501f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
150258dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
150358dfae63SZhangZhen 		if (ret)
150458dfae63SZhangZhen 			goto out_free;
1505dfd79829SMiao Xie 		if (!devid) {
1506dfd79829SMiao Xie 			ret = -EINVAL;
1507dfd79829SMiao Xie 			goto out_free;
1508dfd79829SMiao Xie 		}
1509efe120a0SFrank Holton 		btrfs_info(root->fs_info, "resizing devid %llu", devid);
1510f46b5a66SChristoph Hellwig 	}
1511dba60f3fSMiao Xie 
1512aa1b8cd4SStefan Behrens 	device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1513f46b5a66SChristoph Hellwig 	if (!device) {
1514efe120a0SFrank Holton 		btrfs_info(root->fs_info, "resizer unable to find device %llu",
1515c1c9ff7cSGeert Uytterhoeven 		       devid);
1516dfd79829SMiao Xie 		ret = -ENODEV;
1517c9e9f97bSIlya Dryomov 		goto out_free;
1518f46b5a66SChristoph Hellwig 	}
1519dba60f3fSMiao Xie 
1520dba60f3fSMiao Xie 	if (!device->writeable) {
1521efe120a0SFrank Holton 		btrfs_info(root->fs_info,
1522efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1523c1c9ff7cSGeert Uytterhoeven 		       devid);
1524dfd79829SMiao Xie 		ret = -EPERM;
15254e42ae1bSLiu Bo 		goto out_free;
15264e42ae1bSLiu Bo 	}
15274e42ae1bSLiu Bo 
1528f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1529f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1530f46b5a66SChristoph Hellwig 	else {
1531f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1532f46b5a66SChristoph Hellwig 			mod = -1;
1533f46b5a66SChristoph Hellwig 			sizestr++;
1534f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1535f46b5a66SChristoph Hellwig 			mod = 1;
1536f46b5a66SChristoph Hellwig 			sizestr++;
1537f46b5a66SChristoph Hellwig 		}
15389a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
15399a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1540f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1541c9e9f97bSIlya Dryomov 			goto out_free;
1542f46b5a66SChristoph Hellwig 		}
1543f46b5a66SChristoph Hellwig 	}
1544f46b5a66SChristoph Hellwig 
154563a212abSStefan Behrens 	if (device->is_tgtdev_for_dev_replace) {
1546dfd79829SMiao Xie 		ret = -EPERM;
154763a212abSStefan Behrens 		goto out_free;
154863a212abSStefan Behrens 	}
154963a212abSStefan Behrens 
15507cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1551f46b5a66SChristoph Hellwig 
1552f46b5a66SChristoph Hellwig 	if (mod < 0) {
1553f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1554f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1555c9e9f97bSIlya Dryomov 			goto out_free;
1556f46b5a66SChristoph Hellwig 		}
1557f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1558f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1559eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1560902c68a4SGui Hecheng 			ret = -ERANGE;
1561eb8052e0SWenliang Fan 			goto out_free;
1562eb8052e0SWenliang Fan 		}
1563f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1564f46b5a66SChristoph Hellwig 	}
1565f46b5a66SChristoph Hellwig 
1566f46b5a66SChristoph Hellwig 	if (new_size < 256 * 1024 * 1024) {
1567f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1568c9e9f97bSIlya Dryomov 		goto out_free;
1569f46b5a66SChristoph Hellwig 	}
1570f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1571f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1572c9e9f97bSIlya Dryomov 		goto out_free;
1573f46b5a66SChristoph Hellwig 	}
1574f46b5a66SChristoph Hellwig 
1575b8b93addSDavid Sterba 	new_size = div_u64(new_size, root->sectorsize);
1576f46b5a66SChristoph Hellwig 	new_size *= root->sectorsize;
1577f46b5a66SChristoph Hellwig 
1578efe120a0SFrank Holton 	printk_in_rcu(KERN_INFO "BTRFS: new size for %s is %llu\n",
1579c1c9ff7cSGeert Uytterhoeven 		      rcu_str_deref(device->name), new_size);
1580f46b5a66SChristoph Hellwig 
1581f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1582a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
158398d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
158498d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1585c9e9f97bSIlya Dryomov 			goto out_free;
158698d5dc13STsutomu Itoh 		}
1587f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
1588f46b5a66SChristoph Hellwig 		btrfs_commit_transaction(trans, root);
1589ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1590f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
15910253f40eSjeff.liu 	} /* equal, nothing need to do */
1592f46b5a66SChristoph Hellwig 
1593c9e9f97bSIlya Dryomov out_free:
1594f46b5a66SChristoph Hellwig 	kfree(vol_args);
1595c9e9f97bSIlya Dryomov out:
1596c9e9f97bSIlya Dryomov 	mutex_unlock(&root->fs_info->volume_mutex);
15975ac00addSStefan Behrens 	atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
159818f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1599f46b5a66SChristoph Hellwig 	return ret;
1600f46b5a66SChristoph Hellwig }
1601f46b5a66SChristoph Hellwig 
160272fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
16036f72c7e2SArne Jansen 				char *name, unsigned long fd, int subvol,
16046f72c7e2SArne Jansen 				u64 *transid, bool readonly,
16058696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1606f46b5a66SChristoph Hellwig {
1607f46b5a66SChristoph Hellwig 	int namelen;
16083de4586cSChris Mason 	int ret = 0;
1609f46b5a66SChristoph Hellwig 
1610a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1611a874a63eSLiu Bo 	if (ret)
1612a874a63eSLiu Bo 		goto out;
1613a874a63eSLiu Bo 
161472fd032eSSage Weil 	namelen = strlen(name);
161572fd032eSSage Weil 	if (strchr(name, '/')) {
1616f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1617a874a63eSLiu Bo 		goto out_drop_write;
1618f46b5a66SChristoph Hellwig 	}
1619f46b5a66SChristoph Hellwig 
162016780cabSChris Mason 	if (name[0] == '.' &&
162116780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
162216780cabSChris Mason 		ret = -EEXIST;
1623a874a63eSLiu Bo 		goto out_drop_write;
162416780cabSChris Mason 	}
162516780cabSChris Mason 
16263de4586cSChris Mason 	if (subvol) {
162772fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
16286f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1629cb8e7090SChristoph Hellwig 	} else {
16302903ff01SAl Viro 		struct fd src = fdget(fd);
16313de4586cSChris Mason 		struct inode *src_inode;
16322903ff01SAl Viro 		if (!src.file) {
16333de4586cSChris Mason 			ret = -EINVAL;
1634a874a63eSLiu Bo 			goto out_drop_write;
16353de4586cSChris Mason 		}
16363de4586cSChris Mason 
1637496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1638496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1639efe120a0SFrank Holton 			btrfs_info(BTRFS_I(src_inode)->root->fs_info,
1640efe120a0SFrank Holton 				   "Snapshot src from another FS");
164123ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1642d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1643d0242061SDavid Sterba 			/*
1644d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1645d0242061SDavid Sterba 			 * are limited to own subvolumes only
1646d0242061SDavid Sterba 			 */
1647d0242061SDavid Sterba 			ret = -EPERM;
1648ecd18815SAl Viro 		} else {
164972fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
165072fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
16516f72c7e2SArne Jansen 					     transid, readonly, inherit);
1652ecd18815SAl Viro 		}
16532903ff01SAl Viro 		fdput(src);
1654cb8e7090SChristoph Hellwig 	}
1655a874a63eSLiu Bo out_drop_write:
1656a874a63eSLiu Bo 	mnt_drop_write_file(file);
1657f46b5a66SChristoph Hellwig out:
165872fd032eSSage Weil 	return ret;
165972fd032eSSage Weil }
166072fd032eSSage Weil 
166172fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1662fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
166372fd032eSSage Weil {
1664fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
166572fd032eSSage Weil 	int ret;
166672fd032eSSage Weil 
1667fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1668fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1669fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1670fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1671fa0d2b9bSLi Zefan 
1672fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1673b83cc969SLi Zefan 					      vol_args->fd, subvol,
16746f72c7e2SArne Jansen 					      NULL, false, NULL);
1675fa0d2b9bSLi Zefan 
1676fa0d2b9bSLi Zefan 	kfree(vol_args);
1677fa0d2b9bSLi Zefan 	return ret;
1678fa0d2b9bSLi Zefan }
1679fa0d2b9bSLi Zefan 
1680fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1681fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1682fa0d2b9bSLi Zefan {
1683fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1684fa0d2b9bSLi Zefan 	int ret;
1685fdfb1e4fSLi Zefan 	u64 transid = 0;
1686fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1687b83cc969SLi Zefan 	bool readonly = false;
16886f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
168972fd032eSSage Weil 
1690fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1691fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1692fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1693fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1694fdfb1e4fSLi Zefan 
1695b83cc969SLi Zefan 	if (vol_args->flags &
16966f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
16976f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1698b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1699c47ca32dSDan Carpenter 		goto free_args;
1700fdfb1e4fSLi Zefan 	}
1701fdfb1e4fSLi Zefan 
1702fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1703fdfb1e4fSLi Zefan 		ptr = &transid;
1704b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1705b83cc969SLi Zefan 		readonly = true;
17066f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
17076f72c7e2SArne Jansen 		if (vol_args->size > PAGE_CACHE_SIZE) {
17086f72c7e2SArne Jansen 			ret = -EINVAL;
1709c47ca32dSDan Carpenter 			goto free_args;
17106f72c7e2SArne Jansen 		}
17116f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
17126f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
17136f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1714c47ca32dSDan Carpenter 			goto free_args;
17156f72c7e2SArne Jansen 		}
17166f72c7e2SArne Jansen 	}
171775eaa0e2SSage Weil 
1718fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
17196f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
17208696c533SMiao Xie 					      readonly, inherit);
1721c47ca32dSDan Carpenter 	if (ret)
1722c47ca32dSDan Carpenter 		goto free_inherit;
172375eaa0e2SSage Weil 
1724c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1725fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1726c47ca32dSDan Carpenter 					transid),
1727c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
172875eaa0e2SSage Weil 		ret = -EFAULT;
1729c47ca32dSDan Carpenter 
1730c47ca32dSDan Carpenter free_inherit:
17316f72c7e2SArne Jansen 	kfree(inherit);
1732c47ca32dSDan Carpenter free_args:
1733c47ca32dSDan Carpenter 	kfree(vol_args);
1734f46b5a66SChristoph Hellwig 	return ret;
1735f46b5a66SChristoph Hellwig }
1736f46b5a66SChristoph Hellwig 
17370caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
17380caa102dSLi Zefan 						void __user *arg)
17390caa102dSLi Zefan {
1740496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17410caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17420caa102dSLi Zefan 	int ret = 0;
17430caa102dSLi Zefan 	u64 flags = 0;
17440caa102dSLi Zefan 
174533345d01SLi Zefan 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
17460caa102dSLi Zefan 		return -EINVAL;
17470caa102dSLi Zefan 
17480caa102dSLi Zefan 	down_read(&root->fs_info->subvol_sem);
17490caa102dSLi Zefan 	if (btrfs_root_readonly(root))
17500caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
17510caa102dSLi Zefan 	up_read(&root->fs_info->subvol_sem);
17520caa102dSLi Zefan 
17530caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
17540caa102dSLi Zefan 		ret = -EFAULT;
17550caa102dSLi Zefan 
17560caa102dSLi Zefan 	return ret;
17570caa102dSLi Zefan }
17580caa102dSLi Zefan 
17590caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
17600caa102dSLi Zefan 					      void __user *arg)
17610caa102dSLi Zefan {
1762496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17630caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17640caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
17650caa102dSLi Zefan 	u64 root_flags;
17660caa102dSLi Zefan 	u64 flags;
17670caa102dSLi Zefan 	int ret = 0;
17680caa102dSLi Zefan 
1769bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1770bd60ea0fSDavid Sterba 		return -EPERM;
1771bd60ea0fSDavid Sterba 
1772b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1773b9ca0664SLiu Bo 	if (ret)
1774b9ca0664SLiu Bo 		goto out;
17750caa102dSLi Zefan 
1776b9ca0664SLiu Bo 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1777b9ca0664SLiu Bo 		ret = -EINVAL;
1778b9ca0664SLiu Bo 		goto out_drop_write;
1779b9ca0664SLiu Bo 	}
17800caa102dSLi Zefan 
1781b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1782b9ca0664SLiu Bo 		ret = -EFAULT;
1783b9ca0664SLiu Bo 		goto out_drop_write;
1784b9ca0664SLiu Bo 	}
17850caa102dSLi Zefan 
1786b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1787b9ca0664SLiu Bo 		ret = -EINVAL;
1788b9ca0664SLiu Bo 		goto out_drop_write;
1789b9ca0664SLiu Bo 	}
17900caa102dSLi Zefan 
1791b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1792b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1793b9ca0664SLiu Bo 		goto out_drop_write;
1794b9ca0664SLiu Bo 	}
17950caa102dSLi Zefan 
17960caa102dSLi Zefan 	down_write(&root->fs_info->subvol_sem);
17970caa102dSLi Zefan 
17980caa102dSLi Zefan 	/* nothing to do */
17990caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1800b9ca0664SLiu Bo 		goto out_drop_sem;
18010caa102dSLi Zefan 
18020caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
18032c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
18040caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
18050caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
18062c686537SDavid Sterba 	} else {
18072c686537SDavid Sterba 		/*
18082c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
18092c686537SDavid Sterba 		 * send
18102c686537SDavid Sterba 		 */
18112c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
18122c686537SDavid Sterba 		if (root->send_in_progress == 0) {
18130caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
18140caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
18152c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18162c686537SDavid Sterba 		} else {
18172c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18182c686537SDavid Sterba 			btrfs_warn(root->fs_info,
18192c686537SDavid Sterba 			"Attempt to set subvolume %llu read-write during send",
18202c686537SDavid Sterba 					root->root_key.objectid);
18212c686537SDavid Sterba 			ret = -EPERM;
18222c686537SDavid Sterba 			goto out_drop_sem;
18232c686537SDavid Sterba 		}
18242c686537SDavid Sterba 	}
18250caa102dSLi Zefan 
18260caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
18270caa102dSLi Zefan 	if (IS_ERR(trans)) {
18280caa102dSLi Zefan 		ret = PTR_ERR(trans);
18290caa102dSLi Zefan 		goto out_reset;
18300caa102dSLi Zefan 	}
18310caa102dSLi Zefan 
1832b4dc2b8cSLi Zefan 	ret = btrfs_update_root(trans, root->fs_info->tree_root,
18330caa102dSLi Zefan 				&root->root_key, &root->root_item);
18340caa102dSLi Zefan 
18350caa102dSLi Zefan 	btrfs_commit_transaction(trans, root);
18360caa102dSLi Zefan out_reset:
18370caa102dSLi Zefan 	if (ret)
18380caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1839b9ca0664SLiu Bo out_drop_sem:
18400caa102dSLi Zefan 	up_write(&root->fs_info->subvol_sem);
1841b9ca0664SLiu Bo out_drop_write:
1842b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1843b9ca0664SLiu Bo out:
18440caa102dSLi Zefan 	return ret;
18450caa102dSLi Zefan }
18460caa102dSLi Zefan 
184776dda93cSYan, Zheng /*
184876dda93cSYan, Zheng  * helper to check if the subvolume references other subvolumes
184976dda93cSYan, Zheng  */
185076dda93cSYan, Zheng static noinline int may_destroy_subvol(struct btrfs_root *root)
185176dda93cSYan, Zheng {
185276dda93cSYan, Zheng 	struct btrfs_path *path;
1853175a2b87SJosef Bacik 	struct btrfs_dir_item *di;
185476dda93cSYan, Zheng 	struct btrfs_key key;
1855175a2b87SJosef Bacik 	u64 dir_id;
185676dda93cSYan, Zheng 	int ret;
185776dda93cSYan, Zheng 
185876dda93cSYan, Zheng 	path = btrfs_alloc_path();
185976dda93cSYan, Zheng 	if (!path)
186076dda93cSYan, Zheng 		return -ENOMEM;
186176dda93cSYan, Zheng 
1862175a2b87SJosef Bacik 	/* Make sure this root isn't set as the default subvol */
1863175a2b87SJosef Bacik 	dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1864175a2b87SJosef Bacik 	di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1865175a2b87SJosef Bacik 				   dir_id, "default", 7, 0);
1866175a2b87SJosef Bacik 	if (di && !IS_ERR(di)) {
1867175a2b87SJosef Bacik 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1868175a2b87SJosef Bacik 		if (key.objectid == root->root_key.objectid) {
186972de6b53SGuangyu Sun 			ret = -EPERM;
187072de6b53SGuangyu Sun 			btrfs_err(root->fs_info, "deleting default subvolume "
187172de6b53SGuangyu Sun 				  "%llu is not allowed", key.objectid);
1872175a2b87SJosef Bacik 			goto out;
1873175a2b87SJosef Bacik 		}
1874175a2b87SJosef Bacik 		btrfs_release_path(path);
1875175a2b87SJosef Bacik 	}
1876175a2b87SJosef Bacik 
187776dda93cSYan, Zheng 	key.objectid = root->root_key.objectid;
187876dda93cSYan, Zheng 	key.type = BTRFS_ROOT_REF_KEY;
187976dda93cSYan, Zheng 	key.offset = (u64)-1;
188076dda93cSYan, Zheng 
188176dda93cSYan, Zheng 	ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
188276dda93cSYan, Zheng 				&key, path, 0, 0);
188376dda93cSYan, Zheng 	if (ret < 0)
188476dda93cSYan, Zheng 		goto out;
188576dda93cSYan, Zheng 	BUG_ON(ret == 0);
188676dda93cSYan, Zheng 
188776dda93cSYan, Zheng 	ret = 0;
188876dda93cSYan, Zheng 	if (path->slots[0] > 0) {
188976dda93cSYan, Zheng 		path->slots[0]--;
189076dda93cSYan, Zheng 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
189176dda93cSYan, Zheng 		if (key.objectid == root->root_key.objectid &&
189276dda93cSYan, Zheng 		    key.type == BTRFS_ROOT_REF_KEY)
189376dda93cSYan, Zheng 			ret = -ENOTEMPTY;
189476dda93cSYan, Zheng 	}
189576dda93cSYan, Zheng out:
189676dda93cSYan, Zheng 	btrfs_free_path(path);
189776dda93cSYan, Zheng 	return ret;
189876dda93cSYan, Zheng }
189976dda93cSYan, Zheng 
1900ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1901ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1902ac8e9819SChris Mason {
1903abc6e134SChris Mason 	struct btrfs_key test;
1904abc6e134SChris Mason 	int ret;
1905abc6e134SChris Mason 
1906abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1907abc6e134SChris Mason 	test.type = sk->min_type;
1908abc6e134SChris Mason 	test.offset = sk->min_offset;
1909abc6e134SChris Mason 
1910abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1911abc6e134SChris Mason 	if (ret < 0)
1912ac8e9819SChris Mason 		return 0;
1913abc6e134SChris Mason 
1914abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1915abc6e134SChris Mason 	test.type = sk->max_type;
1916abc6e134SChris Mason 	test.offset = sk->max_offset;
1917abc6e134SChris Mason 
1918abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1919abc6e134SChris Mason 	if (ret > 0)
1920ac8e9819SChris Mason 		return 0;
1921ac8e9819SChris Mason 	return 1;
1922ac8e9819SChris Mason }
1923ac8e9819SChris Mason 
1924ac8e9819SChris Mason static noinline int copy_to_sk(struct btrfs_root *root,
1925ac8e9819SChris Mason 			       struct btrfs_path *path,
1926ac8e9819SChris Mason 			       struct btrfs_key *key,
1927ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
19289b6e817dSGerhard Heift 			       size_t *buf_size,
1929ba346b35SGerhard Heift 			       char __user *ubuf,
1930ac8e9819SChris Mason 			       unsigned long *sk_offset,
1931ac8e9819SChris Mason 			       int *num_found)
1932ac8e9819SChris Mason {
1933ac8e9819SChris Mason 	u64 found_transid;
1934ac8e9819SChris Mason 	struct extent_buffer *leaf;
1935ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
1936*dd81d459SNaohiro Aota 	struct btrfs_key test;
1937ac8e9819SChris Mason 	unsigned long item_off;
1938ac8e9819SChris Mason 	unsigned long item_len;
1939ac8e9819SChris Mason 	int nritems;
1940ac8e9819SChris Mason 	int i;
1941ac8e9819SChris Mason 	int slot;
1942ac8e9819SChris Mason 	int ret = 0;
1943ac8e9819SChris Mason 
1944ac8e9819SChris Mason 	leaf = path->nodes[0];
1945ac8e9819SChris Mason 	slot = path->slots[0];
1946ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
1947ac8e9819SChris Mason 
1948ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
1949ac8e9819SChris Mason 		i = nritems;
1950ac8e9819SChris Mason 		goto advance_key;
1951ac8e9819SChris Mason 	}
1952ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
1953ac8e9819SChris Mason 
1954ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
1955ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
1956ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
1957ac8e9819SChris Mason 
195803b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
195903b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
196003b71c6cSGabriel de Perthuis 			continue;
196103b71c6cSGabriel de Perthuis 
19629b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
19638f5f6178SGerhard Heift 			if (*num_found) {
1964ac8e9819SChris Mason 				ret = 1;
19658f5f6178SGerhard Heift 				goto out;
19668f5f6178SGerhard Heift 			}
19678f5f6178SGerhard Heift 
19688f5f6178SGerhard Heift 			/*
19698f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
19708f5f6178SGerhard Heift 			 * handle -EOVERFLOW
19718f5f6178SGerhard Heift 			 */
19728f5f6178SGerhard Heift 
19739b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
1974ac8e9819SChris Mason 			item_len = 0;
19758f5f6178SGerhard Heift 			ret = -EOVERFLOW;
19768f5f6178SGerhard Heift 		}
1977ac8e9819SChris Mason 
19789b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
1979ac8e9819SChris Mason 			ret = 1;
198025c9bc2eSGerhard Heift 			goto out;
1981ac8e9819SChris Mason 		}
1982ac8e9819SChris Mason 
1983ac8e9819SChris Mason 		sh.objectid = key->objectid;
1984ac8e9819SChris Mason 		sh.offset = key->offset;
1985ac8e9819SChris Mason 		sh.type = key->type;
1986ac8e9819SChris Mason 		sh.len = item_len;
1987ac8e9819SChris Mason 		sh.transid = found_transid;
1988ac8e9819SChris Mason 
1989ac8e9819SChris Mason 		/* copy search result header */
1990ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
1991ba346b35SGerhard Heift 			ret = -EFAULT;
1992ba346b35SGerhard Heift 			goto out;
1993ba346b35SGerhard Heift 		}
1994ba346b35SGerhard Heift 
1995ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
1996ac8e9819SChris Mason 
1997ac8e9819SChris Mason 		if (item_len) {
1998ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
1999ac8e9819SChris Mason 			/* copy the item */
2000ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
2001ba346b35SGerhard Heift 						       item_off, item_len)) {
2002ba346b35SGerhard Heift 				ret = -EFAULT;
2003ba346b35SGerhard Heift 				goto out;
2004ba346b35SGerhard Heift 			}
2005ba346b35SGerhard Heift 
2006ac8e9819SChris Mason 			*sk_offset += item_len;
2007ac8e9819SChris Mason 		}
2008e2156867SHugo Mills 		(*num_found)++;
2009ac8e9819SChris Mason 
20108f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
20118f5f6178SGerhard Heift 			goto out;
20128f5f6178SGerhard Heift 
201325c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
201425c9bc2eSGerhard Heift 			ret = 1;
201525c9bc2eSGerhard Heift 			goto out;
201625c9bc2eSGerhard Heift 		}
2017ac8e9819SChris Mason 	}
2018ac8e9819SChris Mason advance_key:
2019ac8e9819SChris Mason 	ret = 0;
2020*dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2021*dd81d459SNaohiro Aota 	test.type = sk->max_type;
2022*dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2023*dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2024*dd81d459SNaohiro Aota 		ret = 1;
2025*dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2026abc6e134SChris Mason 		key->offset++;
2027*dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2028abc6e134SChris Mason 		key->offset = 0;
2029abc6e134SChris Mason 		key->type++;
2030*dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2031abc6e134SChris Mason 		key->offset = 0;
2032abc6e134SChris Mason 		key->type = 0;
2033abc6e134SChris Mason 		key->objectid++;
2034abc6e134SChris Mason 	} else
2035abc6e134SChris Mason 		ret = 1;
203625c9bc2eSGerhard Heift out:
2037ba346b35SGerhard Heift 	/*
2038ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2039ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2040ba346b35SGerhard Heift 	 *     * all items were found
2041ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2042ba346b35SGerhard Heift 	 *     leaf
2043ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2044ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2045ba346b35SGerhard Heift 	 */
2046ac8e9819SChris Mason 	return ret;
2047ac8e9819SChris Mason }
2048ac8e9819SChris Mason 
2049ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
205012544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
20519b6e817dSGerhard Heift 				 size_t *buf_size,
2052ba346b35SGerhard Heift 				 char __user *ubuf)
2053ac8e9819SChris Mason {
2054ac8e9819SChris Mason 	struct btrfs_root *root;
2055ac8e9819SChris Mason 	struct btrfs_key key;
2056ac8e9819SChris Mason 	struct btrfs_path *path;
2057ac8e9819SChris Mason 	struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
2058ac8e9819SChris Mason 	int ret;
2059ac8e9819SChris Mason 	int num_found = 0;
2060ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2061ac8e9819SChris Mason 
20629b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
20639b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
206412544442SGerhard Heift 		return -EOVERFLOW;
20659b6e817dSGerhard Heift 	}
206612544442SGerhard Heift 
2067ac8e9819SChris Mason 	path = btrfs_alloc_path();
2068ac8e9819SChris Mason 	if (!path)
2069ac8e9819SChris Mason 		return -ENOMEM;
2070ac8e9819SChris Mason 
2071ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2072ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2073ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2074ac8e9819SChris Mason 	} else {
2075ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2076ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2077ac8e9819SChris Mason 		key.offset = (u64)-1;
2078ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2079ac8e9819SChris Mason 		if (IS_ERR(root)) {
2080efe120a0SFrank Holton 			printk(KERN_ERR "BTRFS: could not find root %llu\n",
2081ac8e9819SChris Mason 			       sk->tree_id);
2082ac8e9819SChris Mason 			btrfs_free_path(path);
2083ac8e9819SChris Mason 			return -ENOENT;
2084ac8e9819SChris Mason 		}
2085ac8e9819SChris Mason 	}
2086ac8e9819SChris Mason 
2087ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2088ac8e9819SChris Mason 	key.type = sk->min_type;
2089ac8e9819SChris Mason 	key.offset = sk->min_offset;
2090ac8e9819SChris Mason 
2091ac8e9819SChris Mason 	while (1) {
20926174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2093ac8e9819SChris Mason 		if (ret != 0) {
2094ac8e9819SChris Mason 			if (ret > 0)
2095ac8e9819SChris Mason 				ret = 0;
2096ac8e9819SChris Mason 			goto err;
2097ac8e9819SChris Mason 		}
2098ba346b35SGerhard Heift 		ret = copy_to_sk(root, path, &key, sk, buf_size, ubuf,
2099ac8e9819SChris Mason 				 &sk_offset, &num_found);
2100b3b4aa74SDavid Sterba 		btrfs_release_path(path);
210125c9bc2eSGerhard Heift 		if (ret)
2102ac8e9819SChris Mason 			break;
2103ac8e9819SChris Mason 
2104ac8e9819SChris Mason 	}
21058f5f6178SGerhard Heift 	if (ret > 0)
2106ac8e9819SChris Mason 		ret = 0;
2107ac8e9819SChris Mason err:
2108ac8e9819SChris Mason 	sk->nr_items = num_found;
2109ac8e9819SChris Mason 	btrfs_free_path(path);
2110ac8e9819SChris Mason 	return ret;
2111ac8e9819SChris Mason }
2112ac8e9819SChris Mason 
2113ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2114ac8e9819SChris Mason 					   void __user *argp)
2115ac8e9819SChris Mason {
2116ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2117ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2118ac8e9819SChris Mason 	struct inode *inode;
2119ac8e9819SChris Mason 	int ret;
21209b6e817dSGerhard Heift 	size_t buf_size;
2121ac8e9819SChris Mason 
2122ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2123ac8e9819SChris Mason 		return -EPERM;
2124ac8e9819SChris Mason 
2125ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2126ac8e9819SChris Mason 
2127ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2128ba346b35SGerhard Heift 		return -EFAULT;
2129ba346b35SGerhard Heift 
2130ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2131ac8e9819SChris Mason 
2132496ad9aaSAl Viro 	inode = file_inode(file);
2133ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
21348f5f6178SGerhard Heift 
21358f5f6178SGerhard Heift 	/*
21368f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
21378f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
21388f5f6178SGerhard Heift 	 */
21398f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
21408f5f6178SGerhard Heift 		ret = 0;
21418f5f6178SGerhard Heift 
2142ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2143ac8e9819SChris Mason 		ret = -EFAULT;
2144ac8e9819SChris Mason 	return ret;
2145ac8e9819SChris Mason }
2146ac8e9819SChris Mason 
2147cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2148cc68a8a5SGerhard Heift 					       void __user *argp)
2149cc68a8a5SGerhard Heift {
2150cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2151cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2152cc68a8a5SGerhard Heift 	struct inode *inode;
2153cc68a8a5SGerhard Heift 	int ret;
2154cc68a8a5SGerhard Heift 	size_t buf_size;
2155cc68a8a5SGerhard Heift 	const size_t buf_limit = 16 * 1024 * 1024;
2156cc68a8a5SGerhard Heift 
2157cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2158cc68a8a5SGerhard Heift 		return -EPERM;
2159cc68a8a5SGerhard Heift 
2160cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2161cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2162cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2163cc68a8a5SGerhard Heift 		return -EFAULT;
2164cc68a8a5SGerhard Heift 
2165cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2166cc68a8a5SGerhard Heift 
2167cc68a8a5SGerhard Heift 	if (buf_size < sizeof(struct btrfs_ioctl_search_header))
2168cc68a8a5SGerhard Heift 		return -EOVERFLOW;
2169cc68a8a5SGerhard Heift 
2170cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2171cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2172cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2173cc68a8a5SGerhard Heift 
2174cc68a8a5SGerhard Heift 	inode = file_inode(file);
2175cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2176cc68a8a5SGerhard Heift 			   (char *)(&uarg->buf[0]));
2177cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2178cc68a8a5SGerhard Heift 		ret = -EFAULT;
2179cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2180cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2181cc68a8a5SGerhard Heift 		ret = -EFAULT;
2182cc68a8a5SGerhard Heift 
218376dda93cSYan, Zheng 	return ret;
218476dda93cSYan, Zheng }
218576dda93cSYan, Zheng 
218698d377a0STARUISI Hiroaki /*
2187ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2188ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
218998d377a0STARUISI Hiroaki  */
219098d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
219198d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
219298d377a0STARUISI Hiroaki {
219398d377a0STARUISI Hiroaki 	struct btrfs_root *root;
219498d377a0STARUISI Hiroaki 	struct btrfs_key key;
2195ac8e9819SChris Mason 	char *ptr;
219698d377a0STARUISI Hiroaki 	int ret = -1;
219798d377a0STARUISI Hiroaki 	int slot;
219898d377a0STARUISI Hiroaki 	int len;
219998d377a0STARUISI Hiroaki 	int total_len = 0;
220098d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
220198d377a0STARUISI Hiroaki 	struct extent_buffer *l;
220298d377a0STARUISI Hiroaki 	struct btrfs_path *path;
220398d377a0STARUISI Hiroaki 
220498d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
220598d377a0STARUISI Hiroaki 		name[0]='\0';
220698d377a0STARUISI Hiroaki 		return 0;
220798d377a0STARUISI Hiroaki 	}
220898d377a0STARUISI Hiroaki 
220998d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
221098d377a0STARUISI Hiroaki 	if (!path)
221198d377a0STARUISI Hiroaki 		return -ENOMEM;
221298d377a0STARUISI Hiroaki 
2213ac8e9819SChris Mason 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
221498d377a0STARUISI Hiroaki 
221598d377a0STARUISI Hiroaki 	key.objectid = tree_id;
221698d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
221798d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
221898d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
221998d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2220efe120a0SFrank Holton 		printk(KERN_ERR "BTRFS: could not find root %llu\n", tree_id);
22218ad6fcabSChris Mason 		ret = -ENOENT;
22228ad6fcabSChris Mason 		goto out;
222398d377a0STARUISI Hiroaki 	}
222498d377a0STARUISI Hiroaki 
222598d377a0STARUISI Hiroaki 	key.objectid = dirid;
222698d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
22278ad6fcabSChris Mason 	key.offset = (u64)-1;
222898d377a0STARUISI Hiroaki 
222998d377a0STARUISI Hiroaki 	while (1) {
223098d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
223198d377a0STARUISI Hiroaki 		if (ret < 0)
223298d377a0STARUISI Hiroaki 			goto out;
223318674c6cSFilipe David Borba Manana 		else if (ret > 0) {
223418674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
223518674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
223618674c6cSFilipe David Borba Manana 			if (ret < 0)
223718674c6cSFilipe David Borba Manana 				goto out;
223818674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2239ac8e9819SChris Mason 				ret = -ENOENT;
224098d377a0STARUISI Hiroaki 				goto out;
2241ac8e9819SChris Mason 			}
224218674c6cSFilipe David Borba Manana 		}
224318674c6cSFilipe David Borba Manana 
224418674c6cSFilipe David Borba Manana 		l = path->nodes[0];
224518674c6cSFilipe David Borba Manana 		slot = path->slots[0];
224618674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
224798d377a0STARUISI Hiroaki 
224898d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
224998d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
225098d377a0STARUISI Hiroaki 		ptr -= len + 1;
225198d377a0STARUISI Hiroaki 		total_len += len + 1;
2252a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2253a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
225498d377a0STARUISI Hiroaki 			goto out;
2255a696cf35SFilipe David Borba Manana 		}
225698d377a0STARUISI Hiroaki 
225798d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
225898d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
225998d377a0STARUISI Hiroaki 
226098d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
226198d377a0STARUISI Hiroaki 			break;
226298d377a0STARUISI Hiroaki 
2263b3b4aa74SDavid Sterba 		btrfs_release_path(path);
226498d377a0STARUISI Hiroaki 		key.objectid = key.offset;
22658ad6fcabSChris Mason 		key.offset = (u64)-1;
226698d377a0STARUISI Hiroaki 		dirid = key.objectid;
226798d377a0STARUISI Hiroaki 	}
226877906a50SLi Zefan 	memmove(name, ptr, total_len);
226998d377a0STARUISI Hiroaki 	name[total_len] = '\0';
227098d377a0STARUISI Hiroaki 	ret = 0;
227198d377a0STARUISI Hiroaki out:
227298d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2273ac8e9819SChris Mason 	return ret;
2274ac8e9819SChris Mason }
2275ac8e9819SChris Mason 
2276ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2277ac8e9819SChris Mason 					   void __user *argp)
2278ac8e9819SChris Mason {
2279ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2280ac8e9819SChris Mason 	 struct inode *inode;
228101b810b8SDavid Sterba 	int ret = 0;
2282ac8e9819SChris Mason 
22832354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
22842354d08fSJulia Lawall 	if (IS_ERR(args))
22852354d08fSJulia Lawall 		return PTR_ERR(args);
2286c2b96929SDan Carpenter 
2287496ad9aaSAl Viro 	inode = file_inode(file);
2288ac8e9819SChris Mason 
228901b810b8SDavid Sterba 	/*
229001b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
229101b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
229201b810b8SDavid Sterba 	 */
22931b53ac4dSChris Mason 	if (args->treeid == 0)
22941b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
22951b53ac4dSChris Mason 
229601b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
229701b810b8SDavid Sterba 		args->name[0] = 0;
229801b810b8SDavid Sterba 		goto out;
229901b810b8SDavid Sterba 	}
230001b810b8SDavid Sterba 
230101b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
230201b810b8SDavid Sterba 		ret = -EPERM;
230301b810b8SDavid Sterba 		goto out;
230401b810b8SDavid Sterba 	}
230501b810b8SDavid Sterba 
2306ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2307ac8e9819SChris Mason 					args->treeid, args->objectid,
2308ac8e9819SChris Mason 					args->name);
2309ac8e9819SChris Mason 
231001b810b8SDavid Sterba out:
2311ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2312ac8e9819SChris Mason 		ret = -EFAULT;
2313ac8e9819SChris Mason 
2314ac8e9819SChris Mason 	kfree(args);
231598d377a0STARUISI Hiroaki 	return ret;
231698d377a0STARUISI Hiroaki }
231798d377a0STARUISI Hiroaki 
231876dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
231976dda93cSYan, Zheng 					     void __user *arg)
232076dda93cSYan, Zheng {
232154563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
232276dda93cSYan, Zheng 	struct dentry *dentry;
23232b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
232476dda93cSYan, Zheng 	struct inode *inode;
232576dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
232676dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
232776dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
232876dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
2329c58aaad2SMiao Xie 	struct btrfs_block_rsv block_rsv;
2330521e0546SDavid Sterba 	u64 root_flags;
2331c58aaad2SMiao Xie 	u64 qgroup_reserved;
233276dda93cSYan, Zheng 	int namelen;
233376dda93cSYan, Zheng 	int ret;
233476dda93cSYan, Zheng 	int err = 0;
233576dda93cSYan, Zheng 
233676dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
233776dda93cSYan, Zheng 	if (IS_ERR(vol_args))
233876dda93cSYan, Zheng 		return PTR_ERR(vol_args);
233976dda93cSYan, Zheng 
234076dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
234176dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
234276dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
234376dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
234476dda93cSYan, Zheng 		err = -EINVAL;
234576dda93cSYan, Zheng 		goto out;
234676dda93cSYan, Zheng 	}
234776dda93cSYan, Zheng 
2348a561be71SAl Viro 	err = mnt_want_write_file(file);
234976dda93cSYan, Zheng 	if (err)
235076dda93cSYan, Zheng 		goto out;
235176dda93cSYan, Zheng 
2352521e0546SDavid Sterba 
23535c50c9b8SDavid Sterba 	err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
23545c50c9b8SDavid Sterba 	if (err == -EINTR)
2355e43f998eSDavid Sterba 		goto out_drop_write;
235676dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
235776dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
235876dda93cSYan, Zheng 		err = PTR_ERR(dentry);
235976dda93cSYan, Zheng 		goto out_unlock_dir;
236076dda93cSYan, Zheng 	}
236176dda93cSYan, Zheng 
23622b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
236376dda93cSYan, Zheng 		err = -ENOENT;
236476dda93cSYan, Zheng 		goto out_dput;
236576dda93cSYan, Zheng 	}
236676dda93cSYan, Zheng 
23672b0143b5SDavid Howells 	inode = d_inode(dentry);
23684260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
23694260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
23704260f7c7SSage Weil 		/*
23714260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
23724260f7c7SSage Weil 		 * option, when the user has write+exec access to the
23734260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
23744260f7c7SSage Weil 		 * allowed.
23754260f7c7SSage Weil 		 *
23764260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
23774260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
23784260f7c7SSage Weil 		 * otherwise be able to delete.
23794260f7c7SSage Weil 		 *
23804260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
23814260f7c7SSage Weil 		 * rmdir(2).
23824260f7c7SSage Weil 		 */
23834260f7c7SSage Weil 		err = -EPERM;
23844260f7c7SSage Weil 		if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
23854260f7c7SSage Weil 			goto out_dput;
23864260f7c7SSage Weil 
23874260f7c7SSage Weil 		/*
23884260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
23894260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
23904260f7c7SSage Weil 		 * must be called on the dentry referencing the root
23914260f7c7SSage Weil 		 * of the subvol, not a random directory contained
23924260f7c7SSage Weil 		 * within it.
23934260f7c7SSage Weil 		 */
23944260f7c7SSage Weil 		err = -EINVAL;
23954260f7c7SSage Weil 		if (root == dest)
23964260f7c7SSage Weil 			goto out_dput;
23974260f7c7SSage Weil 
23984260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
23994260f7c7SSage Weil 		if (err)
24004260f7c7SSage Weil 			goto out_dput;
24015c39da5bSMiao Xie 	}
24024260f7c7SSage Weil 
24035c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
24044260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
24054260f7c7SSage Weil 	if (err)
24064260f7c7SSage Weil 		goto out_dput;
24074260f7c7SSage Weil 
240833345d01SLi Zefan 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
240976dda93cSYan, Zheng 		err = -EINVAL;
241076dda93cSYan, Zheng 		goto out_dput;
241176dda93cSYan, Zheng 	}
241276dda93cSYan, Zheng 
241376dda93cSYan, Zheng 	mutex_lock(&inode->i_mutex);
2414521e0546SDavid Sterba 
2415521e0546SDavid Sterba 	/*
2416521e0546SDavid Sterba 	 * Don't allow to delete a subvolume with send in progress. This is
2417521e0546SDavid Sterba 	 * inside the i_mutex so the error handling that has to drop the bit
2418521e0546SDavid Sterba 	 * again is not run concurrently.
2419521e0546SDavid Sterba 	 */
2420521e0546SDavid Sterba 	spin_lock(&dest->root_item_lock);
2421c55bfa67SFilipe Manana 	root_flags = btrfs_root_flags(&dest->root_item);
2422c55bfa67SFilipe Manana 	if (dest->send_in_progress == 0) {
2423c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2424521e0546SDavid Sterba 				root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2425521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2426521e0546SDavid Sterba 	} else {
2427521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2428521e0546SDavid Sterba 		btrfs_warn(root->fs_info,
2429521e0546SDavid Sterba 			"Attempt to delete subvolume %llu during send",
2430c55bfa67SFilipe Manana 			dest->root_key.objectid);
2431521e0546SDavid Sterba 		err = -EPERM;
2432909e26dcSOmar Sandoval 		goto out_unlock_inode;
2433521e0546SDavid Sterba 	}
2434521e0546SDavid Sterba 
243576dda93cSYan, Zheng 	down_write(&root->fs_info->subvol_sem);
243676dda93cSYan, Zheng 
243776dda93cSYan, Zheng 	err = may_destroy_subvol(dest);
243876dda93cSYan, Zheng 	if (err)
243976dda93cSYan, Zheng 		goto out_up_write;
244076dda93cSYan, Zheng 
2441c58aaad2SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2442c58aaad2SMiao Xie 	/*
2443c58aaad2SMiao Xie 	 * One for dir inode, two for dir entries, two for root
2444c58aaad2SMiao Xie 	 * ref/backref.
2445c58aaad2SMiao Xie 	 */
2446c58aaad2SMiao Xie 	err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2447ee3441b4SJeff Mahoney 					       5, &qgroup_reserved, true);
2448c58aaad2SMiao Xie 	if (err)
2449c58aaad2SMiao Xie 		goto out_up_write;
2450c58aaad2SMiao Xie 
2451a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 0);
2452a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
2453a22285a6SYan, Zheng 		err = PTR_ERR(trans);
2454c58aaad2SMiao Xie 		goto out_release;
2455a22285a6SYan, Zheng 	}
2456c58aaad2SMiao Xie 	trans->block_rsv = &block_rsv;
2457c58aaad2SMiao Xie 	trans->bytes_reserved = block_rsv.size;
2458a22285a6SYan, Zheng 
245976dda93cSYan, Zheng 	ret = btrfs_unlink_subvol(trans, root, dir,
246076dda93cSYan, Zheng 				dest->root_key.objectid,
246176dda93cSYan, Zheng 				dentry->d_name.name,
246276dda93cSYan, Zheng 				dentry->d_name.len);
246379787eaaSJeff Mahoney 	if (ret) {
246479787eaaSJeff Mahoney 		err = ret;
246579787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
246679787eaaSJeff Mahoney 		goto out_end_trans;
246779787eaaSJeff Mahoney 	}
246876dda93cSYan, Zheng 
246976dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, dest);
247076dda93cSYan, Zheng 
247176dda93cSYan, Zheng 	memset(&dest->root_item.drop_progress, 0,
247276dda93cSYan, Zheng 		sizeof(dest->root_item.drop_progress));
247376dda93cSYan, Zheng 	dest->root_item.drop_level = 0;
247476dda93cSYan, Zheng 	btrfs_set_root_refs(&dest->root_item, 0);
247576dda93cSYan, Zheng 
247627cdeb70SMiao Xie 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
247776dda93cSYan, Zheng 		ret = btrfs_insert_orphan_item(trans,
247876dda93cSYan, Zheng 					root->fs_info->tree_root,
247976dda93cSYan, Zheng 					dest->root_key.objectid);
248079787eaaSJeff Mahoney 		if (ret) {
248179787eaaSJeff Mahoney 			btrfs_abort_transaction(trans, root, ret);
248279787eaaSJeff Mahoney 			err = ret;
248379787eaaSJeff Mahoney 			goto out_end_trans;
2484d68fc57bSYan, Zheng 		}
248579787eaaSJeff Mahoney 	}
2486dd5f9615SStefan Behrens 
2487dd5f9615SStefan Behrens 	ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2488dd5f9615SStefan Behrens 				  dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2489dd5f9615SStefan Behrens 				  dest->root_key.objectid);
2490dd5f9615SStefan Behrens 	if (ret && ret != -ENOENT) {
2491dd5f9615SStefan Behrens 		btrfs_abort_transaction(trans, root, ret);
2492dd5f9615SStefan Behrens 		err = ret;
2493dd5f9615SStefan Behrens 		goto out_end_trans;
2494dd5f9615SStefan Behrens 	}
2495dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2496dd5f9615SStefan Behrens 		ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2497dd5f9615SStefan Behrens 					  dest->root_item.received_uuid,
2498dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2499dd5f9615SStefan Behrens 					  dest->root_key.objectid);
2500dd5f9615SStefan Behrens 		if (ret && ret != -ENOENT) {
2501dd5f9615SStefan Behrens 			btrfs_abort_transaction(trans, root, ret);
2502dd5f9615SStefan Behrens 			err = ret;
2503dd5f9615SStefan Behrens 			goto out_end_trans;
2504dd5f9615SStefan Behrens 		}
2505dd5f9615SStefan Behrens 	}
2506dd5f9615SStefan Behrens 
250779787eaaSJeff Mahoney out_end_trans:
2508c58aaad2SMiao Xie 	trans->block_rsv = NULL;
2509c58aaad2SMiao Xie 	trans->bytes_reserved = 0;
2510531cb13fSSage Weil 	ret = btrfs_end_transaction(trans, root);
251179787eaaSJeff Mahoney 	if (ret && !err)
251279787eaaSJeff Mahoney 		err = ret;
251376dda93cSYan, Zheng 	inode->i_flags |= S_DEAD;
2514c58aaad2SMiao Xie out_release:
2515c58aaad2SMiao Xie 	btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
251676dda93cSYan, Zheng out_up_write:
251776dda93cSYan, Zheng 	up_write(&root->fs_info->subvol_sem);
2518521e0546SDavid Sterba 	if (err) {
2519521e0546SDavid Sterba 		spin_lock(&dest->root_item_lock);
2520c55bfa67SFilipe Manana 		root_flags = btrfs_root_flags(&dest->root_item);
2521c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2522521e0546SDavid Sterba 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2523521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2524521e0546SDavid Sterba 	}
2525909e26dcSOmar Sandoval out_unlock_inode:
252676dda93cSYan, Zheng 	mutex_unlock(&inode->i_mutex);
252776dda93cSYan, Zheng 	if (!err) {
252864ad6c48SOmar Sandoval 		d_invalidate(dentry);
252976dda93cSYan, Zheng 		btrfs_invalidate_inodes(dest);
253076dda93cSYan, Zheng 		d_delete(dentry);
253161155aa0SDavid Sterba 		ASSERT(dest->send_in_progress == 0);
2532fa6ac876SLiu Bo 
2533fa6ac876SLiu Bo 		/* the last ref */
253457cdc8dbSDavid Sterba 		if (dest->ino_cache_inode) {
253557cdc8dbSDavid Sterba 			iput(dest->ino_cache_inode);
253657cdc8dbSDavid Sterba 			dest->ino_cache_inode = NULL;
2537fa6ac876SLiu Bo 		}
253876dda93cSYan, Zheng 	}
253976dda93cSYan, Zheng out_dput:
254076dda93cSYan, Zheng 	dput(dentry);
254176dda93cSYan, Zheng out_unlock_dir:
254276dda93cSYan, Zheng 	mutex_unlock(&dir->i_mutex);
2543e43f998eSDavid Sterba out_drop_write:
25442a79f17eSAl Viro 	mnt_drop_write_file(file);
254576dda93cSYan, Zheng out:
254676dda93cSYan, Zheng 	kfree(vol_args);
254776dda93cSYan, Zheng 	return err;
254876dda93cSYan, Zheng }
254976dda93cSYan, Zheng 
25501e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2551f46b5a66SChristoph Hellwig {
2552496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2553f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
25541e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2555c146afadSYan Zheng 	int ret;
2556c146afadSYan Zheng 
255725122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
255825122d15SIlya Dryomov 	if (ret)
255925122d15SIlya Dryomov 		return ret;
2560b83cc969SLi Zefan 
256125122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
256225122d15SIlya Dryomov 		ret = -EROFS;
256325122d15SIlya Dryomov 		goto out;
25645ac00addSStefan Behrens 	}
2565f46b5a66SChristoph Hellwig 
2566f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2567f46b5a66SChristoph Hellwig 	case S_IFDIR:
2568e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2569e441d54dSChris Mason 			ret = -EPERM;
2570e441d54dSChris Mason 			goto out;
2571e441d54dSChris Mason 		}
2572de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
25738929ecfaSYan, Zheng 		if (ret)
25748929ecfaSYan, Zheng 			goto out;
2575de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root->fs_info->extent_root);
2576f46b5a66SChristoph Hellwig 		break;
2577f46b5a66SChristoph Hellwig 	case S_IFREG:
2578e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2579e441d54dSChris Mason 			ret = -EINVAL;
2580e441d54dSChris Mason 			goto out;
2581e441d54dSChris Mason 		}
25821e701a32SChris Mason 
25831e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
25841e701a32SChris Mason 		if (!range) {
25851e701a32SChris Mason 			ret = -ENOMEM;
25861e701a32SChris Mason 			goto out;
25871e701a32SChris Mason 		}
25881e701a32SChris Mason 
25891e701a32SChris Mason 		if (argp) {
25901e701a32SChris Mason 			if (copy_from_user(range, argp,
25911e701a32SChris Mason 					   sizeof(*range))) {
25921e701a32SChris Mason 				ret = -EFAULT;
25931e701a32SChris Mason 				kfree(range);
2594683be16eSDan Carpenter 				goto out;
25951e701a32SChris Mason 			}
25961e701a32SChris Mason 			/* compression requires us to start the IO */
25971e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
25981e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
25991e701a32SChris Mason 				range->extent_thresh = (u32)-1;
26001e701a32SChris Mason 			}
26011e701a32SChris Mason 		} else {
26021e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
26031e701a32SChris Mason 			range->len = (u64)-1;
26041e701a32SChris Mason 		}
2605496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
26064cb5300bSChris Mason 					range, 0, 0);
26074cb5300bSChris Mason 		if (ret > 0)
26084cb5300bSChris Mason 			ret = 0;
26091e701a32SChris Mason 		kfree(range);
2610f46b5a66SChristoph Hellwig 		break;
26118929ecfaSYan, Zheng 	default:
26128929ecfaSYan, Zheng 		ret = -EINVAL;
2613f46b5a66SChristoph Hellwig 	}
2614e441d54dSChris Mason out:
261525122d15SIlya Dryomov 	mnt_drop_write_file(file);
2616e441d54dSChris Mason 	return ret;
2617f46b5a66SChristoph Hellwig }
2618f46b5a66SChristoph Hellwig 
2619b2950863SChristoph Hellwig static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2620f46b5a66SChristoph Hellwig {
2621f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2622f46b5a66SChristoph Hellwig 	int ret;
2623f46b5a66SChristoph Hellwig 
2624e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2625e441d54dSChris Mason 		return -EPERM;
2626e441d54dSChris Mason 
26275ac00addSStefan Behrens 	if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
26285ac00addSStefan Behrens 			1)) {
2629e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2630c9e9f97bSIlya Dryomov 	}
2631c9e9f97bSIlya Dryomov 
26325ac00addSStefan Behrens 	mutex_lock(&root->fs_info->volume_mutex);
2633dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2634c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2635c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2636c9e9f97bSIlya Dryomov 		goto out;
2637c9e9f97bSIlya Dryomov 	}
2638f46b5a66SChristoph Hellwig 
26395516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2640f46b5a66SChristoph Hellwig 	ret = btrfs_init_new_device(root, vol_args->name);
2641f46b5a66SChristoph Hellwig 
264243d20761SAnand Jain 	if (!ret)
264343d20761SAnand Jain 		btrfs_info(root->fs_info, "disk added %s",vol_args->name);
264443d20761SAnand Jain 
2645f46b5a66SChristoph Hellwig 	kfree(vol_args);
2646c9e9f97bSIlya Dryomov out:
2647c9e9f97bSIlya Dryomov 	mutex_unlock(&root->fs_info->volume_mutex);
26485ac00addSStefan Behrens 	atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2649f46b5a66SChristoph Hellwig 	return ret;
2650f46b5a66SChristoph Hellwig }
2651f46b5a66SChristoph Hellwig 
2652da24927bSMiao Xie static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2653f46b5a66SChristoph Hellwig {
2654496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2655f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2656f46b5a66SChristoph Hellwig 	int ret;
2657f46b5a66SChristoph Hellwig 
2658e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2659e441d54dSChris Mason 		return -EPERM;
2660e441d54dSChris Mason 
2661da24927bSMiao Xie 	ret = mnt_want_write_file(file);
2662da24927bSMiao Xie 	if (ret)
2663da24927bSMiao Xie 		return ret;
2664c146afadSYan Zheng 
2665dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2666c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2667c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2668c47ca32dSDan Carpenter 		goto err_drop;
2669c9e9f97bSIlya Dryomov 	}
2670f46b5a66SChristoph Hellwig 
26715516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2672f46b5a66SChristoph Hellwig 
2673183860f6SAnand Jain 	if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2674183860f6SAnand Jain 			1)) {
2675183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2676183860f6SAnand Jain 		goto out;
2677183860f6SAnand Jain 	}
2678183860f6SAnand Jain 
2679183860f6SAnand Jain 	mutex_lock(&root->fs_info->volume_mutex);
2680183860f6SAnand Jain 	ret = btrfs_rm_device(root, vol_args->name);
2681c9e9f97bSIlya Dryomov 	mutex_unlock(&root->fs_info->volume_mutex);
26825ac00addSStefan Behrens 	atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2683183860f6SAnand Jain 
2684ec95d491SAnand Jain 	if (!ret)
2685ec95d491SAnand Jain 		btrfs_info(root->fs_info, "disk deleted %s",vol_args->name);
2686ec95d491SAnand Jain 
2687183860f6SAnand Jain out:
2688183860f6SAnand Jain 	kfree(vol_args);
2689c47ca32dSDan Carpenter err_drop:
26904ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
2691f46b5a66SChristoph Hellwig 	return ret;
2692f46b5a66SChristoph Hellwig }
2693f46b5a66SChristoph Hellwig 
2694475f6387SJan Schmidt static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2695475f6387SJan Schmidt {
2696027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
2697475f6387SJan Schmidt 	struct btrfs_device *device;
2698475f6387SJan Schmidt 	struct btrfs_device *next;
2699475f6387SJan Schmidt 	struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2700027ed2f0SLi Zefan 	int ret = 0;
2701475f6387SJan Schmidt 
2702027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2703027ed2f0SLi Zefan 	if (!fi_args)
2704027ed2f0SLi Zefan 		return -ENOMEM;
2705027ed2f0SLi Zefan 
2706f7171750SFilipe David Borba Manana 	mutex_lock(&fs_devices->device_list_mutex);
2707027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
2708027ed2f0SLi Zefan 	memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2709475f6387SJan Schmidt 
2710475f6387SJan Schmidt 	list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2711027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
2712027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
2713475f6387SJan Schmidt 	}
2714475f6387SJan Schmidt 	mutex_unlock(&fs_devices->device_list_mutex);
2715475f6387SJan Schmidt 
271680a773fbSDavid Sterba 	fi_args->nodesize = root->fs_info->super_copy->nodesize;
271780a773fbSDavid Sterba 	fi_args->sectorsize = root->fs_info->super_copy->sectorsize;
271880a773fbSDavid Sterba 	fi_args->clone_alignment = root->fs_info->super_copy->sectorsize;
271980a773fbSDavid Sterba 
2720027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2721027ed2f0SLi Zefan 		ret = -EFAULT;
2722475f6387SJan Schmidt 
2723027ed2f0SLi Zefan 	kfree(fi_args);
2724027ed2f0SLi Zefan 	return ret;
2725475f6387SJan Schmidt }
2726475f6387SJan Schmidt 
2727475f6387SJan Schmidt static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2728475f6387SJan Schmidt {
2729475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
2730475f6387SJan Schmidt 	struct btrfs_device *dev;
2731475f6387SJan Schmidt 	struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2732475f6387SJan Schmidt 	int ret = 0;
2733475f6387SJan Schmidt 	char *s_uuid = NULL;
2734475f6387SJan Schmidt 
2735475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
2736475f6387SJan Schmidt 	if (IS_ERR(di_args))
2737475f6387SJan Schmidt 		return PTR_ERR(di_args);
2738475f6387SJan Schmidt 
2739dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
2740475f6387SJan Schmidt 		s_uuid = di_args->uuid;
2741475f6387SJan Schmidt 
2742475f6387SJan Schmidt 	mutex_lock(&fs_devices->device_list_mutex);
2743aa1b8cd4SStefan Behrens 	dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2744475f6387SJan Schmidt 
2745475f6387SJan Schmidt 	if (!dev) {
2746475f6387SJan Schmidt 		ret = -ENODEV;
2747475f6387SJan Schmidt 		goto out;
2748475f6387SJan Schmidt 	}
2749475f6387SJan Schmidt 
2750475f6387SJan Schmidt 	di_args->devid = dev->devid;
27517cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
27527cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2753475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2754a27202fbSJim Meyering 	if (dev->name) {
2755606686eeSJosef Bacik 		struct rcu_string *name;
2756606686eeSJosef Bacik 
2757606686eeSJosef Bacik 		rcu_read_lock();
2758606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
2759606686eeSJosef Bacik 		strncpy(di_args->path, name->str, sizeof(di_args->path));
2760606686eeSJosef Bacik 		rcu_read_unlock();
2761a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
2762a27202fbSJim Meyering 	} else {
276399ba55adSStefan Behrens 		di_args->path[0] = '\0';
2764a27202fbSJim Meyering 	}
2765475f6387SJan Schmidt 
2766475f6387SJan Schmidt out:
276755793c0dSDavid Sterba 	mutex_unlock(&fs_devices->device_list_mutex);
2768475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2769475f6387SJan Schmidt 		ret = -EFAULT;
2770475f6387SJan Schmidt 
2771475f6387SJan Schmidt 	kfree(di_args);
2772475f6387SJan Schmidt 	return ret;
2773475f6387SJan Schmidt }
2774475f6387SJan Schmidt 
2775f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2776416161dbSMark Fasheh {
2777416161dbSMark Fasheh 	struct page *page;
2778416161dbSMark Fasheh 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2779416161dbSMark Fasheh 
2780416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
2781416161dbSMark Fasheh 	if (!page)
2782416161dbSMark Fasheh 		return NULL;
2783416161dbSMark Fasheh 
2784416161dbSMark Fasheh 	if (!PageUptodate(page)) {
2785416161dbSMark Fasheh 		if (extent_read_full_page_nolock(tree, page, btrfs_get_extent,
2786416161dbSMark Fasheh 						 0))
2787416161dbSMark Fasheh 			return NULL;
2788416161dbSMark Fasheh 		lock_page(page);
2789416161dbSMark Fasheh 		if (!PageUptodate(page)) {
2790416161dbSMark Fasheh 			unlock_page(page);
2791416161dbSMark Fasheh 			page_cache_release(page);
2792416161dbSMark Fasheh 			return NULL;
2793416161dbSMark Fasheh 		}
2794416161dbSMark Fasheh 	}
2795416161dbSMark Fasheh 	unlock_page(page);
2796416161dbSMark Fasheh 
2797416161dbSMark Fasheh 	return page;
2798416161dbSMark Fasheh }
2799416161dbSMark Fasheh 
2800f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
2801f4414602SMark Fasheh 			       int num_pages, u64 off)
2802f4414602SMark Fasheh {
2803f4414602SMark Fasheh 	int i;
2804f4414602SMark Fasheh 	pgoff_t index = off >> PAGE_CACHE_SHIFT;
2805f4414602SMark Fasheh 
2806f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
2807f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
2808f4414602SMark Fasheh 		if (!pages[i])
2809f4414602SMark Fasheh 			return -ENOMEM;
2810f4414602SMark Fasheh 	}
2811f4414602SMark Fasheh 	return 0;
2812f4414602SMark Fasheh }
2813f4414602SMark Fasheh 
281477fe20dcSMark Fasheh static inline void lock_extent_range(struct inode *inode, u64 off, u64 len)
281577fe20dcSMark Fasheh {
281677fe20dcSMark Fasheh 	/* do any pending delalloc/csum calc on src, one way or
281777fe20dcSMark Fasheh 	   another, and lock file content */
281877fe20dcSMark Fasheh 	while (1) {
281977fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
282077fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
282177fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
282277fe20dcSMark Fasheh 							    off + len - 1);
2823ff5df9b8SFilipe Manana 		if ((!ordered ||
2824ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
2825ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
282677fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2827ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2828ff5df9b8SFilipe Manana 			if (ordered)
2829ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
283077fe20dcSMark Fasheh 			break;
2831ff5df9b8SFilipe Manana 		}
283277fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
283377fe20dcSMark Fasheh 		if (ordered)
283477fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
283577fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
283677fe20dcSMark Fasheh 	}
283777fe20dcSMark Fasheh }
283877fe20dcSMark Fasheh 
2839f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2840416161dbSMark Fasheh {
2841416161dbSMark Fasheh 	mutex_unlock(&inode1->i_mutex);
2842416161dbSMark Fasheh 	mutex_unlock(&inode2->i_mutex);
2843416161dbSMark Fasheh }
2844416161dbSMark Fasheh 
2845f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2846f4414602SMark Fasheh {
2847f4414602SMark Fasheh 	if (inode1 < inode2)
2848f4414602SMark Fasheh 		swap(inode1, inode2);
2849f4414602SMark Fasheh 
2850f4414602SMark Fasheh 	mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2851f4414602SMark Fasheh 	if (inode1 != inode2)
2852f4414602SMark Fasheh 		mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2853f4414602SMark Fasheh }
2854f4414602SMark Fasheh 
2855f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2856f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
2857f4414602SMark Fasheh {
2858f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2859f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2860f4414602SMark Fasheh }
2861f4414602SMark Fasheh 
2862f4414602SMark Fasheh static void btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2863416161dbSMark Fasheh 				     struct inode *inode2, u64 loff2, u64 len)
2864416161dbSMark Fasheh {
2865416161dbSMark Fasheh 	if (inode1 < inode2) {
2866416161dbSMark Fasheh 		swap(inode1, inode2);
2867416161dbSMark Fasheh 		swap(loff1, loff2);
2868416161dbSMark Fasheh 	}
2869416161dbSMark Fasheh 	lock_extent_range(inode1, loff1, len);
2870f4414602SMark Fasheh 	if (inode1 != inode2)
2871416161dbSMark Fasheh 		lock_extent_range(inode2, loff2, len);
2872416161dbSMark Fasheh }
2873f4414602SMark Fasheh 
2874f4414602SMark Fasheh struct cmp_pages {
2875f4414602SMark Fasheh 	int		num_pages;
2876f4414602SMark Fasheh 	struct page	**src_pages;
2877f4414602SMark Fasheh 	struct page	**dst_pages;
2878f4414602SMark Fasheh };
2879f4414602SMark Fasheh 
2880f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2881f4414602SMark Fasheh {
2882f4414602SMark Fasheh 	int i;
2883f4414602SMark Fasheh 	struct page *pg;
2884f4414602SMark Fasheh 
2885f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
2886f4414602SMark Fasheh 		pg = cmp->src_pages[i];
2887f4414602SMark Fasheh 		if (pg)
2888f4414602SMark Fasheh 			page_cache_release(pg);
2889f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
2890f4414602SMark Fasheh 		if (pg)
2891f4414602SMark Fasheh 			page_cache_release(pg);
2892f4414602SMark Fasheh 	}
2893f4414602SMark Fasheh 	kfree(cmp->src_pages);
2894f4414602SMark Fasheh 	kfree(cmp->dst_pages);
2895f4414602SMark Fasheh }
2896f4414602SMark Fasheh 
2897f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2898f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
2899f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
2900f4414602SMark Fasheh {
2901f4414602SMark Fasheh 	int ret;
2902f4414602SMark Fasheh 	int num_pages = PAGE_CACHE_ALIGN(len) >> PAGE_CACHE_SHIFT;
2903f4414602SMark Fasheh 	struct page **src_pgarr, **dst_pgarr;
2904f4414602SMark Fasheh 
2905f4414602SMark Fasheh 	/*
2906f4414602SMark Fasheh 	 * We must gather up all the pages before we initiate our
2907f4414602SMark Fasheh 	 * extent locking. We use an array for the page pointers. Size
2908f4414602SMark Fasheh 	 * of the array is bounded by len, which is in turn bounded by
2909f4414602SMark Fasheh 	 * BTRFS_MAX_DEDUPE_LEN.
2910f4414602SMark Fasheh 	 */
2911f4414602SMark Fasheh 	src_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2912f4414602SMark Fasheh 	dst_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2913f4414602SMark Fasheh 	if (!src_pgarr || !dst_pgarr) {
2914f4414602SMark Fasheh 		kfree(src_pgarr);
2915f4414602SMark Fasheh 		kfree(dst_pgarr);
2916f4414602SMark Fasheh 		return -ENOMEM;
2917f4414602SMark Fasheh 	}
2918f4414602SMark Fasheh 	cmp->num_pages = num_pages;
2919f4414602SMark Fasheh 	cmp->src_pages = src_pgarr;
2920f4414602SMark Fasheh 	cmp->dst_pages = dst_pgarr;
2921f4414602SMark Fasheh 
2922f4414602SMark Fasheh 	ret = gather_extent_pages(src, cmp->src_pages, cmp->num_pages, loff);
2923f4414602SMark Fasheh 	if (ret)
2924f4414602SMark Fasheh 		goto out;
2925f4414602SMark Fasheh 
2926f4414602SMark Fasheh 	ret = gather_extent_pages(dst, cmp->dst_pages, cmp->num_pages, dst_loff);
2927f4414602SMark Fasheh 
2928f4414602SMark Fasheh out:
2929f4414602SMark Fasheh 	if (ret)
2930f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
2931f4414602SMark Fasheh 	return 0;
2932416161dbSMark Fasheh }
2933416161dbSMark Fasheh 
2934416161dbSMark Fasheh static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2935f4414602SMark Fasheh 			  u64 dst_loff, u64 len, struct cmp_pages *cmp)
2936416161dbSMark Fasheh {
2937416161dbSMark Fasheh 	int ret = 0;
2938f4414602SMark Fasheh 	int i;
2939416161dbSMark Fasheh 	struct page *src_page, *dst_page;
2940416161dbSMark Fasheh 	unsigned int cmp_len = PAGE_CACHE_SIZE;
2941416161dbSMark Fasheh 	void *addr, *dst_addr;
2942416161dbSMark Fasheh 
2943f4414602SMark Fasheh 	i = 0;
2944416161dbSMark Fasheh 	while (len) {
2945416161dbSMark Fasheh 		if (len < PAGE_CACHE_SIZE)
2946416161dbSMark Fasheh 			cmp_len = len;
2947416161dbSMark Fasheh 
2948f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
2949f4414602SMark Fasheh 
2950f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
2951f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
2952f4414602SMark Fasheh 
2953416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
2954416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
2955416161dbSMark Fasheh 
2956416161dbSMark Fasheh 		flush_dcache_page(src_page);
2957416161dbSMark Fasheh 		flush_dcache_page(dst_page);
2958416161dbSMark Fasheh 
2959416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
2960416161dbSMark Fasheh 			ret = BTRFS_SAME_DATA_DIFFERS;
2961416161dbSMark Fasheh 
2962416161dbSMark Fasheh 		kunmap_atomic(addr);
2963416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
2964416161dbSMark Fasheh 
2965416161dbSMark Fasheh 		if (ret)
2966416161dbSMark Fasheh 			break;
2967416161dbSMark Fasheh 
2968416161dbSMark Fasheh 		len -= cmp_len;
2969f4414602SMark Fasheh 		i++;
2970416161dbSMark Fasheh 	}
2971416161dbSMark Fasheh 
2972416161dbSMark Fasheh 	return ret;
2973416161dbSMark Fasheh }
2974416161dbSMark Fasheh 
2975e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
2976e1d227a4SMark Fasheh 				     u64 olen)
2977416161dbSMark Fasheh {
2978e1d227a4SMark Fasheh 	u64 len = *plen;
2979416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2980416161dbSMark Fasheh 
2981e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
2982416161dbSMark Fasheh 		return -EINVAL;
2983e1d227a4SMark Fasheh 
2984e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
2985e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
2986e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
2987e1d227a4SMark Fasheh 
2988416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
2989416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2990416161dbSMark Fasheh 		return -EINVAL;
2991416161dbSMark Fasheh 
2992416161dbSMark Fasheh 	return 0;
2993416161dbSMark Fasheh }
2994416161dbSMark Fasheh 
2995e1d227a4SMark Fasheh static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
2996416161dbSMark Fasheh 			     struct inode *dst, u64 dst_loff)
2997416161dbSMark Fasheh {
2998416161dbSMark Fasheh 	int ret;
2999e1d227a4SMark Fasheh 	u64 len = olen;
3000f4414602SMark Fasheh 	struct cmp_pages cmp;
30010efa9f48SMark Fasheh 	int same_inode = 0;
30020efa9f48SMark Fasheh 	u64 same_lock_start = 0;
30030efa9f48SMark Fasheh 	u64 same_lock_len = 0;
3004416161dbSMark Fasheh 
3005416161dbSMark Fasheh 	if (src == dst)
30060efa9f48SMark Fasheh 		same_inode = 1;
3007416161dbSMark Fasheh 
3008113e8283SFilipe Manana 	if (len == 0)
3009113e8283SFilipe Manana 		return 0;
3010113e8283SFilipe Manana 
30110efa9f48SMark Fasheh 	if (same_inode) {
30120efa9f48SMark Fasheh 		mutex_lock(&src->i_mutex);
30130efa9f48SMark Fasheh 
30140efa9f48SMark Fasheh 		ret = extent_same_check_offsets(src, loff, &len, olen);
30150efa9f48SMark Fasheh 		if (ret)
30160efa9f48SMark Fasheh 			goto out_unlock;
30170efa9f48SMark Fasheh 
30180efa9f48SMark Fasheh 		/*
30190efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
30200efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
30210efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
30220efa9f48SMark Fasheh 		 *
30230efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
30240efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
30250efa9f48SMark Fasheh 		 * reject the request.
30260efa9f48SMark Fasheh 		 *
30270efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
30280efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
30290efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
30300efa9f48SMark Fasheh 		 * i_size.
30310efa9f48SMark Fasheh 		 */
30320efa9f48SMark Fasheh 		if (len != olen) {
30330efa9f48SMark Fasheh 			ret = -EINVAL;
30340efa9f48SMark Fasheh 			goto out_unlock;
30350efa9f48SMark Fasheh 		}
30360efa9f48SMark Fasheh 
30370efa9f48SMark Fasheh 		/* Check for overlapping ranges */
30380efa9f48SMark Fasheh 		if (dst_loff + len > loff && dst_loff < loff + len) {
30390efa9f48SMark Fasheh 			ret = -EINVAL;
30400efa9f48SMark Fasheh 			goto out_unlock;
30410efa9f48SMark Fasheh 		}
30420efa9f48SMark Fasheh 
30430efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
30440efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
30450efa9f48SMark Fasheh 	} else {
3046f4414602SMark Fasheh 		btrfs_double_inode_lock(src, dst);
3047416161dbSMark Fasheh 
3048e1d227a4SMark Fasheh 		ret = extent_same_check_offsets(src, loff, &len, olen);
3049416161dbSMark Fasheh 		if (ret)
3050416161dbSMark Fasheh 			goto out_unlock;
3051416161dbSMark Fasheh 
3052e1d227a4SMark Fasheh 		ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3053416161dbSMark Fasheh 		if (ret)
3054416161dbSMark Fasheh 			goto out_unlock;
30550efa9f48SMark Fasheh 	}
3056416161dbSMark Fasheh 
3057416161dbSMark Fasheh 	/* don't make the dst file partly checksummed */
3058416161dbSMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3059416161dbSMark Fasheh 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3060416161dbSMark Fasheh 		ret = -EINVAL;
3061416161dbSMark Fasheh 		goto out_unlock;
3062416161dbSMark Fasheh 	}
3063416161dbSMark Fasheh 
3064f4414602SMark Fasheh 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3065f4414602SMark Fasheh 	if (ret)
3066f4414602SMark Fasheh 		goto out_unlock;
3067f4414602SMark Fasheh 
30680efa9f48SMark Fasheh 	if (same_inode)
30690efa9f48SMark Fasheh 		lock_extent_range(src, same_lock_start, same_lock_len);
30700efa9f48SMark Fasheh 	else
3071f4414602SMark Fasheh 		btrfs_double_extent_lock(src, loff, dst, dst_loff, len);
3072f4414602SMark Fasheh 
3073207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
3074f4414602SMark Fasheh 	ret = btrfs_cmp_data(src, loff, dst, dst_loff, olen, &cmp);
3075416161dbSMark Fasheh 	if (ret == 0)
30761c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3077416161dbSMark Fasheh 
30780efa9f48SMark Fasheh 	if (same_inode)
30790efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
30800efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
30810efa9f48SMark Fasheh 	else
3082f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3083f4414602SMark Fasheh 
3084f4414602SMark Fasheh 	btrfs_cmp_data_free(&cmp);
3085416161dbSMark Fasheh out_unlock:
30860efa9f48SMark Fasheh 	if (same_inode)
30870efa9f48SMark Fasheh 		mutex_unlock(&src->i_mutex);
30880efa9f48SMark Fasheh 	else
3089f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3090416161dbSMark Fasheh 
3091416161dbSMark Fasheh 	return ret;
3092416161dbSMark Fasheh }
3093416161dbSMark Fasheh 
3094416161dbSMark Fasheh #define BTRFS_MAX_DEDUPE_LEN	(16 * 1024 * 1024)
3095416161dbSMark Fasheh 
3096416161dbSMark Fasheh static long btrfs_ioctl_file_extent_same(struct file *file,
30971c1c8747SAl Viro 			struct btrfs_ioctl_same_args __user *argp)
3098416161dbSMark Fasheh {
3099497b4050SFilipe Manana 	struct btrfs_ioctl_same_args *same = NULL;
3100cbf8b8caSMark Fasheh 	struct btrfs_ioctl_same_extent_info *info;
31011c1c8747SAl Viro 	struct inode *src = file_inode(file);
3102416161dbSMark Fasheh 	u64 off;
3103416161dbSMark Fasheh 	u64 len;
3104416161dbSMark Fasheh 	int i;
3105416161dbSMark Fasheh 	int ret;
3106cbf8b8caSMark Fasheh 	unsigned long size;
3107416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3108416161dbSMark Fasheh 	bool is_admin = capable(CAP_SYS_ADMIN);
31091c1c8747SAl Viro 	u16 count;
3110416161dbSMark Fasheh 
3111416161dbSMark Fasheh 	if (!(file->f_mode & FMODE_READ))
3112416161dbSMark Fasheh 		return -EINVAL;
3113416161dbSMark Fasheh 
3114416161dbSMark Fasheh 	ret = mnt_want_write_file(file);
3115416161dbSMark Fasheh 	if (ret)
3116416161dbSMark Fasheh 		return ret;
3117416161dbSMark Fasheh 
31181c1c8747SAl Viro 	if (get_user(count, &argp->dest_count)) {
3119416161dbSMark Fasheh 		ret = -EFAULT;
3120416161dbSMark Fasheh 		goto out;
3121416161dbSMark Fasheh 	}
3122416161dbSMark Fasheh 
31231c1c8747SAl Viro 	size = offsetof(struct btrfs_ioctl_same_args __user, info[count]);
3124cbf8b8caSMark Fasheh 
31251c1c8747SAl Viro 	same = memdup_user(argp, size);
3126cbf8b8caSMark Fasheh 
3127229eed43SGeyslan G. Bem 	if (IS_ERR(same)) {
3128229eed43SGeyslan G. Bem 		ret = PTR_ERR(same);
3129497b4050SFilipe Manana 		same = NULL;
3130cbf8b8caSMark Fasheh 		goto out;
3131cbf8b8caSMark Fasheh 	}
3132cbf8b8caSMark Fasheh 
3133cbf8b8caSMark Fasheh 	off = same->logical_offset;
3134cbf8b8caSMark Fasheh 	len = same->length;
3135416161dbSMark Fasheh 
3136416161dbSMark Fasheh 	/*
3137416161dbSMark Fasheh 	 * Limit the total length we will dedupe for each operation.
3138416161dbSMark Fasheh 	 * This is intended to bound the total time spent in this
3139416161dbSMark Fasheh 	 * ioctl to something sane.
3140416161dbSMark Fasheh 	 */
3141416161dbSMark Fasheh 	if (len > BTRFS_MAX_DEDUPE_LEN)
3142416161dbSMark Fasheh 		len = BTRFS_MAX_DEDUPE_LEN;
3143416161dbSMark Fasheh 
3144416161dbSMark Fasheh 	if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
3145416161dbSMark Fasheh 		/*
3146416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3147416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3148416161dbSMark Fasheh 		 * this situation without an update.
3149416161dbSMark Fasheh 		 */
3150416161dbSMark Fasheh 		ret = -EINVAL;
3151416161dbSMark Fasheh 		goto out;
3152416161dbSMark Fasheh 	}
3153416161dbSMark Fasheh 
3154416161dbSMark Fasheh 	ret = -EISDIR;
3155416161dbSMark Fasheh 	if (S_ISDIR(src->i_mode))
3156416161dbSMark Fasheh 		goto out;
3157416161dbSMark Fasheh 
3158416161dbSMark Fasheh 	ret = -EACCES;
3159416161dbSMark Fasheh 	if (!S_ISREG(src->i_mode))
3160416161dbSMark Fasheh 		goto out;
3161416161dbSMark Fasheh 
3162cbf8b8caSMark Fasheh 	/* pre-format output fields to sane values */
31631c1c8747SAl Viro 	for (i = 0; i < count; i++) {
3164cbf8b8caSMark Fasheh 		same->info[i].bytes_deduped = 0ULL;
3165cbf8b8caSMark Fasheh 		same->info[i].status = 0;
3166416161dbSMark Fasheh 	}
3167416161dbSMark Fasheh 
31681c1c8747SAl Viro 	for (i = 0, info = same->info; i < count; i++, info++) {
31691c1c8747SAl Viro 		struct inode *dst;
31701c1c8747SAl Viro 		struct fd dst_file = fdget(info->fd);
31711c1c8747SAl Viro 		if (!dst_file.file) {
3172cbf8b8caSMark Fasheh 			info->status = -EBADF;
31731c1c8747SAl Viro 			continue;
3174416161dbSMark Fasheh 		}
31751c1c8747SAl Viro 		dst = file_inode(dst_file.file);
3176416161dbSMark Fasheh 
31771c1c8747SAl Viro 		if (!(is_admin || (dst_file.file->f_mode & FMODE_WRITE))) {
3178cbf8b8caSMark Fasheh 			info->status = -EINVAL;
31791c1c8747SAl Viro 		} else if (file->f_path.mnt != dst_file.file->f_path.mnt) {
3180cbf8b8caSMark Fasheh 			info->status = -EXDEV;
31811c1c8747SAl Viro 		} else if (S_ISDIR(dst->i_mode)) {
3182cbf8b8caSMark Fasheh 			info->status = -EISDIR;
31831c1c8747SAl Viro 		} else if (!S_ISREG(dst->i_mode)) {
3184cbf8b8caSMark Fasheh 			info->status = -EACCES;
31851c1c8747SAl Viro 		} else {
3186cbf8b8caSMark Fasheh 			info->status = btrfs_extent_same(src, off, len, dst,
3187cbf8b8caSMark Fasheh 							info->logical_offset);
3188cbf8b8caSMark Fasheh 			if (info->status == 0)
3189cbf8b8caSMark Fasheh 				info->bytes_deduped += len;
31901c1c8747SAl Viro 		}
31911c1c8747SAl Viro 		fdput(dst_file);
3192cbf8b8caSMark Fasheh 	}
3193416161dbSMark Fasheh 
3194cbf8b8caSMark Fasheh 	ret = copy_to_user(argp, same, size);
3195cbf8b8caSMark Fasheh 	if (ret)
3196416161dbSMark Fasheh 		ret = -EFAULT;
3197416161dbSMark Fasheh 
3198416161dbSMark Fasheh out:
3199416161dbSMark Fasheh 	mnt_drop_write_file(file);
3200497b4050SFilipe Manana 	kfree(same);
3201416161dbSMark Fasheh 	return ret;
3202416161dbSMark Fasheh }
3203416161dbSMark Fasheh 
3204fcebe456SJosef Bacik /* Helper to check and see if this root currently has a ref on the given disk
3205fcebe456SJosef Bacik  * bytenr.  If it does then we need to update the quota for this root.  This
3206fcebe456SJosef Bacik  * doesn't do anything if quotas aren't enabled.
3207fcebe456SJosef Bacik  */
3208fcebe456SJosef Bacik static int check_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3209fcebe456SJosef Bacik 		     u64 disko)
3210fcebe456SJosef Bacik {
32113284da7bSDavid Sterba 	struct seq_list tree_mod_seq_elem = SEQ_LIST_INIT(tree_mod_seq_elem);
3212fcebe456SJosef Bacik 	struct ulist *roots;
3213fcebe456SJosef Bacik 	struct ulist_iterator uiter;
3214fcebe456SJosef Bacik 	struct ulist_node *root_node = NULL;
3215fcebe456SJosef Bacik 	int ret;
3216fcebe456SJosef Bacik 
3217fcebe456SJosef Bacik 	if (!root->fs_info->quota_enabled)
3218fcebe456SJosef Bacik 		return 1;
3219fcebe456SJosef Bacik 
3220fcebe456SJosef Bacik 	btrfs_get_tree_mod_seq(root->fs_info, &tree_mod_seq_elem);
3221fcebe456SJosef Bacik 	ret = btrfs_find_all_roots(trans, root->fs_info, disko,
3222fcebe456SJosef Bacik 				   tree_mod_seq_elem.seq, &roots);
3223fcebe456SJosef Bacik 	if (ret < 0)
3224fcebe456SJosef Bacik 		goto out;
3225fcebe456SJosef Bacik 	ret = 0;
3226fcebe456SJosef Bacik 	ULIST_ITER_INIT(&uiter);
3227fcebe456SJosef Bacik 	while ((root_node = ulist_next(roots, &uiter))) {
3228fcebe456SJosef Bacik 		if (root_node->val == root->objectid) {
3229fcebe456SJosef Bacik 			ret = 1;
3230fcebe456SJosef Bacik 			break;
3231fcebe456SJosef Bacik 		}
3232fcebe456SJosef Bacik 	}
3233fcebe456SJosef Bacik 	ulist_free(roots);
3234fcebe456SJosef Bacik out:
3235fcebe456SJosef Bacik 	btrfs_put_tree_mod_seq(root->fs_info, &tree_mod_seq_elem);
3236fcebe456SJosef Bacik 	return ret;
3237fcebe456SJosef Bacik }
3238fcebe456SJosef Bacik 
3239f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3240f82a9901SFilipe Manana 				     struct inode *inode,
3241f82a9901SFilipe Manana 				     u64 endoff,
3242f82a9901SFilipe Manana 				     const u64 destoff,
32431c919a5eSMark Fasheh 				     const u64 olen,
32441c919a5eSMark Fasheh 				     int no_time_update)
3245f82a9901SFilipe Manana {
3246f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3247f82a9901SFilipe Manana 	int ret;
3248f82a9901SFilipe Manana 
3249f82a9901SFilipe Manana 	inode_inc_iversion(inode);
32501c919a5eSMark Fasheh 	if (!no_time_update)
3251f82a9901SFilipe Manana 		inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3252f82a9901SFilipe Manana 	/*
3253f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3254f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3255f82a9901SFilipe Manana 	 */
3256f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3257f82a9901SFilipe Manana 		endoff = destoff + olen;
3258f82a9901SFilipe Manana 	if (endoff > inode->i_size)
3259f82a9901SFilipe Manana 		btrfs_i_size_write(inode, endoff);
3260f82a9901SFilipe Manana 
3261f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3262f82a9901SFilipe Manana 	if (ret) {
3263f82a9901SFilipe Manana 		btrfs_abort_transaction(trans, root, ret);
3264f82a9901SFilipe Manana 		btrfs_end_transaction(trans, root);
3265f82a9901SFilipe Manana 		goto out;
3266f82a9901SFilipe Manana 	}
3267f82a9901SFilipe Manana 	ret = btrfs_end_transaction(trans, root);
3268f82a9901SFilipe Manana out:
3269f82a9901SFilipe Manana 	return ret;
3270f82a9901SFilipe Manana }
3271f82a9901SFilipe Manana 
32727ffbb598SFilipe Manana static void clone_update_extent_map(struct inode *inode,
32737ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
32747ffbb598SFilipe Manana 				    const struct btrfs_path *path,
32757ffbb598SFilipe Manana 				    const u64 hole_offset,
32767ffbb598SFilipe Manana 				    const u64 hole_len)
32777ffbb598SFilipe Manana {
32787ffbb598SFilipe Manana 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
32797ffbb598SFilipe Manana 	struct extent_map *em;
32807ffbb598SFilipe Manana 	int ret;
32817ffbb598SFilipe Manana 
32827ffbb598SFilipe Manana 	em = alloc_extent_map();
32837ffbb598SFilipe Manana 	if (!em) {
32847ffbb598SFilipe Manana 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
32857ffbb598SFilipe Manana 			&BTRFS_I(inode)->runtime_flags);
32867ffbb598SFilipe Manana 		return;
32877ffbb598SFilipe Manana 	}
32887ffbb598SFilipe Manana 
328914f59796SFilipe Manana 	if (path) {
329014f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
329114f59796SFilipe Manana 
329214f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
329314f59796SFilipe Manana 				    struct btrfs_file_extent_item);
32947ffbb598SFilipe Manana 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
32957ffbb598SFilipe Manana 		em->generation = -1;
32967ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
32977ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
32987ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
32997ffbb598SFilipe Manana 				&BTRFS_I(inode)->runtime_flags);
33007ffbb598SFilipe Manana 	} else {
33017ffbb598SFilipe Manana 		em->start = hole_offset;
33027ffbb598SFilipe Manana 		em->len = hole_len;
33037ffbb598SFilipe Manana 		em->ram_bytes = em->len;
33047ffbb598SFilipe Manana 		em->orig_start = hole_offset;
33057ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
33067ffbb598SFilipe Manana 		em->block_len = 0;
33077ffbb598SFilipe Manana 		em->orig_block_len = 0;
33087ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
33097ffbb598SFilipe Manana 		em->generation = trans->transid;
33107ffbb598SFilipe Manana 	}
33117ffbb598SFilipe Manana 
33127ffbb598SFilipe Manana 	while (1) {
33137ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
33147ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
33157ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
33167ffbb598SFilipe Manana 		if (ret != -EEXIST) {
33177ffbb598SFilipe Manana 			free_extent_map(em);
33187ffbb598SFilipe Manana 			break;
33197ffbb598SFilipe Manana 		}
33207ffbb598SFilipe Manana 		btrfs_drop_extent_cache(inode, em->start,
33217ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
33227ffbb598SFilipe Manana 	}
33237ffbb598SFilipe Manana 
3324ee39b432SDavid Sterba 	if (ret)
33257ffbb598SFilipe Manana 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
33267ffbb598SFilipe Manana 			&BTRFS_I(inode)->runtime_flags);
33277ffbb598SFilipe Manana }
33287ffbb598SFilipe Manana 
332932b7c687SMark Fasheh /**
333032b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
333132b7c687SMark Fasheh  *
333232b7c687SMark Fasheh  * @src: Inode to clone from
333332b7c687SMark Fasheh  * @inode: Inode to clone to
333432b7c687SMark Fasheh  * @off: Offset within source to start clone from
333532b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
33361c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
333732b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
33381c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
333932b7c687SMark Fasheh  */
334032b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3341f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
33421c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3343f46b5a66SChristoph Hellwig {
3344f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
334532b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3346f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
334732b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
334832b7c687SMark Fasheh 	char *buf = NULL;
3349ae01a0abSYan Zheng 	struct btrfs_key key;
3350f46b5a66SChristoph Hellwig 	u32 nritems;
3351f46b5a66SChristoph Hellwig 	int slot;
3352ae01a0abSYan Zheng 	int ret;
3353fcebe456SJosef Bacik 	int no_quota;
3354f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3355fcebe456SJosef Bacik 	u64 last_disko = 0;
3356f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3357ae01a0abSYan Zheng 
3358ae01a0abSYan Zheng 	ret = -ENOMEM;
3359707e8a07SDavid Sterba 	buf = vmalloc(root->nodesize);
3360ae01a0abSYan Zheng 	if (!buf)
336132b7c687SMark Fasheh 		return ret;
3362ae01a0abSYan Zheng 
3363ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3364ae01a0abSYan Zheng 	if (!path) {
3365ae01a0abSYan Zheng 		vfree(buf);
336632b7c687SMark Fasheh 		return ret;
3367ae01a0abSYan Zheng 	}
336832b7c687SMark Fasheh 
3369ae01a0abSYan Zheng 	path->reada = 2;
3370c5c9cd4dSSage Weil 	/* clone data */
337133345d01SLi Zefan 	key.objectid = btrfs_ino(src);
3372ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
33732c463823SFilipe Manana 	key.offset = off;
3374f46b5a66SChristoph Hellwig 
3375f46b5a66SChristoph Hellwig 	while (1) {
3376de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3377df858e76SFilipe Manana 
3378f46b5a66SChristoph Hellwig 		/*
3379f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3380f46b5a66SChristoph Hellwig 		 * tree.
3381f46b5a66SChristoph Hellwig 		 */
3382e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3383362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3384362a20c5SDavid Sterba 				0, 0);
3385f46b5a66SChristoph Hellwig 		if (ret < 0)
3386f46b5a66SChristoph Hellwig 			goto out;
33872c463823SFilipe Manana 		/*
33882c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
33892c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
33902c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
33912c463823SFilipe Manana 		 */
33922c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
33932c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
33942c463823SFilipe Manana 					      path->slots[0] - 1);
33952c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
33962c463823SFilipe Manana 				path->slots[0]--;
33972c463823SFilipe Manana 		}
3398f46b5a66SChristoph Hellwig 
3399ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3400e4355f34SFilipe David Borba Manana process_slot:
3401fcebe456SJosef Bacik 		no_quota = 1;
3402ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3403362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3404f46b5a66SChristoph Hellwig 			if (ret < 0)
3405f46b5a66SChristoph Hellwig 				goto out;
3406f46b5a66SChristoph Hellwig 			if (ret > 0)
3407f46b5a66SChristoph Hellwig 				break;
3408ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3409f46b5a66SChristoph Hellwig 		}
3410f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3411f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3412f46b5a66SChristoph Hellwig 
3413ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3414962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
341533345d01SLi Zefan 		    key.objectid != btrfs_ino(src))
3416f46b5a66SChristoph Hellwig 			break;
3417f46b5a66SChristoph Hellwig 
3418962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3419c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3420c5c9cd4dSSage Weil 			int type;
342131840ae1SZheng Yan 			u32 size;
342231840ae1SZheng Yan 			struct btrfs_key new_key;
3423c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3424c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3425c5c9cd4dSSage Weil 			u8 comp;
3426f82a9901SFilipe Manana 			u64 drop_start;
342731840ae1SZheng Yan 
3428c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3429c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3430c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3431c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3432c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3433c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3434d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3435d397712bSChris Mason 								      extent);
3436d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3437d397712bSChris Mason 								 extent);
3438c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3439d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3440d397712bSChris Mason 								    extent);
3441c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3442c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3443c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3444c5c9cd4dSSage Weil 								    extent);
3445c5c9cd4dSSage Weil 			}
344631840ae1SZheng Yan 
34472c463823SFilipe Manana 			/*
34482c463823SFilipe Manana 			 * The first search might have left us at an extent
34492c463823SFilipe Manana 			 * item that ends before our target range's start, can
34502c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
34512c463823SFilipe Manana 			 */
34522c463823SFilipe Manana 			if (key.offset + datal <= off) {
3453e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3454e4355f34SFilipe David Borba Manana 				goto process_slot;
34552c463823SFilipe Manana 			} else if (key.offset >= off + len) {
34562c463823SFilipe Manana 				break;
3457e4355f34SFilipe David Borba Manana 			}
3458df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3459e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3460e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3461e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3462e4355f34SFilipe David Borba Manana 					   size);
3463e4355f34SFilipe David Borba Manana 
3464e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3465e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3466c5c9cd4dSSage Weil 
346731840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
346833345d01SLi Zefan 			new_key.objectid = btrfs_ino(inode);
34694d728ec7SLi Zefan 			if (off <= key.offset)
3470c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
34714d728ec7SLi Zefan 			else
34724d728ec7SLi Zefan 				new_key.offset = destoff;
3473c5c9cd4dSSage Weil 
3474b6f3409bSSage Weil 			/*
3475f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3476f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3477f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3478f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3479f82a9901SFilipe Manana 			 * partially overlaps it).
3480f82a9901SFilipe Manana 			 */
3481f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3482f82a9901SFilipe Manana 				drop_start = last_dest_end;
3483f82a9901SFilipe Manana 			else
3484f82a9901SFilipe Manana 				drop_start = new_key.offset;
3485f82a9901SFilipe Manana 
3486f82a9901SFilipe Manana 			/*
3487b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3488b6f3409bSSage Weil 			 * 1 - add new extent
3489b6f3409bSSage Weil 			 * 1 - inode update
3490b6f3409bSSage Weil 			 */
3491b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3492a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3493a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3494a22285a6SYan, Zheng 				goto out;
3495a22285a6SYan, Zheng 			}
3496a22285a6SYan, Zheng 
3497c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3498c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3499d72c0842SLi Zefan 				/*
3500d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3501d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3502d72c0842SLi Zefan 				 */
3503d72c0842SLi Zefan 
350493915584SAntonio Ospite 				/* subtract range b */
3505d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3506d72c0842SLi Zefan 					datal = off + len - key.offset;
3507d72c0842SLi Zefan 
350893915584SAntonio Ospite 				/* subtract range a */
3509a22285a6SYan, Zheng 				if (off > key.offset) {
3510a22285a6SYan, Zheng 					datao += off - key.offset;
3511a22285a6SYan, Zheng 					datal -= off - key.offset;
3512a22285a6SYan, Zheng 				}
3513a22285a6SYan, Zheng 
35145dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3515f82a9901SFilipe Manana 							 drop_start,
3516a22285a6SYan, Zheng 							 new_key.offset + datal,
35172671485dSJosef Bacik 							 1);
351879787eaaSJeff Mahoney 				if (ret) {
35193f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
352000fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
352100fdf13aSLiu Bo 								root, ret);
352279787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
352379787eaaSJeff Mahoney 					goto out;
352479787eaaSJeff Mahoney 				}
3525a22285a6SYan, Zheng 
352631840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
352731840ae1SZheng Yan 							      &new_key, size);
352879787eaaSJeff Mahoney 				if (ret) {
352979787eaaSJeff Mahoney 					btrfs_abort_transaction(trans, root,
353079787eaaSJeff Mahoney 								ret);
353179787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
353279787eaaSJeff Mahoney 					goto out;
353379787eaaSJeff Mahoney 				}
353431840ae1SZheng Yan 
353531840ae1SZheng Yan 				leaf = path->nodes[0];
353631840ae1SZheng Yan 				slot = path->slots[0];
353731840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
353831840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
353931840ae1SZheng Yan 					    size);
3540ae01a0abSYan Zheng 
3541f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3542f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3543c5c9cd4dSSage Weil 
3544c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3545c5c9cd4dSSage Weil 				if (!disko)
3546c5c9cd4dSSage Weil 					datao = 0;
3547c5c9cd4dSSage Weil 
3548c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3549c5c9cd4dSSage Weil 							     datao);
3550c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3551c5c9cd4dSSage Weil 								datal);
3552fcebe456SJosef Bacik 
3553fcebe456SJosef Bacik 				/*
3554fcebe456SJosef Bacik 				 * We need to look up the roots that point at
3555fcebe456SJosef Bacik 				 * this bytenr and see if the new root does.  If
3556fcebe456SJosef Bacik 				 * it does not we need to make sure we update
3557fcebe456SJosef Bacik 				 * quotas appropriately.
3558fcebe456SJosef Bacik 				 */
3559fcebe456SJosef Bacik 				if (disko && root != BTRFS_I(src)->root &&
3560fcebe456SJosef Bacik 				    disko != last_disko) {
3561fcebe456SJosef Bacik 					no_quota = check_ref(trans, root,
3562fcebe456SJosef Bacik 							     disko);
3563fcebe456SJosef Bacik 					if (no_quota < 0) {
3564fcebe456SJosef Bacik 						btrfs_abort_transaction(trans,
3565fcebe456SJosef Bacik 									root,
3566fcebe456SJosef Bacik 									ret);
3567fcebe456SJosef Bacik 						btrfs_end_transaction(trans,
3568fcebe456SJosef Bacik 								      root);
3569fcebe456SJosef Bacik 						ret = no_quota;
3570fcebe456SJosef Bacik 						goto out;
3571fcebe456SJosef Bacik 					}
3572fcebe456SJosef Bacik 				}
3573fcebe456SJosef Bacik 
3574c5c9cd4dSSage Weil 				if (disko) {
3575c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
3576ae01a0abSYan Zheng 					ret = btrfs_inc_extent_ref(trans, root,
35775d4f98a2SYan Zheng 							disko, diskl, 0,
3578f46b5a66SChristoph Hellwig 							root->root_key.objectid,
357933345d01SLi Zefan 							btrfs_ino(inode),
358066d7e7f0SArne Jansen 							new_key.offset - datao,
3581fcebe456SJosef Bacik 							no_quota);
358279787eaaSJeff Mahoney 					if (ret) {
358379787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
358479787eaaSJeff Mahoney 									root,
358579787eaaSJeff Mahoney 									ret);
358679787eaaSJeff Mahoney 						btrfs_end_transaction(trans,
358779787eaaSJeff Mahoney 								      root);
358879787eaaSJeff Mahoney 						goto out;
358979787eaaSJeff Mahoney 
359079787eaaSJeff Mahoney 					}
3591f46b5a66SChristoph Hellwig 				}
3592c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3593c5c9cd4dSSage Weil 				u64 skip = 0;
3594c5c9cd4dSSage Weil 				u64 trim = 0;
3595d3ecfcdfSLiu Bo 				u64 aligned_end = 0;
3596d3ecfcdfSLiu Bo 
3597ed958762SFilipe Manana 				/*
3598ed958762SFilipe Manana 				 * Don't copy an inline extent into an offset
3599ed958762SFilipe Manana 				 * greater than zero. Having an inline extent
3600ed958762SFilipe Manana 				 * at such an offset results in chaos as btrfs
3601ed958762SFilipe Manana 				 * isn't prepared for such cases. Just skip
3602ed958762SFilipe Manana 				 * this case for the same reasons as commented
3603ed958762SFilipe Manana 				 * at btrfs_ioctl_clone().
3604ed958762SFilipe Manana 				 */
3605ed958762SFilipe Manana 				if (last_dest_end > 0) {
3606ed958762SFilipe Manana 					ret = -EOPNOTSUPP;
3607ed958762SFilipe Manana 					btrfs_end_transaction(trans, root);
3608ed958762SFilipe Manana 					goto out;
3609ed958762SFilipe Manana 				}
3610ed958762SFilipe Manana 
3611c5c9cd4dSSage Weil 				if (off > key.offset) {
3612c5c9cd4dSSage Weil 					skip = off - key.offset;
3613c5c9cd4dSSage Weil 					new_key.offset += skip;
361431840ae1SZheng Yan 				}
3615d397712bSChris Mason 
3616c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3617c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3618d397712bSChris Mason 
3619c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3620c5c9cd4dSSage Weil 					ret = -EINVAL;
3621a22285a6SYan, Zheng 					btrfs_end_transaction(trans, root);
3622c5c9cd4dSSage Weil 					goto out;
362331840ae1SZheng Yan 				}
3624c5c9cd4dSSage Weil 				size -= skip + trim;
3625c5c9cd4dSSage Weil 				datal -= skip + trim;
3626a22285a6SYan, Zheng 
3627d3ecfcdfSLiu Bo 				aligned_end = ALIGN(new_key.offset + datal,
3628d3ecfcdfSLiu Bo 						    root->sectorsize);
36295dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3630f82a9901SFilipe Manana 							 drop_start,
3631d3ecfcdfSLiu Bo 							 aligned_end,
36322671485dSJosef Bacik 							 1);
363379787eaaSJeff Mahoney 				if (ret) {
36343f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
36353a29bc09SChris Mason 						btrfs_abort_transaction(trans,
36363a29bc09SChris Mason 							root, ret);
363779787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
363879787eaaSJeff Mahoney 					goto out;
363979787eaaSJeff Mahoney 				}
3640a22285a6SYan, Zheng 
3641c5c9cd4dSSage Weil 				ret = btrfs_insert_empty_item(trans, root, path,
3642c5c9cd4dSSage Weil 							      &new_key, size);
364379787eaaSJeff Mahoney 				if (ret) {
364479787eaaSJeff Mahoney 					btrfs_abort_transaction(trans, root,
364579787eaaSJeff Mahoney 								ret);
364679787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
364779787eaaSJeff Mahoney 					goto out;
364879787eaaSJeff Mahoney 				}
3649c5c9cd4dSSage Weil 
3650c5c9cd4dSSage Weil 				if (skip) {
3651d397712bSChris Mason 					u32 start =
3652d397712bSChris Mason 					  btrfs_file_extent_calc_inline_size(0);
3653c5c9cd4dSSage Weil 					memmove(buf+start, buf+start+skip,
3654c5c9cd4dSSage Weil 						datal);
3655c5c9cd4dSSage Weil 				}
3656c5c9cd4dSSage Weil 
3657c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3658c5c9cd4dSSage Weil 				slot = path->slots[0];
3659c5c9cd4dSSage Weil 				write_extent_buffer(leaf, buf,
3660c5c9cd4dSSage Weil 					    btrfs_item_ptr_offset(leaf, slot),
3661c5c9cd4dSSage Weil 					    size);
3662c5c9cd4dSSage Weil 				inode_add_bytes(inode, datal);
3663c5c9cd4dSSage Weil 			}
3664c5c9cd4dSSage Weil 
36657ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
36667ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
36677ffbb598SFilipe Manana 				clone_update_extent_map(inode, trans,
366814f59796SFilipe Manana 						NULL, drop_start,
36697ffbb598SFilipe Manana 						new_key.offset - drop_start);
36707ffbb598SFilipe Manana 
367114f59796SFilipe Manana 			clone_update_extent_map(inode, trans, path, 0, 0);
36727ffbb598SFilipe Manana 
3673c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3674b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3675c5c9cd4dSSage Weil 
367662e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
367762e2390eSFilipe Manana 					      root->sectorsize);
3678f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3679f82a9901SFilipe Manana 							last_dest_end,
36801c919a5eSMark Fasheh 							destoff, olen,
36811c919a5eSMark Fasheh 							no_time_update);
3682f82a9901SFilipe Manana 			if (ret)
368379787eaaSJeff Mahoney 				goto out;
36842c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
36852c463823SFilipe Manana 				break;
3686a22285a6SYan, Zheng 		}
3687b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3688df858e76SFilipe Manana 		key.offset = next_key_min_offset;
3689ae01a0abSYan Zheng 	}
3690f46b5a66SChristoph Hellwig 	ret = 0;
369132b7c687SMark Fasheh 
3692f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3693f82a9901SFilipe Manana 		/*
3694f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3695f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3696f82a9901SFilipe Manana 		 */
3697b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3698f82a9901SFilipe Manana 
3699f82a9901SFilipe Manana 		/*
3700f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3701f82a9901SFilipe Manana 		 * 1 - inode update
3702f82a9901SFilipe Manana 		 */
3703f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3704f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3705f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3706f82a9901SFilipe Manana 			goto out;
3707f82a9901SFilipe Manana 		}
3708f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3709f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3710f82a9901SFilipe Manana 		if (ret) {
3711f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
3712f82a9901SFilipe Manana 				btrfs_abort_transaction(trans, root, ret);
3713f82a9901SFilipe Manana 			btrfs_end_transaction(trans, root);
3714f82a9901SFilipe Manana 			goto out;
3715f82a9901SFilipe Manana 		}
371614f59796SFilipe Manana 		clone_update_extent_map(inode, trans, NULL, last_dest_end,
371714f59796SFilipe Manana 					destoff + len - last_dest_end);
3718f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
37191c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3720f82a9901SFilipe Manana 	}
3721f82a9901SFilipe Manana 
3722f46b5a66SChristoph Hellwig out:
372332b7c687SMark Fasheh 	btrfs_free_path(path);
372432b7c687SMark Fasheh 	vfree(buf);
372532b7c687SMark Fasheh 	return ret;
372632b7c687SMark Fasheh }
372732b7c687SMark Fasheh 
372832b7c687SMark Fasheh static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
372932b7c687SMark Fasheh 				       u64 off, u64 olen, u64 destoff)
373032b7c687SMark Fasheh {
373154563d41SAl Viro 	struct inode *inode = file_inode(file);
373232b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
373332b7c687SMark Fasheh 	struct fd src_file;
373432b7c687SMark Fasheh 	struct inode *src;
373532b7c687SMark Fasheh 	int ret;
373632b7c687SMark Fasheh 	u64 len = olen;
373732b7c687SMark Fasheh 	u64 bs = root->fs_info->sb->s_blocksize;
373832b7c687SMark Fasheh 	int same_inode = 0;
373932b7c687SMark Fasheh 
374032b7c687SMark Fasheh 	/*
374132b7c687SMark Fasheh 	 * TODO:
374232b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
374332b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
374432b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
374532b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
374600fdf13aSLiu Bo 	 *
374700fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
374800fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
374932b7c687SMark Fasheh 	 */
375032b7c687SMark Fasheh 
375132b7c687SMark Fasheh 	/* the destination must be opened for writing */
375232b7c687SMark Fasheh 	if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
375332b7c687SMark Fasheh 		return -EINVAL;
375432b7c687SMark Fasheh 
375532b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
375632b7c687SMark Fasheh 		return -EROFS;
375732b7c687SMark Fasheh 
375832b7c687SMark Fasheh 	ret = mnt_want_write_file(file);
375932b7c687SMark Fasheh 	if (ret)
376032b7c687SMark Fasheh 		return ret;
376132b7c687SMark Fasheh 
376232b7c687SMark Fasheh 	src_file = fdget(srcfd);
376332b7c687SMark Fasheh 	if (!src_file.file) {
376432b7c687SMark Fasheh 		ret = -EBADF;
376532b7c687SMark Fasheh 		goto out_drop_write;
376632b7c687SMark Fasheh 	}
376732b7c687SMark Fasheh 
376832b7c687SMark Fasheh 	ret = -EXDEV;
376932b7c687SMark Fasheh 	if (src_file.file->f_path.mnt != file->f_path.mnt)
377032b7c687SMark Fasheh 		goto out_fput;
377132b7c687SMark Fasheh 
377232b7c687SMark Fasheh 	src = file_inode(src_file.file);
377332b7c687SMark Fasheh 
377432b7c687SMark Fasheh 	ret = -EINVAL;
377532b7c687SMark Fasheh 	if (src == inode)
377632b7c687SMark Fasheh 		same_inode = 1;
377732b7c687SMark Fasheh 
377832b7c687SMark Fasheh 	/* the src must be open for reading */
377932b7c687SMark Fasheh 	if (!(src_file.file->f_mode & FMODE_READ))
378032b7c687SMark Fasheh 		goto out_fput;
378132b7c687SMark Fasheh 
378232b7c687SMark Fasheh 	/* don't make the dst file partly checksummed */
378332b7c687SMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
378432b7c687SMark Fasheh 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
378532b7c687SMark Fasheh 		goto out_fput;
378632b7c687SMark Fasheh 
378732b7c687SMark Fasheh 	ret = -EISDIR;
378832b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
378932b7c687SMark Fasheh 		goto out_fput;
379032b7c687SMark Fasheh 
379132b7c687SMark Fasheh 	ret = -EXDEV;
379232b7c687SMark Fasheh 	if (src->i_sb != inode->i_sb)
379332b7c687SMark Fasheh 		goto out_fput;
379432b7c687SMark Fasheh 
379532b7c687SMark Fasheh 	if (!same_inode) {
379632b7c687SMark Fasheh 		if (inode < src) {
379732b7c687SMark Fasheh 			mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
379832b7c687SMark Fasheh 			mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD);
379932b7c687SMark Fasheh 		} else {
380032b7c687SMark Fasheh 			mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT);
380132b7c687SMark Fasheh 			mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
380232b7c687SMark Fasheh 		}
380332b7c687SMark Fasheh 	} else {
380432b7c687SMark Fasheh 		mutex_lock(&src->i_mutex);
380532b7c687SMark Fasheh 	}
380632b7c687SMark Fasheh 
380732b7c687SMark Fasheh 	/* determine range to clone */
380832b7c687SMark Fasheh 	ret = -EINVAL;
380932b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
381032b7c687SMark Fasheh 		goto out_unlock;
381132b7c687SMark Fasheh 	if (len == 0)
381232b7c687SMark Fasheh 		olen = len = src->i_size - off;
381332b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
381432b7c687SMark Fasheh 	if (off + len == src->i_size)
381532b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
381632b7c687SMark Fasheh 
3817ccccf3d6SFilipe Manana 	if (len == 0) {
3818ccccf3d6SFilipe Manana 		ret = 0;
3819ccccf3d6SFilipe Manana 		goto out_unlock;
3820ccccf3d6SFilipe Manana 	}
3821ccccf3d6SFilipe Manana 
382232b7c687SMark Fasheh 	/* verify the end result is block aligned */
382332b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
382432b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
382532b7c687SMark Fasheh 		goto out_unlock;
382632b7c687SMark Fasheh 
382732b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
382832b7c687SMark Fasheh 	if (same_inode) {
382932b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
383032b7c687SMark Fasheh 			goto out_unlock;
383132b7c687SMark Fasheh 	}
383232b7c687SMark Fasheh 
383332b7c687SMark Fasheh 	if (destoff > inode->i_size) {
383432b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
383532b7c687SMark Fasheh 		if (ret)
383632b7c687SMark Fasheh 			goto out_unlock;
383732b7c687SMark Fasheh 	}
383832b7c687SMark Fasheh 
3839c125b8bfSFilipe Manana 	/*
3840c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
3841c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
3842c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
3843c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
3844c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
3845c125b8bfSFilipe Manana 	 */
3846c125b8bfSFilipe Manana 	if (same_inode) {
3847c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3848c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
384932b7c687SMark Fasheh 
3850c125b8bfSFilipe Manana 		lock_extent_range(src, lock_start, lock_len);
3851c125b8bfSFilipe Manana 	} else {
385232b7c687SMark Fasheh 		lock_extent_range(src, off, len);
3853c125b8bfSFilipe Manana 		lock_extent_range(inode, destoff, len);
3854c125b8bfSFilipe Manana 	}
385532b7c687SMark Fasheh 
38561c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
385732b7c687SMark Fasheh 
3858c125b8bfSFilipe Manana 	if (same_inode) {
3859c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3860c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
3861c125b8bfSFilipe Manana 
3862c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3863c125b8bfSFilipe Manana 	} else {
3864aa42ffd9SLiu Bo 		unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
3865c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(inode)->io_tree, destoff,
3866c125b8bfSFilipe Manana 			      destoff + len - 1);
3867c125b8bfSFilipe Manana 	}
3868c125b8bfSFilipe Manana 	/*
3869c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3870c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3871c125b8bfSFilipe Manana 	 */
3872c125b8bfSFilipe Manana 	truncate_inode_pages_range(&inode->i_data, destoff,
3873c125b8bfSFilipe Manana 				   PAGE_CACHE_ALIGN(destoff + len) - 1);
3874f46b5a66SChristoph Hellwig out_unlock:
3875c57c2b3eSFilipe David Borba Manana 	if (!same_inode) {
3876c57c2b3eSFilipe David Borba Manana 		if (inode < src) {
3877f46b5a66SChristoph Hellwig 			mutex_unlock(&src->i_mutex);
3878f46b5a66SChristoph Hellwig 			mutex_unlock(&inode->i_mutex);
3879c57c2b3eSFilipe David Borba Manana 		} else {
3880c57c2b3eSFilipe David Borba Manana 			mutex_unlock(&inode->i_mutex);
3881c57c2b3eSFilipe David Borba Manana 			mutex_unlock(&src->i_mutex);
3882c57c2b3eSFilipe David Borba Manana 		}
3883c57c2b3eSFilipe David Borba Manana 	} else {
3884c57c2b3eSFilipe David Borba Manana 		mutex_unlock(&src->i_mutex);
3885c57c2b3eSFilipe David Borba Manana 	}
3886f46b5a66SChristoph Hellwig out_fput:
38872903ff01SAl Viro 	fdput(src_file);
3888ab67b7c1SYan Zheng out_drop_write:
38892a79f17eSAl Viro 	mnt_drop_write_file(file);
3890f46b5a66SChristoph Hellwig 	return ret;
3891f46b5a66SChristoph Hellwig }
3892f46b5a66SChristoph Hellwig 
38937a865e8aSChristoph Hellwig static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
3894c5c9cd4dSSage Weil {
3895c5c9cd4dSSage Weil 	struct btrfs_ioctl_clone_range_args args;
3896c5c9cd4dSSage Weil 
38977a865e8aSChristoph Hellwig 	if (copy_from_user(&args, argp, sizeof(args)))
3898c5c9cd4dSSage Weil 		return -EFAULT;
3899c5c9cd4dSSage Weil 	return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
3900c5c9cd4dSSage Weil 				 args.src_length, args.dest_offset);
3901c5c9cd4dSSage Weil }
3902c5c9cd4dSSage Weil 
3903f46b5a66SChristoph Hellwig /*
3904f46b5a66SChristoph Hellwig  * there are many ways the trans_start and trans_end ioctls can lead
3905f46b5a66SChristoph Hellwig  * to deadlocks.  They should only be used by applications that
3906f46b5a66SChristoph Hellwig  * basically own the machine, and have a very in depth understanding
3907f46b5a66SChristoph Hellwig  * of all the possible deadlocks and enospc problems.
3908f46b5a66SChristoph Hellwig  */
3909b2950863SChristoph Hellwig static long btrfs_ioctl_trans_start(struct file *file)
3910f46b5a66SChristoph Hellwig {
3911496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3912f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
3913f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
39141ab86aedSSage Weil 	int ret;
3915f46b5a66SChristoph Hellwig 
39161ab86aedSSage Weil 	ret = -EPERM;
3917df5b5520SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
3918f46b5a66SChristoph Hellwig 		goto out;
39191ab86aedSSage Weil 
39201ab86aedSSage Weil 	ret = -EINPROGRESS;
39211ab86aedSSage Weil 	if (file->private_data)
39221ab86aedSSage Weil 		goto out;
39239ca9ee09SSage Weil 
3924b83cc969SLi Zefan 	ret = -EROFS;
3925b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
3926b83cc969SLi Zefan 		goto out;
3927b83cc969SLi Zefan 
3928a561be71SAl Viro 	ret = mnt_want_write_file(file);
3929c146afadSYan Zheng 	if (ret)
3930c146afadSYan Zheng 		goto out;
3931c146afadSYan Zheng 
3932a4abeea4SJosef Bacik 	atomic_inc(&root->fs_info->open_ioctl_trans);
39339ca9ee09SSage Weil 
3934f46b5a66SChristoph Hellwig 	ret = -ENOMEM;
39357a7eaa40SJosef Bacik 	trans = btrfs_start_ioctl_transaction(root);
3936abd30bb0STsutomu Itoh 	if (IS_ERR(trans))
39371ab86aedSSage Weil 		goto out_drop;
39381ab86aedSSage Weil 
39391ab86aedSSage Weil 	file->private_data = trans;
39401ab86aedSSage Weil 	return 0;
39411ab86aedSSage Weil 
39421ab86aedSSage Weil out_drop:
3943a4abeea4SJosef Bacik 	atomic_dec(&root->fs_info->open_ioctl_trans);
39442a79f17eSAl Viro 	mnt_drop_write_file(file);
3945f46b5a66SChristoph Hellwig out:
3946f46b5a66SChristoph Hellwig 	return ret;
3947f46b5a66SChristoph Hellwig }
3948f46b5a66SChristoph Hellwig 
39496ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
39506ef5ed0dSJosef Bacik {
3951496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
39526ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
39536ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
39546ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
39556ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
39566ef5ed0dSJosef Bacik 	struct btrfs_path *path;
39576ef5ed0dSJosef Bacik 	struct btrfs_key location;
39586ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
39596ef5ed0dSJosef Bacik 	u64 objectid = 0;
39606ef5ed0dSJosef Bacik 	u64 dir_id;
39613c04ce01SMiao Xie 	int ret;
39626ef5ed0dSJosef Bacik 
39636ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
39646ef5ed0dSJosef Bacik 		return -EPERM;
39656ef5ed0dSJosef Bacik 
39663c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
39673c04ce01SMiao Xie 	if (ret)
39683c04ce01SMiao Xie 		return ret;
39693c04ce01SMiao Xie 
39703c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
39713c04ce01SMiao Xie 		ret = -EFAULT;
39723c04ce01SMiao Xie 		goto out;
39733c04ce01SMiao Xie 	}
39746ef5ed0dSJosef Bacik 
39756ef5ed0dSJosef Bacik 	if (!objectid)
39761cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
39776ef5ed0dSJosef Bacik 
39786ef5ed0dSJosef Bacik 	location.objectid = objectid;
39796ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
39806ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
39816ef5ed0dSJosef Bacik 
39826ef5ed0dSJosef Bacik 	new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
39833c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
39843c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
39853c04ce01SMiao Xie 		goto out;
39863c04ce01SMiao Xie 	}
39876ef5ed0dSJosef Bacik 
39886ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
39893c04ce01SMiao Xie 	if (!path) {
39903c04ce01SMiao Xie 		ret = -ENOMEM;
39913c04ce01SMiao Xie 		goto out;
39923c04ce01SMiao Xie 	}
39936ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
39946ef5ed0dSJosef Bacik 
39956ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
399698d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
39976ef5ed0dSJosef Bacik 		btrfs_free_path(path);
39983c04ce01SMiao Xie 		ret = PTR_ERR(trans);
39993c04ce01SMiao Xie 		goto out;
40006ef5ed0dSJosef Bacik 	}
40016ef5ed0dSJosef Bacik 
40026c41761fSDavid Sterba 	dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
40036ef5ed0dSJosef Bacik 	di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
40046ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
4005cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
40066ef5ed0dSJosef Bacik 		btrfs_free_path(path);
40076ef5ed0dSJosef Bacik 		btrfs_end_transaction(trans, root);
4008efe120a0SFrank Holton 		btrfs_err(new_root->fs_info, "Umm, you don't have the default dir"
4009efe120a0SFrank Holton 			   "item, this isn't going to work");
40103c04ce01SMiao Xie 		ret = -ENOENT;
40113c04ce01SMiao Xie 		goto out;
40126ef5ed0dSJosef Bacik 	}
40136ef5ed0dSJosef Bacik 
40146ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
40156ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
40166ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
40176ef5ed0dSJosef Bacik 	btrfs_free_path(path);
40186ef5ed0dSJosef Bacik 
40192b0ce2c2SMitch Harder 	btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
40206ef5ed0dSJosef Bacik 	btrfs_end_transaction(trans, root);
40213c04ce01SMiao Xie out:
40223c04ce01SMiao Xie 	mnt_drop_write_file(file);
40233c04ce01SMiao Xie 	return ret;
40246ef5ed0dSJosef Bacik }
40256ef5ed0dSJosef Bacik 
40265af3e8ccSStefan Behrens void btrfs_get_block_group_info(struct list_head *groups_list,
4027bf5fc093SJosef Bacik 				struct btrfs_ioctl_space_info *space)
4028bf5fc093SJosef Bacik {
4029bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4030bf5fc093SJosef Bacik 
4031bf5fc093SJosef Bacik 	space->total_bytes = 0;
4032bf5fc093SJosef Bacik 	space->used_bytes = 0;
4033bf5fc093SJosef Bacik 	space->flags = 0;
4034bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4035bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4036bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4037bf5fc093SJosef Bacik 		space->used_bytes +=
4038bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4039bf5fc093SJosef Bacik 	}
4040bf5fc093SJosef Bacik }
4041bf5fc093SJosef Bacik 
404248a3b636SEric Sandeen static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
40431406e432SJosef Bacik {
40441406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
40451406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
40461406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
40477fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
404813f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
40491406e432SJosef Bacik 	struct btrfs_space_info *info;
4050bf5fc093SJosef Bacik 	u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
4051bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_SYSTEM,
4052bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_METADATA,
4053bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
4054bf5fc093SJosef Bacik 	int num_types = 4;
40557fde62bfSChris Mason 	int alloc_size;
40561406e432SJosef Bacik 	int ret = 0;
405751788b1bSDan Rosenberg 	u64 slot_count = 0;
4058bf5fc093SJosef Bacik 	int i, c;
40591406e432SJosef Bacik 
40601406e432SJosef Bacik 	if (copy_from_user(&space_args,
40611406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
40621406e432SJosef Bacik 			   sizeof(space_args)))
40631406e432SJosef Bacik 		return -EFAULT;
40641406e432SJosef Bacik 
4065bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4066bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4067bf5fc093SJosef Bacik 
4068bf5fc093SJosef Bacik 		info = NULL;
40697fde62bfSChris Mason 		rcu_read_lock();
4070bf5fc093SJosef Bacik 		list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
4071bf5fc093SJosef Bacik 					list) {
4072bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4073bf5fc093SJosef Bacik 				info = tmp;
4074bf5fc093SJosef Bacik 				break;
4075bf5fc093SJosef Bacik 			}
4076bf5fc093SJosef Bacik 		}
40777fde62bfSChris Mason 		rcu_read_unlock();
40781406e432SJosef Bacik 
4079bf5fc093SJosef Bacik 		if (!info)
4080bf5fc093SJosef Bacik 			continue;
4081bf5fc093SJosef Bacik 
4082bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4083bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4084bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4085bf5fc093SJosef Bacik 				slot_count++;
4086bf5fc093SJosef Bacik 		}
4087bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4088bf5fc093SJosef Bacik 	}
4089bf5fc093SJosef Bacik 
409036523e95SDavid Sterba 	/*
409136523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
409236523e95SDavid Sterba 	 */
409336523e95SDavid Sterba 	slot_count++;
409436523e95SDavid Sterba 
40957fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
40967fde62bfSChris Mason 	if (space_args.space_slots == 0) {
40977fde62bfSChris Mason 		space_args.total_spaces = slot_count;
40987fde62bfSChris Mason 		goto out;
40997fde62bfSChris Mason 	}
4100bf5fc093SJosef Bacik 
410151788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4102bf5fc093SJosef Bacik 
41037fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4104bf5fc093SJosef Bacik 
41057fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
41067fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
41077fde62bfSChris Mason 	 */
41087fde62bfSChris Mason 	if (alloc_size > PAGE_CACHE_SIZE)
41097fde62bfSChris Mason 		return -ENOMEM;
41107fde62bfSChris Mason 
41117fde62bfSChris Mason 	space_args.total_spaces = 0;
41127fde62bfSChris Mason 	dest = kmalloc(alloc_size, GFP_NOFS);
41137fde62bfSChris Mason 	if (!dest)
41147fde62bfSChris Mason 		return -ENOMEM;
41157fde62bfSChris Mason 	dest_orig = dest;
41167fde62bfSChris Mason 
41177fde62bfSChris Mason 	/* now we have a buffer to copy into */
4118bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4119bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4120bf5fc093SJosef Bacik 
412151788b1bSDan Rosenberg 		if (!slot_count)
412251788b1bSDan Rosenberg 			break;
412351788b1bSDan Rosenberg 
4124bf5fc093SJosef Bacik 		info = NULL;
41251406e432SJosef Bacik 		rcu_read_lock();
4126bf5fc093SJosef Bacik 		list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
4127bf5fc093SJosef Bacik 					list) {
4128bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4129bf5fc093SJosef Bacik 				info = tmp;
41307fde62bfSChris Mason 				break;
4131bf5fc093SJosef Bacik 			}
4132bf5fc093SJosef Bacik 		}
4133bf5fc093SJosef Bacik 		rcu_read_unlock();
41347fde62bfSChris Mason 
4135bf5fc093SJosef Bacik 		if (!info)
4136bf5fc093SJosef Bacik 			continue;
4137bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4138bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4139bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
41405af3e8ccSStefan Behrens 				btrfs_get_block_group_info(
41415af3e8ccSStefan Behrens 					&info->block_groups[c], &space);
41427fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
41431406e432SJosef Bacik 				dest++;
41441406e432SJosef Bacik 				space_args.total_spaces++;
414551788b1bSDan Rosenberg 				slot_count--;
41461406e432SJosef Bacik 			}
414751788b1bSDan Rosenberg 			if (!slot_count)
414851788b1bSDan Rosenberg 				break;
4149bf5fc093SJosef Bacik 		}
4150bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4151bf5fc093SJosef Bacik 	}
41521406e432SJosef Bacik 
415336523e95SDavid Sterba 	/*
415436523e95SDavid Sterba 	 * Add global block reserve
415536523e95SDavid Sterba 	 */
415636523e95SDavid Sterba 	if (slot_count) {
415736523e95SDavid Sterba 		struct btrfs_block_rsv *block_rsv = &root->fs_info->global_block_rsv;
415836523e95SDavid Sterba 
415936523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
416036523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
416136523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
416236523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
416336523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
416436523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
416536523e95SDavid Sterba 		space_args.total_spaces++;
416636523e95SDavid Sterba 	}
416736523e95SDavid Sterba 
41682eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
41697fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
41707fde62bfSChris Mason 
41717fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
41727fde62bfSChris Mason 		ret = -EFAULT;
41737fde62bfSChris Mason 
41747fde62bfSChris Mason 	kfree(dest_orig);
41757fde62bfSChris Mason out:
41767fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
41771406e432SJosef Bacik 		ret = -EFAULT;
41781406e432SJosef Bacik 
41791406e432SJosef Bacik 	return ret;
41801406e432SJosef Bacik }
41811406e432SJosef Bacik 
4182f46b5a66SChristoph Hellwig /*
4183f46b5a66SChristoph Hellwig  * there are many ways the trans_start and trans_end ioctls can lead
4184f46b5a66SChristoph Hellwig  * to deadlocks.  They should only be used by applications that
4185f46b5a66SChristoph Hellwig  * basically own the machine, and have a very in depth understanding
4186f46b5a66SChristoph Hellwig  * of all the possible deadlocks and enospc problems.
4187f46b5a66SChristoph Hellwig  */
4188f46b5a66SChristoph Hellwig long btrfs_ioctl_trans_end(struct file *file)
4189f46b5a66SChristoph Hellwig {
4190496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4191f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
4192f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
4193f46b5a66SChristoph Hellwig 
4194f46b5a66SChristoph Hellwig 	trans = file->private_data;
41951ab86aedSSage Weil 	if (!trans)
41961ab86aedSSage Weil 		return -EINVAL;
4197b214107eSChristoph Hellwig 	file->private_data = NULL;
41989ca9ee09SSage Weil 
41991ab86aedSSage Weil 	btrfs_end_transaction(trans, root);
42001ab86aedSSage Weil 
4201a4abeea4SJosef Bacik 	atomic_dec(&root->fs_info->open_ioctl_trans);
42029ca9ee09SSage Weil 
42032a79f17eSAl Viro 	mnt_drop_write_file(file);
42041ab86aedSSage Weil 	return 0;
4205f46b5a66SChristoph Hellwig }
4206f46b5a66SChristoph Hellwig 
42079a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
42089a8c28beSMiao Xie 					    void __user *argp)
420946204592SSage Weil {
421046204592SSage Weil 	struct btrfs_trans_handle *trans;
421146204592SSage Weil 	u64 transid;
4212db5b493aSTsutomu Itoh 	int ret;
421346204592SSage Weil 
4214d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4215ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4216ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
421798d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4218ff7c1d33SMiao Xie 
4219ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4220ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4221ff7c1d33SMiao Xie 		goto out;
4222ff7c1d33SMiao Xie 	}
422346204592SSage Weil 	transid = trans->transid;
4224db5b493aSTsutomu Itoh 	ret = btrfs_commit_transaction_async(trans, root, 0);
42258b2b2d3cSTsutomu Itoh 	if (ret) {
42268b2b2d3cSTsutomu Itoh 		btrfs_end_transaction(trans, root);
4227db5b493aSTsutomu Itoh 		return ret;
42288b2b2d3cSTsutomu Itoh 	}
4229ff7c1d33SMiao Xie out:
423046204592SSage Weil 	if (argp)
423146204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
423246204592SSage Weil 			return -EFAULT;
423346204592SSage Weil 	return 0;
423446204592SSage Weil }
423546204592SSage Weil 
42369a8c28beSMiao Xie static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
42379a8c28beSMiao Xie 					   void __user *argp)
423846204592SSage Weil {
423946204592SSage Weil 	u64 transid;
424046204592SSage Weil 
424146204592SSage Weil 	if (argp) {
424246204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
424346204592SSage Weil 			return -EFAULT;
424446204592SSage Weil 	} else {
424546204592SSage Weil 		transid = 0;  /* current trans */
424646204592SSage Weil 	}
424746204592SSage Weil 	return btrfs_wait_for_commit(root, transid);
424846204592SSage Weil }
424946204592SSage Weil 
4250b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4251475f6387SJan Schmidt {
4252496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4253475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4254b8e95489SMiao Xie 	int ret;
4255475f6387SJan Schmidt 
4256475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4257475f6387SJan Schmidt 		return -EPERM;
4258475f6387SJan Schmidt 
4259475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4260475f6387SJan Schmidt 	if (IS_ERR(sa))
4261475f6387SJan Schmidt 		return PTR_ERR(sa);
4262475f6387SJan Schmidt 
4263b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4264b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4265b8e95489SMiao Xie 		if (ret)
4266b8e95489SMiao Xie 			goto out;
4267b8e95489SMiao Xie 	}
4268b8e95489SMiao Xie 
4269aa1b8cd4SStefan Behrens 	ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
427063a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
427163a212abSStefan Behrens 			      0);
4272475f6387SJan Schmidt 
4273475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4274475f6387SJan Schmidt 		ret = -EFAULT;
4275475f6387SJan Schmidt 
4276b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4277b8e95489SMiao Xie 		mnt_drop_write_file(file);
4278b8e95489SMiao Xie out:
4279475f6387SJan Schmidt 	kfree(sa);
4280475f6387SJan Schmidt 	return ret;
4281475f6387SJan Schmidt }
4282475f6387SJan Schmidt 
4283475f6387SJan Schmidt static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
4284475f6387SJan Schmidt {
4285475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4286475f6387SJan Schmidt 		return -EPERM;
4287475f6387SJan Schmidt 
4288aa1b8cd4SStefan Behrens 	return btrfs_scrub_cancel(root->fs_info);
4289475f6387SJan Schmidt }
4290475f6387SJan Schmidt 
4291475f6387SJan Schmidt static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
4292475f6387SJan Schmidt 				       void __user *arg)
4293475f6387SJan Schmidt {
4294475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4295475f6387SJan Schmidt 	int ret;
4296475f6387SJan Schmidt 
4297475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4298475f6387SJan Schmidt 		return -EPERM;
4299475f6387SJan Schmidt 
4300475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4301475f6387SJan Schmidt 	if (IS_ERR(sa))
4302475f6387SJan Schmidt 		return PTR_ERR(sa);
4303475f6387SJan Schmidt 
4304475f6387SJan Schmidt 	ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
4305475f6387SJan Schmidt 
4306475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4307475f6387SJan Schmidt 		ret = -EFAULT;
4308475f6387SJan Schmidt 
4309475f6387SJan Schmidt 	kfree(sa);
4310475f6387SJan Schmidt 	return ret;
4311475f6387SJan Schmidt }
4312475f6387SJan Schmidt 
4313c11d2c23SStefan Behrens static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
4314b27f7c0cSDavid Sterba 				      void __user *arg)
4315c11d2c23SStefan Behrens {
4316c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4317c11d2c23SStefan Behrens 	int ret;
4318c11d2c23SStefan Behrens 
4319c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4320c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4321c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4322c11d2c23SStefan Behrens 
4323b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4324b27f7c0cSDavid Sterba 		kfree(sa);
4325b27f7c0cSDavid Sterba 		return -EPERM;
4326b27f7c0cSDavid Sterba 	}
4327b27f7c0cSDavid Sterba 
4328b27f7c0cSDavid Sterba 	ret = btrfs_get_dev_stats(root, sa);
4329c11d2c23SStefan Behrens 
4330c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4331c11d2c23SStefan Behrens 		ret = -EFAULT;
4332c11d2c23SStefan Behrens 
4333c11d2c23SStefan Behrens 	kfree(sa);
4334c11d2c23SStefan Behrens 	return ret;
4335c11d2c23SStefan Behrens }
4336c11d2c23SStefan Behrens 
43373f6bcfbdSStefan Behrens static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
43383f6bcfbdSStefan Behrens {
43393f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
43403f6bcfbdSStefan Behrens 	int ret;
43413f6bcfbdSStefan Behrens 
43423f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
43433f6bcfbdSStefan Behrens 		return -EPERM;
43443f6bcfbdSStefan Behrens 
43453f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
43463f6bcfbdSStefan Behrens 	if (IS_ERR(p))
43473f6bcfbdSStefan Behrens 		return PTR_ERR(p);
43483f6bcfbdSStefan Behrens 
43493f6bcfbdSStefan Behrens 	switch (p->cmd) {
43503f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4351adfa97cbSIlya Dryomov 		if (root->fs_info->sb->s_flags & MS_RDONLY) {
4352adfa97cbSIlya Dryomov 			ret = -EROFS;
4353adfa97cbSIlya Dryomov 			goto out;
4354adfa97cbSIlya Dryomov 		}
43553f6bcfbdSStefan Behrens 		if (atomic_xchg(
43563f6bcfbdSStefan Behrens 			&root->fs_info->mutually_exclusive_operation_running,
43573f6bcfbdSStefan Behrens 			1)) {
4358e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
43593f6bcfbdSStefan Behrens 		} else {
43603f6bcfbdSStefan Behrens 			ret = btrfs_dev_replace_start(root, p);
43613f6bcfbdSStefan Behrens 			atomic_set(
43623f6bcfbdSStefan Behrens 			 &root->fs_info->mutually_exclusive_operation_running,
43633f6bcfbdSStefan Behrens 			 0);
43643f6bcfbdSStefan Behrens 		}
43653f6bcfbdSStefan Behrens 		break;
43663f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
43673f6bcfbdSStefan Behrens 		btrfs_dev_replace_status(root->fs_info, p);
43683f6bcfbdSStefan Behrens 		ret = 0;
43693f6bcfbdSStefan Behrens 		break;
43703f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
43713f6bcfbdSStefan Behrens 		ret = btrfs_dev_replace_cancel(root->fs_info, p);
43723f6bcfbdSStefan Behrens 		break;
43733f6bcfbdSStefan Behrens 	default:
43743f6bcfbdSStefan Behrens 		ret = -EINVAL;
43753f6bcfbdSStefan Behrens 		break;
43763f6bcfbdSStefan Behrens 	}
43773f6bcfbdSStefan Behrens 
43783f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
43793f6bcfbdSStefan Behrens 		ret = -EFAULT;
4380adfa97cbSIlya Dryomov out:
43813f6bcfbdSStefan Behrens 	kfree(p);
43823f6bcfbdSStefan Behrens 	return ret;
43833f6bcfbdSStefan Behrens }
43843f6bcfbdSStefan Behrens 
4385d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4386d7728c96SJan Schmidt {
4387d7728c96SJan Schmidt 	int ret = 0;
4388d7728c96SJan Schmidt 	int i;
4389740c3d22SChris Mason 	u64 rel_ptr;
4390d7728c96SJan Schmidt 	int size;
4391806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4392d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4393d7728c96SJan Schmidt 	struct btrfs_path *path;
4394d7728c96SJan Schmidt 
439582b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4396d7728c96SJan Schmidt 		return -EPERM;
4397d7728c96SJan Schmidt 
4398d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4399d7728c96SJan Schmidt 	if (!path) {
4400d7728c96SJan Schmidt 		ret = -ENOMEM;
4401d7728c96SJan Schmidt 		goto out;
4402d7728c96SJan Schmidt 	}
4403d7728c96SJan Schmidt 
4404d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4405d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4406d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4407d7728c96SJan Schmidt 		ipa = NULL;
4408d7728c96SJan Schmidt 		goto out;
4409d7728c96SJan Schmidt 	}
4410d7728c96SJan Schmidt 
4411d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4412d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4413d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4414d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4415d7728c96SJan Schmidt 		ipath = NULL;
4416d7728c96SJan Schmidt 		goto out;
4417d7728c96SJan Schmidt 	}
4418d7728c96SJan Schmidt 
4419d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4420d7728c96SJan Schmidt 	if (ret < 0)
4421d7728c96SJan Schmidt 		goto out;
4422d7728c96SJan Schmidt 
4423d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4424745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4425745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4426740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4427d7728c96SJan Schmidt 	}
4428d7728c96SJan Schmidt 
4429745c4d8eSJeff Mahoney 	ret = copy_to_user((void *)(unsigned long)ipa->fspath,
4430745c4d8eSJeff Mahoney 			   (void *)(unsigned long)ipath->fspath, size);
4431d7728c96SJan Schmidt 	if (ret) {
4432d7728c96SJan Schmidt 		ret = -EFAULT;
4433d7728c96SJan Schmidt 		goto out;
4434d7728c96SJan Schmidt 	}
4435d7728c96SJan Schmidt 
4436d7728c96SJan Schmidt out:
4437d7728c96SJan Schmidt 	btrfs_free_path(path);
4438d7728c96SJan Schmidt 	free_ipath(ipath);
4439d7728c96SJan Schmidt 	kfree(ipa);
4440d7728c96SJan Schmidt 
4441d7728c96SJan Schmidt 	return ret;
4442d7728c96SJan Schmidt }
4443d7728c96SJan Schmidt 
4444d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4445d7728c96SJan Schmidt {
4446d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4447d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4448d7728c96SJan Schmidt 
4449d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4450d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4451d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4452d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4453d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4454d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4455d7728c96SJan Schmidt 	} else {
4456d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4457d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4458d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4459d7728c96SJan Schmidt 	}
4460d7728c96SJan Schmidt 
4461d7728c96SJan Schmidt 	return 0;
4462d7728c96SJan Schmidt }
4463d7728c96SJan Schmidt 
4464d7728c96SJan Schmidt static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
4465d7728c96SJan Schmidt 					void __user *arg)
4466d7728c96SJan Schmidt {
4467d7728c96SJan Schmidt 	int ret = 0;
4468d7728c96SJan Schmidt 	int size;
4469d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4470d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4471d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4472d7728c96SJan Schmidt 
4473d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4474d7728c96SJan Schmidt 		return -EPERM;
4475d7728c96SJan Schmidt 
4476d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
4477d7728c96SJan Schmidt 	if (IS_ERR(loi)) {
4478d7728c96SJan Schmidt 		ret = PTR_ERR(loi);
4479d7728c96SJan Schmidt 		loi = NULL;
4480d7728c96SJan Schmidt 		goto out;
4481d7728c96SJan Schmidt 	}
4482d7728c96SJan Schmidt 
4483d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4484d7728c96SJan Schmidt 	if (!path) {
4485d7728c96SJan Schmidt 		ret = -ENOMEM;
4486d7728c96SJan Schmidt 		goto out;
4487d7728c96SJan Schmidt 	}
4488d7728c96SJan Schmidt 
4489425d17a2SLiu Bo 	size = min_t(u32, loi->size, 64 * 1024);
4490d7728c96SJan Schmidt 	inodes = init_data_container(size);
4491d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4492d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4493d7728c96SJan Schmidt 		inodes = NULL;
4494d7728c96SJan Schmidt 		goto out;
4495d7728c96SJan Schmidt 	}
4496d7728c96SJan Schmidt 
4497df031f07SLiu Bo 	ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
4498df031f07SLiu Bo 					  build_ino_list, inodes);
4499df031f07SLiu Bo 	if (ret == -EINVAL)
4500d7728c96SJan Schmidt 		ret = -ENOENT;
4501d7728c96SJan Schmidt 	if (ret < 0)
4502d7728c96SJan Schmidt 		goto out;
4503d7728c96SJan Schmidt 
4504745c4d8eSJeff Mahoney 	ret = copy_to_user((void *)(unsigned long)loi->inodes,
4505745c4d8eSJeff Mahoney 			   (void *)(unsigned long)inodes, size);
4506d7728c96SJan Schmidt 	if (ret)
4507d7728c96SJan Schmidt 		ret = -EFAULT;
4508d7728c96SJan Schmidt 
4509d7728c96SJan Schmidt out:
4510d7728c96SJan Schmidt 	btrfs_free_path(path);
4511425d17a2SLiu Bo 	vfree(inodes);
4512d7728c96SJan Schmidt 	kfree(loi);
4513d7728c96SJan Schmidt 
4514d7728c96SJan Schmidt 	return ret;
4515d7728c96SJan Schmidt }
4516d7728c96SJan Schmidt 
451719a39dceSIlya Dryomov void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
4518c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4519c9e9f97bSIlya Dryomov {
4520c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4521c9e9f97bSIlya Dryomov 
4522c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4523c9e9f97bSIlya Dryomov 
4524837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_running))
4525837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4526837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4527837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4528a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4529a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4530837d5b6eSIlya Dryomov 
4531c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4532c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4533c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
453419a39dceSIlya Dryomov 
453519a39dceSIlya Dryomov 	if (lock) {
453619a39dceSIlya Dryomov 		spin_lock(&fs_info->balance_lock);
453719a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
453819a39dceSIlya Dryomov 		spin_unlock(&fs_info->balance_lock);
453919a39dceSIlya Dryomov 	} else {
454019a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
454119a39dceSIlya Dryomov 	}
4542c9e9f97bSIlya Dryomov }
4543c9e9f97bSIlya Dryomov 
45449ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4545c9e9f97bSIlya Dryomov {
4546496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4547c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4548c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4549c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4550ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4551c9e9f97bSIlya Dryomov 	int ret;
4552c9e9f97bSIlya Dryomov 
4553c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4554c9e9f97bSIlya Dryomov 		return -EPERM;
4555c9e9f97bSIlya Dryomov 
4556e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
45579ba1f6e4SLiu Bo 	if (ret)
45589ba1f6e4SLiu Bo 		return ret;
45599ba1f6e4SLiu Bo 
4560ed0fb78fSIlya Dryomov again:
4561ed0fb78fSIlya Dryomov 	if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
4562c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->volume_mutex);
4563c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4564ed0fb78fSIlya Dryomov 		need_unlock = true;
4565ed0fb78fSIlya Dryomov 		goto locked;
4566ed0fb78fSIlya Dryomov 	}
4567ed0fb78fSIlya Dryomov 
4568ed0fb78fSIlya Dryomov 	/*
4569ed0fb78fSIlya Dryomov 	 * mut. excl. ops lock is locked.  Three possibilites:
4570ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4571ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4572ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4573ed0fb78fSIlya Dryomov 	 */
4574ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4575ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4576ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
4577ed0fb78fSIlya Dryomov 		if (!atomic_read(&fs_info->balance_running)) {
4578ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4579ed0fb78fSIlya Dryomov 			if (!mutex_trylock(&fs_info->volume_mutex))
4580ed0fb78fSIlya Dryomov 				goto again;
4581ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4582ed0fb78fSIlya Dryomov 
4583ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
4584ed0fb78fSIlya Dryomov 			    !atomic_read(&fs_info->balance_running)) {
4585ed0fb78fSIlya Dryomov 				/* this is (3) */
4586ed0fb78fSIlya Dryomov 				need_unlock = false;
4587ed0fb78fSIlya Dryomov 				goto locked;
4588ed0fb78fSIlya Dryomov 			}
4589ed0fb78fSIlya Dryomov 
4590ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4591ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->volume_mutex);
4592ed0fb78fSIlya Dryomov 			goto again;
4593ed0fb78fSIlya Dryomov 		} else {
4594ed0fb78fSIlya Dryomov 			/* this is (2) */
4595ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4596ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4597ed0fb78fSIlya Dryomov 			goto out;
4598ed0fb78fSIlya Dryomov 		}
4599ed0fb78fSIlya Dryomov 	} else {
4600ed0fb78fSIlya Dryomov 		/* this is (1) */
4601ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4602e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4603ed0fb78fSIlya Dryomov 		goto out;
4604ed0fb78fSIlya Dryomov 	}
4605ed0fb78fSIlya Dryomov 
4606ed0fb78fSIlya Dryomov locked:
4607ed0fb78fSIlya Dryomov 	BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
4608c9e9f97bSIlya Dryomov 
4609c9e9f97bSIlya Dryomov 	if (arg) {
4610c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4611c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4612c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4613ed0fb78fSIlya Dryomov 			goto out_unlock;
4614c9e9f97bSIlya Dryomov 		}
4615de322263SIlya Dryomov 
4616de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4617de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4618de322263SIlya Dryomov 				ret = -ENOTCONN;
4619de322263SIlya Dryomov 				goto out_bargs;
4620de322263SIlya Dryomov 			}
4621de322263SIlya Dryomov 
4622de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4623de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4624de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4625de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4626de322263SIlya Dryomov 
4627de322263SIlya Dryomov 			goto do_balance;
4628de322263SIlya Dryomov 		}
4629c9e9f97bSIlya Dryomov 	} else {
4630c9e9f97bSIlya Dryomov 		bargs = NULL;
4631c9e9f97bSIlya Dryomov 	}
4632c9e9f97bSIlya Dryomov 
4633ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4634837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4635837d5b6eSIlya Dryomov 		goto out_bargs;
4636837d5b6eSIlya Dryomov 	}
4637837d5b6eSIlya Dryomov 
4638c9e9f97bSIlya Dryomov 	bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4639c9e9f97bSIlya Dryomov 	if (!bctl) {
4640c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4641c9e9f97bSIlya Dryomov 		goto out_bargs;
4642c9e9f97bSIlya Dryomov 	}
4643c9e9f97bSIlya Dryomov 
4644c9e9f97bSIlya Dryomov 	bctl->fs_info = fs_info;
4645c9e9f97bSIlya Dryomov 	if (arg) {
4646c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4647c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4648c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4649c9e9f97bSIlya Dryomov 
4650c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4651f43ffb60SIlya Dryomov 	} else {
4652f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4653f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4654c9e9f97bSIlya Dryomov 	}
4655c9e9f97bSIlya Dryomov 
4656de322263SIlya Dryomov do_balance:
4657c9e9f97bSIlya Dryomov 	/*
4658ed0fb78fSIlya Dryomov 	 * Ownership of bctl and mutually_exclusive_operation_running
4659ed0fb78fSIlya Dryomov 	 * goes to to btrfs_balance.  bctl is freed in __cancel_balance,
4660ed0fb78fSIlya Dryomov 	 * or, if restriper was paused all the way until unmount, in
4661ed0fb78fSIlya Dryomov 	 * free_fs_info.  mutually_exclusive_operation_running is
4662ed0fb78fSIlya Dryomov 	 * cleared in __cancel_balance.
4663c9e9f97bSIlya Dryomov 	 */
4664ed0fb78fSIlya Dryomov 	need_unlock = false;
4665ed0fb78fSIlya Dryomov 
4666ed0fb78fSIlya Dryomov 	ret = btrfs_balance(bctl, bargs);
4667ed0fb78fSIlya Dryomov 
4668c9e9f97bSIlya Dryomov 	if (arg) {
4669c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4670c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4671c9e9f97bSIlya Dryomov 	}
4672c9e9f97bSIlya Dryomov 
4673c9e9f97bSIlya Dryomov out_bargs:
4674c9e9f97bSIlya Dryomov 	kfree(bargs);
4675ed0fb78fSIlya Dryomov out_unlock:
4676c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4677c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->volume_mutex);
4678ed0fb78fSIlya Dryomov 	if (need_unlock)
4679ed0fb78fSIlya Dryomov 		atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
4680ed0fb78fSIlya Dryomov out:
4681e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4682c9e9f97bSIlya Dryomov 	return ret;
4683c9e9f97bSIlya Dryomov }
4684c9e9f97bSIlya Dryomov 
4685837d5b6eSIlya Dryomov static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
4686837d5b6eSIlya Dryomov {
4687837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4688837d5b6eSIlya Dryomov 		return -EPERM;
4689837d5b6eSIlya Dryomov 
4690837d5b6eSIlya Dryomov 	switch (cmd) {
4691837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
4692837d5b6eSIlya Dryomov 		return btrfs_pause_balance(root->fs_info);
4693a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
4694a7e99c69SIlya Dryomov 		return btrfs_cancel_balance(root->fs_info);
4695837d5b6eSIlya Dryomov 	}
4696837d5b6eSIlya Dryomov 
4697837d5b6eSIlya Dryomov 	return -EINVAL;
4698837d5b6eSIlya Dryomov }
4699837d5b6eSIlya Dryomov 
470019a39dceSIlya Dryomov static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
470119a39dceSIlya Dryomov 					 void __user *arg)
470219a39dceSIlya Dryomov {
470319a39dceSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
470419a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
470519a39dceSIlya Dryomov 	int ret = 0;
470619a39dceSIlya Dryomov 
470719a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
470819a39dceSIlya Dryomov 		return -EPERM;
470919a39dceSIlya Dryomov 
471019a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
471119a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
471219a39dceSIlya Dryomov 		ret = -ENOTCONN;
471319a39dceSIlya Dryomov 		goto out;
471419a39dceSIlya Dryomov 	}
471519a39dceSIlya Dryomov 
471619a39dceSIlya Dryomov 	bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
471719a39dceSIlya Dryomov 	if (!bargs) {
471819a39dceSIlya Dryomov 		ret = -ENOMEM;
471919a39dceSIlya Dryomov 		goto out;
472019a39dceSIlya Dryomov 	}
472119a39dceSIlya Dryomov 
472219a39dceSIlya Dryomov 	update_ioctl_balance_args(fs_info, 1, bargs);
472319a39dceSIlya Dryomov 
472419a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
472519a39dceSIlya Dryomov 		ret = -EFAULT;
472619a39dceSIlya Dryomov 
472719a39dceSIlya Dryomov 	kfree(bargs);
472819a39dceSIlya Dryomov out:
472919a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
473019a39dceSIlya Dryomov 	return ret;
473119a39dceSIlya Dryomov }
473219a39dceSIlya Dryomov 
4733905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
47345d13a37bSArne Jansen {
4735496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
47365d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
47375d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
47385d13a37bSArne Jansen 	int ret;
47395d13a37bSArne Jansen 	int err;
47405d13a37bSArne Jansen 
47415d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
47425d13a37bSArne Jansen 		return -EPERM;
47435d13a37bSArne Jansen 
4744905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4745905b0ddaSMiao Xie 	if (ret)
4746905b0ddaSMiao Xie 		return ret;
47475d13a37bSArne Jansen 
47485d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4749905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4750905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4751905b0ddaSMiao Xie 		goto drop_write;
4752905b0ddaSMiao Xie 	}
47535d13a37bSArne Jansen 
47547708f029SWang Shilong 	down_write(&root->fs_info->subvol_sem);
475592f183aaSWang Shilong 	trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
47565d13a37bSArne Jansen 	if (IS_ERR(trans)) {
47575d13a37bSArne Jansen 		ret = PTR_ERR(trans);
47585d13a37bSArne Jansen 		goto out;
47595d13a37bSArne Jansen 	}
47605d13a37bSArne Jansen 
47615d13a37bSArne Jansen 	switch (sa->cmd) {
47625d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
47635d13a37bSArne Jansen 		ret = btrfs_quota_enable(trans, root->fs_info);
47645d13a37bSArne Jansen 		break;
47655d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
47665d13a37bSArne Jansen 		ret = btrfs_quota_disable(trans, root->fs_info);
47675d13a37bSArne Jansen 		break;
47685d13a37bSArne Jansen 	default:
47695d13a37bSArne Jansen 		ret = -EINVAL;
47705d13a37bSArne Jansen 		break;
47715d13a37bSArne Jansen 	}
47725d13a37bSArne Jansen 
477392f183aaSWang Shilong 	err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
47745d13a37bSArne Jansen 	if (err && !ret)
47755d13a37bSArne Jansen 		ret = err;
47765d13a37bSArne Jansen out:
47775d13a37bSArne Jansen 	kfree(sa);
47787708f029SWang Shilong 	up_write(&root->fs_info->subvol_sem);
4779905b0ddaSMiao Xie drop_write:
4780905b0ddaSMiao Xie 	mnt_drop_write_file(file);
47815d13a37bSArne Jansen 	return ret;
47825d13a37bSArne Jansen }
47835d13a37bSArne Jansen 
4784905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
47855d13a37bSArne Jansen {
4786496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
47875d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
47885d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
47895d13a37bSArne Jansen 	int ret;
47905d13a37bSArne Jansen 	int err;
47915d13a37bSArne Jansen 
47925d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
47935d13a37bSArne Jansen 		return -EPERM;
47945d13a37bSArne Jansen 
4795905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4796905b0ddaSMiao Xie 	if (ret)
4797905b0ddaSMiao Xie 		return ret;
47985d13a37bSArne Jansen 
47995d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4800905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4801905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4802905b0ddaSMiao Xie 		goto drop_write;
4803905b0ddaSMiao Xie 	}
48045d13a37bSArne Jansen 
48055d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
48065d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48075d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48085d13a37bSArne Jansen 		goto out;
48095d13a37bSArne Jansen 	}
48105d13a37bSArne Jansen 
48115d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
48125d13a37bSArne Jansen 	if (sa->assign) {
48135d13a37bSArne Jansen 		ret = btrfs_add_qgroup_relation(trans, root->fs_info,
48145d13a37bSArne Jansen 						sa->src, sa->dst);
48155d13a37bSArne Jansen 	} else {
48165d13a37bSArne Jansen 		ret = btrfs_del_qgroup_relation(trans, root->fs_info,
48175d13a37bSArne Jansen 						sa->src, sa->dst);
48185d13a37bSArne Jansen 	}
48195d13a37bSArne Jansen 
4820e082f563SQu Wenruo 	/* update qgroup status and info */
4821e082f563SQu Wenruo 	err = btrfs_run_qgroups(trans, root->fs_info);
4822e082f563SQu Wenruo 	if (err < 0)
4823e082f563SQu Wenruo 		btrfs_error(root->fs_info, ret,
4824e082f563SQu Wenruo 			    "failed to update qgroup status and info\n");
48255d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
48265d13a37bSArne Jansen 	if (err && !ret)
48275d13a37bSArne Jansen 		ret = err;
48285d13a37bSArne Jansen 
48295d13a37bSArne Jansen out:
48305d13a37bSArne Jansen 	kfree(sa);
4831905b0ddaSMiao Xie drop_write:
4832905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48335d13a37bSArne Jansen 	return ret;
48345d13a37bSArne Jansen }
48355d13a37bSArne Jansen 
4836905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
48375d13a37bSArne Jansen {
4838496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
48395d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
48405d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48415d13a37bSArne Jansen 	int ret;
48425d13a37bSArne Jansen 	int err;
48435d13a37bSArne Jansen 
48445d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48455d13a37bSArne Jansen 		return -EPERM;
48465d13a37bSArne Jansen 
4847905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4848905b0ddaSMiao Xie 	if (ret)
4849905b0ddaSMiao Xie 		return ret;
48505d13a37bSArne Jansen 
48515d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4852905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4853905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4854905b0ddaSMiao Xie 		goto drop_write;
4855905b0ddaSMiao Xie 	}
48565d13a37bSArne Jansen 
4857d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4858d86e56cfSMiao Xie 		ret = -EINVAL;
4859d86e56cfSMiao Xie 		goto out;
4860d86e56cfSMiao Xie 	}
4861d86e56cfSMiao Xie 
48625d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
48635d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48645d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48655d13a37bSArne Jansen 		goto out;
48665d13a37bSArne Jansen 	}
48675d13a37bSArne Jansen 
48685d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
48695d13a37bSArne Jansen 	if (sa->create) {
48704087cf24SDongsheng Yang 		ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid);
48715d13a37bSArne Jansen 	} else {
48725d13a37bSArne Jansen 		ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
48735d13a37bSArne Jansen 	}
48745d13a37bSArne Jansen 
48755d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
48765d13a37bSArne Jansen 	if (err && !ret)
48775d13a37bSArne Jansen 		ret = err;
48785d13a37bSArne Jansen 
48795d13a37bSArne Jansen out:
48805d13a37bSArne Jansen 	kfree(sa);
4881905b0ddaSMiao Xie drop_write:
4882905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48835d13a37bSArne Jansen 	return ret;
48845d13a37bSArne Jansen }
48855d13a37bSArne Jansen 
4886905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
48875d13a37bSArne Jansen {
4888496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
48895d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
48905d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48915d13a37bSArne Jansen 	int ret;
48925d13a37bSArne Jansen 	int err;
48935d13a37bSArne Jansen 	u64 qgroupid;
48945d13a37bSArne Jansen 
48955d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48965d13a37bSArne Jansen 		return -EPERM;
48975d13a37bSArne Jansen 
4898905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4899905b0ddaSMiao Xie 	if (ret)
4900905b0ddaSMiao Xie 		return ret;
49015d13a37bSArne Jansen 
49025d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4903905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4904905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4905905b0ddaSMiao Xie 		goto drop_write;
4906905b0ddaSMiao Xie 	}
49075d13a37bSArne Jansen 
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 	qgroupid = sa->qgroupid;
49155d13a37bSArne Jansen 	if (!qgroupid) {
49165d13a37bSArne Jansen 		/* take the current subvol as qgroup */
49175d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
49185d13a37bSArne Jansen 	}
49195d13a37bSArne Jansen 
49205d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
49215d13a37bSArne Jansen 	ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
49225d13a37bSArne Jansen 
49235d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
49245d13a37bSArne Jansen 	if (err && !ret)
49255d13a37bSArne Jansen 		ret = err;
49265d13a37bSArne Jansen 
49275d13a37bSArne Jansen out:
49285d13a37bSArne Jansen 	kfree(sa);
4929905b0ddaSMiao Xie drop_write:
4930905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49315d13a37bSArne Jansen 	return ret;
49325d13a37bSArne Jansen }
49335d13a37bSArne Jansen 
49342f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
49352f232036SJan Schmidt {
49366d0379ecSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
49372f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
49382f232036SJan Schmidt 	int ret;
49392f232036SJan Schmidt 
49402f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
49412f232036SJan Schmidt 		return -EPERM;
49422f232036SJan Schmidt 
49432f232036SJan Schmidt 	ret = mnt_want_write_file(file);
49442f232036SJan Schmidt 	if (ret)
49452f232036SJan Schmidt 		return ret;
49462f232036SJan Schmidt 
49472f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
49482f232036SJan Schmidt 	if (IS_ERR(qsa)) {
49492f232036SJan Schmidt 		ret = PTR_ERR(qsa);
49502f232036SJan Schmidt 		goto drop_write;
49512f232036SJan Schmidt 	}
49522f232036SJan Schmidt 
49532f232036SJan Schmidt 	if (qsa->flags) {
49542f232036SJan Schmidt 		ret = -EINVAL;
49552f232036SJan Schmidt 		goto out;
49562f232036SJan Schmidt 	}
49572f232036SJan Schmidt 
49582f232036SJan Schmidt 	ret = btrfs_qgroup_rescan(root->fs_info);
49592f232036SJan Schmidt 
49602f232036SJan Schmidt out:
49612f232036SJan Schmidt 	kfree(qsa);
49622f232036SJan Schmidt drop_write:
49632f232036SJan Schmidt 	mnt_drop_write_file(file);
49642f232036SJan Schmidt 	return ret;
49652f232036SJan Schmidt }
49662f232036SJan Schmidt 
49672f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
49682f232036SJan Schmidt {
49696d0379ecSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
49702f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
49712f232036SJan Schmidt 	int ret = 0;
49722f232036SJan Schmidt 
49732f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
49742f232036SJan Schmidt 		return -EPERM;
49752f232036SJan Schmidt 
49762f232036SJan Schmidt 	qsa = kzalloc(sizeof(*qsa), GFP_NOFS);
49772f232036SJan Schmidt 	if (!qsa)
49782f232036SJan Schmidt 		return -ENOMEM;
49792f232036SJan Schmidt 
49802f232036SJan Schmidt 	if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
49812f232036SJan Schmidt 		qsa->flags = 1;
49822f232036SJan Schmidt 		qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
49832f232036SJan Schmidt 	}
49842f232036SJan Schmidt 
49852f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
49862f232036SJan Schmidt 		ret = -EFAULT;
49872f232036SJan Schmidt 
49882f232036SJan Schmidt 	kfree(qsa);
49892f232036SJan Schmidt 	return ret;
49902f232036SJan Schmidt }
49912f232036SJan Schmidt 
499257254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
499357254b6eSJan Schmidt {
499454563d41SAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
499557254b6eSJan Schmidt 
499657254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
499757254b6eSJan Schmidt 		return -EPERM;
499857254b6eSJan Schmidt 
499957254b6eSJan Schmidt 	return btrfs_qgroup_wait_for_completion(root->fs_info);
500057254b6eSJan Schmidt }
500157254b6eSJan Schmidt 
5002abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
5003abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
50048ea05e3aSAlexander Block {
5005496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
50068ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
50078ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
50088ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
50098ea05e3aSAlexander Block 	struct timespec ct = CURRENT_TIME;
50108ea05e3aSAlexander Block 	int ret = 0;
5011dd5f9615SStefan Behrens 	int received_uuid_changed;
50128ea05e3aSAlexander Block 
5013bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
5014bd60ea0fSDavid Sterba 		return -EPERM;
5015bd60ea0fSDavid Sterba 
50168ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
50178ea05e3aSAlexander Block 	if (ret < 0)
50188ea05e3aSAlexander Block 		return ret;
50198ea05e3aSAlexander Block 
50208ea05e3aSAlexander Block 	down_write(&root->fs_info->subvol_sem);
50218ea05e3aSAlexander Block 
50228ea05e3aSAlexander Block 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
50238ea05e3aSAlexander Block 		ret = -EINVAL;
50248ea05e3aSAlexander Block 		goto out;
50258ea05e3aSAlexander Block 	}
50268ea05e3aSAlexander Block 
50278ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
50288ea05e3aSAlexander Block 		ret = -EROFS;
50298ea05e3aSAlexander Block 		goto out;
50308ea05e3aSAlexander Block 	}
50318ea05e3aSAlexander Block 
5032dd5f9615SStefan Behrens 	/*
5033dd5f9615SStefan Behrens 	 * 1 - root item
5034dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5035dd5f9615SStefan Behrens 	 */
5036dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
50378ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
50388ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
50398ea05e3aSAlexander Block 		trans = NULL;
50408ea05e3aSAlexander Block 		goto out;
50418ea05e3aSAlexander Block 	}
50428ea05e3aSAlexander Block 
50438ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
50448ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
50458ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
50468ea05e3aSAlexander Block 
5047dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5048dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5049dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5050dd5f9615SStefan Behrens 	    !btrfs_is_empty_uuid(root_item->received_uuid))
5051dd5f9615SStefan Behrens 		btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
5052dd5f9615SStefan Behrens 				    root_item->received_uuid,
5053dd5f9615SStefan Behrens 				    BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5054dd5f9615SStefan Behrens 				    root->root_key.objectid);
50558ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
50568ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
50578ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
50583cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
50593cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
50603cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
50613cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
50628ea05e3aSAlexander Block 
50638ea05e3aSAlexander Block 	ret = btrfs_update_root(trans, root->fs_info->tree_root,
50648ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
50658ea05e3aSAlexander Block 	if (ret < 0) {
50668ea05e3aSAlexander Block 		btrfs_end_transaction(trans, root);
50678ea05e3aSAlexander Block 		goto out;
5068dd5f9615SStefan Behrens 	}
5069dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5070dd5f9615SStefan Behrens 		ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
5071dd5f9615SStefan Behrens 					  sa->uuid,
5072dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5073dd5f9615SStefan Behrens 					  root->root_key.objectid);
5074dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
5075dd5f9615SStefan Behrens 			btrfs_abort_transaction(trans, root, ret);
5076dd5f9615SStefan Behrens 			goto out;
5077dd5f9615SStefan Behrens 		}
5078dd5f9615SStefan Behrens 	}
50798ea05e3aSAlexander Block 	ret = btrfs_commit_transaction(trans, root);
5080dd5f9615SStefan Behrens 	if (ret < 0) {
5081dd5f9615SStefan Behrens 		btrfs_abort_transaction(trans, root, ret);
50828ea05e3aSAlexander Block 		goto out;
50838ea05e3aSAlexander Block 	}
50848ea05e3aSAlexander Block 
5085abccd00fSHugo Mills out:
5086abccd00fSHugo Mills 	up_write(&root->fs_info->subvol_sem);
5087abccd00fSHugo Mills 	mnt_drop_write_file(file);
5088abccd00fSHugo Mills 	return ret;
5089abccd00fSHugo Mills }
5090abccd00fSHugo Mills 
5091abccd00fSHugo Mills #ifdef CONFIG_64BIT
5092abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5093abccd00fSHugo Mills 						void __user *arg)
5094abccd00fSHugo Mills {
5095abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5096abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5097abccd00fSHugo Mills 	int ret = 0;
5098abccd00fSHugo Mills 
5099abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
5100abccd00fSHugo Mills 	if (IS_ERR(args32)) {
5101abccd00fSHugo Mills 		ret = PTR_ERR(args32);
5102abccd00fSHugo Mills 		args32 = NULL;
5103abccd00fSHugo Mills 		goto out;
5104abccd00fSHugo Mills 	}
5105abccd00fSHugo Mills 
5106abccd00fSHugo Mills 	args64 = kmalloc(sizeof(*args64), GFP_NOFS);
510784dbeb87SDan Carpenter 	if (!args64) {
510884dbeb87SDan Carpenter 		ret = -ENOMEM;
5109abccd00fSHugo Mills 		goto out;
5110abccd00fSHugo Mills 	}
5111abccd00fSHugo Mills 
5112abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5113abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5114abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5115abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5116abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5117abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5118abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5119abccd00fSHugo Mills 	args64->flags = args32->flags;
5120abccd00fSHugo Mills 
5121abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5122abccd00fSHugo Mills 	if (ret)
5123abccd00fSHugo Mills 		goto out;
5124abccd00fSHugo Mills 
5125abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5126abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5127abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5128abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5129abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5130abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5131abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5132abccd00fSHugo Mills 	args32->flags = args64->flags;
5133abccd00fSHugo Mills 
5134abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5135abccd00fSHugo Mills 	if (ret)
5136abccd00fSHugo Mills 		ret = -EFAULT;
5137abccd00fSHugo Mills 
5138abccd00fSHugo Mills out:
5139abccd00fSHugo Mills 	kfree(args32);
5140abccd00fSHugo Mills 	kfree(args64);
5141abccd00fSHugo Mills 	return ret;
5142abccd00fSHugo Mills }
5143abccd00fSHugo Mills #endif
5144abccd00fSHugo Mills 
5145abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5146abccd00fSHugo Mills 					    void __user *arg)
5147abccd00fSHugo Mills {
5148abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5149abccd00fSHugo Mills 	int ret = 0;
5150abccd00fSHugo Mills 
5151abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
5152abccd00fSHugo Mills 	if (IS_ERR(sa)) {
5153abccd00fSHugo Mills 		ret = PTR_ERR(sa);
5154abccd00fSHugo Mills 		sa = NULL;
5155abccd00fSHugo Mills 		goto out;
5156abccd00fSHugo Mills 	}
5157abccd00fSHugo Mills 
5158abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5159abccd00fSHugo Mills 
5160abccd00fSHugo Mills 	if (ret)
5161abccd00fSHugo Mills 		goto out;
5162abccd00fSHugo Mills 
51638ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
51648ea05e3aSAlexander Block 	if (ret)
51658ea05e3aSAlexander Block 		ret = -EFAULT;
51668ea05e3aSAlexander Block 
51678ea05e3aSAlexander Block out:
51688ea05e3aSAlexander Block 	kfree(sa);
51698ea05e3aSAlexander Block 	return ret;
51708ea05e3aSAlexander Block }
51718ea05e3aSAlexander Block 
5172867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5173867ab667Sjeff.liu {
51746d0379ecSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5175a1b83ac5SAnand Jain 	size_t len;
5176867ab667Sjeff.liu 	int ret;
5177a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5178a1b83ac5SAnand Jain 
5179a1b83ac5SAnand Jain 	spin_lock(&root->fs_info->super_lock);
5180a1b83ac5SAnand Jain 	memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5181a1b83ac5SAnand Jain 	spin_unlock(&root->fs_info->super_lock);
5182a1b83ac5SAnand Jain 
5183a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5184867ab667Sjeff.liu 
5185867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
5186efe120a0SFrank Holton 		btrfs_warn(root->fs_info,
5187efe120a0SFrank Holton 			"label is too long, return the first %zu bytes", --len);
5188867ab667Sjeff.liu 	}
5189867ab667Sjeff.liu 
5190867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5191867ab667Sjeff.liu 
5192867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5193867ab667Sjeff.liu }
5194867ab667Sjeff.liu 
5195a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5196a8bfd4abSjeff.liu {
51976d0379ecSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
5198a8bfd4abSjeff.liu 	struct btrfs_super_block *super_block = root->fs_info->super_copy;
5199a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5200a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5201a8bfd4abSjeff.liu 	int ret;
5202a8bfd4abSjeff.liu 
5203a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5204a8bfd4abSjeff.liu 		return -EPERM;
5205a8bfd4abSjeff.liu 
5206a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5207a8bfd4abSjeff.liu 		return -EFAULT;
5208a8bfd4abSjeff.liu 
5209a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
5210efe120a0SFrank Holton 		btrfs_err(root->fs_info, "unable to set label with more than %d bytes",
5211a8bfd4abSjeff.liu 		       BTRFS_LABEL_SIZE - 1);
5212a8bfd4abSjeff.liu 		return -EINVAL;
5213a8bfd4abSjeff.liu 	}
5214a8bfd4abSjeff.liu 
5215a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5216a8bfd4abSjeff.liu 	if (ret)
5217a8bfd4abSjeff.liu 		return ret;
5218a8bfd4abSjeff.liu 
5219a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5220a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5221a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5222a8bfd4abSjeff.liu 		goto out_unlock;
5223a8bfd4abSjeff.liu 	}
5224a8bfd4abSjeff.liu 
5225a1b83ac5SAnand Jain 	spin_lock(&root->fs_info->super_lock);
5226a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
5227a1b83ac5SAnand Jain 	spin_unlock(&root->fs_info->super_lock);
5228d0270acaSJeff Mahoney 	ret = btrfs_commit_transaction(trans, root);
5229a8bfd4abSjeff.liu 
5230a8bfd4abSjeff.liu out_unlock:
5231a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5232a8bfd4abSjeff.liu 	return ret;
5233a8bfd4abSjeff.liu }
5234a8bfd4abSjeff.liu 
52352eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
52362eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
52372eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
52382eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
52392eaa055fSJeff Mahoney 
52402eaa055fSJeff Mahoney static int btrfs_ioctl_get_supported_features(struct file *file,
52412eaa055fSJeff Mahoney 					      void __user *arg)
52422eaa055fSJeff Mahoney {
52432eaa055fSJeff Mahoney 	static struct btrfs_ioctl_feature_flags features[3] = {
52442eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
52452eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
52462eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
52472eaa055fSJeff Mahoney 	};
52482eaa055fSJeff Mahoney 
52492eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
52502eaa055fSJeff Mahoney 		return -EFAULT;
52512eaa055fSJeff Mahoney 
52522eaa055fSJeff Mahoney 	return 0;
52532eaa055fSJeff Mahoney }
52542eaa055fSJeff Mahoney 
52552eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
52562eaa055fSJeff Mahoney {
52572eaa055fSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
52582eaa055fSJeff Mahoney 	struct btrfs_super_block *super_block = root->fs_info->super_copy;
52592eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
52602eaa055fSJeff Mahoney 
52612eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
52622eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
52632eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
52642eaa055fSJeff Mahoney 
52652eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
52662eaa055fSJeff Mahoney 		return -EFAULT;
52672eaa055fSJeff Mahoney 
52682eaa055fSJeff Mahoney 	return 0;
52692eaa055fSJeff Mahoney }
52702eaa055fSJeff Mahoney 
52713b02a68aSJeff Mahoney static int check_feature_bits(struct btrfs_root *root,
52723b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
52732eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
52742eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
52752eaa055fSJeff Mahoney {
52763b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
52773b02a68aSJeff Mahoney 	char *names;
52782eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
52792eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
52802eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
52812eaa055fSJeff Mahoney 
52822eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
52832eaa055fSJeff Mahoney 	if (unsupported) {
52843b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
52853b02a68aSJeff Mahoney 		if (names) {
52863b02a68aSJeff Mahoney 			btrfs_warn(root->fs_info,
52873b02a68aSJeff Mahoney 			   "this kernel does not support the %s feature bit%s",
52883b02a68aSJeff Mahoney 			   names, strchr(names, ',') ? "s" : "");
52893b02a68aSJeff Mahoney 			kfree(names);
52903b02a68aSJeff Mahoney 		} else
52912eaa055fSJeff Mahoney 			btrfs_warn(root->fs_info,
52922eaa055fSJeff Mahoney 			   "this kernel does not support %s bits 0x%llx",
52932eaa055fSJeff Mahoney 			   type, unsupported);
52942eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
52952eaa055fSJeff Mahoney 	}
52962eaa055fSJeff Mahoney 
52972eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
52982eaa055fSJeff Mahoney 	if (disallowed) {
52993b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
53003b02a68aSJeff Mahoney 		if (names) {
53013b02a68aSJeff Mahoney 			btrfs_warn(root->fs_info,
53023b02a68aSJeff Mahoney 			   "can't set the %s feature bit%s while mounted",
53033b02a68aSJeff Mahoney 			   names, strchr(names, ',') ? "s" : "");
53043b02a68aSJeff Mahoney 			kfree(names);
53053b02a68aSJeff Mahoney 		} else
53062eaa055fSJeff Mahoney 			btrfs_warn(root->fs_info,
53072eaa055fSJeff Mahoney 			   "can't set %s bits 0x%llx while mounted",
53082eaa055fSJeff Mahoney 			   type, disallowed);
53092eaa055fSJeff Mahoney 		return -EPERM;
53102eaa055fSJeff Mahoney 	}
53112eaa055fSJeff Mahoney 
53122eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
53132eaa055fSJeff Mahoney 	if (disallowed) {
53143b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
53153b02a68aSJeff Mahoney 		if (names) {
53163b02a68aSJeff Mahoney 			btrfs_warn(root->fs_info,
53173b02a68aSJeff Mahoney 			   "can't clear the %s feature bit%s while mounted",
53183b02a68aSJeff Mahoney 			   names, strchr(names, ',') ? "s" : "");
53193b02a68aSJeff Mahoney 			kfree(names);
53203b02a68aSJeff Mahoney 		} else
53212eaa055fSJeff Mahoney 			btrfs_warn(root->fs_info,
53222eaa055fSJeff Mahoney 			   "can't clear %s bits 0x%llx while mounted",
53232eaa055fSJeff Mahoney 			   type, disallowed);
53242eaa055fSJeff Mahoney 		return -EPERM;
53252eaa055fSJeff Mahoney 	}
53262eaa055fSJeff Mahoney 
53272eaa055fSJeff Mahoney 	return 0;
53282eaa055fSJeff Mahoney }
53292eaa055fSJeff Mahoney 
53302eaa055fSJeff Mahoney #define check_feature(root, change_mask, flags, mask_base)	\
53313b02a68aSJeff Mahoney check_feature_bits(root, FEAT_##mask_base, change_mask, flags,	\
53322eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
53332eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
53342eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
53352eaa055fSJeff Mahoney 
53362eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
53372eaa055fSJeff Mahoney {
53382eaa055fSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
53392eaa055fSJeff Mahoney 	struct btrfs_super_block *super_block = root->fs_info->super_copy;
53402eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
53412eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
53422eaa055fSJeff Mahoney 	u64 newflags;
53432eaa055fSJeff Mahoney 	int ret;
53442eaa055fSJeff Mahoney 
53452eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
53462eaa055fSJeff Mahoney 		return -EPERM;
53472eaa055fSJeff Mahoney 
53482eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
53492eaa055fSJeff Mahoney 		return -EFAULT;
53502eaa055fSJeff Mahoney 
53512eaa055fSJeff Mahoney 	/* Nothing to do */
53522eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
53532eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
53542eaa055fSJeff Mahoney 		return 0;
53552eaa055fSJeff Mahoney 
53562eaa055fSJeff Mahoney 	ret = check_feature(root, flags[0].compat_flags,
53572eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
53582eaa055fSJeff Mahoney 	if (ret)
53592eaa055fSJeff Mahoney 		return ret;
53602eaa055fSJeff Mahoney 
53612eaa055fSJeff Mahoney 	ret = check_feature(root, flags[0].compat_ro_flags,
53622eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
53632eaa055fSJeff Mahoney 	if (ret)
53642eaa055fSJeff Mahoney 		return ret;
53652eaa055fSJeff Mahoney 
53662eaa055fSJeff Mahoney 	ret = check_feature(root, flags[0].incompat_flags,
53672eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
53682eaa055fSJeff Mahoney 	if (ret)
53692eaa055fSJeff Mahoney 		return ret;
53702eaa055fSJeff Mahoney 
53718051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
53722eaa055fSJeff Mahoney 	if (IS_ERR(trans))
53732eaa055fSJeff Mahoney 		return PTR_ERR(trans);
53742eaa055fSJeff Mahoney 
53752eaa055fSJeff Mahoney 	spin_lock(&root->fs_info->super_lock);
53762eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
53772eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
53782eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
53792eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
53802eaa055fSJeff Mahoney 
53812eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
53822eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
53832eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
53842eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
53852eaa055fSJeff Mahoney 
53862eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
53872eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
53882eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
53892eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
53902eaa055fSJeff Mahoney 	spin_unlock(&root->fs_info->super_lock);
53912eaa055fSJeff Mahoney 
5392d0270acaSJeff Mahoney 	return btrfs_commit_transaction(trans, root);
53932eaa055fSJeff Mahoney }
53942eaa055fSJeff Mahoney 
5395f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5396f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5397f46b5a66SChristoph Hellwig {
5398496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
53994bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5400f46b5a66SChristoph Hellwig 
5401f46b5a66SChristoph Hellwig 	switch (cmd) {
54026cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
54036cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
54046cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
54056cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
54066cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
54076cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5408f7039b1dSLi Dongyang 	case FITRIM:
5409f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5410f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5411fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5412fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5413fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
54143de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5415fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
54166f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
54176f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
541876dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
541976dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
54200caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
54210caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
54220caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
54230caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
54246ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
54256ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5426f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
54271e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
54281e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
54291e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5430f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5431198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5432f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
54334bcabaa3SChristoph Hellwig 		return btrfs_ioctl_add_dev(root, argp);
5434f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5435da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
5436475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
5437475f6387SJan Schmidt 		return btrfs_ioctl_fs_info(root, argp);
5438475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
5439475f6387SJan Schmidt 		return btrfs_ioctl_dev_info(root, argp);
5440f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
54419ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5442f46b5a66SChristoph Hellwig 	case BTRFS_IOC_CLONE:
5443c5c9cd4dSSage Weil 		return btrfs_ioctl_clone(file, arg, 0, 0, 0);
5444c5c9cd4dSSage Weil 	case BTRFS_IOC_CLONE_RANGE:
54457a865e8aSChristoph Hellwig 		return btrfs_ioctl_clone_range(file, argp);
5446f46b5a66SChristoph Hellwig 	case BTRFS_IOC_TRANS_START:
5447f46b5a66SChristoph Hellwig 		return btrfs_ioctl_trans_start(file);
5448f46b5a66SChristoph Hellwig 	case BTRFS_IOC_TRANS_END:
5449f46b5a66SChristoph Hellwig 		return btrfs_ioctl_trans_end(file);
5450ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5451ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5452cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5453cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5454ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5455ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5456d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5457d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5458d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5459d7728c96SJan Schmidt 		return btrfs_ioctl_logical_to_ino(root, argp);
54601406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
54611406e432SJosef Bacik 		return btrfs_ioctl_space_info(root, argp);
54629b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
54639b199859SFilipe David Borba Manana 		int ret;
54649b199859SFilipe David Borba Manana 
54656c255e67SMiao Xie 		ret = btrfs_start_delalloc_roots(root->fs_info, 0, -1);
54669b199859SFilipe David Borba Manana 		if (ret)
54679b199859SFilipe David Borba Manana 			return ret;
5468ddb52f4fSAl Viro 		ret = btrfs_sync_fs(file_inode(file)->i_sb, 1);
54692fad4e83SDavid Sterba 		/*
54702fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
54712fad4e83SDavid Sterba 		 * namely it pokes the cleaner ktread that will start
54722fad4e83SDavid Sterba 		 * processing uncleaned subvols.
54732fad4e83SDavid Sterba 		 */
54742fad4e83SDavid Sterba 		wake_up_process(root->fs_info->transaction_kthread);
54759b199859SFilipe David Borba Manana 		return ret;
54769b199859SFilipe David Borba Manana 	}
547746204592SSage Weil 	case BTRFS_IOC_START_SYNC:
54789a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
547946204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
54809a8c28beSMiao Xie 		return btrfs_ioctl_wait_sync(root, argp);
5481475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5482b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5483475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
5484475f6387SJan Schmidt 		return btrfs_ioctl_scrub_cancel(root, argp);
5485475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
5486475f6387SJan Schmidt 		return btrfs_ioctl_scrub_progress(root, argp);
5487c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
54889ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5489837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
5490837d5b6eSIlya Dryomov 		return btrfs_ioctl_balance_ctl(root, arg);
549119a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
549219a39dceSIlya Dryomov 		return btrfs_ioctl_balance_progress(root, argp);
54938ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
54948ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5495abccd00fSHugo Mills #ifdef CONFIG_64BIT
5496abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5497abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5498abccd00fSHugo Mills #endif
549931db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
550031db9f7cSAlexander Block 		return btrfs_ioctl_send(file, argp);
5501c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
5502b27f7c0cSDavid Sterba 		return btrfs_ioctl_get_dev_stats(root, argp);
55035d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5504905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
55055d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5506905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
55075d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5508905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
55095d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5510905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
55112f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
55122f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
55132f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
55142f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
551557254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
551657254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
55173f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
55183f6bcfbdSStefan Behrens 		return btrfs_ioctl_dev_replace(root, argp);
5519867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5520867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5521a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5522a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
5523416161dbSMark Fasheh 	case BTRFS_IOC_FILE_EXTENT_SAME:
5524416161dbSMark Fasheh 		return btrfs_ioctl_file_extent_same(file, argp);
55252eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
55262eaa055fSJeff Mahoney 		return btrfs_ioctl_get_supported_features(file, argp);
55272eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
55282eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
55292eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
55302eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5531f46b5a66SChristoph Hellwig 	}
5532f46b5a66SChristoph Hellwig 
5533f46b5a66SChristoph Hellwig 	return -ENOTTY;
5534f46b5a66SChristoph Hellwig }
5535