xref: /openbmc/linux/fs/btrfs/ioctl.c (revision 2ff7e61e)
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/compat.h>
37f46b5a66SChristoph Hellwig #include <linux/bit_spinlock.h>
38cb8e7090SChristoph Hellwig #include <linux/security.h>
39f46b5a66SChristoph Hellwig #include <linux/xattr.h>
407ea394f1SYan Zheng #include <linux/vmalloc.h>
415a0e3ad6STejun Heo #include <linux/slab.h>
42f7039b1dSLi Dongyang #include <linux/blkdev.h>
438ea05e3aSAlexander Block #include <linux/uuid.h>
4455e301fdSFilipe Brandenburger #include <linux/btrfs.h>
45416161dbSMark Fasheh #include <linux/uaccess.h>
46f46b5a66SChristoph Hellwig #include "ctree.h"
47f46b5a66SChristoph Hellwig #include "disk-io.h"
48f46b5a66SChristoph Hellwig #include "transaction.h"
49f46b5a66SChristoph Hellwig #include "btrfs_inode.h"
50f46b5a66SChristoph Hellwig #include "print-tree.h"
51f46b5a66SChristoph Hellwig #include "volumes.h"
52925baeddSChris Mason #include "locking.h"
53581bb050SLi Zefan #include "inode-map.h"
54d7728c96SJan Schmidt #include "backref.h"
55606686eeSJosef Bacik #include "rcu-string.h"
5631db9f7cSAlexander Block #include "send.h"
573f6bcfbdSStefan Behrens #include "dev-replace.h"
5863541927SFilipe David Borba Manana #include "props.h"
593b02a68aSJeff Mahoney #include "sysfs.h"
60fcebe456SJosef Bacik #include "qgroup.h"
611ec9a1aeSFilipe Manana #include "tree-log.h"
62ebb8765bSAnand Jain #include "compression.h"
63f46b5a66SChristoph Hellwig 
64abccd00fSHugo Mills #ifdef CONFIG_64BIT
65abccd00fSHugo Mills /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
66abccd00fSHugo Mills  * structures are incorrect, as the timespec structure from userspace
67abccd00fSHugo Mills  * is 4 bytes too small. We define these alternatives here to teach
68abccd00fSHugo Mills  * the kernel about the 32-bit struct packing.
69abccd00fSHugo Mills  */
70abccd00fSHugo Mills struct btrfs_ioctl_timespec_32 {
71abccd00fSHugo Mills 	__u64 sec;
72abccd00fSHugo Mills 	__u32 nsec;
73abccd00fSHugo Mills } __attribute__ ((__packed__));
74abccd00fSHugo Mills 
75abccd00fSHugo Mills struct btrfs_ioctl_received_subvol_args_32 {
76abccd00fSHugo Mills 	char	uuid[BTRFS_UUID_SIZE];	/* in */
77abccd00fSHugo Mills 	__u64	stransid;		/* in */
78abccd00fSHugo Mills 	__u64	rtransid;		/* out */
79abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 stime; /* in */
80abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 rtime; /* out */
81abccd00fSHugo Mills 	__u64	flags;			/* in */
82abccd00fSHugo Mills 	__u64	reserved[16];		/* in */
83abccd00fSHugo Mills } __attribute__ ((__packed__));
84abccd00fSHugo Mills 
85abccd00fSHugo Mills #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
86abccd00fSHugo Mills 				struct btrfs_ioctl_received_subvol_args_32)
87abccd00fSHugo Mills #endif
88abccd00fSHugo Mills 
89abccd00fSHugo Mills 
90416161dbSMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
911c919a5eSMark Fasheh 		       u64 off, u64 olen, u64 olen_aligned, u64 destoff,
921c919a5eSMark Fasheh 		       int no_time_update);
93416161dbSMark Fasheh 
946cbff00fSChristoph Hellwig /* Mask out flags that are inappropriate for the given type of inode. */
956cbff00fSChristoph Hellwig static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
966cbff00fSChristoph Hellwig {
976cbff00fSChristoph Hellwig 	if (S_ISDIR(mode))
986cbff00fSChristoph Hellwig 		return flags;
996cbff00fSChristoph Hellwig 	else if (S_ISREG(mode))
1006cbff00fSChristoph Hellwig 		return flags & ~FS_DIRSYNC_FL;
1016cbff00fSChristoph Hellwig 	else
1026cbff00fSChristoph Hellwig 		return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
1036cbff00fSChristoph Hellwig }
104f46b5a66SChristoph Hellwig 
1056cbff00fSChristoph Hellwig /*
1066cbff00fSChristoph Hellwig  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
1076cbff00fSChristoph Hellwig  */
1086cbff00fSChristoph Hellwig static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
1096cbff00fSChristoph Hellwig {
1106cbff00fSChristoph Hellwig 	unsigned int iflags = 0;
1116cbff00fSChristoph Hellwig 
1126cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_SYNC)
1136cbff00fSChristoph Hellwig 		iflags |= FS_SYNC_FL;
1146cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_IMMUTABLE)
1156cbff00fSChristoph Hellwig 		iflags |= FS_IMMUTABLE_FL;
1166cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_APPEND)
1176cbff00fSChristoph Hellwig 		iflags |= FS_APPEND_FL;
1186cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NODUMP)
1196cbff00fSChristoph Hellwig 		iflags |= FS_NODUMP_FL;
1206cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NOATIME)
1216cbff00fSChristoph Hellwig 		iflags |= FS_NOATIME_FL;
1226cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_DIRSYNC)
1236cbff00fSChristoph Hellwig 		iflags |= FS_DIRSYNC_FL;
124d0092bddSLi Zefan 	if (flags & BTRFS_INODE_NODATACOW)
125d0092bddSLi Zefan 		iflags |= FS_NOCOW_FL;
126d0092bddSLi Zefan 
12713f48dc9SSatoru Takeuchi 	if (flags & BTRFS_INODE_NOCOMPRESS)
128d0092bddSLi Zefan 		iflags |= FS_NOCOMP_FL;
12913f48dc9SSatoru Takeuchi 	else if (flags & BTRFS_INODE_COMPRESS)
13013f48dc9SSatoru Takeuchi 		iflags |= FS_COMPR_FL;
1316cbff00fSChristoph Hellwig 
1326cbff00fSChristoph Hellwig 	return iflags;
1336cbff00fSChristoph Hellwig }
1346cbff00fSChristoph Hellwig 
1356cbff00fSChristoph Hellwig /*
1366cbff00fSChristoph Hellwig  * Update inode->i_flags based on the btrfs internal flags.
1376cbff00fSChristoph Hellwig  */
1386cbff00fSChristoph Hellwig void btrfs_update_iflags(struct inode *inode)
1396cbff00fSChristoph Hellwig {
1406cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
1413cc79392SFilipe Manana 	unsigned int new_fl = 0;
1426cbff00fSChristoph Hellwig 
1436cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_SYNC)
1443cc79392SFilipe Manana 		new_fl |= S_SYNC;
1456cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_IMMUTABLE)
1463cc79392SFilipe Manana 		new_fl |= S_IMMUTABLE;
1476cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_APPEND)
1483cc79392SFilipe Manana 		new_fl |= S_APPEND;
1496cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_NOATIME)
1503cc79392SFilipe Manana 		new_fl |= S_NOATIME;
1516cbff00fSChristoph Hellwig 	if (ip->flags & BTRFS_INODE_DIRSYNC)
1523cc79392SFilipe Manana 		new_fl |= S_DIRSYNC;
1533cc79392SFilipe Manana 
1543cc79392SFilipe Manana 	set_mask_bits(&inode->i_flags,
1553cc79392SFilipe Manana 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
1563cc79392SFilipe Manana 		      new_fl);
1576cbff00fSChristoph Hellwig }
1586cbff00fSChristoph Hellwig 
1596cbff00fSChristoph Hellwig /*
1606cbff00fSChristoph Hellwig  * Inherit flags from the parent inode.
1616cbff00fSChristoph Hellwig  *
162e27425d6SJosef Bacik  * Currently only the compression flags and the cow flags are inherited.
1636cbff00fSChristoph Hellwig  */
1646cbff00fSChristoph Hellwig void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
1656cbff00fSChristoph Hellwig {
1660b4dcea5SChris Mason 	unsigned int flags;
1670b4dcea5SChris Mason 
1680b4dcea5SChris Mason 	if (!dir)
1690b4dcea5SChris Mason 		return;
1700b4dcea5SChris Mason 
1710b4dcea5SChris Mason 	flags = BTRFS_I(dir)->flags;
1726cbff00fSChristoph Hellwig 
173e27425d6SJosef Bacik 	if (flags & BTRFS_INODE_NOCOMPRESS) {
174e27425d6SJosef Bacik 		BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
175e27425d6SJosef Bacik 		BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
176e27425d6SJosef Bacik 	} else if (flags & BTRFS_INODE_COMPRESS) {
177e27425d6SJosef Bacik 		BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
178e27425d6SJosef Bacik 		BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
179e27425d6SJosef Bacik 	}
1806cbff00fSChristoph Hellwig 
181213490b3SLiu Bo 	if (flags & BTRFS_INODE_NODATACOW) {
182e27425d6SJosef Bacik 		BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
183213490b3SLiu Bo 		if (S_ISREG(inode->i_mode))
184213490b3SLiu Bo 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
185213490b3SLiu Bo 	}
186e27425d6SJosef Bacik 
1876cbff00fSChristoph Hellwig 	btrfs_update_iflags(inode);
1886cbff00fSChristoph Hellwig }
1896cbff00fSChristoph Hellwig 
1906cbff00fSChristoph Hellwig static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
1916cbff00fSChristoph Hellwig {
192496ad9aaSAl Viro 	struct btrfs_inode *ip = BTRFS_I(file_inode(file));
1936cbff00fSChristoph Hellwig 	unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
1946cbff00fSChristoph Hellwig 
1956cbff00fSChristoph Hellwig 	if (copy_to_user(arg, &flags, sizeof(flags)))
1966cbff00fSChristoph Hellwig 		return -EFAULT;
1976cbff00fSChristoph Hellwig 	return 0;
1986cbff00fSChristoph Hellwig }
1996cbff00fSChristoph Hellwig 
20075e7cb7fSLiu Bo static int check_flags(unsigned int flags)
20175e7cb7fSLiu Bo {
20275e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
20375e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
20475e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
205e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
206e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
20775e7cb7fSLiu Bo 		return -EOPNOTSUPP;
20875e7cb7fSLiu Bo 
20975e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
21075e7cb7fSLiu Bo 		return -EINVAL;
21175e7cb7fSLiu Bo 
21275e7cb7fSLiu Bo 	return 0;
21375e7cb7fSLiu Bo }
21475e7cb7fSLiu Bo 
2156cbff00fSChristoph Hellwig static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
2166cbff00fSChristoph Hellwig {
217496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2180b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2196cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
2206cbff00fSChristoph Hellwig 	struct btrfs_root *root = ip->root;
2216cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
2226cbff00fSChristoph Hellwig 	unsigned int flags, oldflags;
2236cbff00fSChristoph Hellwig 	int ret;
224f062abf0SLi Zefan 	u64 ip_oldflags;
225f062abf0SLi Zefan 	unsigned int i_oldflags;
2267e97b8daSDavid Sterba 	umode_t mode;
2276cbff00fSChristoph Hellwig 
228bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
229bd60ea0fSDavid Sterba 		return -EPERM;
230bd60ea0fSDavid Sterba 
231b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
232b83cc969SLi Zefan 		return -EROFS;
233b83cc969SLi Zefan 
2346cbff00fSChristoph Hellwig 	if (copy_from_user(&flags, arg, sizeof(flags)))
2356cbff00fSChristoph Hellwig 		return -EFAULT;
2366cbff00fSChristoph Hellwig 
23775e7cb7fSLiu Bo 	ret = check_flags(flags);
23875e7cb7fSLiu Bo 	if (ret)
23975e7cb7fSLiu Bo 		return ret;
2406cbff00fSChristoph Hellwig 
241e7848683SJan Kara 	ret = mnt_want_write_file(file);
242e7848683SJan Kara 	if (ret)
243e7848683SJan Kara 		return ret;
244e7848683SJan Kara 
2455955102cSAl Viro 	inode_lock(inode);
2466cbff00fSChristoph Hellwig 
247f062abf0SLi Zefan 	ip_oldflags = ip->flags;
248f062abf0SLi Zefan 	i_oldflags = inode->i_flags;
2497e97b8daSDavid Sterba 	mode = inode->i_mode;
250f062abf0SLi Zefan 
2516cbff00fSChristoph Hellwig 	flags = btrfs_mask_flags(inode->i_mode, flags);
2526cbff00fSChristoph Hellwig 	oldflags = btrfs_flags_to_ioctl(ip->flags);
2536cbff00fSChristoph Hellwig 	if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
2546cbff00fSChristoph Hellwig 		if (!capable(CAP_LINUX_IMMUTABLE)) {
2556cbff00fSChristoph Hellwig 			ret = -EPERM;
2566cbff00fSChristoph Hellwig 			goto out_unlock;
2576cbff00fSChristoph Hellwig 		}
2586cbff00fSChristoph Hellwig 	}
2596cbff00fSChristoph Hellwig 
2606cbff00fSChristoph Hellwig 	if (flags & FS_SYNC_FL)
2616cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_SYNC;
2626cbff00fSChristoph Hellwig 	else
2636cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_SYNC;
2646cbff00fSChristoph Hellwig 	if (flags & FS_IMMUTABLE_FL)
2656cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_IMMUTABLE;
2666cbff00fSChristoph Hellwig 	else
2676cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_IMMUTABLE;
2686cbff00fSChristoph Hellwig 	if (flags & FS_APPEND_FL)
2696cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_APPEND;
2706cbff00fSChristoph Hellwig 	else
2716cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_APPEND;
2726cbff00fSChristoph Hellwig 	if (flags & FS_NODUMP_FL)
2736cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NODUMP;
2746cbff00fSChristoph Hellwig 	else
2756cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NODUMP;
2766cbff00fSChristoph Hellwig 	if (flags & FS_NOATIME_FL)
2776cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NOATIME;
2786cbff00fSChristoph Hellwig 	else
2796cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NOATIME;
2806cbff00fSChristoph Hellwig 	if (flags & FS_DIRSYNC_FL)
2816cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_DIRSYNC;
2826cbff00fSChristoph Hellwig 	else
2836cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_DIRSYNC;
2847e97b8daSDavid Sterba 	if (flags & FS_NOCOW_FL) {
2857e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2867e97b8daSDavid Sterba 			/*
2877e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2887e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2897e97b8daSDavid Sterba 			 * status of the file and will not set it.
2907e97b8daSDavid Sterba 			 */
2917e97b8daSDavid Sterba 			if (inode->i_size == 0)
2927e97b8daSDavid Sterba 				ip->flags |= BTRFS_INODE_NODATACOW
2937e97b8daSDavid Sterba 					   | BTRFS_INODE_NODATASUM;
2947e97b8daSDavid Sterba 		} else {
295e1e8fb6aSLi Zefan 			ip->flags |= BTRFS_INODE_NODATACOW;
2967e97b8daSDavid Sterba 		}
2977e97b8daSDavid Sterba 	} else {
2987e97b8daSDavid Sterba 		/*
29901327610SNicholas D Steeves 		 * Revert back under same assumptions as above
3007e97b8daSDavid Sterba 		 */
3017e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
3027e97b8daSDavid Sterba 			if (inode->i_size == 0)
3037e97b8daSDavid Sterba 				ip->flags &= ~(BTRFS_INODE_NODATACOW
3047e97b8daSDavid Sterba 				             | BTRFS_INODE_NODATASUM);
3057e97b8daSDavid Sterba 		} else {
306e1e8fb6aSLi Zefan 			ip->flags &= ~BTRFS_INODE_NODATACOW;
3077e97b8daSDavid Sterba 		}
3087e97b8daSDavid Sterba 	}
3096cbff00fSChristoph Hellwig 
31075e7cb7fSLiu Bo 	/*
31175e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
31275e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
31375e7cb7fSLiu Bo 	 * things smaller.
31475e7cb7fSLiu Bo 	 */
31575e7cb7fSLiu Bo 	if (flags & FS_NOCOMP_FL) {
31675e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_COMPRESS;
31775e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_NOCOMPRESS;
31863541927SFilipe David Borba Manana 
31963541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
32063541927SFilipe David Borba Manana 		if (ret && ret != -ENODATA)
32163541927SFilipe David Borba Manana 			goto out_drop;
32275e7cb7fSLiu Bo 	} else if (flags & FS_COMPR_FL) {
32363541927SFilipe David Borba Manana 		const char *comp;
32463541927SFilipe David Borba Manana 
32575e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_COMPRESS;
32675e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
32763541927SFilipe David Borba Manana 
3280b246afaSJeff Mahoney 		if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
32963541927SFilipe David Borba Manana 			comp = "lzo";
33063541927SFilipe David Borba Manana 		else
33163541927SFilipe David Borba Manana 			comp = "zlib";
33263541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression",
33363541927SFilipe David Borba Manana 				     comp, strlen(comp), 0);
33463541927SFilipe David Borba Manana 		if (ret)
33563541927SFilipe David Borba Manana 			goto out_drop;
33663541927SFilipe David Borba Manana 
337ebcb904dSLi Zefan 	} else {
33878a017a2SFilipe Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
33978a017a2SFilipe Manana 		if (ret && ret != -ENODATA)
34078a017a2SFilipe Manana 			goto out_drop;
341ebcb904dSLi Zefan 		ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
34275e7cb7fSLiu Bo 	}
3436cbff00fSChristoph Hellwig 
3444da6f1a3SLi Zefan 	trans = btrfs_start_transaction(root, 1);
345f062abf0SLi Zefan 	if (IS_ERR(trans)) {
346f062abf0SLi Zefan 		ret = PTR_ERR(trans);
347f062abf0SLi Zefan 		goto out_drop;
348f062abf0SLi Zefan 	}
3496cbff00fSChristoph Hellwig 
350306424ccSLi Zefan 	btrfs_update_iflags(inode);
3510c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
352c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3536cbff00fSChristoph Hellwig 	ret = btrfs_update_inode(trans, root, inode);
3546cbff00fSChristoph Hellwig 
3556cbff00fSChristoph Hellwig 	btrfs_end_transaction(trans, root);
356f062abf0SLi Zefan  out_drop:
357f062abf0SLi Zefan 	if (ret) {
358f062abf0SLi Zefan 		ip->flags = ip_oldflags;
359f062abf0SLi Zefan 		inode->i_flags = i_oldflags;
360f062abf0SLi Zefan 	}
3616cbff00fSChristoph Hellwig 
3626cbff00fSChristoph Hellwig  out_unlock:
3635955102cSAl Viro 	inode_unlock(inode);
364e7848683SJan Kara 	mnt_drop_write_file(file);
3652d4e6f6aSliubo 	return ret;
3666cbff00fSChristoph Hellwig }
3676cbff00fSChristoph Hellwig 
3686cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
3696cbff00fSChristoph Hellwig {
370496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3716cbff00fSChristoph Hellwig 
3726cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
3736cbff00fSChristoph Hellwig }
374f46b5a66SChristoph Hellwig 
375f7039b1dSLi Dongyang static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
376f7039b1dSLi Dongyang {
3770b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
3780b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
379f7039b1dSLi Dongyang 	struct btrfs_device *device;
380f7039b1dSLi Dongyang 	struct request_queue *q;
381f7039b1dSLi Dongyang 	struct fstrim_range range;
382f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
383f7039b1dSLi Dongyang 	u64 num_devices = 0;
384815745cfSAl Viro 	u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
385f7039b1dSLi Dongyang 	int ret;
386f7039b1dSLi Dongyang 
387f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
388f7039b1dSLi Dongyang 		return -EPERM;
389f7039b1dSLi Dongyang 
3901f78160cSXiao Guangrong 	rcu_read_lock();
3911f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
3921f78160cSXiao Guangrong 				dev_list) {
393f7039b1dSLi Dongyang 		if (!device->bdev)
394f7039b1dSLi Dongyang 			continue;
395f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
396f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
397f7039b1dSLi Dongyang 			num_devices++;
398f7039b1dSLi Dongyang 			minlen = min((u64)q->limits.discard_granularity,
399f7039b1dSLi Dongyang 				     minlen);
400f7039b1dSLi Dongyang 		}
401f7039b1dSLi Dongyang 	}
4021f78160cSXiao Guangrong 	rcu_read_unlock();
403f4c697e6SLukas Czerner 
404f7039b1dSLi Dongyang 	if (!num_devices)
405f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
406f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
407f7039b1dSLi Dongyang 		return -EFAULT;
408e515c18bSLukas Czerner 	if (range.start > total_bytes ||
409e515c18bSLukas Czerner 	    range.len < fs_info->sb->s_blocksize)
410f4c697e6SLukas Czerner 		return -EINVAL;
411f7039b1dSLi Dongyang 
412f4c697e6SLukas Czerner 	range.len = min(range.len, total_bytes - range.start);
413f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
4142ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
415f7039b1dSLi Dongyang 	if (ret < 0)
416f7039b1dSLi Dongyang 		return ret;
417f7039b1dSLi Dongyang 
418f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
419f7039b1dSLi Dongyang 		return -EFAULT;
420f7039b1dSLi Dongyang 
421f7039b1dSLi Dongyang 	return 0;
422f7039b1dSLi Dongyang }
423f7039b1dSLi Dongyang 
424dd5f9615SStefan Behrens int btrfs_is_empty_uuid(u8 *uuid)
425dd5f9615SStefan Behrens {
42646e0f66aSChris Mason 	int i;
42746e0f66aSChris Mason 
42846e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
42946e0f66aSChris Mason 		if (uuid[i])
43046e0f66aSChris Mason 			return 0;
43146e0f66aSChris Mason 	}
43246e0f66aSChris Mason 	return 1;
433dd5f9615SStefan Behrens }
434dd5f9615SStefan Behrens 
435d5c12070SMiao Xie static noinline int create_subvol(struct inode *dir,
436cb8e7090SChristoph Hellwig 				  struct dentry *dentry,
43772fd032eSSage Weil 				  char *name, int namelen,
4386f72c7e2SArne Jansen 				  u64 *async_transid,
4398696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
440f46b5a66SChristoph Hellwig {
4410b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
442f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
443f46b5a66SChristoph Hellwig 	struct btrfs_key key;
44449a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
445f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
446f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
447d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
44876dda93cSYan, Zheng 	struct btrfs_root *new_root;
449d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
450c2050a45SDeepa Dinamani 	struct timespec cur_time = current_time(dir);
4515662344bSTsutomu Itoh 	struct inode *inode;
452f46b5a66SChristoph Hellwig 	int ret;
453f46b5a66SChristoph Hellwig 	int err;
454f46b5a66SChristoph Hellwig 	u64 objectid;
455f46b5a66SChristoph Hellwig 	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
4563de4586cSChris Mason 	u64 index = 0;
457d5c12070SMiao Xie 	u64 qgroup_reserved;
4588ea05e3aSAlexander Block 	uuid_le new_uuid;
459f46b5a66SChristoph Hellwig 
46049a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
46149a3c4d9SDavid Sterba 	if (!root_item)
46249a3c4d9SDavid Sterba 		return -ENOMEM;
46349a3c4d9SDavid Sterba 
4640b246afaSJeff Mahoney 	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
4652fbe8c8aSAl Viro 	if (ret)
46649a3c4d9SDavid Sterba 		goto fail_free;
4676a912213SJosef Bacik 
468e09fe2d2SQu Wenruo 	/*
469e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
47001327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
471e09fe2d2SQu Wenruo 	 */
47249a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
47349a3c4d9SDavid Sterba 		ret = -ENOSPC;
47449a3c4d9SDavid Sterba 		goto fail_free;
47549a3c4d9SDavid Sterba 	}
476e09fe2d2SQu Wenruo 
477d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4789ed74f2dSJosef Bacik 	/*
479d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
480d5c12070SMiao Xie 	 * of create_snapshot().
4819ed74f2dSJosef Bacik 	 */
482d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
483dd5f9615SStefan Behrens 					       8, &qgroup_reserved, false);
484d5c12070SMiao Xie 	if (ret)
48549a3c4d9SDavid Sterba 		goto fail_free;
486f46b5a66SChristoph Hellwig 
487d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
488d5c12070SMiao Xie 	if (IS_ERR(trans)) {
489d5c12070SMiao Xie 		ret = PTR_ERR(trans);
4902ff7e61eSJeff Mahoney 		btrfs_subvolume_release_metadata(fs_info, &block_rsv,
491de6e8200SLiu Bo 						 qgroup_reserved);
49249a3c4d9SDavid Sterba 		goto fail_free;
493d5c12070SMiao Xie 	}
494d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
495d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
496f46b5a66SChristoph Hellwig 
4970b246afaSJeff Mahoney 	ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
4986f72c7e2SArne Jansen 	if (ret)
4996f72c7e2SArne Jansen 		goto fail;
5006f72c7e2SArne Jansen 
5014d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
5028e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
5038e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
5048e8a1e31SJosef Bacik 		goto fail;
5058e8a1e31SJosef Bacik 	}
506f46b5a66SChristoph Hellwig 
507b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
508f46b5a66SChristoph Hellwig 	btrfs_set_header_bytenr(leaf, leaf->start);
509f46b5a66SChristoph Hellwig 	btrfs_set_header_generation(leaf, trans->transid);
5105d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
511f46b5a66SChristoph Hellwig 	btrfs_set_header_owner(leaf, objectid);
512f46b5a66SChristoph Hellwig 
5130b246afaSJeff Mahoney 	write_extent_buffer_fsid(leaf, fs_info->fsid);
5140b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
515f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
516f46b5a66SChristoph Hellwig 
51749a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
5183cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
5193cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
5203cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
521da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
5220b246afaSJeff Mahoney 				     fs_info->nodesize);
5233cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
524f46b5a66SChristoph Hellwig 
52549a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
52649a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
5273cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
52808fe4db1SLi Zefan 
52949a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
53049a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
53149a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
53249a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
53349a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
53449a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
535f46b5a66SChristoph Hellwig 
53649a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
53749a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
5388ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
53949a3c4d9SDavid Sterba 	memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
54049a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
54149a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
54249a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
54349a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
54449a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
545f46b5a66SChristoph Hellwig 
546925baeddSChris Mason 	btrfs_tree_unlock(leaf);
547f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
548f46b5a66SChristoph Hellwig 	leaf = NULL;
549f46b5a66SChristoph Hellwig 
55049a3c4d9SDavid Sterba 	btrfs_set_root_dirid(root_item, new_dirid);
551f46b5a66SChristoph Hellwig 
552f46b5a66SChristoph Hellwig 	key.objectid = objectid;
5535d4f98a2SYan Zheng 	key.offset = 0;
554962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
5550b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
55649a3c4d9SDavid Sterba 				root_item);
557f46b5a66SChristoph Hellwig 	if (ret)
558f46b5a66SChristoph Hellwig 		goto fail;
559f46b5a66SChristoph Hellwig 
56076dda93cSYan, Zheng 	key.offset = (u64)-1;
5610b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &key);
56279787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
56379787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
56466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
56579787eaaSJeff Mahoney 		goto fail;
56679787eaaSJeff Mahoney 	}
56776dda93cSYan, Zheng 
56876dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
56976dda93cSYan, Zheng 
57063541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
571ce598979SMark Fasheh 	if (ret) {
572ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
57366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
574ce598979SMark Fasheh 		goto fail;
575ce598979SMark Fasheh 	}
576ce598979SMark Fasheh 
577f32e48e9SChandan Rajendra 	mutex_lock(&new_root->objectid_mutex);
578f32e48e9SChandan Rajendra 	new_root->highest_objectid = new_dirid;
579f32e48e9SChandan Rajendra 	mutex_unlock(&new_root->objectid_mutex);
580f32e48e9SChandan Rajendra 
581f46b5a66SChristoph Hellwig 	/*
582f46b5a66SChristoph Hellwig 	 * insert the directory item
583f46b5a66SChristoph Hellwig 	 */
5843de4586cSChris Mason 	ret = btrfs_set_inode_index(dir, &index);
58579787eaaSJeff Mahoney 	if (ret) {
58666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
58779787eaaSJeff Mahoney 		goto fail;
58879787eaaSJeff Mahoney 	}
5893de4586cSChris Mason 
5903de4586cSChris Mason 	ret = btrfs_insert_dir_item(trans, root,
59116cdcec7SMiao Xie 				    name, namelen, dir, &key,
5923de4586cSChris Mason 				    BTRFS_FT_DIR, index);
59379787eaaSJeff Mahoney 	if (ret) {
59466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
595f46b5a66SChristoph Hellwig 		goto fail;
59679787eaaSJeff Mahoney 	}
5970660b5afSChris Mason 
59852c26179SYan Zheng 	btrfs_i_size_write(dir, dir->i_size + namelen * 2);
59952c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
60052c26179SYan Zheng 	BUG_ON(ret);
60152c26179SYan Zheng 
6020b246afaSJeff Mahoney 	ret = btrfs_add_root_ref(trans, fs_info,
6034df27c4dSYan, Zheng 				 objectid, root->root_key.objectid,
60433345d01SLi Zefan 				 btrfs_ino(dir), index, name, namelen);
6050660b5afSChris Mason 	BUG_ON(ret);
6060660b5afSChris Mason 
6070b246afaSJeff Mahoney 	ret = btrfs_uuid_tree_add(trans, fs_info, root_item->uuid,
6086bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
609dd5f9615SStefan Behrens 	if (ret)
61066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
611dd5f9615SStefan Behrens 
612f46b5a66SChristoph Hellwig fail:
61349a3c4d9SDavid Sterba 	kfree(root_item);
614d5c12070SMiao Xie 	trans->block_rsv = NULL;
615d5c12070SMiao Xie 	trans->bytes_reserved = 0;
6162ff7e61eSJeff Mahoney 	btrfs_subvolume_release_metadata(fs_info, &block_rsv, qgroup_reserved);
617de6e8200SLiu Bo 
61872fd032eSSage Weil 	if (async_transid) {
61972fd032eSSage Weil 		*async_transid = trans->transid;
62072fd032eSSage Weil 		err = btrfs_commit_transaction_async(trans, root, 1);
62100d71c9cSMiao Xie 		if (err)
62200d71c9cSMiao Xie 			err = btrfs_commit_transaction(trans, root);
62372fd032eSSage Weil 	} else {
62476dda93cSYan, Zheng 		err = btrfs_commit_transaction(trans, root);
62572fd032eSSage Weil 	}
626f46b5a66SChristoph Hellwig 	if (err && !ret)
627f46b5a66SChristoph Hellwig 		ret = err;
6281a65e24bSChris Mason 
6295662344bSTsutomu Itoh 	if (!ret) {
6305662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
631de6e8200SLiu Bo 		if (IS_ERR(inode))
632de6e8200SLiu Bo 			return PTR_ERR(inode);
6335662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
6345662344bSTsutomu Itoh 	}
635f46b5a66SChristoph Hellwig 	return ret;
63649a3c4d9SDavid Sterba 
63749a3c4d9SDavid Sterba fail_free:
63849a3c4d9SDavid Sterba 	kfree(root_item);
63949a3c4d9SDavid Sterba 	return ret;
640f46b5a66SChristoph Hellwig }
641f46b5a66SChristoph Hellwig 
6429ea24bbeSFilipe Manana static void btrfs_wait_for_no_snapshoting_writes(struct btrfs_root *root)
6438257b2dcSMiao Xie {
6448257b2dcSMiao Xie 	s64 writers;
6458257b2dcSMiao Xie 	DEFINE_WAIT(wait);
6468257b2dcSMiao Xie 
6478257b2dcSMiao Xie 	do {
6488257b2dcSMiao Xie 		prepare_to_wait(&root->subv_writers->wait, &wait,
6498257b2dcSMiao Xie 				TASK_UNINTERRUPTIBLE);
6508257b2dcSMiao Xie 
6518257b2dcSMiao Xie 		writers = percpu_counter_sum(&root->subv_writers->counter);
6528257b2dcSMiao Xie 		if (writers)
6538257b2dcSMiao Xie 			schedule();
6548257b2dcSMiao Xie 
6558257b2dcSMiao Xie 		finish_wait(&root->subv_writers->wait, &wait);
6568257b2dcSMiao Xie 	} while (writers);
6578257b2dcSMiao Xie }
6588257b2dcSMiao Xie 
659e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
660e9662f70SMiao Xie 			   struct dentry *dentry, char *name, int namelen,
661e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
662e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
663f46b5a66SChristoph Hellwig {
6640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6652e4bfab9SYan, Zheng 	struct inode *inode;
666f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
667f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
6682e4bfab9SYan, Zheng 	int ret;
669f46b5a66SChristoph Hellwig 
67027cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
671f46b5a66SChristoph Hellwig 		return -EINVAL;
672f46b5a66SChristoph Hellwig 
673a1ee7362SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
674a1ee7362SDavid Sterba 	if (!pending_snapshot)
675a1ee7362SDavid Sterba 		return -ENOMEM;
676a1ee7362SDavid Sterba 
677b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
678b0c0ea63SDavid Sterba 			GFP_NOFS);
6798546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
6808546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
681b0c0ea63SDavid Sterba 		ret = -ENOMEM;
682b0c0ea63SDavid Sterba 		goto free_pending;
683b0c0ea63SDavid Sterba 	}
684b0c0ea63SDavid Sterba 
6858257b2dcSMiao Xie 	atomic_inc(&root->will_be_snapshoted);
6864e857c58SPeter Zijlstra 	smp_mb__after_atomic();
6879ea24bbeSFilipe Manana 	btrfs_wait_for_no_snapshoting_writes(root);
6888257b2dcSMiao Xie 
6896a03843dSMiao Xie 	ret = btrfs_start_delalloc_inodes(root, 0);
6906a03843dSMiao Xie 	if (ret)
691a1ee7362SDavid Sterba 		goto dec_and_free;
6926a03843dSMiao Xie 
693578def7cSFilipe Manana 	btrfs_wait_ordered_extents(root, -1, 0, (u64)-1);
6946a03843dSMiao Xie 
69566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
69666d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
697d5c12070SMiao Xie 	/*
698d5c12070SMiao Xie 	 * 1 - parent dir inode
699d5c12070SMiao Xie 	 * 2 - dir entries
700d5c12070SMiao Xie 	 * 1 - root item
701d5c12070SMiao Xie 	 * 2 - root ref/backref
702d5c12070SMiao Xie 	 * 1 - root of snapshot
703dd5f9615SStefan Behrens 	 * 1 - UUID item
704d5c12070SMiao Xie 	 */
705d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
706dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
707ee3441b4SJeff Mahoney 					&pending_snapshot->qgroup_reserved,
708ee3441b4SJeff Mahoney 					false);
709d5c12070SMiao Xie 	if (ret)
710a1ee7362SDavid Sterba 		goto dec_and_free;
711d5c12070SMiao Xie 
712a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
713a22285a6SYan, Zheng 	pending_snapshot->root = root;
714b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
715e9662f70SMiao Xie 	pending_snapshot->dir = dir;
7168696c533SMiao Xie 	pending_snapshot->inherit = inherit;
717a22285a6SYan, Zheng 
718d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
719a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
720a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
721a22285a6SYan, Zheng 		goto fail;
722a22285a6SYan, Zheng 	}
723a22285a6SYan, Zheng 
7240b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
725a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
726a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
7270b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
72872fd032eSSage Weil 	if (async_transid) {
72972fd032eSSage Weil 		*async_transid = trans->transid;
73072fd032eSSage Weil 		ret = btrfs_commit_transaction_async(trans,
7310b246afaSJeff Mahoney 				     fs_info->extent_root, 1);
73200d71c9cSMiao Xie 		if (ret)
73300d71c9cSMiao Xie 			ret = btrfs_commit_transaction(trans, root);
73472fd032eSSage Weil 	} else {
73572fd032eSSage Weil 		ret = btrfs_commit_transaction(trans,
7360b246afaSJeff Mahoney 					       fs_info->extent_root);
73772fd032eSSage Weil 	}
738aec8030aSMiao Xie 	if (ret)
739c37b2b62SJosef Bacik 		goto fail;
740a22285a6SYan, Zheng 
741a22285a6SYan, Zheng 	ret = pending_snapshot->error;
742f46b5a66SChristoph Hellwig 	if (ret)
7432e4bfab9SYan, Zheng 		goto fail;
744f46b5a66SChristoph Hellwig 
745d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
746d3797308SChris Mason 	if (ret)
747d3797308SChris Mason 		goto fail;
748d3797308SChris Mason 
7492b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
7502e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
7512e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
7522e4bfab9SYan, Zheng 		goto fail;
7532e4bfab9SYan, Zheng 	}
7545662344bSTsutomu Itoh 
7552e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
7562e4bfab9SYan, Zheng 	ret = 0;
7572e4bfab9SYan, Zheng fail:
7582ff7e61eSJeff Mahoney 	btrfs_subvolume_release_metadata(fs_info,
759d5c12070SMiao Xie 					 &pending_snapshot->block_rsv,
760d5c12070SMiao Xie 					 pending_snapshot->qgroup_reserved);
761a1ee7362SDavid Sterba dec_and_free:
7629ea24bbeSFilipe Manana 	if (atomic_dec_and_test(&root->will_be_snapshoted))
7639ea24bbeSFilipe Manana 		wake_up_atomic_t(&root->will_be_snapshoted);
764b0c0ea63SDavid Sterba free_pending:
765b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
7668546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
767a1ee7362SDavid Sterba 	kfree(pending_snapshot);
768a1ee7362SDavid Sterba 
769f46b5a66SChristoph Hellwig 	return ret;
770f46b5a66SChristoph Hellwig }
771f46b5a66SChristoph Hellwig 
7724260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
7734260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
7744260f7c7SSage Weil  *  whether the type of victim is right.
7754260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
7764260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
7774260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
7784260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
7794260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
7804260f7c7SSage Weil  *	a. be owner of dir, or
7814260f7c7SSage Weil  *	b. be owner of victim, or
7824260f7c7SSage Weil  *	c. have CAP_FOWNER capability
78301327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
7844260f7c7SSage Weil  *     links pointing to it.
7854260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
7864260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
7874260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
7884260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
7894260f7c7SSage Weil  *     nfs_async_unlink().
7904260f7c7SSage Weil  */
7914260f7c7SSage Weil 
7924260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
7934260f7c7SSage Weil {
7944260f7c7SSage Weil 	int error;
7954260f7c7SSage Weil 
7962b0143b5SDavid Howells 	if (d_really_is_negative(victim))
7974260f7c7SSage Weil 		return -ENOENT;
7984260f7c7SSage Weil 
7992b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
8004fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
8014260f7c7SSage Weil 
8024260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
8034260f7c7SSage Weil 	if (error)
8044260f7c7SSage Weil 		return error;
8054260f7c7SSage Weil 	if (IS_APPEND(dir))
8064260f7c7SSage Weil 		return -EPERM;
8072b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
8082b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
8094260f7c7SSage Weil 		return -EPERM;
8104260f7c7SSage Weil 	if (isdir) {
811e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
8124260f7c7SSage Weil 			return -ENOTDIR;
8134260f7c7SSage Weil 		if (IS_ROOT(victim))
8144260f7c7SSage Weil 			return -EBUSY;
815e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
8164260f7c7SSage Weil 		return -EISDIR;
8174260f7c7SSage Weil 	if (IS_DEADDIR(dir))
8184260f7c7SSage Weil 		return -ENOENT;
8194260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
8204260f7c7SSage Weil 		return -EBUSY;
8214260f7c7SSage Weil 	return 0;
8224260f7c7SSage Weil }
8234260f7c7SSage Weil 
824cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
825cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
826cb8e7090SChristoph Hellwig {
8272b0143b5SDavid Howells 	if (d_really_is_positive(child))
828cb8e7090SChristoph Hellwig 		return -EEXIST;
829cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
830cb8e7090SChristoph Hellwig 		return -ENOENT;
831cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
832cb8e7090SChristoph Hellwig }
833cb8e7090SChristoph Hellwig 
834cb8e7090SChristoph Hellwig /*
835cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
836cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
837cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
838cb8e7090SChristoph Hellwig  */
83976dda93cSYan, Zheng static noinline int btrfs_mksubvol(struct path *parent,
84076dda93cSYan, Zheng 				   char *name, int namelen,
84172fd032eSSage Weil 				   struct btrfs_root *snap_src,
8426f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
8438696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
844cb8e7090SChristoph Hellwig {
8452b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
8460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
847cb8e7090SChristoph Hellwig 	struct dentry *dentry;
848cb8e7090SChristoph Hellwig 	int error;
849cb8e7090SChristoph Hellwig 
85000235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
85100235411SAl Viro 	if (error == -EINTR)
85200235411SAl Viro 		return error;
853cb8e7090SChristoph Hellwig 
854cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
855cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
856cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
857cb8e7090SChristoph Hellwig 		goto out_unlock;
858cb8e7090SChristoph Hellwig 
85976dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
860cb8e7090SChristoph Hellwig 	if (error)
861a874a63eSLiu Bo 		goto out_dput;
862cb8e7090SChristoph Hellwig 
8639c52057cSChris Mason 	/*
8649c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
8659c52057cSChris Mason 	 * check for them now when we can safely fail
8669c52057cSChris Mason 	 */
8679c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
8689c52057cSChris Mason 					       dir->i_ino, name,
8699c52057cSChris Mason 					       namelen);
8709c52057cSChris Mason 	if (error)
8719c52057cSChris Mason 		goto out_dput;
8729c52057cSChris Mason 
8730b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
87476dda93cSYan, Zheng 
87576dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
87676dda93cSYan, Zheng 		goto out_up_read;
87776dda93cSYan, Zheng 
8783de4586cSChris Mason 	if (snap_src) {
879e9662f70SMiao Xie 		error = create_snapshot(snap_src, dir, dentry, name, namelen,
8806f72c7e2SArne Jansen 					async_transid, readonly, inherit);
8813de4586cSChris Mason 	} else {
882d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
883d5c12070SMiao Xie 				      async_transid, inherit);
8843de4586cSChris Mason 	}
88576dda93cSYan, Zheng 	if (!error)
88676dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
88776dda93cSYan, Zheng out_up_read:
8880b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
889cb8e7090SChristoph Hellwig out_dput:
890cb8e7090SChristoph Hellwig 	dput(dentry);
891cb8e7090SChristoph Hellwig out_unlock:
8925955102cSAl Viro 	inode_unlock(dir);
893cb8e7090SChristoph Hellwig 	return error;
894cb8e7090SChristoph Hellwig }
895cb8e7090SChristoph Hellwig 
8964cb5300bSChris Mason /*
8974cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
8984cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
8994cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
9004cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
9014cb5300bSChris Mason  * part of the file
9024cb5300bSChris Mason  */
903aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
9044cb5300bSChris Mason {
9054cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9064cb5300bSChris Mason 	struct extent_map *em = NULL;
9074cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9084cb5300bSChris Mason 	u64 end;
9094cb5300bSChris Mason 
9104cb5300bSChris Mason 	read_lock(&em_tree->lock);
91109cbfeafSKirill A. Shutemov 	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
9124cb5300bSChris Mason 	read_unlock(&em_tree->lock);
9134cb5300bSChris Mason 
9144cb5300bSChris Mason 	if (em) {
9154cb5300bSChris Mason 		end = extent_map_end(em);
9164cb5300bSChris Mason 		free_extent_map(em);
9174cb5300bSChris Mason 		if (end - offset > thresh)
9184cb5300bSChris Mason 			return 0;
9194cb5300bSChris Mason 	}
9204cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
9214cb5300bSChris Mason 	thresh /= 2;
9224cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
9234cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
9244cb5300bSChris Mason 	if (end >= thresh)
9254cb5300bSChris Mason 		return 0;
9264cb5300bSChris Mason 	return 1;
9274cb5300bSChris Mason }
9284cb5300bSChris Mason 
9294cb5300bSChris Mason /*
9304cb5300bSChris Mason  * helper function to walk through a file and find extents
9314cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
9324cb5300bSChris Mason  *
9334cb5300bSChris Mason  * This is used by the defragging code to find new and small
9344cb5300bSChris Mason  * extents
9354cb5300bSChris Mason  */
9364cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
9374cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
938aab110abSDavid Sterba 			    u64 *off, u32 thresh)
9394cb5300bSChris Mason {
9404cb5300bSChris Mason 	struct btrfs_path *path;
9414cb5300bSChris Mason 	struct btrfs_key min_key;
9424cb5300bSChris Mason 	struct extent_buffer *leaf;
9434cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
9444cb5300bSChris Mason 	int type;
9454cb5300bSChris Mason 	int ret;
946a4689d2bSDavid Sterba 	u64 ino = btrfs_ino(inode);
9474cb5300bSChris Mason 
9484cb5300bSChris Mason 	path = btrfs_alloc_path();
9494cb5300bSChris Mason 	if (!path)
9504cb5300bSChris Mason 		return -ENOMEM;
9514cb5300bSChris Mason 
952a4689d2bSDavid Sterba 	min_key.objectid = ino;
9534cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
9544cb5300bSChris Mason 	min_key.offset = *off;
9554cb5300bSChris Mason 
9564cb5300bSChris Mason 	while (1) {
9576174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
9584cb5300bSChris Mason 		if (ret != 0)
9594cb5300bSChris Mason 			goto none;
960f094c9bdSFilipe Manana process_slot:
961a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
9624cb5300bSChris Mason 			goto none;
9634cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
9644cb5300bSChris Mason 			goto none;
9654cb5300bSChris Mason 
9664cb5300bSChris Mason 		leaf = path->nodes[0];
9674cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
9684cb5300bSChris Mason 					struct btrfs_file_extent_item);
9694cb5300bSChris Mason 
9704cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
9714cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
9724cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
9734cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
9744cb5300bSChris Mason 			*off = min_key.offset;
9754cb5300bSChris Mason 			btrfs_free_path(path);
9764cb5300bSChris Mason 			return 0;
9774cb5300bSChris Mason 		}
9784cb5300bSChris Mason 
979f094c9bdSFilipe Manana 		path->slots[0]++;
980f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
981f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
982f094c9bdSFilipe Manana 			goto process_slot;
983f094c9bdSFilipe Manana 		}
984f094c9bdSFilipe Manana 
9854cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
9864cb5300bSChris Mason 			goto none;
9874cb5300bSChris Mason 
9884cb5300bSChris Mason 		min_key.offset++;
9894cb5300bSChris Mason 		btrfs_release_path(path);
9904cb5300bSChris Mason 	}
9914cb5300bSChris Mason none:
9924cb5300bSChris Mason 	btrfs_free_path(path);
9934cb5300bSChris Mason 	return -ENOENT;
9944cb5300bSChris Mason }
9954cb5300bSChris Mason 
9966c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
99717ce6ef8SLiu Bo {
99817ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
999940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10006c282eb4SLi Zefan 	struct extent_map *em;
100109cbfeafSKirill A. Shutemov 	u64 len = PAGE_SIZE;
1002940100a4SChris Mason 
1003940100a4SChris Mason 	/*
1004940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
1005940100a4SChris Mason 	 * the full extent lock
1006940100a4SChris Mason 	 */
1007940100a4SChris Mason 	read_lock(&em_tree->lock);
1008940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
1009940100a4SChris Mason 	read_unlock(&em_tree->lock);
1010940100a4SChris Mason 
1011940100a4SChris Mason 	if (!em) {
1012308d9800SFilipe Manana 		struct extent_state *cached = NULL;
1013308d9800SFilipe Manana 		u64 end = start + len - 1;
1014308d9800SFilipe Manana 
1015940100a4SChris Mason 		/* get the big lock and read metadata off disk */
1016ff13db41SDavid Sterba 		lock_extent_bits(io_tree, start, end, &cached);
1017940100a4SChris Mason 		em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
1018308d9800SFilipe Manana 		unlock_extent_cached(io_tree, start, end, &cached, GFP_NOFS);
1019940100a4SChris Mason 
10206cf8bfbfSDan Carpenter 		if (IS_ERR(em))
10216c282eb4SLi Zefan 			return NULL;
1022940100a4SChris Mason 	}
1023940100a4SChris Mason 
10246c282eb4SLi Zefan 	return em;
10256c282eb4SLi Zefan }
10266c282eb4SLi Zefan 
10276c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
10286c282eb4SLi Zefan {
10296c282eb4SLi Zefan 	struct extent_map *next;
10306c282eb4SLi Zefan 	bool ret = true;
10316c282eb4SLi Zefan 
10326c282eb4SLi Zefan 	/* this is the last extent */
10336c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
10346c282eb4SLi Zefan 		return false;
10356c282eb4SLi Zefan 
10366c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
1037e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1038e9512d72SChris Mason 		ret = false;
1039e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1040ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
10416c282eb4SLi Zefan 		ret = false;
10426c282eb4SLi Zefan 
10436c282eb4SLi Zefan 	free_extent_map(next);
10446c282eb4SLi Zefan 	return ret;
10456c282eb4SLi Zefan }
10466c282eb4SLi Zefan 
1047aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1048a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
1049a43a2111SAndrew Mahone 			       int compress)
10506c282eb4SLi Zefan {
10516c282eb4SLi Zefan 	struct extent_map *em;
10526c282eb4SLi Zefan 	int ret = 1;
10536c282eb4SLi Zefan 	bool next_mergeable = true;
10544a3560c4SLiu Bo 	bool prev_mergeable = true;
10556c282eb4SLi Zefan 
10566c282eb4SLi Zefan 	/*
10576c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
10586c282eb4SLi Zefan 	 * defragging it
10596c282eb4SLi Zefan 	 */
10606c282eb4SLi Zefan 	if (start < *defrag_end)
10616c282eb4SLi Zefan 		return 1;
10626c282eb4SLi Zefan 
10636c282eb4SLi Zefan 	*skip = 0;
10646c282eb4SLi Zefan 
10656c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
10666c282eb4SLi Zefan 	if (!em)
10676c282eb4SLi Zefan 		return 0;
10686c282eb4SLi Zefan 
1069940100a4SChris Mason 	/* this will cover holes, and inline extents */
107017ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1071940100a4SChris Mason 		ret = 0;
107217ce6ef8SLiu Bo 		goto out;
107317ce6ef8SLiu Bo 	}
107417ce6ef8SLiu Bo 
10754a3560c4SLiu Bo 	if (!*defrag_end)
10764a3560c4SLiu Bo 		prev_mergeable = false;
10774a3560c4SLiu Bo 
10786c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1079940100a4SChris Mason 	/*
10806c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
10816c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1082940100a4SChris Mason 	 */
1083a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
10844a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1085940100a4SChris Mason 		ret = 0;
108617ce6ef8SLiu Bo out:
1087940100a4SChris Mason 	/*
1088940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1089940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1090940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1091940100a4SChris Mason 	 *
1092940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1093940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1094940100a4SChris Mason 	 */
1095940100a4SChris Mason 	if (ret) {
1096940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1097940100a4SChris Mason 	} else {
1098940100a4SChris Mason 		*last_len = 0;
1099940100a4SChris Mason 		*skip = extent_map_end(em);
1100940100a4SChris Mason 		*defrag_end = 0;
1101940100a4SChris Mason 	}
1102940100a4SChris Mason 
1103940100a4SChris Mason 	free_extent_map(em);
1104940100a4SChris Mason 	return ret;
1105940100a4SChris Mason }
1106940100a4SChris Mason 
11074cb5300bSChris Mason /*
11084cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
11094cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
11104cb5300bSChris Mason  * to COW and defrag.
11114cb5300bSChris Mason  *
11124cb5300bSChris Mason  * It also makes sure the delalloc code has enough
11134cb5300bSChris Mason  * dirty data to avoid making new small extents as part
11144cb5300bSChris Mason  * of the defrag
11154cb5300bSChris Mason  *
11164cb5300bSChris Mason  * It's a good idea to start RA on this range
11174cb5300bSChris Mason  * before calling this.
11184cb5300bSChris Mason  */
11194cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
11204cb5300bSChris Mason 				    struct page **pages,
11214cb5300bSChris Mason 				    unsigned long start_index,
1122c41570c9SJustin Maggard 				    unsigned long num_pages)
1123f46b5a66SChristoph Hellwig {
11244cb5300bSChris Mason 	unsigned long file_end;
11254cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1126f46b5a66SChristoph Hellwig 	u64 page_start;
1127f46b5a66SChristoph Hellwig 	u64 page_end;
11281f12bd06SLiu Bo 	u64 page_cnt;
11294cb5300bSChris Mason 	int ret;
11304cb5300bSChris Mason 	int i;
11314cb5300bSChris Mason 	int i_done;
11324cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
11334cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1134600a45e1SMiao Xie 	struct extent_io_tree *tree;
11353b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
11364cb5300bSChris Mason 
113709cbfeafSKirill A. Shutemov 	file_end = (isize - 1) >> PAGE_SHIFT;
11381f12bd06SLiu Bo 	if (!isize || start_index > file_end)
11391f12bd06SLiu Bo 		return 0;
11401f12bd06SLiu Bo 
11411f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
11424cb5300bSChris Mason 
11434cb5300bSChris Mason 	ret = btrfs_delalloc_reserve_space(inode,
114409cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
114509cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
11464cb5300bSChris Mason 	if (ret)
11474cb5300bSChris Mason 		return ret;
11484cb5300bSChris Mason 	i_done = 0;
1149600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
11504cb5300bSChris Mason 
11514cb5300bSChris Mason 	/* step one, lock all the pages */
11521f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
11534cb5300bSChris Mason 		struct page *page;
1154600a45e1SMiao Xie again:
1155a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
11563b16a4e3SJosef Bacik 					   start_index + i, mask);
11574cb5300bSChris Mason 		if (!page)
11584cb5300bSChris Mason 			break;
11594cb5300bSChris Mason 
1160600a45e1SMiao Xie 		page_start = page_offset(page);
116109cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
1162600a45e1SMiao Xie 		while (1) {
1163308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1164ff13db41SDavid Sterba 					 &cached_state);
1165600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1166600a45e1SMiao Xie 							      page_start);
1167308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1168308d9800SFilipe Manana 					     &cached_state, GFP_NOFS);
1169600a45e1SMiao Xie 			if (!ordered)
1170600a45e1SMiao Xie 				break;
1171600a45e1SMiao Xie 
1172600a45e1SMiao Xie 			unlock_page(page);
1173600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1174600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1175600a45e1SMiao Xie 			lock_page(page);
11761f12bd06SLiu Bo 			/*
11771f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
11781f12bd06SLiu Bo 			 * it was released or not.
11791f12bd06SLiu Bo 			 */
11801f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
11811f12bd06SLiu Bo 				unlock_page(page);
118209cbfeafSKirill A. Shutemov 				put_page(page);
11831f12bd06SLiu Bo 				goto again;
11841f12bd06SLiu Bo 			}
1185600a45e1SMiao Xie 		}
1186600a45e1SMiao Xie 
11874cb5300bSChris Mason 		if (!PageUptodate(page)) {
11884cb5300bSChris Mason 			btrfs_readpage(NULL, page);
11894cb5300bSChris Mason 			lock_page(page);
11904cb5300bSChris Mason 			if (!PageUptodate(page)) {
11914cb5300bSChris Mason 				unlock_page(page);
119209cbfeafSKirill A. Shutemov 				put_page(page);
11934cb5300bSChris Mason 				ret = -EIO;
11944cb5300bSChris Mason 				break;
11954cb5300bSChris Mason 			}
11964cb5300bSChris Mason 		}
1197600a45e1SMiao Xie 
1198600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1199600a45e1SMiao Xie 			unlock_page(page);
120009cbfeafSKirill A. Shutemov 			put_page(page);
1201600a45e1SMiao Xie 			goto again;
1202600a45e1SMiao Xie 		}
1203600a45e1SMiao Xie 
12044cb5300bSChris Mason 		pages[i] = page;
12054cb5300bSChris Mason 		i_done++;
12064cb5300bSChris Mason 	}
12074cb5300bSChris Mason 	if (!i_done || ret)
12084cb5300bSChris Mason 		goto out;
12094cb5300bSChris Mason 
12104cb5300bSChris Mason 	if (!(inode->i_sb->s_flags & MS_ACTIVE))
12114cb5300bSChris Mason 		goto out;
12124cb5300bSChris Mason 
12134cb5300bSChris Mason 	/*
12144cb5300bSChris Mason 	 * so now we have a nice long stream of locked
12154cb5300bSChris Mason 	 * and up to date pages, lets wait on them
12164cb5300bSChris Mason 	 */
12174cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
12184cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
12194cb5300bSChris Mason 
12204cb5300bSChris Mason 	page_start = page_offset(pages[0]);
122109cbfeafSKirill A. Shutemov 	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
12224cb5300bSChris Mason 
12234cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1224ff13db41SDavid Sterba 			 page_start, page_end - 1, &cached_state);
12254cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
12264cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
12279e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
12289e8a4a8bSLiu Bo 			  &cached_state, GFP_NOFS);
12294cb5300bSChris Mason 
12301f12bd06SLiu Bo 	if (i_done != page_cnt) {
12319e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
12329e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
12339e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
12344cb5300bSChris Mason 		btrfs_delalloc_release_space(inode,
123509cbfeafSKirill A. Shutemov 				start_index << PAGE_SHIFT,
123609cbfeafSKirill A. Shutemov 				(page_cnt - i_done) << PAGE_SHIFT);
12374cb5300bSChris Mason 	}
12384cb5300bSChris Mason 
12394cb5300bSChris Mason 
12409e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1241018ed4f7SDavid Sterba 			  &cached_state);
12424cb5300bSChris Mason 
12434cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
12444cb5300bSChris Mason 			     page_start, page_end - 1, &cached_state,
12454cb5300bSChris Mason 			     GFP_NOFS);
12464cb5300bSChris Mason 
12474cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12484cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
12494cb5300bSChris Mason 		ClearPageChecked(pages[i]);
12504cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
12514cb5300bSChris Mason 		set_page_dirty(pages[i]);
12524cb5300bSChris Mason 		unlock_page(pages[i]);
125309cbfeafSKirill A. Shutemov 		put_page(pages[i]);
12544cb5300bSChris Mason 	}
12554cb5300bSChris Mason 	return i_done;
12564cb5300bSChris Mason out:
12574cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12584cb5300bSChris Mason 		unlock_page(pages[i]);
125909cbfeafSKirill A. Shutemov 		put_page(pages[i]);
12604cb5300bSChris Mason 	}
12617cf5b976SQu Wenruo 	btrfs_delalloc_release_space(inode,
126209cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
126309cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
12644cb5300bSChris Mason 	return ret;
12654cb5300bSChris Mason 
12664cb5300bSChris Mason }
12674cb5300bSChris Mason 
12684cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
12694cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
12704cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
12714cb5300bSChris Mason {
12720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
12734cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
12744cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
12754cb5300bSChris Mason 	unsigned long last_index;
1276151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1277940100a4SChris Mason 	u64 last_len = 0;
1278940100a4SChris Mason 	u64 skip = 0;
1279940100a4SChris Mason 	u64 defrag_end = 0;
12804cb5300bSChris Mason 	u64 newer_off = range->start;
1281f46b5a66SChristoph Hellwig 	unsigned long i;
1282008873eaSLi Zefan 	unsigned long ra_index = 0;
1283f46b5a66SChristoph Hellwig 	int ret;
12844cb5300bSChris Mason 	int defrag_count = 0;
12851a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1286aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
128709cbfeafSKirill A. Shutemov 	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1288c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
1289ee22184bSByongho Lee 	u64 new_align = ~((u64)SZ_128K - 1);
12904cb5300bSChris Mason 	struct page **pages = NULL;
12914cb5300bSChris Mason 
12920abd5b17SLiu Bo 	if (isize == 0)
12930abd5b17SLiu Bo 		return 0;
12940abd5b17SLiu Bo 
12950abd5b17SLiu Bo 	if (range->start >= isize)
12960abd5b17SLiu Bo 		return -EINVAL;
12971a419d85SLi Zefan 
12981a419d85SLi Zefan 	if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
12991a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
13001a419d85SLi Zefan 			return -EINVAL;
13011a419d85SLi Zefan 		if (range->compress_type)
13021a419d85SLi Zefan 			compress_type = range->compress_type;
13031a419d85SLi Zefan 	}
1304f46b5a66SChristoph Hellwig 
13050abd5b17SLiu Bo 	if (extent_thresh == 0)
1306ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1307f46b5a66SChristoph Hellwig 
13084cb5300bSChris Mason 	/*
13094cb5300bSChris Mason 	 * if we were not given a file, allocate a readahead
13104cb5300bSChris Mason 	 * context
13114cb5300bSChris Mason 	 */
13124cb5300bSChris Mason 	if (!file) {
13134cb5300bSChris Mason 		ra = kzalloc(sizeof(*ra), GFP_NOFS);
13144cb5300bSChris Mason 		if (!ra)
13154cb5300bSChris Mason 			return -ENOMEM;
13164cb5300bSChris Mason 		file_ra_state_init(ra, inode->i_mapping);
13174cb5300bSChris Mason 	} else {
13184cb5300bSChris Mason 		ra = &file->f_ra;
13194cb5300bSChris Mason 	}
13204cb5300bSChris Mason 
1321d9b0d9baSDulshani Gunawardhana 	pages = kmalloc_array(max_cluster, sizeof(struct page *),
13224cb5300bSChris Mason 			GFP_NOFS);
13234cb5300bSChris Mason 	if (!pages) {
13244cb5300bSChris Mason 		ret = -ENOMEM;
13254cb5300bSChris Mason 		goto out_ra;
13264cb5300bSChris Mason 	}
13274cb5300bSChris Mason 
13284cb5300bSChris Mason 	/* find the last page to defrag */
13291e701a32SChris Mason 	if (range->start + range->len > range->start) {
1330151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
133109cbfeafSKirill A. Shutemov 			 range->start + range->len - 1) >> PAGE_SHIFT;
13321e701a32SChris Mason 	} else {
133309cbfeafSKirill A. Shutemov 		last_index = (isize - 1) >> PAGE_SHIFT;
13341e701a32SChris Mason 	}
13351e701a32SChris Mason 
13364cb5300bSChris Mason 	if (newer_than) {
13374cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
1338ee22184bSByongho Lee 				       &newer_off, SZ_64K);
13394cb5300bSChris Mason 		if (!ret) {
13404cb5300bSChris Mason 			range->start = newer_off;
13414cb5300bSChris Mason 			/*
13424cb5300bSChris Mason 			 * we always align our defrag to help keep
13434cb5300bSChris Mason 			 * the extents in the file evenly spaced
13444cb5300bSChris Mason 			 */
134509cbfeafSKirill A. Shutemov 			i = (newer_off & new_align) >> PAGE_SHIFT;
13464cb5300bSChris Mason 		} else
13474cb5300bSChris Mason 			goto out_ra;
13484cb5300bSChris Mason 	} else {
134909cbfeafSKirill A. Shutemov 		i = range->start >> PAGE_SHIFT;
13504cb5300bSChris Mason 	}
13514cb5300bSChris Mason 	if (!max_to_defrag)
1352070034bdSchandan 		max_to_defrag = last_index - i + 1;
13534cb5300bSChris Mason 
13542a0f7f57SLi Zefan 	/*
13552a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
13562a0f7f57SLi Zefan 	 * written sequentially.
13572a0f7f57SLi Zefan 	 */
13582a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
13592a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
13602a0f7f57SLi Zefan 
1361f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
136209cbfeafSKirill A. Shutemov 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
13634cb5300bSChris Mason 		/*
13644cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
13654cb5300bSChris Mason 		 * the FS
13664cb5300bSChris Mason 		 */
13674cb5300bSChris Mason 		if (!(inode->i_sb->s_flags & MS_ACTIVE))
13684cb5300bSChris Mason 			break;
13694cb5300bSChris Mason 
13700b246afaSJeff Mahoney 		if (btrfs_defrag_cancelled(fs_info)) {
13710b246afaSJeff Mahoney 			btrfs_debug(fs_info, "defrag_file cancelled");
1372210549ebSDavid Sterba 			ret = -EAGAIN;
1373210549ebSDavid Sterba 			break;
1374210549ebSDavid Sterba 		}
1375210549ebSDavid Sterba 
137609cbfeafSKirill A. Shutemov 		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
13776c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
1378a43a2111SAndrew Mahone 					 &defrag_end, range->flags &
1379a43a2111SAndrew Mahone 					 BTRFS_DEFRAG_RANGE_COMPRESS)) {
1380940100a4SChris Mason 			unsigned long next;
1381940100a4SChris Mason 			/*
1382940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1383940100a4SChris Mason 			 * bump our counter by the suggested amount
1384940100a4SChris Mason 			 */
138509cbfeafSKirill A. Shutemov 			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1386940100a4SChris Mason 			i = max(i + 1, next);
1387940100a4SChris Mason 			continue;
1388940100a4SChris Mason 		}
1389008873eaSLi Zefan 
1390008873eaSLi Zefan 		if (!newer_than) {
139109cbfeafSKirill A. Shutemov 			cluster = (PAGE_ALIGN(defrag_end) >>
139209cbfeafSKirill A. Shutemov 				   PAGE_SHIFT) - i;
1393008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1394008873eaSLi Zefan 		} else {
1395008873eaSLi Zefan 			cluster = max_cluster;
1396008873eaSLi Zefan 		}
1397008873eaSLi Zefan 
1398008873eaSLi Zefan 		if (i + cluster > ra_index) {
1399008873eaSLi Zefan 			ra_index = max(i, ra_index);
1400008873eaSLi Zefan 			btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1401008873eaSLi Zefan 				       cluster);
1402e4826a5bSchandan 			ra_index += cluster;
1403008873eaSLi Zefan 		}
14044cb5300bSChris Mason 
14055955102cSAl Viro 		inode_lock(inode);
1406633085c7SFilipe David Borba Manana 		if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1407633085c7SFilipe David Borba Manana 			BTRFS_I(inode)->force_compress = compress_type;
1408008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1409ecb8bea8SLiu Bo 		if (ret < 0) {
14105955102cSAl Viro 			inode_unlock(inode);
14114cb5300bSChris Mason 			goto out_ra;
1412ecb8bea8SLiu Bo 		}
14134cb5300bSChris Mason 
14144cb5300bSChris Mason 		defrag_count += ret;
1415d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
14165955102cSAl Viro 		inode_unlock(inode);
14174cb5300bSChris Mason 
14184cb5300bSChris Mason 		if (newer_than) {
14194cb5300bSChris Mason 			if (newer_off == (u64)-1)
14204cb5300bSChris Mason 				break;
14214cb5300bSChris Mason 
1422e1f041e1SLiu Bo 			if (ret > 0)
1423e1f041e1SLiu Bo 				i += ret;
1424e1f041e1SLiu Bo 
14254cb5300bSChris Mason 			newer_off = max(newer_off + 1,
142609cbfeafSKirill A. Shutemov 					(u64)i << PAGE_SHIFT);
14274cb5300bSChris Mason 
1428ee22184bSByongho Lee 			ret = find_new_extents(root, inode, newer_than,
1429ee22184bSByongho Lee 					       &newer_off, SZ_64K);
14304cb5300bSChris Mason 			if (!ret) {
14314cb5300bSChris Mason 				range->start = newer_off;
143209cbfeafSKirill A. Shutemov 				i = (newer_off & new_align) >> PAGE_SHIFT;
14334cb5300bSChris Mason 			} else {
14344cb5300bSChris Mason 				break;
1435940100a4SChris Mason 			}
14364cb5300bSChris Mason 		} else {
1437008873eaSLi Zefan 			if (ret > 0) {
1438cbcc8326SLi Zefan 				i += ret;
143909cbfeafSKirill A. Shutemov 				last_len += ret << PAGE_SHIFT;
1440008873eaSLi Zefan 			} else {
1441940100a4SChris Mason 				i++;
1442008873eaSLi Zefan 				last_len = 0;
1443008873eaSLi Zefan 			}
1444f46b5a66SChristoph Hellwig 		}
14454cb5300bSChris Mason 	}
1446f46b5a66SChristoph Hellwig 
1447dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
14481e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1449dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1450dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1451dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1452dec8ef90SFilipe Manana 	}
14531e701a32SChris Mason 
14541e701a32SChris Mason 	if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
14551e701a32SChris Mason 		/* the filemap_flush will queue IO into the worker threads, but
14561e701a32SChris Mason 		 * we have to make sure the IO is actually started and that
14571e701a32SChris Mason 		 * ordered extents get created before we return
14581e701a32SChris Mason 		 */
14590b246afaSJeff Mahoney 		atomic_inc(&fs_info->async_submit_draining);
14600b246afaSJeff Mahoney 		while (atomic_read(&fs_info->nr_async_submits) ||
14610b246afaSJeff Mahoney 		       atomic_read(&fs_info->async_delalloc_pages)) {
14620b246afaSJeff Mahoney 			wait_event(fs_info->async_submit_wait,
14630b246afaSJeff Mahoney 				   (atomic_read(&fs_info->nr_async_submits) == 0 &&
14640b246afaSJeff Mahoney 				    atomic_read(&fs_info->async_delalloc_pages) == 0));
14651e701a32SChris Mason 		}
14660b246afaSJeff Mahoney 		atomic_dec(&fs_info->async_submit_draining);
14671e701a32SChris Mason 	}
14681e701a32SChris Mason 
14691a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
14700b246afaSJeff Mahoney 		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
14711a419d85SLi Zefan 	}
14721a419d85SLi Zefan 
147360ccf82fSDiego Calleja 	ret = defrag_count;
1474940100a4SChris Mason 
14754cb5300bSChris Mason out_ra:
1476633085c7SFilipe David Borba Manana 	if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
14775955102cSAl Viro 		inode_lock(inode);
1478633085c7SFilipe David Borba Manana 		BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
14795955102cSAl Viro 		inode_unlock(inode);
1480633085c7SFilipe David Borba Manana 	}
14814cb5300bSChris Mason 	if (!file)
14824cb5300bSChris Mason 		kfree(ra);
14834cb5300bSChris Mason 	kfree(pages);
1484940100a4SChris Mason 	return ret;
1485f46b5a66SChristoph Hellwig }
1486f46b5a66SChristoph Hellwig 
1487198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
148876dda93cSYan, Zheng 					void __user *arg)
1489f46b5a66SChristoph Hellwig {
14900b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
14910b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1492f46b5a66SChristoph Hellwig 	u64 new_size;
1493f46b5a66SChristoph Hellwig 	u64 old_size;
1494f46b5a66SChristoph Hellwig 	u64 devid = 1;
14950b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1496f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1497f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1498f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1499f46b5a66SChristoph Hellwig 	char *sizestr;
15009a40f122SGui Hecheng 	char *retptr;
1501f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1502f46b5a66SChristoph Hellwig 	int ret = 0;
1503f46b5a66SChristoph Hellwig 	int mod = 0;
1504f46b5a66SChristoph Hellwig 
1505e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1506e441d54dSChris Mason 		return -EPERM;
1507e441d54dSChris Mason 
1508198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1509198605a8SMiao Xie 	if (ret)
1510198605a8SMiao Xie 		return ret;
1511198605a8SMiao Xie 
15120b246afaSJeff Mahoney 	if (atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
151397547676SMiao Xie 		mnt_drop_write_file(file);
1514e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1515c9e9f97bSIlya Dryomov 	}
1516c9e9f97bSIlya Dryomov 
15170b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
1518dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1519c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1520c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1521c9e9f97bSIlya Dryomov 		goto out;
1522c9e9f97bSIlya Dryomov 	}
15235516e595SMark Fasheh 
15245516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1525f46b5a66SChristoph Hellwig 
1526f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1527f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1528f46b5a66SChristoph Hellwig 	if (devstr) {
1529f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1530f46b5a66SChristoph Hellwig 		*devstr = '\0';
1531f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
153258dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
153358dfae63SZhangZhen 		if (ret)
153458dfae63SZhangZhen 			goto out_free;
1535dfd79829SMiao Xie 		if (!devid) {
1536dfd79829SMiao Xie 			ret = -EINVAL;
1537dfd79829SMiao Xie 			goto out_free;
1538dfd79829SMiao Xie 		}
15390b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1540f46b5a66SChristoph Hellwig 	}
1541dba60f3fSMiao Xie 
15420b246afaSJeff Mahoney 	device = btrfs_find_device(fs_info, devid, NULL, NULL);
1543f46b5a66SChristoph Hellwig 	if (!device) {
15440b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1545c1c9ff7cSGeert Uytterhoeven 			   devid);
1546dfd79829SMiao Xie 		ret = -ENODEV;
1547c9e9f97bSIlya Dryomov 		goto out_free;
1548f46b5a66SChristoph Hellwig 	}
1549dba60f3fSMiao Xie 
1550dba60f3fSMiao Xie 	if (!device->writeable) {
15510b246afaSJeff Mahoney 		btrfs_info(fs_info,
1552efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1553c1c9ff7cSGeert Uytterhoeven 		       devid);
1554dfd79829SMiao Xie 		ret = -EPERM;
15554e42ae1bSLiu Bo 		goto out_free;
15564e42ae1bSLiu Bo 	}
15574e42ae1bSLiu Bo 
1558f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1559f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1560f46b5a66SChristoph Hellwig 	else {
1561f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1562f46b5a66SChristoph Hellwig 			mod = -1;
1563f46b5a66SChristoph Hellwig 			sizestr++;
1564f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1565f46b5a66SChristoph Hellwig 			mod = 1;
1566f46b5a66SChristoph Hellwig 			sizestr++;
1567f46b5a66SChristoph Hellwig 		}
15689a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
15699a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1570f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1571c9e9f97bSIlya Dryomov 			goto out_free;
1572f46b5a66SChristoph Hellwig 		}
1573f46b5a66SChristoph Hellwig 	}
1574f46b5a66SChristoph Hellwig 
157563a212abSStefan Behrens 	if (device->is_tgtdev_for_dev_replace) {
1576dfd79829SMiao Xie 		ret = -EPERM;
157763a212abSStefan Behrens 		goto out_free;
157863a212abSStefan Behrens 	}
157963a212abSStefan Behrens 
15807cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1581f46b5a66SChristoph Hellwig 
1582f46b5a66SChristoph Hellwig 	if (mod < 0) {
1583f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1584f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1585c9e9f97bSIlya Dryomov 			goto out_free;
1586f46b5a66SChristoph Hellwig 		}
1587f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1588f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1589eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1590902c68a4SGui Hecheng 			ret = -ERANGE;
1591eb8052e0SWenliang Fan 			goto out_free;
1592eb8052e0SWenliang Fan 		}
1593f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1594f46b5a66SChristoph Hellwig 	}
1595f46b5a66SChristoph Hellwig 
1596ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1597f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1598c9e9f97bSIlya Dryomov 		goto out_free;
1599f46b5a66SChristoph Hellwig 	}
1600f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1601f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1602c9e9f97bSIlya Dryomov 		goto out_free;
1603f46b5a66SChristoph Hellwig 	}
1604f46b5a66SChristoph Hellwig 
16050b246afaSJeff Mahoney 	new_size = div_u64(new_size, fs_info->sectorsize);
16060b246afaSJeff Mahoney 	new_size *= fs_info->sectorsize;
1607f46b5a66SChristoph Hellwig 
16080b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1609c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1610f46b5a66SChristoph Hellwig 
1611f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1612a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
161398d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
161498d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1615c9e9f97bSIlya Dryomov 			goto out_free;
161698d5dc13STsutomu Itoh 		}
1617f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
1618f46b5a66SChristoph Hellwig 		btrfs_commit_transaction(trans, root);
1619ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1620f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
16210253f40eSjeff.liu 	} /* equal, nothing need to do */
1622f46b5a66SChristoph Hellwig 
1623c9e9f97bSIlya Dryomov out_free:
1624f46b5a66SChristoph Hellwig 	kfree(vol_args);
1625c9e9f97bSIlya Dryomov out:
16260b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
16270b246afaSJeff Mahoney 	atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
162818f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1629f46b5a66SChristoph Hellwig 	return ret;
1630f46b5a66SChristoph Hellwig }
1631f46b5a66SChristoph Hellwig 
163272fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
16336f72c7e2SArne Jansen 				char *name, unsigned long fd, int subvol,
16346f72c7e2SArne Jansen 				u64 *transid, bool readonly,
16358696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1636f46b5a66SChristoph Hellwig {
1637f46b5a66SChristoph Hellwig 	int namelen;
16383de4586cSChris Mason 	int ret = 0;
1639f46b5a66SChristoph Hellwig 
1640325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1641325c50e3SJeff Mahoney 		return -ENOTDIR;
1642325c50e3SJeff Mahoney 
1643a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1644a874a63eSLiu Bo 	if (ret)
1645a874a63eSLiu Bo 		goto out;
1646a874a63eSLiu Bo 
164772fd032eSSage Weil 	namelen = strlen(name);
164872fd032eSSage Weil 	if (strchr(name, '/')) {
1649f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1650a874a63eSLiu Bo 		goto out_drop_write;
1651f46b5a66SChristoph Hellwig 	}
1652f46b5a66SChristoph Hellwig 
165316780cabSChris Mason 	if (name[0] == '.' &&
165416780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
165516780cabSChris Mason 		ret = -EEXIST;
1656a874a63eSLiu Bo 		goto out_drop_write;
165716780cabSChris Mason 	}
165816780cabSChris Mason 
16593de4586cSChris Mason 	if (subvol) {
166072fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
16616f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1662cb8e7090SChristoph Hellwig 	} else {
16632903ff01SAl Viro 		struct fd src = fdget(fd);
16643de4586cSChris Mason 		struct inode *src_inode;
16652903ff01SAl Viro 		if (!src.file) {
16663de4586cSChris Mason 			ret = -EINVAL;
1667a874a63eSLiu Bo 			goto out_drop_write;
16683de4586cSChris Mason 		}
16693de4586cSChris Mason 
1670496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1671496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1672c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1673efe120a0SFrank Holton 				   "Snapshot src from another FS");
167423ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1675d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1676d0242061SDavid Sterba 			/*
1677d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1678d0242061SDavid Sterba 			 * are limited to own subvolumes only
1679d0242061SDavid Sterba 			 */
1680d0242061SDavid Sterba 			ret = -EPERM;
1681ecd18815SAl Viro 		} else {
168272fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
168372fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
16846f72c7e2SArne Jansen 					     transid, readonly, inherit);
1685ecd18815SAl Viro 		}
16862903ff01SAl Viro 		fdput(src);
1687cb8e7090SChristoph Hellwig 	}
1688a874a63eSLiu Bo out_drop_write:
1689a874a63eSLiu Bo 	mnt_drop_write_file(file);
1690f46b5a66SChristoph Hellwig out:
169172fd032eSSage Weil 	return ret;
169272fd032eSSage Weil }
169372fd032eSSage Weil 
169472fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1695fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
169672fd032eSSage Weil {
1697fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
169872fd032eSSage Weil 	int ret;
169972fd032eSSage Weil 
1700325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1701325c50e3SJeff Mahoney 		return -ENOTDIR;
1702325c50e3SJeff Mahoney 
1703fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1704fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1705fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1706fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1707fa0d2b9bSLi Zefan 
1708fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1709b83cc969SLi Zefan 					      vol_args->fd, subvol,
17106f72c7e2SArne Jansen 					      NULL, false, NULL);
1711fa0d2b9bSLi Zefan 
1712fa0d2b9bSLi Zefan 	kfree(vol_args);
1713fa0d2b9bSLi Zefan 	return ret;
1714fa0d2b9bSLi Zefan }
1715fa0d2b9bSLi Zefan 
1716fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1717fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1718fa0d2b9bSLi Zefan {
1719fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1720fa0d2b9bSLi Zefan 	int ret;
1721fdfb1e4fSLi Zefan 	u64 transid = 0;
1722fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1723b83cc969SLi Zefan 	bool readonly = false;
17246f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
172572fd032eSSage Weil 
1726325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1727325c50e3SJeff Mahoney 		return -ENOTDIR;
1728325c50e3SJeff Mahoney 
1729fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1730fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1731fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1732fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1733fdfb1e4fSLi Zefan 
1734b83cc969SLi Zefan 	if (vol_args->flags &
17356f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
17366f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1737b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1738c47ca32dSDan Carpenter 		goto free_args;
1739fdfb1e4fSLi Zefan 	}
1740fdfb1e4fSLi Zefan 
1741fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1742fdfb1e4fSLi Zefan 		ptr = &transid;
1743b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1744b83cc969SLi Zefan 		readonly = true;
17456f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
174609cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
17476f72c7e2SArne Jansen 			ret = -EINVAL;
1748c47ca32dSDan Carpenter 			goto free_args;
17496f72c7e2SArne Jansen 		}
17506f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
17516f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
17526f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1753c47ca32dSDan Carpenter 			goto free_args;
17546f72c7e2SArne Jansen 		}
17556f72c7e2SArne Jansen 	}
175675eaa0e2SSage Weil 
1757fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
17586f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
17598696c533SMiao Xie 					      readonly, inherit);
1760c47ca32dSDan Carpenter 	if (ret)
1761c47ca32dSDan Carpenter 		goto free_inherit;
176275eaa0e2SSage Weil 
1763c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1764fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1765c47ca32dSDan Carpenter 					transid),
1766c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
176775eaa0e2SSage Weil 		ret = -EFAULT;
1768c47ca32dSDan Carpenter 
1769c47ca32dSDan Carpenter free_inherit:
17706f72c7e2SArne Jansen 	kfree(inherit);
1771c47ca32dSDan Carpenter free_args:
1772c47ca32dSDan Carpenter 	kfree(vol_args);
1773f46b5a66SChristoph Hellwig 	return ret;
1774f46b5a66SChristoph Hellwig }
1775f46b5a66SChristoph Hellwig 
17760caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
17770caa102dSLi Zefan 						void __user *arg)
17780caa102dSLi Zefan {
1779496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17800b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17810caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17820caa102dSLi Zefan 	int ret = 0;
17830caa102dSLi Zefan 	u64 flags = 0;
17840caa102dSLi Zefan 
178533345d01SLi Zefan 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
17860caa102dSLi Zefan 		return -EINVAL;
17870caa102dSLi Zefan 
17880b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
17890caa102dSLi Zefan 	if (btrfs_root_readonly(root))
17900caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
17910b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
17920caa102dSLi Zefan 
17930caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
17940caa102dSLi Zefan 		ret = -EFAULT;
17950caa102dSLi Zefan 
17960caa102dSLi Zefan 	return ret;
17970caa102dSLi Zefan }
17980caa102dSLi Zefan 
17990caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
18000caa102dSLi Zefan 					      void __user *arg)
18010caa102dSLi Zefan {
1802496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18040caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
18050caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
18060caa102dSLi Zefan 	u64 root_flags;
18070caa102dSLi Zefan 	u64 flags;
18080caa102dSLi Zefan 	int ret = 0;
18090caa102dSLi Zefan 
1810bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1811bd60ea0fSDavid Sterba 		return -EPERM;
1812bd60ea0fSDavid Sterba 
1813b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1814b9ca0664SLiu Bo 	if (ret)
1815b9ca0664SLiu Bo 		goto out;
18160caa102dSLi Zefan 
1817b9ca0664SLiu Bo 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1818b9ca0664SLiu Bo 		ret = -EINVAL;
1819b9ca0664SLiu Bo 		goto out_drop_write;
1820b9ca0664SLiu Bo 	}
18210caa102dSLi Zefan 
1822b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1823b9ca0664SLiu Bo 		ret = -EFAULT;
1824b9ca0664SLiu Bo 		goto out_drop_write;
1825b9ca0664SLiu Bo 	}
18260caa102dSLi Zefan 
1827b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1828b9ca0664SLiu Bo 		ret = -EINVAL;
1829b9ca0664SLiu Bo 		goto out_drop_write;
1830b9ca0664SLiu Bo 	}
18310caa102dSLi Zefan 
1832b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1833b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1834b9ca0664SLiu Bo 		goto out_drop_write;
1835b9ca0664SLiu Bo 	}
18360caa102dSLi Zefan 
18370b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
18380caa102dSLi Zefan 
18390caa102dSLi Zefan 	/* nothing to do */
18400caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1841b9ca0664SLiu Bo 		goto out_drop_sem;
18420caa102dSLi Zefan 
18430caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
18442c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
18450caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
18460caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
18472c686537SDavid Sterba 	} else {
18482c686537SDavid Sterba 		/*
18492c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
18502c686537SDavid Sterba 		 * send
18512c686537SDavid Sterba 		 */
18522c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
18532c686537SDavid Sterba 		if (root->send_in_progress == 0) {
18540caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
18550caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
18562c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18572c686537SDavid Sterba 		} else {
18582c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18590b246afaSJeff Mahoney 			btrfs_warn(fs_info,
18602c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
18612c686537SDavid Sterba 				   root->root_key.objectid);
18622c686537SDavid Sterba 			ret = -EPERM;
18632c686537SDavid Sterba 			goto out_drop_sem;
18642c686537SDavid Sterba 		}
18652c686537SDavid Sterba 	}
18660caa102dSLi Zefan 
18670caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
18680caa102dSLi Zefan 	if (IS_ERR(trans)) {
18690caa102dSLi Zefan 		ret = PTR_ERR(trans);
18700caa102dSLi Zefan 		goto out_reset;
18710caa102dSLi Zefan 	}
18720caa102dSLi Zefan 
18730b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
18740caa102dSLi Zefan 				&root->root_key, &root->root_item);
18750caa102dSLi Zefan 
18760caa102dSLi Zefan 	btrfs_commit_transaction(trans, root);
18770caa102dSLi Zefan out_reset:
18780caa102dSLi Zefan 	if (ret)
18790caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1880b9ca0664SLiu Bo out_drop_sem:
18810b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
1882b9ca0664SLiu Bo out_drop_write:
1883b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1884b9ca0664SLiu Bo out:
18850caa102dSLi Zefan 	return ret;
18860caa102dSLi Zefan }
18870caa102dSLi Zefan 
188876dda93cSYan, Zheng /*
188976dda93cSYan, Zheng  * helper to check if the subvolume references other subvolumes
189076dda93cSYan, Zheng  */
189176dda93cSYan, Zheng static noinline int may_destroy_subvol(struct btrfs_root *root)
189276dda93cSYan, Zheng {
18930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
189476dda93cSYan, Zheng 	struct btrfs_path *path;
1895175a2b87SJosef Bacik 	struct btrfs_dir_item *di;
189676dda93cSYan, Zheng 	struct btrfs_key key;
1897175a2b87SJosef Bacik 	u64 dir_id;
189876dda93cSYan, Zheng 	int ret;
189976dda93cSYan, Zheng 
190076dda93cSYan, Zheng 	path = btrfs_alloc_path();
190176dda93cSYan, Zheng 	if (!path)
190276dda93cSYan, Zheng 		return -ENOMEM;
190376dda93cSYan, Zheng 
1904175a2b87SJosef Bacik 	/* Make sure this root isn't set as the default subvol */
19050b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
19060b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
1907175a2b87SJosef Bacik 				   dir_id, "default", 7, 0);
1908175a2b87SJosef Bacik 	if (di && !IS_ERR(di)) {
1909175a2b87SJosef Bacik 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1910175a2b87SJosef Bacik 		if (key.objectid == root->root_key.objectid) {
191172de6b53SGuangyu Sun 			ret = -EPERM;
19120b246afaSJeff Mahoney 			btrfs_err(fs_info,
19135d163e0eSJeff Mahoney 				  "deleting default subvolume %llu is not allowed",
19145d163e0eSJeff Mahoney 				  key.objectid);
1915175a2b87SJosef Bacik 			goto out;
1916175a2b87SJosef Bacik 		}
1917175a2b87SJosef Bacik 		btrfs_release_path(path);
1918175a2b87SJosef Bacik 	}
1919175a2b87SJosef Bacik 
192076dda93cSYan, Zheng 	key.objectid = root->root_key.objectid;
192176dda93cSYan, Zheng 	key.type = BTRFS_ROOT_REF_KEY;
192276dda93cSYan, Zheng 	key.offset = (u64)-1;
192376dda93cSYan, Zheng 
19240b246afaSJeff Mahoney 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
192576dda93cSYan, Zheng 	if (ret < 0)
192676dda93cSYan, Zheng 		goto out;
192776dda93cSYan, Zheng 	BUG_ON(ret == 0);
192876dda93cSYan, Zheng 
192976dda93cSYan, Zheng 	ret = 0;
193076dda93cSYan, Zheng 	if (path->slots[0] > 0) {
193176dda93cSYan, Zheng 		path->slots[0]--;
193276dda93cSYan, Zheng 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
193376dda93cSYan, Zheng 		if (key.objectid == root->root_key.objectid &&
193476dda93cSYan, Zheng 		    key.type == BTRFS_ROOT_REF_KEY)
193576dda93cSYan, Zheng 			ret = -ENOTEMPTY;
193676dda93cSYan, Zheng 	}
193776dda93cSYan, Zheng out:
193876dda93cSYan, Zheng 	btrfs_free_path(path);
193976dda93cSYan, Zheng 	return ret;
194076dda93cSYan, Zheng }
194176dda93cSYan, Zheng 
1942ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1943ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1944ac8e9819SChris Mason {
1945abc6e134SChris Mason 	struct btrfs_key test;
1946abc6e134SChris Mason 	int ret;
1947abc6e134SChris Mason 
1948abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1949abc6e134SChris Mason 	test.type = sk->min_type;
1950abc6e134SChris Mason 	test.offset = sk->min_offset;
1951abc6e134SChris Mason 
1952abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1953abc6e134SChris Mason 	if (ret < 0)
1954ac8e9819SChris Mason 		return 0;
1955abc6e134SChris Mason 
1956abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1957abc6e134SChris Mason 	test.type = sk->max_type;
1958abc6e134SChris Mason 	test.offset = sk->max_offset;
1959abc6e134SChris Mason 
1960abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1961abc6e134SChris Mason 	if (ret > 0)
1962ac8e9819SChris Mason 		return 0;
1963ac8e9819SChris Mason 	return 1;
1964ac8e9819SChris Mason }
1965ac8e9819SChris Mason 
1966df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
1967ac8e9819SChris Mason 			       struct btrfs_key *key,
1968ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
19699b6e817dSGerhard Heift 			       size_t *buf_size,
1970ba346b35SGerhard Heift 			       char __user *ubuf,
1971ac8e9819SChris Mason 			       unsigned long *sk_offset,
1972ac8e9819SChris Mason 			       int *num_found)
1973ac8e9819SChris Mason {
1974ac8e9819SChris Mason 	u64 found_transid;
1975ac8e9819SChris Mason 	struct extent_buffer *leaf;
1976ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
1977dd81d459SNaohiro Aota 	struct btrfs_key test;
1978ac8e9819SChris Mason 	unsigned long item_off;
1979ac8e9819SChris Mason 	unsigned long item_len;
1980ac8e9819SChris Mason 	int nritems;
1981ac8e9819SChris Mason 	int i;
1982ac8e9819SChris Mason 	int slot;
1983ac8e9819SChris Mason 	int ret = 0;
1984ac8e9819SChris Mason 
1985ac8e9819SChris Mason 	leaf = path->nodes[0];
1986ac8e9819SChris Mason 	slot = path->slots[0];
1987ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
1988ac8e9819SChris Mason 
1989ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
1990ac8e9819SChris Mason 		i = nritems;
1991ac8e9819SChris Mason 		goto advance_key;
1992ac8e9819SChris Mason 	}
1993ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
1994ac8e9819SChris Mason 
1995ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
1996ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
1997ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
1998ac8e9819SChris Mason 
199903b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
200003b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
200103b71c6cSGabriel de Perthuis 			continue;
200203b71c6cSGabriel de Perthuis 
20039b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
20048f5f6178SGerhard Heift 			if (*num_found) {
2005ac8e9819SChris Mason 				ret = 1;
20068f5f6178SGerhard Heift 				goto out;
20078f5f6178SGerhard Heift 			}
20088f5f6178SGerhard Heift 
20098f5f6178SGerhard Heift 			/*
20108f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
20118f5f6178SGerhard Heift 			 * handle -EOVERFLOW
20128f5f6178SGerhard Heift 			 */
20138f5f6178SGerhard Heift 
20149b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
2015ac8e9819SChris Mason 			item_len = 0;
20168f5f6178SGerhard Heift 			ret = -EOVERFLOW;
20178f5f6178SGerhard Heift 		}
2018ac8e9819SChris Mason 
20199b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2020ac8e9819SChris Mason 			ret = 1;
202125c9bc2eSGerhard Heift 			goto out;
2022ac8e9819SChris Mason 		}
2023ac8e9819SChris Mason 
2024ac8e9819SChris Mason 		sh.objectid = key->objectid;
2025ac8e9819SChris Mason 		sh.offset = key->offset;
2026ac8e9819SChris Mason 		sh.type = key->type;
2027ac8e9819SChris Mason 		sh.len = item_len;
2028ac8e9819SChris Mason 		sh.transid = found_transid;
2029ac8e9819SChris Mason 
2030ac8e9819SChris Mason 		/* copy search result header */
2031ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2032ba346b35SGerhard Heift 			ret = -EFAULT;
2033ba346b35SGerhard Heift 			goto out;
2034ba346b35SGerhard Heift 		}
2035ba346b35SGerhard Heift 
2036ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2037ac8e9819SChris Mason 
2038ac8e9819SChris Mason 		if (item_len) {
2039ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2040ac8e9819SChris Mason 			/* copy the item */
2041ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
2042ba346b35SGerhard Heift 						       item_off, item_len)) {
2043ba346b35SGerhard Heift 				ret = -EFAULT;
2044ba346b35SGerhard Heift 				goto out;
2045ba346b35SGerhard Heift 			}
2046ba346b35SGerhard Heift 
2047ac8e9819SChris Mason 			*sk_offset += item_len;
2048ac8e9819SChris Mason 		}
2049e2156867SHugo Mills 		(*num_found)++;
2050ac8e9819SChris Mason 
20518f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
20528f5f6178SGerhard Heift 			goto out;
20538f5f6178SGerhard Heift 
205425c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
205525c9bc2eSGerhard Heift 			ret = 1;
205625c9bc2eSGerhard Heift 			goto out;
205725c9bc2eSGerhard Heift 		}
2058ac8e9819SChris Mason 	}
2059ac8e9819SChris Mason advance_key:
2060ac8e9819SChris Mason 	ret = 0;
2061dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2062dd81d459SNaohiro Aota 	test.type = sk->max_type;
2063dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2064dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2065dd81d459SNaohiro Aota 		ret = 1;
2066dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2067abc6e134SChris Mason 		key->offset++;
2068dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2069abc6e134SChris Mason 		key->offset = 0;
2070abc6e134SChris Mason 		key->type++;
2071dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2072abc6e134SChris Mason 		key->offset = 0;
2073abc6e134SChris Mason 		key->type = 0;
2074abc6e134SChris Mason 		key->objectid++;
2075abc6e134SChris Mason 	} else
2076abc6e134SChris Mason 		ret = 1;
207725c9bc2eSGerhard Heift out:
2078ba346b35SGerhard Heift 	/*
2079ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2080ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2081ba346b35SGerhard Heift 	 *     * all items were found
2082ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2083ba346b35SGerhard Heift 	 *     leaf
2084ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2085ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2086ba346b35SGerhard Heift 	 */
2087ac8e9819SChris Mason 	return ret;
2088ac8e9819SChris Mason }
2089ac8e9819SChris Mason 
2090ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
209112544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
20929b6e817dSGerhard Heift 				 size_t *buf_size,
2093ba346b35SGerhard Heift 				 char __user *ubuf)
2094ac8e9819SChris Mason {
20950b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2096ac8e9819SChris Mason 	struct btrfs_root *root;
2097ac8e9819SChris Mason 	struct btrfs_key key;
2098ac8e9819SChris Mason 	struct btrfs_path *path;
2099ac8e9819SChris Mason 	int ret;
2100ac8e9819SChris Mason 	int num_found = 0;
2101ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2102ac8e9819SChris Mason 
21039b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
21049b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
210512544442SGerhard Heift 		return -EOVERFLOW;
21069b6e817dSGerhard Heift 	}
210712544442SGerhard Heift 
2108ac8e9819SChris Mason 	path = btrfs_alloc_path();
2109ac8e9819SChris Mason 	if (!path)
2110ac8e9819SChris Mason 		return -ENOMEM;
2111ac8e9819SChris Mason 
2112ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2113ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2114ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2115ac8e9819SChris Mason 	} else {
2116ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2117ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2118ac8e9819SChris Mason 		key.offset = (u64)-1;
2119ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2120ac8e9819SChris Mason 		if (IS_ERR(root)) {
2121ac8e9819SChris Mason 			btrfs_free_path(path);
2122ac8e9819SChris Mason 			return -ENOENT;
2123ac8e9819SChris Mason 		}
2124ac8e9819SChris Mason 	}
2125ac8e9819SChris Mason 
2126ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2127ac8e9819SChris Mason 	key.type = sk->min_type;
2128ac8e9819SChris Mason 	key.offset = sk->min_offset;
2129ac8e9819SChris Mason 
2130ac8e9819SChris Mason 	while (1) {
21316174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2132ac8e9819SChris Mason 		if (ret != 0) {
2133ac8e9819SChris Mason 			if (ret > 0)
2134ac8e9819SChris Mason 				ret = 0;
2135ac8e9819SChris Mason 			goto err;
2136ac8e9819SChris Mason 		}
2137df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2138ac8e9819SChris Mason 				 &sk_offset, &num_found);
2139b3b4aa74SDavid Sterba 		btrfs_release_path(path);
214025c9bc2eSGerhard Heift 		if (ret)
2141ac8e9819SChris Mason 			break;
2142ac8e9819SChris Mason 
2143ac8e9819SChris Mason 	}
21448f5f6178SGerhard Heift 	if (ret > 0)
2145ac8e9819SChris Mason 		ret = 0;
2146ac8e9819SChris Mason err:
2147ac8e9819SChris Mason 	sk->nr_items = num_found;
2148ac8e9819SChris Mason 	btrfs_free_path(path);
2149ac8e9819SChris Mason 	return ret;
2150ac8e9819SChris Mason }
2151ac8e9819SChris Mason 
2152ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2153ac8e9819SChris Mason 					   void __user *argp)
2154ac8e9819SChris Mason {
2155ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2156ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2157ac8e9819SChris Mason 	struct inode *inode;
2158ac8e9819SChris Mason 	int ret;
21599b6e817dSGerhard Heift 	size_t buf_size;
2160ac8e9819SChris Mason 
2161ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2162ac8e9819SChris Mason 		return -EPERM;
2163ac8e9819SChris Mason 
2164ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2165ac8e9819SChris Mason 
2166ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2167ba346b35SGerhard Heift 		return -EFAULT;
2168ba346b35SGerhard Heift 
2169ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2170ac8e9819SChris Mason 
2171496ad9aaSAl Viro 	inode = file_inode(file);
2172ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
21738f5f6178SGerhard Heift 
21748f5f6178SGerhard Heift 	/*
21758f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
21768f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
21778f5f6178SGerhard Heift 	 */
21788f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
21798f5f6178SGerhard Heift 		ret = 0;
21808f5f6178SGerhard Heift 
2181ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2182ac8e9819SChris Mason 		ret = -EFAULT;
2183ac8e9819SChris Mason 	return ret;
2184ac8e9819SChris Mason }
2185ac8e9819SChris Mason 
2186cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2187cc68a8a5SGerhard Heift 					       void __user *argp)
2188cc68a8a5SGerhard Heift {
2189cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2190cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2191cc68a8a5SGerhard Heift 	struct inode *inode;
2192cc68a8a5SGerhard Heift 	int ret;
2193cc68a8a5SGerhard Heift 	size_t buf_size;
2194ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2195cc68a8a5SGerhard Heift 
2196cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2197cc68a8a5SGerhard Heift 		return -EPERM;
2198cc68a8a5SGerhard Heift 
2199cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2200cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2201cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2202cc68a8a5SGerhard Heift 		return -EFAULT;
2203cc68a8a5SGerhard Heift 
2204cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2205cc68a8a5SGerhard Heift 
2206cc68a8a5SGerhard Heift 	if (buf_size < sizeof(struct btrfs_ioctl_search_header))
2207cc68a8a5SGerhard Heift 		return -EOVERFLOW;
2208cc68a8a5SGerhard Heift 
2209cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2210cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2211cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2212cc68a8a5SGerhard Heift 
2213cc68a8a5SGerhard Heift 	inode = file_inode(file);
2214cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2215cc68a8a5SGerhard Heift 			   (char *)(&uarg->buf[0]));
2216cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2217cc68a8a5SGerhard Heift 		ret = -EFAULT;
2218cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2219cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2220cc68a8a5SGerhard Heift 		ret = -EFAULT;
2221cc68a8a5SGerhard Heift 
222276dda93cSYan, Zheng 	return ret;
222376dda93cSYan, Zheng }
222476dda93cSYan, Zheng 
222598d377a0STARUISI Hiroaki /*
2226ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2227ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
222898d377a0STARUISI Hiroaki  */
222998d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
223098d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
223198d377a0STARUISI Hiroaki {
223298d377a0STARUISI Hiroaki 	struct btrfs_root *root;
223398d377a0STARUISI Hiroaki 	struct btrfs_key key;
2234ac8e9819SChris Mason 	char *ptr;
223598d377a0STARUISI Hiroaki 	int ret = -1;
223698d377a0STARUISI Hiroaki 	int slot;
223798d377a0STARUISI Hiroaki 	int len;
223898d377a0STARUISI Hiroaki 	int total_len = 0;
223998d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
224098d377a0STARUISI Hiroaki 	struct extent_buffer *l;
224198d377a0STARUISI Hiroaki 	struct btrfs_path *path;
224298d377a0STARUISI Hiroaki 
224398d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
224498d377a0STARUISI Hiroaki 		name[0]='\0';
224598d377a0STARUISI Hiroaki 		return 0;
224698d377a0STARUISI Hiroaki 	}
224798d377a0STARUISI Hiroaki 
224898d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
224998d377a0STARUISI Hiroaki 	if (!path)
225098d377a0STARUISI Hiroaki 		return -ENOMEM;
225198d377a0STARUISI Hiroaki 
2252ac8e9819SChris Mason 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
225398d377a0STARUISI Hiroaki 
225498d377a0STARUISI Hiroaki 	key.objectid = tree_id;
225598d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
225698d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
225798d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
225898d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2259f14d104dSDavid Sterba 		btrfs_err(info, "could not find root %llu", tree_id);
22608ad6fcabSChris Mason 		ret = -ENOENT;
22618ad6fcabSChris Mason 		goto out;
226298d377a0STARUISI Hiroaki 	}
226398d377a0STARUISI Hiroaki 
226498d377a0STARUISI Hiroaki 	key.objectid = dirid;
226598d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
22668ad6fcabSChris Mason 	key.offset = (u64)-1;
226798d377a0STARUISI Hiroaki 
226898d377a0STARUISI Hiroaki 	while (1) {
226998d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
227098d377a0STARUISI Hiroaki 		if (ret < 0)
227198d377a0STARUISI Hiroaki 			goto out;
227218674c6cSFilipe David Borba Manana 		else if (ret > 0) {
227318674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
227418674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
227518674c6cSFilipe David Borba Manana 			if (ret < 0)
227618674c6cSFilipe David Borba Manana 				goto out;
227718674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2278ac8e9819SChris Mason 				ret = -ENOENT;
227998d377a0STARUISI Hiroaki 				goto out;
2280ac8e9819SChris Mason 			}
228118674c6cSFilipe David Borba Manana 		}
228218674c6cSFilipe David Borba Manana 
228318674c6cSFilipe David Borba Manana 		l = path->nodes[0];
228418674c6cSFilipe David Borba Manana 		slot = path->slots[0];
228518674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
228698d377a0STARUISI Hiroaki 
228798d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
228898d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
228998d377a0STARUISI Hiroaki 		ptr -= len + 1;
229098d377a0STARUISI Hiroaki 		total_len += len + 1;
2291a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2292a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
229398d377a0STARUISI Hiroaki 			goto out;
2294a696cf35SFilipe David Borba Manana 		}
229598d377a0STARUISI Hiroaki 
229698d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
229798d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
229898d377a0STARUISI Hiroaki 
229998d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
230098d377a0STARUISI Hiroaki 			break;
230198d377a0STARUISI Hiroaki 
2302b3b4aa74SDavid Sterba 		btrfs_release_path(path);
230398d377a0STARUISI Hiroaki 		key.objectid = key.offset;
23048ad6fcabSChris Mason 		key.offset = (u64)-1;
230598d377a0STARUISI Hiroaki 		dirid = key.objectid;
230698d377a0STARUISI Hiroaki 	}
230777906a50SLi Zefan 	memmove(name, ptr, total_len);
230898d377a0STARUISI Hiroaki 	name[total_len] = '\0';
230998d377a0STARUISI Hiroaki 	ret = 0;
231098d377a0STARUISI Hiroaki out:
231198d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2312ac8e9819SChris Mason 	return ret;
2313ac8e9819SChris Mason }
2314ac8e9819SChris Mason 
2315ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2316ac8e9819SChris Mason 					   void __user *argp)
2317ac8e9819SChris Mason {
2318ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2319ac8e9819SChris Mason 	 struct inode *inode;
232001b810b8SDavid Sterba 	int ret = 0;
2321ac8e9819SChris Mason 
23222354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
23232354d08fSJulia Lawall 	if (IS_ERR(args))
23242354d08fSJulia Lawall 		return PTR_ERR(args);
2325c2b96929SDan Carpenter 
2326496ad9aaSAl Viro 	inode = file_inode(file);
2327ac8e9819SChris Mason 
232801b810b8SDavid Sterba 	/*
232901b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
233001b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
233101b810b8SDavid Sterba 	 */
23321b53ac4dSChris Mason 	if (args->treeid == 0)
23331b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
23341b53ac4dSChris Mason 
233501b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
233601b810b8SDavid Sterba 		args->name[0] = 0;
233701b810b8SDavid Sterba 		goto out;
233801b810b8SDavid Sterba 	}
233901b810b8SDavid Sterba 
234001b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
234101b810b8SDavid Sterba 		ret = -EPERM;
234201b810b8SDavid Sterba 		goto out;
234301b810b8SDavid Sterba 	}
234401b810b8SDavid Sterba 
2345ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2346ac8e9819SChris Mason 					args->treeid, args->objectid,
2347ac8e9819SChris Mason 					args->name);
2348ac8e9819SChris Mason 
234901b810b8SDavid Sterba out:
2350ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2351ac8e9819SChris Mason 		ret = -EFAULT;
2352ac8e9819SChris Mason 
2353ac8e9819SChris Mason 	kfree(args);
235498d377a0STARUISI Hiroaki 	return ret;
235598d377a0STARUISI Hiroaki }
235698d377a0STARUISI Hiroaki 
235776dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
235876dda93cSYan, Zheng 					     void __user *arg)
235976dda93cSYan, Zheng {
236054563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
23610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
236276dda93cSYan, Zheng 	struct dentry *dentry;
23632b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
236476dda93cSYan, Zheng 	struct inode *inode;
236576dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
236676dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
236776dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
236876dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
2369c58aaad2SMiao Xie 	struct btrfs_block_rsv block_rsv;
2370521e0546SDavid Sterba 	u64 root_flags;
2371c58aaad2SMiao Xie 	u64 qgroup_reserved;
237276dda93cSYan, Zheng 	int namelen;
237376dda93cSYan, Zheng 	int ret;
237476dda93cSYan, Zheng 	int err = 0;
237576dda93cSYan, Zheng 
2376325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2377325c50e3SJeff Mahoney 		return -ENOTDIR;
2378325c50e3SJeff Mahoney 
237976dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
238076dda93cSYan, Zheng 	if (IS_ERR(vol_args))
238176dda93cSYan, Zheng 		return PTR_ERR(vol_args);
238276dda93cSYan, Zheng 
238376dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
238476dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
238576dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
238676dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
238776dda93cSYan, Zheng 		err = -EINVAL;
238876dda93cSYan, Zheng 		goto out;
238976dda93cSYan, Zheng 	}
239076dda93cSYan, Zheng 
2391a561be71SAl Viro 	err = mnt_want_write_file(file);
239276dda93cSYan, Zheng 	if (err)
239376dda93cSYan, Zheng 		goto out;
239476dda93cSYan, Zheng 
2395521e0546SDavid Sterba 
239600235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
239700235411SAl Viro 	if (err == -EINTR)
239800235411SAl Viro 		goto out_drop_write;
239976dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
240076dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
240176dda93cSYan, Zheng 		err = PTR_ERR(dentry);
240276dda93cSYan, Zheng 		goto out_unlock_dir;
240376dda93cSYan, Zheng 	}
240476dda93cSYan, Zheng 
24052b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
240676dda93cSYan, Zheng 		err = -ENOENT;
240776dda93cSYan, Zheng 		goto out_dput;
240876dda93cSYan, Zheng 	}
240976dda93cSYan, Zheng 
24102b0143b5SDavid Howells 	inode = d_inode(dentry);
24114260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
24124260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
24134260f7c7SSage Weil 		/*
24144260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
24154260f7c7SSage Weil 		 * option, when the user has write+exec access to the
24164260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
24174260f7c7SSage Weil 		 * allowed.
24184260f7c7SSage Weil 		 *
24194260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
24204260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
24214260f7c7SSage Weil 		 * otherwise be able to delete.
24224260f7c7SSage Weil 		 *
24234260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
24244260f7c7SSage Weil 		 * rmdir(2).
24254260f7c7SSage Weil 		 */
24264260f7c7SSage Weil 		err = -EPERM;
24270b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
24284260f7c7SSage Weil 			goto out_dput;
24294260f7c7SSage Weil 
24304260f7c7SSage Weil 		/*
24314260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
24324260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
24334260f7c7SSage Weil 		 * must be called on the dentry referencing the root
24344260f7c7SSage Weil 		 * of the subvol, not a random directory contained
24354260f7c7SSage Weil 		 * within it.
24364260f7c7SSage Weil 		 */
24374260f7c7SSage Weil 		err = -EINVAL;
24384260f7c7SSage Weil 		if (root == dest)
24394260f7c7SSage Weil 			goto out_dput;
24404260f7c7SSage Weil 
24414260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
24424260f7c7SSage Weil 		if (err)
24434260f7c7SSage Weil 			goto out_dput;
24445c39da5bSMiao Xie 	}
24454260f7c7SSage Weil 
24465c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
24474260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
24484260f7c7SSage Weil 	if (err)
24494260f7c7SSage Weil 		goto out_dput;
24504260f7c7SSage Weil 
245133345d01SLi Zefan 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
245276dda93cSYan, Zheng 		err = -EINVAL;
245376dda93cSYan, Zheng 		goto out_dput;
245476dda93cSYan, Zheng 	}
245576dda93cSYan, Zheng 
24565955102cSAl Viro 	inode_lock(inode);
2457521e0546SDavid Sterba 
2458521e0546SDavid Sterba 	/*
2459521e0546SDavid Sterba 	 * Don't allow to delete a subvolume with send in progress. This is
2460521e0546SDavid Sterba 	 * inside the i_mutex so the error handling that has to drop the bit
2461521e0546SDavid Sterba 	 * again is not run concurrently.
2462521e0546SDavid Sterba 	 */
2463521e0546SDavid Sterba 	spin_lock(&dest->root_item_lock);
2464c55bfa67SFilipe Manana 	root_flags = btrfs_root_flags(&dest->root_item);
2465c55bfa67SFilipe Manana 	if (dest->send_in_progress == 0) {
2466c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2467521e0546SDavid Sterba 				root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2468521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2469521e0546SDavid Sterba 	} else {
2470521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
24710b246afaSJeff Mahoney 		btrfs_warn(fs_info,
2472521e0546SDavid Sterba 			   "Attempt to delete subvolume %llu during send",
2473c55bfa67SFilipe Manana 			   dest->root_key.objectid);
2474521e0546SDavid Sterba 		err = -EPERM;
2475909e26dcSOmar Sandoval 		goto out_unlock_inode;
2476521e0546SDavid Sterba 	}
2477521e0546SDavid Sterba 
24780b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
247976dda93cSYan, Zheng 
248076dda93cSYan, Zheng 	err = may_destroy_subvol(dest);
248176dda93cSYan, Zheng 	if (err)
248276dda93cSYan, Zheng 		goto out_up_write;
248376dda93cSYan, Zheng 
2484c58aaad2SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2485c58aaad2SMiao Xie 	/*
2486c58aaad2SMiao Xie 	 * One for dir inode, two for dir entries, two for root
2487c58aaad2SMiao Xie 	 * ref/backref.
2488c58aaad2SMiao Xie 	 */
2489c58aaad2SMiao Xie 	err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2490ee3441b4SJeff Mahoney 					       5, &qgroup_reserved, true);
2491c58aaad2SMiao Xie 	if (err)
2492c58aaad2SMiao Xie 		goto out_up_write;
2493c58aaad2SMiao Xie 
2494a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 0);
2495a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
2496a22285a6SYan, Zheng 		err = PTR_ERR(trans);
2497c58aaad2SMiao Xie 		goto out_release;
2498a22285a6SYan, Zheng 	}
2499c58aaad2SMiao Xie 	trans->block_rsv = &block_rsv;
2500c58aaad2SMiao Xie 	trans->bytes_reserved = block_rsv.size;
2501a22285a6SYan, Zheng 
25022be63d5cSFilipe Manana 	btrfs_record_snapshot_destroy(trans, dir);
25032be63d5cSFilipe Manana 
250476dda93cSYan, Zheng 	ret = btrfs_unlink_subvol(trans, root, dir,
250576dda93cSYan, Zheng 				dest->root_key.objectid,
250676dda93cSYan, Zheng 				dentry->d_name.name,
250776dda93cSYan, Zheng 				dentry->d_name.len);
250879787eaaSJeff Mahoney 	if (ret) {
250979787eaaSJeff Mahoney 		err = ret;
251066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
251179787eaaSJeff Mahoney 		goto out_end_trans;
251279787eaaSJeff Mahoney 	}
251376dda93cSYan, Zheng 
251476dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, dest);
251576dda93cSYan, Zheng 
251676dda93cSYan, Zheng 	memset(&dest->root_item.drop_progress, 0,
251776dda93cSYan, Zheng 		sizeof(dest->root_item.drop_progress));
251876dda93cSYan, Zheng 	dest->root_item.drop_level = 0;
251976dda93cSYan, Zheng 	btrfs_set_root_refs(&dest->root_item, 0);
252076dda93cSYan, Zheng 
252127cdeb70SMiao Xie 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
252276dda93cSYan, Zheng 		ret = btrfs_insert_orphan_item(trans,
25230b246afaSJeff Mahoney 					fs_info->tree_root,
252476dda93cSYan, Zheng 					dest->root_key.objectid);
252579787eaaSJeff Mahoney 		if (ret) {
252666642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
252779787eaaSJeff Mahoney 			err = ret;
252879787eaaSJeff Mahoney 			goto out_end_trans;
2529d68fc57bSYan, Zheng 		}
253079787eaaSJeff Mahoney 	}
2531dd5f9615SStefan Behrens 
25320b246afaSJeff Mahoney 	ret = btrfs_uuid_tree_rem(trans, fs_info, dest->root_item.uuid,
25336bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL,
2534dd5f9615SStefan Behrens 				  dest->root_key.objectid);
2535dd5f9615SStefan Behrens 	if (ret && ret != -ENOENT) {
253666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
2537dd5f9615SStefan Behrens 		err = ret;
2538dd5f9615SStefan Behrens 		goto out_end_trans;
2539dd5f9615SStefan Behrens 	}
2540dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
25410b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_rem(trans, fs_info,
2542dd5f9615SStefan Behrens 					  dest->root_item.received_uuid,
2543dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2544dd5f9615SStefan Behrens 					  dest->root_key.objectid);
2545dd5f9615SStefan Behrens 		if (ret && ret != -ENOENT) {
254666642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
2547dd5f9615SStefan Behrens 			err = ret;
2548dd5f9615SStefan Behrens 			goto out_end_trans;
2549dd5f9615SStefan Behrens 		}
2550dd5f9615SStefan Behrens 	}
2551dd5f9615SStefan Behrens 
255279787eaaSJeff Mahoney out_end_trans:
2553c58aaad2SMiao Xie 	trans->block_rsv = NULL;
2554c58aaad2SMiao Xie 	trans->bytes_reserved = 0;
2555531cb13fSSage Weil 	ret = btrfs_end_transaction(trans, root);
255679787eaaSJeff Mahoney 	if (ret && !err)
255779787eaaSJeff Mahoney 		err = ret;
255876dda93cSYan, Zheng 	inode->i_flags |= S_DEAD;
2559c58aaad2SMiao Xie out_release:
25602ff7e61eSJeff Mahoney 	btrfs_subvolume_release_metadata(fs_info, &block_rsv, qgroup_reserved);
256176dda93cSYan, Zheng out_up_write:
25620b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
2563521e0546SDavid Sterba 	if (err) {
2564521e0546SDavid Sterba 		spin_lock(&dest->root_item_lock);
2565c55bfa67SFilipe Manana 		root_flags = btrfs_root_flags(&dest->root_item);
2566c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2567521e0546SDavid Sterba 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2568521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2569521e0546SDavid Sterba 	}
2570909e26dcSOmar Sandoval out_unlock_inode:
25715955102cSAl Viro 	inode_unlock(inode);
257276dda93cSYan, Zheng 	if (!err) {
257364ad6c48SOmar Sandoval 		d_invalidate(dentry);
257476dda93cSYan, Zheng 		btrfs_invalidate_inodes(dest);
257576dda93cSYan, Zheng 		d_delete(dentry);
257661155aa0SDavid Sterba 		ASSERT(dest->send_in_progress == 0);
2577fa6ac876SLiu Bo 
2578fa6ac876SLiu Bo 		/* the last ref */
257957cdc8dbSDavid Sterba 		if (dest->ino_cache_inode) {
258057cdc8dbSDavid Sterba 			iput(dest->ino_cache_inode);
258157cdc8dbSDavid Sterba 			dest->ino_cache_inode = NULL;
2582fa6ac876SLiu Bo 		}
258376dda93cSYan, Zheng 	}
258476dda93cSYan, Zheng out_dput:
258576dda93cSYan, Zheng 	dput(dentry);
258676dda93cSYan, Zheng out_unlock_dir:
25875955102cSAl Viro 	inode_unlock(dir);
258800235411SAl Viro out_drop_write:
25892a79f17eSAl Viro 	mnt_drop_write_file(file);
259076dda93cSYan, Zheng out:
259176dda93cSYan, Zheng 	kfree(vol_args);
259276dda93cSYan, Zheng 	return err;
259376dda93cSYan, Zheng }
259476dda93cSYan, Zheng 
25951e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2596f46b5a66SChristoph Hellwig {
2597496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2598f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
25991e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2600c146afadSYan Zheng 	int ret;
2601c146afadSYan Zheng 
260225122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
260325122d15SIlya Dryomov 	if (ret)
260425122d15SIlya Dryomov 		return ret;
2605b83cc969SLi Zefan 
260625122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
260725122d15SIlya Dryomov 		ret = -EROFS;
260825122d15SIlya Dryomov 		goto out;
26095ac00addSStefan Behrens 	}
2610f46b5a66SChristoph Hellwig 
2611f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2612f46b5a66SChristoph Hellwig 	case S_IFDIR:
2613e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2614e441d54dSChris Mason 			ret = -EPERM;
2615e441d54dSChris Mason 			goto out;
2616e441d54dSChris Mason 		}
2617de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
26188929ecfaSYan, Zheng 		if (ret)
26198929ecfaSYan, Zheng 			goto out;
2620de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root->fs_info->extent_root);
2621f46b5a66SChristoph Hellwig 		break;
2622f46b5a66SChristoph Hellwig 	case S_IFREG:
2623e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2624e441d54dSChris Mason 			ret = -EINVAL;
2625e441d54dSChris Mason 			goto out;
2626e441d54dSChris Mason 		}
26271e701a32SChris Mason 
26281e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
26291e701a32SChris Mason 		if (!range) {
26301e701a32SChris Mason 			ret = -ENOMEM;
26311e701a32SChris Mason 			goto out;
26321e701a32SChris Mason 		}
26331e701a32SChris Mason 
26341e701a32SChris Mason 		if (argp) {
26351e701a32SChris Mason 			if (copy_from_user(range, argp,
26361e701a32SChris Mason 					   sizeof(*range))) {
26371e701a32SChris Mason 				ret = -EFAULT;
26381e701a32SChris Mason 				kfree(range);
2639683be16eSDan Carpenter 				goto out;
26401e701a32SChris Mason 			}
26411e701a32SChris Mason 			/* compression requires us to start the IO */
26421e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
26431e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
26441e701a32SChris Mason 				range->extent_thresh = (u32)-1;
26451e701a32SChris Mason 			}
26461e701a32SChris Mason 		} else {
26471e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
26481e701a32SChris Mason 			range->len = (u64)-1;
26491e701a32SChris Mason 		}
2650496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
26514cb5300bSChris Mason 					range, 0, 0);
26524cb5300bSChris Mason 		if (ret > 0)
26534cb5300bSChris Mason 			ret = 0;
26541e701a32SChris Mason 		kfree(range);
2655f46b5a66SChristoph Hellwig 		break;
26568929ecfaSYan, Zheng 	default:
26578929ecfaSYan, Zheng 		ret = -EINVAL;
2658f46b5a66SChristoph Hellwig 	}
2659e441d54dSChris Mason out:
266025122d15SIlya Dryomov 	mnt_drop_write_file(file);
2661e441d54dSChris Mason 	return ret;
2662f46b5a66SChristoph Hellwig }
2663f46b5a66SChristoph Hellwig 
26642ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2665f46b5a66SChristoph Hellwig {
2666f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2667f46b5a66SChristoph Hellwig 	int ret;
2668f46b5a66SChristoph Hellwig 
2669e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2670e441d54dSChris Mason 		return -EPERM;
2671e441d54dSChris Mason 
26720b246afaSJeff Mahoney 	if (atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1))
2673e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2674c9e9f97bSIlya Dryomov 
26750b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
2676dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2677c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2678c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2679c9e9f97bSIlya Dryomov 		goto out;
2680c9e9f97bSIlya Dryomov 	}
2681f46b5a66SChristoph Hellwig 
26825516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
26832ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
2684f46b5a66SChristoph Hellwig 
268543d20761SAnand Jain 	if (!ret)
26860b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
268743d20761SAnand Jain 
2688f46b5a66SChristoph Hellwig 	kfree(vol_args);
2689c9e9f97bSIlya Dryomov out:
26900b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
26910b246afaSJeff Mahoney 	atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
2692f46b5a66SChristoph Hellwig 	return ret;
2693f46b5a66SChristoph Hellwig }
2694f46b5a66SChristoph Hellwig 
26956b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
2696f46b5a66SChristoph Hellwig {
26970b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
26980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
26996b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
2700f46b5a66SChristoph Hellwig 	int ret;
2701f46b5a66SChristoph Hellwig 
2702e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2703e441d54dSChris Mason 		return -EPERM;
2704e441d54dSChris Mason 
2705da24927bSMiao Xie 	ret = mnt_want_write_file(file);
2706da24927bSMiao Xie 	if (ret)
2707da24927bSMiao Xie 		return ret;
2708c146afadSYan Zheng 
2709dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2710c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2711c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2712c47ca32dSDan Carpenter 		goto err_drop;
2713c9e9f97bSIlya Dryomov 	}
2714f46b5a66SChristoph Hellwig 
27156b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
2716735654eaSDavid Sterba 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED)
2717735654eaSDavid Sterba 		return -EOPNOTSUPP;
2718f46b5a66SChristoph Hellwig 
27190b246afaSJeff Mahoney 	if (atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
2720183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2721183860f6SAnand Jain 		goto out;
2722183860f6SAnand Jain 	}
2723183860f6SAnand Jain 
27240b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
2725735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
27262ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
27276b526ed7SAnand Jain 	} else {
27286b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
27292ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
27306b526ed7SAnand Jain 	}
27310b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
27320b246afaSJeff Mahoney 	atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
2733183860f6SAnand Jain 
27346b526ed7SAnand Jain 	if (!ret) {
2735735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
27360b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
27376b526ed7SAnand Jain 					vol_args->devid);
27386b526ed7SAnand Jain 		else
27390b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
27406b526ed7SAnand Jain 					vol_args->name);
27416b526ed7SAnand Jain 	}
2742183860f6SAnand Jain out:
2743183860f6SAnand Jain 	kfree(vol_args);
2744c47ca32dSDan Carpenter err_drop:
27454ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
2746f46b5a66SChristoph Hellwig 	return ret;
2747f46b5a66SChristoph Hellwig }
2748f46b5a66SChristoph Hellwig 
2749f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2750f46b5a66SChristoph Hellwig {
27510b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
27520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2753f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2754f46b5a66SChristoph Hellwig 	int ret;
2755f46b5a66SChristoph Hellwig 
2756f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
2757f46b5a66SChristoph Hellwig 		return -EPERM;
2758f46b5a66SChristoph Hellwig 
2759f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
2760f46b5a66SChristoph Hellwig 	if (ret)
2761f46b5a66SChristoph Hellwig 		return ret;
2762f46b5a66SChristoph Hellwig 
27630b246afaSJeff Mahoney 	if (atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
2764f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
276558d7bbf8SDavid Sterba 		goto out_drop_write;
276658d7bbf8SDavid Sterba 	}
276758d7bbf8SDavid Sterba 
276858d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
276958d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
277058d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
2771f46b5a66SChristoph Hellwig 		goto out;
2772f46b5a66SChristoph Hellwig 	}
2773f46b5a66SChristoph Hellwig 
277458d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
27750b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
27762ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
27770b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
2778f46b5a66SChristoph Hellwig 
2779f46b5a66SChristoph Hellwig 	if (!ret)
27800b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
2781f46b5a66SChristoph Hellwig 	kfree(vol_args);
278258d7bbf8SDavid Sterba out:
27830b246afaSJeff Mahoney 	atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
278458d7bbf8SDavid Sterba out_drop_write:
2785f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
278658d7bbf8SDavid Sterba 
2787f46b5a66SChristoph Hellwig 	return ret;
2788f46b5a66SChristoph Hellwig }
2789f46b5a66SChristoph Hellwig 
27902ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
27912ff7e61eSJeff Mahoney 				void __user *arg)
2792475f6387SJan Schmidt {
2793027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
2794475f6387SJan Schmidt 	struct btrfs_device *device;
27950b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2796027ed2f0SLi Zefan 	int ret = 0;
2797475f6387SJan Schmidt 
2798027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2799027ed2f0SLi Zefan 	if (!fi_args)
2800027ed2f0SLi Zefan 		return -ENOMEM;
2801027ed2f0SLi Zefan 
2802f7171750SFilipe David Borba Manana 	mutex_lock(&fs_devices->device_list_mutex);
2803027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
28040b246afaSJeff Mahoney 	memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
2805475f6387SJan Schmidt 
2806d7641a49SByongho Lee 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
2807027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
2808027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
2809475f6387SJan Schmidt 	}
2810475f6387SJan Schmidt 	mutex_unlock(&fs_devices->device_list_mutex);
2811475f6387SJan Schmidt 
28120b246afaSJeff Mahoney 	fi_args->nodesize = fs_info->super_copy->nodesize;
28130b246afaSJeff Mahoney 	fi_args->sectorsize = fs_info->super_copy->sectorsize;
28140b246afaSJeff Mahoney 	fi_args->clone_alignment = fs_info->super_copy->sectorsize;
281580a773fbSDavid Sterba 
2816027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2817027ed2f0SLi Zefan 		ret = -EFAULT;
2818475f6387SJan Schmidt 
2819027ed2f0SLi Zefan 	kfree(fi_args);
2820027ed2f0SLi Zefan 	return ret;
2821475f6387SJan Schmidt }
2822475f6387SJan Schmidt 
28232ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
28242ff7e61eSJeff Mahoney 				 void __user *arg)
2825475f6387SJan Schmidt {
2826475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
2827475f6387SJan Schmidt 	struct btrfs_device *dev;
28280b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2829475f6387SJan Schmidt 	int ret = 0;
2830475f6387SJan Schmidt 	char *s_uuid = NULL;
2831475f6387SJan Schmidt 
2832475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
2833475f6387SJan Schmidt 	if (IS_ERR(di_args))
2834475f6387SJan Schmidt 		return PTR_ERR(di_args);
2835475f6387SJan Schmidt 
2836dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
2837475f6387SJan Schmidt 		s_uuid = di_args->uuid;
2838475f6387SJan Schmidt 
2839475f6387SJan Schmidt 	mutex_lock(&fs_devices->device_list_mutex);
28400b246afaSJeff Mahoney 	dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
2841475f6387SJan Schmidt 
2842475f6387SJan Schmidt 	if (!dev) {
2843475f6387SJan Schmidt 		ret = -ENODEV;
2844475f6387SJan Schmidt 		goto out;
2845475f6387SJan Schmidt 	}
2846475f6387SJan Schmidt 
2847475f6387SJan Schmidt 	di_args->devid = dev->devid;
28487cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
28497cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2850475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2851a27202fbSJim Meyering 	if (dev->name) {
2852606686eeSJosef Bacik 		struct rcu_string *name;
2853606686eeSJosef Bacik 
2854606686eeSJosef Bacik 		rcu_read_lock();
2855606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
2856606686eeSJosef Bacik 		strncpy(di_args->path, name->str, sizeof(di_args->path));
2857606686eeSJosef Bacik 		rcu_read_unlock();
2858a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
2859a27202fbSJim Meyering 	} else {
286099ba55adSStefan Behrens 		di_args->path[0] = '\0';
2861a27202fbSJim Meyering 	}
2862475f6387SJan Schmidt 
2863475f6387SJan Schmidt out:
286455793c0dSDavid Sterba 	mutex_unlock(&fs_devices->device_list_mutex);
2865475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2866475f6387SJan Schmidt 		ret = -EFAULT;
2867475f6387SJan Schmidt 
2868475f6387SJan Schmidt 	kfree(di_args);
2869475f6387SJan Schmidt 	return ret;
2870475f6387SJan Schmidt }
2871475f6387SJan Schmidt 
2872f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2873416161dbSMark Fasheh {
2874416161dbSMark Fasheh 	struct page *page;
2875416161dbSMark Fasheh 
2876416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
2877416161dbSMark Fasheh 	if (!page)
287831314002SFilipe Manana 		return ERR_PTR(-ENOMEM);
2879416161dbSMark Fasheh 
2880416161dbSMark Fasheh 	if (!PageUptodate(page)) {
288131314002SFilipe Manana 		int ret;
288231314002SFilipe Manana 
288331314002SFilipe Manana 		ret = btrfs_readpage(NULL, page);
288431314002SFilipe Manana 		if (ret)
288531314002SFilipe Manana 			return ERR_PTR(ret);
2886416161dbSMark Fasheh 		lock_page(page);
2887416161dbSMark Fasheh 		if (!PageUptodate(page)) {
2888416161dbSMark Fasheh 			unlock_page(page);
288909cbfeafSKirill A. Shutemov 			put_page(page);
289031314002SFilipe Manana 			return ERR_PTR(-EIO);
2891416161dbSMark Fasheh 		}
289231314002SFilipe Manana 		if (page->mapping != inode->i_mapping) {
2893416161dbSMark Fasheh 			unlock_page(page);
289409cbfeafSKirill A. Shutemov 			put_page(page);
289531314002SFilipe Manana 			return ERR_PTR(-EAGAIN);
2896416161dbSMark Fasheh 		}
2897416161dbSMark Fasheh 	}
2898416161dbSMark Fasheh 
2899416161dbSMark Fasheh 	return page;
2900416161dbSMark Fasheh }
2901416161dbSMark Fasheh 
2902f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
2903f4414602SMark Fasheh 			       int num_pages, u64 off)
2904f4414602SMark Fasheh {
2905f4414602SMark Fasheh 	int i;
290609cbfeafSKirill A. Shutemov 	pgoff_t index = off >> PAGE_SHIFT;
2907f4414602SMark Fasheh 
2908f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
290931314002SFilipe Manana again:
2910f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
291131314002SFilipe Manana 		if (IS_ERR(pages[i])) {
291231314002SFilipe Manana 			int err = PTR_ERR(pages[i]);
291331314002SFilipe Manana 
291431314002SFilipe Manana 			if (err == -EAGAIN)
291531314002SFilipe Manana 				goto again;
291631314002SFilipe Manana 			pages[i] = NULL;
291731314002SFilipe Manana 			return err;
291831314002SFilipe Manana 		}
2919f4414602SMark Fasheh 	}
2920f4414602SMark Fasheh 	return 0;
2921f4414602SMark Fasheh }
2922f4414602SMark Fasheh 
2923e0bd70c6SFilipe Manana static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2924e0bd70c6SFilipe Manana 			     bool retry_range_locking)
292577fe20dcSMark Fasheh {
2926e0bd70c6SFilipe Manana 	/*
2927e0bd70c6SFilipe Manana 	 * Do any pending delalloc/csum calculations on inode, one way or
2928e0bd70c6SFilipe Manana 	 * another, and lock file content.
2929e0bd70c6SFilipe Manana 	 * The locking order is:
2930e0bd70c6SFilipe Manana 	 *
2931e0bd70c6SFilipe Manana 	 *   1) pages
2932e0bd70c6SFilipe Manana 	 *   2) range in the inode's io tree
2933e0bd70c6SFilipe Manana 	 */
293477fe20dcSMark Fasheh 	while (1) {
293577fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
293677fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
293777fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
293877fe20dcSMark Fasheh 							    off + len - 1);
2939ff5df9b8SFilipe Manana 		if ((!ordered ||
2940ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
2941ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
294277fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2943ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2944ff5df9b8SFilipe Manana 			if (ordered)
2945ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
294677fe20dcSMark Fasheh 			break;
2947ff5df9b8SFilipe Manana 		}
294877fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
294977fe20dcSMark Fasheh 		if (ordered)
295077fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
2951e0bd70c6SFilipe Manana 		if (!retry_range_locking)
2952e0bd70c6SFilipe Manana 			return -EAGAIN;
295377fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
295477fe20dcSMark Fasheh 	}
2955e0bd70c6SFilipe Manana 	return 0;
295677fe20dcSMark Fasheh }
295777fe20dcSMark Fasheh 
2958f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2959416161dbSMark Fasheh {
29605955102cSAl Viro 	inode_unlock(inode1);
29615955102cSAl Viro 	inode_unlock(inode2);
2962416161dbSMark Fasheh }
2963416161dbSMark Fasheh 
2964f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2965f4414602SMark Fasheh {
2966f4414602SMark Fasheh 	if (inode1 < inode2)
2967f4414602SMark Fasheh 		swap(inode1, inode2);
2968f4414602SMark Fasheh 
29695955102cSAl Viro 	inode_lock_nested(inode1, I_MUTEX_PARENT);
29705955102cSAl Viro 	inode_lock_nested(inode2, I_MUTEX_CHILD);
2971f4414602SMark Fasheh }
2972f4414602SMark Fasheh 
2973f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2974f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
2975f4414602SMark Fasheh {
2976f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2977f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2978f4414602SMark Fasheh }
2979f4414602SMark Fasheh 
2980e0bd70c6SFilipe Manana static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2981e0bd70c6SFilipe Manana 				    struct inode *inode2, u64 loff2, u64 len,
2982e0bd70c6SFilipe Manana 				    bool retry_range_locking)
2983416161dbSMark Fasheh {
2984e0bd70c6SFilipe Manana 	int ret;
2985e0bd70c6SFilipe Manana 
2986416161dbSMark Fasheh 	if (inode1 < inode2) {
2987416161dbSMark Fasheh 		swap(inode1, inode2);
2988416161dbSMark Fasheh 		swap(loff1, loff2);
2989416161dbSMark Fasheh 	}
2990e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2991e0bd70c6SFilipe Manana 	if (ret)
2992e0bd70c6SFilipe Manana 		return ret;
2993e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2994e0bd70c6SFilipe Manana 	if (ret)
2995e0bd70c6SFilipe Manana 		unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2996e0bd70c6SFilipe Manana 			      loff1 + len - 1);
2997e0bd70c6SFilipe Manana 	return ret;
2998416161dbSMark Fasheh }
2999f4414602SMark Fasheh 
3000f4414602SMark Fasheh struct cmp_pages {
3001f4414602SMark Fasheh 	int		num_pages;
3002f4414602SMark Fasheh 	struct page	**src_pages;
3003f4414602SMark Fasheh 	struct page	**dst_pages;
3004f4414602SMark Fasheh };
3005f4414602SMark Fasheh 
3006f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
3007f4414602SMark Fasheh {
3008f4414602SMark Fasheh 	int i;
3009f4414602SMark Fasheh 	struct page *pg;
3010f4414602SMark Fasheh 
3011f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
3012f4414602SMark Fasheh 		pg = cmp->src_pages[i];
3013e0bd70c6SFilipe Manana 		if (pg) {
3014e0bd70c6SFilipe Manana 			unlock_page(pg);
301509cbfeafSKirill A. Shutemov 			put_page(pg);
3016e0bd70c6SFilipe Manana 		}
3017f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
3018e0bd70c6SFilipe Manana 		if (pg) {
3019e0bd70c6SFilipe Manana 			unlock_page(pg);
302009cbfeafSKirill A. Shutemov 			put_page(pg);
3021f4414602SMark Fasheh 		}
3022e0bd70c6SFilipe Manana 	}
3023f4414602SMark Fasheh 	kfree(cmp->src_pages);
3024f4414602SMark Fasheh 	kfree(cmp->dst_pages);
3025f4414602SMark Fasheh }
3026f4414602SMark Fasheh 
3027f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
3028f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
3029f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
3030f4414602SMark Fasheh {
3031f4414602SMark Fasheh 	int ret;
303209cbfeafSKirill A. Shutemov 	int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
3033f4414602SMark Fasheh 	struct page **src_pgarr, **dst_pgarr;
3034f4414602SMark Fasheh 
3035f4414602SMark Fasheh 	/*
3036f4414602SMark Fasheh 	 * We must gather up all the pages before we initiate our
3037f4414602SMark Fasheh 	 * extent locking. We use an array for the page pointers. Size
3038f4414602SMark Fasheh 	 * of the array is bounded by len, which is in turn bounded by
3039f4414602SMark Fasheh 	 * BTRFS_MAX_DEDUPE_LEN.
3040f4414602SMark Fasheh 	 */
304166722f7cSDavid Sterba 	src_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
304266722f7cSDavid Sterba 	dst_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
3043f4414602SMark Fasheh 	if (!src_pgarr || !dst_pgarr) {
3044f4414602SMark Fasheh 		kfree(src_pgarr);
3045f4414602SMark Fasheh 		kfree(dst_pgarr);
3046f4414602SMark Fasheh 		return -ENOMEM;
3047f4414602SMark Fasheh 	}
3048f4414602SMark Fasheh 	cmp->num_pages = num_pages;
3049f4414602SMark Fasheh 	cmp->src_pages = src_pgarr;
3050f4414602SMark Fasheh 	cmp->dst_pages = dst_pgarr;
3051f4414602SMark Fasheh 
3052f4414602SMark Fasheh 	ret = gather_extent_pages(src, cmp->src_pages, cmp->num_pages, loff);
3053f4414602SMark Fasheh 	if (ret)
3054f4414602SMark Fasheh 		goto out;
3055f4414602SMark Fasheh 
3056f4414602SMark Fasheh 	ret = gather_extent_pages(dst, cmp->dst_pages, cmp->num_pages, dst_loff);
3057f4414602SMark Fasheh 
3058f4414602SMark Fasheh out:
3059f4414602SMark Fasheh 	if (ret)
3060f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
3061f4414602SMark Fasheh 	return 0;
3062416161dbSMark Fasheh }
3063416161dbSMark Fasheh 
3064416161dbSMark Fasheh static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
3065f4414602SMark Fasheh 			  u64 dst_loff, u64 len, struct cmp_pages *cmp)
3066416161dbSMark Fasheh {
3067416161dbSMark Fasheh 	int ret = 0;
3068f4414602SMark Fasheh 	int i;
3069416161dbSMark Fasheh 	struct page *src_page, *dst_page;
307009cbfeafSKirill A. Shutemov 	unsigned int cmp_len = PAGE_SIZE;
3071416161dbSMark Fasheh 	void *addr, *dst_addr;
3072416161dbSMark Fasheh 
3073f4414602SMark Fasheh 	i = 0;
3074416161dbSMark Fasheh 	while (len) {
307509cbfeafSKirill A. Shutemov 		if (len < PAGE_SIZE)
3076416161dbSMark Fasheh 			cmp_len = len;
3077416161dbSMark Fasheh 
3078f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
3079f4414602SMark Fasheh 
3080f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
3081f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
3082e0bd70c6SFilipe Manana 		ASSERT(PageLocked(src_page));
3083e0bd70c6SFilipe Manana 		ASSERT(PageLocked(dst_page));
3084f4414602SMark Fasheh 
3085416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
3086416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
3087416161dbSMark Fasheh 
3088416161dbSMark Fasheh 		flush_dcache_page(src_page);
3089416161dbSMark Fasheh 		flush_dcache_page(dst_page);
3090416161dbSMark Fasheh 
3091416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
30922b3909f8SDarrick J. Wong 			ret = -EBADE;
3093416161dbSMark Fasheh 
3094416161dbSMark Fasheh 		kunmap_atomic(addr);
3095416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
3096416161dbSMark Fasheh 
3097416161dbSMark Fasheh 		if (ret)
3098416161dbSMark Fasheh 			break;
3099416161dbSMark Fasheh 
3100416161dbSMark Fasheh 		len -= cmp_len;
3101f4414602SMark Fasheh 		i++;
3102416161dbSMark Fasheh 	}
3103416161dbSMark Fasheh 
3104416161dbSMark Fasheh 	return ret;
3105416161dbSMark Fasheh }
3106416161dbSMark Fasheh 
3107e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3108e1d227a4SMark Fasheh 				     u64 olen)
3109416161dbSMark Fasheh {
3110e1d227a4SMark Fasheh 	u64 len = *plen;
3111416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3112416161dbSMark Fasheh 
3113e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
3114416161dbSMark Fasheh 		return -EINVAL;
3115e1d227a4SMark Fasheh 
3116e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
3117e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
3118e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
3119e1d227a4SMark Fasheh 
3120416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
3121416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3122416161dbSMark Fasheh 		return -EINVAL;
3123416161dbSMark Fasheh 
3124416161dbSMark Fasheh 	return 0;
3125416161dbSMark Fasheh }
3126416161dbSMark Fasheh 
3127e1d227a4SMark Fasheh static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3128416161dbSMark Fasheh 			     struct inode *dst, u64 dst_loff)
3129416161dbSMark Fasheh {
3130416161dbSMark Fasheh 	int ret;
3131e1d227a4SMark Fasheh 	u64 len = olen;
3132f4414602SMark Fasheh 	struct cmp_pages cmp;
31330efa9f48SMark Fasheh 	int same_inode = 0;
31340efa9f48SMark Fasheh 	u64 same_lock_start = 0;
31350efa9f48SMark Fasheh 	u64 same_lock_len = 0;
3136416161dbSMark Fasheh 
3137416161dbSMark Fasheh 	if (src == dst)
31380efa9f48SMark Fasheh 		same_inode = 1;
3139416161dbSMark Fasheh 
3140113e8283SFilipe Manana 	if (len == 0)
3141113e8283SFilipe Manana 		return 0;
3142113e8283SFilipe Manana 
31430efa9f48SMark Fasheh 	if (same_inode) {
31445955102cSAl Viro 		inode_lock(src);
31450efa9f48SMark Fasheh 
31460efa9f48SMark Fasheh 		ret = extent_same_check_offsets(src, loff, &len, olen);
31470efa9f48SMark Fasheh 		if (ret)
31480efa9f48SMark Fasheh 			goto out_unlock;
3149f4dfe687SFilipe Manana 		ret = extent_same_check_offsets(src, dst_loff, &len, olen);
3150f4dfe687SFilipe Manana 		if (ret)
3151f4dfe687SFilipe Manana 			goto out_unlock;
31520efa9f48SMark Fasheh 
31530efa9f48SMark Fasheh 		/*
31540efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
31550efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
31560efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
31570efa9f48SMark Fasheh 		 *
31580efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
31590efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
31600efa9f48SMark Fasheh 		 * reject the request.
31610efa9f48SMark Fasheh 		 *
31620efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
31630efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
31640efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
31650efa9f48SMark Fasheh 		 * i_size.
31660efa9f48SMark Fasheh 		 */
31670efa9f48SMark Fasheh 		if (len != olen) {
31680efa9f48SMark Fasheh 			ret = -EINVAL;
31690efa9f48SMark Fasheh 			goto out_unlock;
31700efa9f48SMark Fasheh 		}
31710efa9f48SMark Fasheh 
31720efa9f48SMark Fasheh 		/* Check for overlapping ranges */
31730efa9f48SMark Fasheh 		if (dst_loff + len > loff && dst_loff < loff + len) {
31740efa9f48SMark Fasheh 			ret = -EINVAL;
31750efa9f48SMark Fasheh 			goto out_unlock;
31760efa9f48SMark Fasheh 		}
31770efa9f48SMark Fasheh 
31780efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
31790efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
31800efa9f48SMark Fasheh 	} else {
3181f4414602SMark Fasheh 		btrfs_double_inode_lock(src, dst);
3182416161dbSMark Fasheh 
3183e1d227a4SMark Fasheh 		ret = extent_same_check_offsets(src, loff, &len, olen);
3184416161dbSMark Fasheh 		if (ret)
3185416161dbSMark Fasheh 			goto out_unlock;
3186416161dbSMark Fasheh 
3187e1d227a4SMark Fasheh 		ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3188416161dbSMark Fasheh 		if (ret)
3189416161dbSMark Fasheh 			goto out_unlock;
31900efa9f48SMark Fasheh 	}
3191416161dbSMark Fasheh 
3192416161dbSMark Fasheh 	/* don't make the dst file partly checksummed */
3193416161dbSMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3194416161dbSMark Fasheh 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3195416161dbSMark Fasheh 		ret = -EINVAL;
3196416161dbSMark Fasheh 		goto out_unlock;
3197416161dbSMark Fasheh 	}
3198416161dbSMark Fasheh 
3199e0bd70c6SFilipe Manana again:
3200f4414602SMark Fasheh 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3201f4414602SMark Fasheh 	if (ret)
3202f4414602SMark Fasheh 		goto out_unlock;
3203f4414602SMark Fasheh 
32040efa9f48SMark Fasheh 	if (same_inode)
3205e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, same_lock_start, same_lock_len,
3206e0bd70c6SFilipe Manana 					false);
32070efa9f48SMark Fasheh 	else
3208e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3209e0bd70c6SFilipe Manana 					       false);
3210e0bd70c6SFilipe Manana 	/*
3211e0bd70c6SFilipe Manana 	 * If one of the inodes has dirty pages in the respective range or
3212e0bd70c6SFilipe Manana 	 * ordered extents, we need to flush dellaloc and wait for all ordered
3213e0bd70c6SFilipe Manana 	 * extents in the range. We must unlock the pages and the ranges in the
3214e0bd70c6SFilipe Manana 	 * io trees to avoid deadlocks when flushing delalloc (requires locking
3215e0bd70c6SFilipe Manana 	 * pages) and when waiting for ordered extents to complete (they require
3216e0bd70c6SFilipe Manana 	 * range locking).
3217e0bd70c6SFilipe Manana 	 */
3218e0bd70c6SFilipe Manana 	if (ret == -EAGAIN) {
3219e0bd70c6SFilipe Manana 		/*
3220e0bd70c6SFilipe Manana 		 * Ranges in the io trees already unlocked. Now unlock all
3221e0bd70c6SFilipe Manana 		 * pages before waiting for all IO to complete.
3222e0bd70c6SFilipe Manana 		 */
3223e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
3224e0bd70c6SFilipe Manana 		if (same_inode) {
3225e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, same_lock_start,
3226e0bd70c6SFilipe Manana 						 same_lock_len);
3227e0bd70c6SFilipe Manana 		} else {
3228e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, loff, len);
3229e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(dst, dst_loff, len);
3230e0bd70c6SFilipe Manana 		}
3231e0bd70c6SFilipe Manana 		goto again;
3232e0bd70c6SFilipe Manana 	}
3233e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3234e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3235e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3236e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
3237e0bd70c6SFilipe Manana 		return ret;
3238e0bd70c6SFilipe Manana 	}
3239f4414602SMark Fasheh 
3240207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
3241f4414602SMark Fasheh 	ret = btrfs_cmp_data(src, loff, dst, dst_loff, olen, &cmp);
3242416161dbSMark Fasheh 	if (ret == 0)
32431c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3244416161dbSMark Fasheh 
32450efa9f48SMark Fasheh 	if (same_inode)
32460efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
32470efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
32480efa9f48SMark Fasheh 	else
3249f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3250f4414602SMark Fasheh 
3251f4414602SMark Fasheh 	btrfs_cmp_data_free(&cmp);
3252416161dbSMark Fasheh out_unlock:
32530efa9f48SMark Fasheh 	if (same_inode)
32545955102cSAl Viro 		inode_unlock(src);
32550efa9f48SMark Fasheh 	else
3256f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3257416161dbSMark Fasheh 
3258416161dbSMark Fasheh 	return ret;
3259416161dbSMark Fasheh }
3260416161dbSMark Fasheh 
3261ee22184bSByongho Lee #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3262416161dbSMark Fasheh 
32632b3909f8SDarrick J. Wong ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
32642b3909f8SDarrick J. Wong 				struct file *dst_file, u64 dst_loff)
3265416161dbSMark Fasheh {
32662b3909f8SDarrick J. Wong 	struct inode *src = file_inode(src_file);
32672b3909f8SDarrick J. Wong 	struct inode *dst = file_inode(dst_file);
3268416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
32692b3909f8SDarrick J. Wong 	ssize_t res;
3270416161dbSMark Fasheh 
32712b3909f8SDarrick J. Wong 	if (olen > BTRFS_MAX_DEDUPE_LEN)
32722b3909f8SDarrick J. Wong 		olen = BTRFS_MAX_DEDUPE_LEN;
3273416161dbSMark Fasheh 
327409cbfeafSKirill A. Shutemov 	if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3275416161dbSMark Fasheh 		/*
3276416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3277416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3278416161dbSMark Fasheh 		 * this situation without an update.
3279416161dbSMark Fasheh 		 */
32802b3909f8SDarrick J. Wong 		return -EINVAL;
3281416161dbSMark Fasheh 	}
3282416161dbSMark Fasheh 
32832b3909f8SDarrick J. Wong 	res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
32842b3909f8SDarrick J. Wong 	if (res)
32852b3909f8SDarrick J. Wong 		return res;
32862b3909f8SDarrick J. Wong 	return olen;
3287416161dbSMark Fasheh }
3288416161dbSMark Fasheh 
3289f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3290f82a9901SFilipe Manana 				     struct inode *inode,
3291f82a9901SFilipe Manana 				     u64 endoff,
3292f82a9901SFilipe Manana 				     const u64 destoff,
32931c919a5eSMark Fasheh 				     const u64 olen,
32941c919a5eSMark Fasheh 				     int no_time_update)
3295f82a9901SFilipe Manana {
3296f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3297f82a9901SFilipe Manana 	int ret;
3298f82a9901SFilipe Manana 
3299f82a9901SFilipe Manana 	inode_inc_iversion(inode);
33001c919a5eSMark Fasheh 	if (!no_time_update)
3301c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3302f82a9901SFilipe Manana 	/*
3303f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3304f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3305f82a9901SFilipe Manana 	 */
3306f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3307f82a9901SFilipe Manana 		endoff = destoff + olen;
3308f82a9901SFilipe Manana 	if (endoff > inode->i_size)
3309f82a9901SFilipe Manana 		btrfs_i_size_write(inode, endoff);
3310f82a9901SFilipe Manana 
3311f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3312f82a9901SFilipe Manana 	if (ret) {
331366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
3314f82a9901SFilipe Manana 		btrfs_end_transaction(trans, root);
3315f82a9901SFilipe Manana 		goto out;
3316f82a9901SFilipe Manana 	}
3317f82a9901SFilipe Manana 	ret = btrfs_end_transaction(trans, root);
3318f82a9901SFilipe Manana out:
3319f82a9901SFilipe Manana 	return ret;
3320f82a9901SFilipe Manana }
3321f82a9901SFilipe Manana 
33227ffbb598SFilipe Manana static void clone_update_extent_map(struct inode *inode,
33237ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
33247ffbb598SFilipe Manana 				    const struct btrfs_path *path,
33257ffbb598SFilipe Manana 				    const u64 hole_offset,
33267ffbb598SFilipe Manana 				    const u64 hole_len)
33277ffbb598SFilipe Manana {
33287ffbb598SFilipe Manana 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
33297ffbb598SFilipe Manana 	struct extent_map *em;
33307ffbb598SFilipe Manana 	int ret;
33317ffbb598SFilipe Manana 
33327ffbb598SFilipe Manana 	em = alloc_extent_map();
33337ffbb598SFilipe Manana 	if (!em) {
33347ffbb598SFilipe Manana 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
33357ffbb598SFilipe Manana 			&BTRFS_I(inode)->runtime_flags);
33367ffbb598SFilipe Manana 		return;
33377ffbb598SFilipe Manana 	}
33387ffbb598SFilipe Manana 
333914f59796SFilipe Manana 	if (path) {
334014f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
334114f59796SFilipe Manana 
334214f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
334314f59796SFilipe Manana 				    struct btrfs_file_extent_item);
33447ffbb598SFilipe Manana 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
33457ffbb598SFilipe Manana 		em->generation = -1;
33467ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
33477ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
33487ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
33497ffbb598SFilipe Manana 				&BTRFS_I(inode)->runtime_flags);
33507ffbb598SFilipe Manana 	} else {
33517ffbb598SFilipe Manana 		em->start = hole_offset;
33527ffbb598SFilipe Manana 		em->len = hole_len;
33537ffbb598SFilipe Manana 		em->ram_bytes = em->len;
33547ffbb598SFilipe Manana 		em->orig_start = hole_offset;
33557ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
33567ffbb598SFilipe Manana 		em->block_len = 0;
33577ffbb598SFilipe Manana 		em->orig_block_len = 0;
33587ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
33597ffbb598SFilipe Manana 		em->generation = trans->transid;
33607ffbb598SFilipe Manana 	}
33617ffbb598SFilipe Manana 
33627ffbb598SFilipe Manana 	while (1) {
33637ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
33647ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
33657ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
33667ffbb598SFilipe Manana 		if (ret != -EEXIST) {
33677ffbb598SFilipe Manana 			free_extent_map(em);
33687ffbb598SFilipe Manana 			break;
33697ffbb598SFilipe Manana 		}
33707ffbb598SFilipe Manana 		btrfs_drop_extent_cache(inode, em->start,
33717ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
33727ffbb598SFilipe Manana 	}
33737ffbb598SFilipe Manana 
3374ee39b432SDavid Sterba 	if (ret)
33757ffbb598SFilipe Manana 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
33767ffbb598SFilipe Manana 			&BTRFS_I(inode)->runtime_flags);
33777ffbb598SFilipe Manana }
33787ffbb598SFilipe Manana 
33798039d87dSFilipe Manana /*
33808039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
33818039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
33828039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
33838039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
33848039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
33858039d87dSFilipe Manana  *
33868039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
33878039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
33888039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
33898039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
33908039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
33918039d87dSFilipe Manana  * i_mutex, which we are holding here).
33928039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
33938039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
33948039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
33958039d87dSFilipe Manana  *
33968039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
33978039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
33988039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
33998039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
34008039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
34018039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
34028039d87dSFilipe Manana  * the former.
34038039d87dSFilipe Manana  */
34048039d87dSFilipe Manana static int clone_copy_inline_extent(struct inode *src,
34058039d87dSFilipe Manana 				    struct inode *dst,
34068039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
34078039d87dSFilipe Manana 				    struct btrfs_path *path,
34088039d87dSFilipe Manana 				    struct btrfs_key *new_key,
34098039d87dSFilipe Manana 				    const u64 drop_start,
34108039d87dSFilipe Manana 				    const u64 datal,
34118039d87dSFilipe Manana 				    const u64 skip,
34128039d87dSFilipe Manana 				    const u64 size,
34138039d87dSFilipe Manana 				    char *inline_data)
34148039d87dSFilipe Manana {
34150b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
34168039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
34178039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
34180b246afaSJeff Mahoney 				      fs_info->sectorsize);
34198039d87dSFilipe Manana 	int ret;
34208039d87dSFilipe Manana 	struct btrfs_key key;
34218039d87dSFilipe Manana 
34228039d87dSFilipe Manana 	if (new_key->offset > 0)
34238039d87dSFilipe Manana 		return -EOPNOTSUPP;
34248039d87dSFilipe Manana 
34258039d87dSFilipe Manana 	key.objectid = btrfs_ino(dst);
34268039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
34278039d87dSFilipe Manana 	key.offset = 0;
34288039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
34298039d87dSFilipe Manana 	if (ret < 0) {
34308039d87dSFilipe Manana 		return ret;
34318039d87dSFilipe Manana 	} else if (ret > 0) {
34328039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
34338039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
34348039d87dSFilipe Manana 			if (ret < 0)
34358039d87dSFilipe Manana 				return ret;
34368039d87dSFilipe Manana 			else if (ret > 0)
34378039d87dSFilipe Manana 				goto copy_inline_extent;
34388039d87dSFilipe Manana 		}
34398039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
34408039d87dSFilipe Manana 		if (key.objectid == btrfs_ino(dst) &&
34418039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
34428039d87dSFilipe Manana 			ASSERT(key.offset > 0);
34438039d87dSFilipe Manana 			return -EOPNOTSUPP;
34448039d87dSFilipe Manana 		}
34458039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
34468039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
34478039d87dSFilipe Manana 		u64 ext_len;
34488039d87dSFilipe Manana 
34498039d87dSFilipe Manana 		/*
34508039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
34518039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
34528039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
34538039d87dSFilipe Manana 		 */
34548039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
34558039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
34568039d87dSFilipe Manana 		/*
34578039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
34588039d87dSFilipe Manana 		 * following it.
34598039d87dSFilipe Manana 		 */
34608039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
34618039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
34628039d87dSFilipe Manana 			goto copy_inline_extent;
34638039d87dSFilipe Manana 
34648039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
34658039d87dSFilipe Manana 		if (ext_len > aligned_end)
34668039d87dSFilipe Manana 			return -EOPNOTSUPP;
34678039d87dSFilipe Manana 
34688039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
34698039d87dSFilipe Manana 		if (ret < 0) {
34708039d87dSFilipe Manana 			return ret;
34718039d87dSFilipe Manana 		} else if (ret == 0) {
34728039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
34738039d87dSFilipe Manana 					      path->slots[0]);
34748039d87dSFilipe Manana 			if (key.objectid == btrfs_ino(dst) &&
34758039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
34768039d87dSFilipe Manana 				return -EOPNOTSUPP;
34778039d87dSFilipe Manana 		}
34788039d87dSFilipe Manana 	}
34798039d87dSFilipe Manana 
34808039d87dSFilipe Manana copy_inline_extent:
34818039d87dSFilipe Manana 	/*
34828039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
34838039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
34848039d87dSFilipe Manana 	 */
34858039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
34868039d87dSFilipe Manana 		/*
34878039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
34888039d87dSFilipe Manana 		 * This would require copying the data from the source inline
34898039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
34908039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
34918039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
34928039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
34938039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
34948039d87dSFilipe Manana 		 * inline extent).
34958039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
34968039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
34978039d87dSFilipe Manana 		 */
34988039d87dSFilipe Manana 		return -EOPNOTSUPP;
34998039d87dSFilipe Manana 	}
35008039d87dSFilipe Manana 
35018039d87dSFilipe Manana 	btrfs_release_path(path);
35028039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
35038039d87dSFilipe Manana 	if (ret)
35048039d87dSFilipe Manana 		return ret;
35058039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
35068039d87dSFilipe Manana 	if (ret)
35078039d87dSFilipe Manana 		return ret;
35088039d87dSFilipe Manana 
35098039d87dSFilipe Manana 	if (skip) {
35108039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
35118039d87dSFilipe Manana 
35128039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
35138039d87dSFilipe Manana 	}
35148039d87dSFilipe Manana 
35158039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
35168039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
35178039d87dSFilipe Manana 						  path->slots[0]),
35188039d87dSFilipe Manana 			    size);
35198039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
35208039d87dSFilipe Manana 
35218039d87dSFilipe Manana 	return 0;
35228039d87dSFilipe Manana }
35238039d87dSFilipe Manana 
352432b7c687SMark Fasheh /**
352532b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
352632b7c687SMark Fasheh  *
352732b7c687SMark Fasheh  * @src: Inode to clone from
352832b7c687SMark Fasheh  * @inode: Inode to clone to
352932b7c687SMark Fasheh  * @off: Offset within source to start clone from
353032b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
35311c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
353232b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
35331c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
353432b7c687SMark Fasheh  */
353532b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3536f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
35371c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3538f46b5a66SChristoph Hellwig {
35390b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3540f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
354132b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3542f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
354332b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
354432b7c687SMark Fasheh 	char *buf = NULL;
3545ae01a0abSYan Zheng 	struct btrfs_key key;
3546f46b5a66SChristoph Hellwig 	u32 nritems;
3547f46b5a66SChristoph Hellwig 	int slot;
3548ae01a0abSYan Zheng 	int ret;
3549f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3550f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3551ae01a0abSYan Zheng 
3552ae01a0abSYan Zheng 	ret = -ENOMEM;
35530b246afaSJeff Mahoney 	buf = kmalloc(fs_info->nodesize, GFP_KERNEL | __GFP_NOWARN);
355415351955SDavid Sterba 	if (!buf) {
35550b246afaSJeff Mahoney 		buf = vmalloc(fs_info->nodesize);
3556ae01a0abSYan Zheng 		if (!buf)
355732b7c687SMark Fasheh 			return ret;
355815351955SDavid Sterba 	}
3559ae01a0abSYan Zheng 
3560ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3561ae01a0abSYan Zheng 	if (!path) {
356215351955SDavid Sterba 		kvfree(buf);
356332b7c687SMark Fasheh 		return ret;
3564ae01a0abSYan Zheng 	}
356532b7c687SMark Fasheh 
3566e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3567c5c9cd4dSSage Weil 	/* clone data */
356833345d01SLi Zefan 	key.objectid = btrfs_ino(src);
3569ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
35702c463823SFilipe Manana 	key.offset = off;
3571f46b5a66SChristoph Hellwig 
3572f46b5a66SChristoph Hellwig 	while (1) {
3573de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3574df858e76SFilipe Manana 
3575f46b5a66SChristoph Hellwig 		/*
3576f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3577f46b5a66SChristoph Hellwig 		 * tree.
3578f46b5a66SChristoph Hellwig 		 */
3579e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3580362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3581362a20c5SDavid Sterba 				0, 0);
3582f46b5a66SChristoph Hellwig 		if (ret < 0)
3583f46b5a66SChristoph Hellwig 			goto out;
35842c463823SFilipe Manana 		/*
35852c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
35862c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
35872c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
35882c463823SFilipe Manana 		 */
35892c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
35902c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
35912c463823SFilipe Manana 					      path->slots[0] - 1);
35922c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
35932c463823SFilipe Manana 				path->slots[0]--;
35942c463823SFilipe Manana 		}
3595f46b5a66SChristoph Hellwig 
3596ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3597e4355f34SFilipe David Borba Manana process_slot:
3598ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3599362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3600f46b5a66SChristoph Hellwig 			if (ret < 0)
3601f46b5a66SChristoph Hellwig 				goto out;
3602f46b5a66SChristoph Hellwig 			if (ret > 0)
3603f46b5a66SChristoph Hellwig 				break;
3604ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3605f46b5a66SChristoph Hellwig 		}
3606f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3607f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3608f46b5a66SChristoph Hellwig 
3609ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3610962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
361133345d01SLi Zefan 		    key.objectid != btrfs_ino(src))
3612f46b5a66SChristoph Hellwig 			break;
3613f46b5a66SChristoph Hellwig 
3614962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3615c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3616c5c9cd4dSSage Weil 			int type;
361731840ae1SZheng Yan 			u32 size;
361831840ae1SZheng Yan 			struct btrfs_key new_key;
3619c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3620c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3621c5c9cd4dSSage Weil 			u8 comp;
3622f82a9901SFilipe Manana 			u64 drop_start;
362331840ae1SZheng Yan 
3624c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3625c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3626c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3627c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3628c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3629c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3630d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3631d397712bSChris Mason 								      extent);
3632d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3633d397712bSChris Mason 								 extent);
3634c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3635d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3636d397712bSChris Mason 								    extent);
3637c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3638c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3639c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3640c5c9cd4dSSage Weil 								    extent);
3641c5c9cd4dSSage Weil 			}
364231840ae1SZheng Yan 
36432c463823SFilipe Manana 			/*
36442c463823SFilipe Manana 			 * The first search might have left us at an extent
36452c463823SFilipe Manana 			 * item that ends before our target range's start, can
36462c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
36472c463823SFilipe Manana 			 */
36482c463823SFilipe Manana 			if (key.offset + datal <= off) {
3649e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3650e4355f34SFilipe David Borba Manana 				goto process_slot;
36512c463823SFilipe Manana 			} else if (key.offset >= off + len) {
36522c463823SFilipe Manana 				break;
3653e4355f34SFilipe David Borba Manana 			}
3654df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3655e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3656e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3657e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3658e4355f34SFilipe David Borba Manana 					   size);
3659e4355f34SFilipe David Borba Manana 
3660e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3661e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3662c5c9cd4dSSage Weil 
366331840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
366433345d01SLi Zefan 			new_key.objectid = btrfs_ino(inode);
36654d728ec7SLi Zefan 			if (off <= key.offset)
3666c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
36674d728ec7SLi Zefan 			else
36684d728ec7SLi Zefan 				new_key.offset = destoff;
3669c5c9cd4dSSage Weil 
3670b6f3409bSSage Weil 			/*
3671f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3672f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3673f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3674f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3675f82a9901SFilipe Manana 			 * partially overlaps it).
3676f82a9901SFilipe Manana 			 */
3677f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3678f82a9901SFilipe Manana 				drop_start = last_dest_end;
3679f82a9901SFilipe Manana 			else
3680f82a9901SFilipe Manana 				drop_start = new_key.offset;
3681f82a9901SFilipe Manana 
3682f82a9901SFilipe Manana 			/*
3683b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3684b6f3409bSSage Weil 			 * 1 - add new extent
3685b6f3409bSSage Weil 			 * 1 - inode update
3686b6f3409bSSage Weil 			 */
3687b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3688a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3689a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3690a22285a6SYan, Zheng 				goto out;
3691a22285a6SYan, Zheng 			}
3692a22285a6SYan, Zheng 
3693c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3694c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3695d72c0842SLi Zefan 				/*
3696d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3697d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3698d72c0842SLi Zefan 				 */
3699d72c0842SLi Zefan 
370093915584SAntonio Ospite 				/* subtract range b */
3701d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3702d72c0842SLi Zefan 					datal = off + len - key.offset;
3703d72c0842SLi Zefan 
370493915584SAntonio Ospite 				/* subtract range a */
3705a22285a6SYan, Zheng 				if (off > key.offset) {
3706a22285a6SYan, Zheng 					datao += off - key.offset;
3707a22285a6SYan, Zheng 					datal -= off - key.offset;
3708a22285a6SYan, Zheng 				}
3709a22285a6SYan, Zheng 
37105dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3711f82a9901SFilipe Manana 							 drop_start,
3712a22285a6SYan, Zheng 							 new_key.offset + datal,
37132671485dSJosef Bacik 							 1);
371479787eaaSJeff Mahoney 				if (ret) {
37153f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
371600fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
371766642832SJeff Mahoney 									ret);
371879787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
371979787eaaSJeff Mahoney 					goto out;
372079787eaaSJeff Mahoney 				}
3721a22285a6SYan, Zheng 
372231840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
372331840ae1SZheng Yan 							      &new_key, size);
372479787eaaSJeff Mahoney 				if (ret) {
372566642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
372679787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
372779787eaaSJeff Mahoney 					goto out;
372879787eaaSJeff Mahoney 				}
372931840ae1SZheng Yan 
373031840ae1SZheng Yan 				leaf = path->nodes[0];
373131840ae1SZheng Yan 				slot = path->slots[0];
373231840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
373331840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
373431840ae1SZheng Yan 					    size);
3735ae01a0abSYan Zheng 
3736f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3737f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3738c5c9cd4dSSage Weil 
3739c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3740c5c9cd4dSSage Weil 				if (!disko)
3741c5c9cd4dSSage Weil 					datao = 0;
3742c5c9cd4dSSage Weil 
3743c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3744c5c9cd4dSSage Weil 							     datao);
3745c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3746c5c9cd4dSSage Weil 								datal);
3747fcebe456SJosef Bacik 
3748c5c9cd4dSSage Weil 				if (disko) {
3749c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
37502ff7e61eSJeff Mahoney 					ret = btrfs_inc_extent_ref(trans,
37512ff7e61eSJeff Mahoney 							fs_info,
37525d4f98a2SYan Zheng 							disko, diskl, 0,
3753f46b5a66SChristoph Hellwig 							root->root_key.objectid,
375433345d01SLi Zefan 							btrfs_ino(inode),
3755b06c4bf5SFilipe Manana 							new_key.offset - datao);
375679787eaaSJeff Mahoney 					if (ret) {
375779787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
375879787eaaSJeff Mahoney 									ret);
375979787eaaSJeff Mahoney 						btrfs_end_transaction(trans,
376079787eaaSJeff Mahoney 								      root);
376179787eaaSJeff Mahoney 						goto out;
376279787eaaSJeff Mahoney 
376379787eaaSJeff Mahoney 					}
3764f46b5a66SChristoph Hellwig 				}
3765c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3766c5c9cd4dSSage Weil 				u64 skip = 0;
3767c5c9cd4dSSage Weil 				u64 trim = 0;
3768ed958762SFilipe Manana 
3769c5c9cd4dSSage Weil 				if (off > key.offset) {
3770c5c9cd4dSSage Weil 					skip = off - key.offset;
3771c5c9cd4dSSage Weil 					new_key.offset += skip;
377231840ae1SZheng Yan 				}
3773d397712bSChris Mason 
3774c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3775c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3776d397712bSChris Mason 
3777c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3778c5c9cd4dSSage Weil 					ret = -EINVAL;
3779a22285a6SYan, Zheng 					btrfs_end_transaction(trans, root);
3780c5c9cd4dSSage Weil 					goto out;
378131840ae1SZheng Yan 				}
3782c5c9cd4dSSage Weil 				size -= skip + trim;
3783c5c9cd4dSSage Weil 				datal -= skip + trim;
3784a22285a6SYan, Zheng 
37858039d87dSFilipe Manana 				ret = clone_copy_inline_extent(src, inode,
37868039d87dSFilipe Manana 							       trans, path,
37878039d87dSFilipe Manana 							       &new_key,
3788f82a9901SFilipe Manana 							       drop_start,
37898039d87dSFilipe Manana 							       datal,
37908039d87dSFilipe Manana 							       skip, size, buf);
379179787eaaSJeff Mahoney 				if (ret) {
37923f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
37933a29bc09SChris Mason 						btrfs_abort_transaction(trans,
379479787eaaSJeff Mahoney 									ret);
379579787eaaSJeff Mahoney 					btrfs_end_transaction(trans, root);
379679787eaaSJeff Mahoney 					goto out;
379779787eaaSJeff Mahoney 				}
3798c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3799c5c9cd4dSSage Weil 				slot = path->slots[0];
3800c5c9cd4dSSage Weil 			}
3801c5c9cd4dSSage Weil 
38027ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
38037ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
38047ffbb598SFilipe Manana 				clone_update_extent_map(inode, trans,
380514f59796SFilipe Manana 						NULL, drop_start,
38067ffbb598SFilipe Manana 						new_key.offset - drop_start);
38077ffbb598SFilipe Manana 
380814f59796SFilipe Manana 			clone_update_extent_map(inode, trans, path, 0, 0);
38097ffbb598SFilipe Manana 
3810c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3811b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3812c5c9cd4dSSage Weil 
381362e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
38140b246afaSJeff Mahoney 					      fs_info->sectorsize);
3815f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3816f82a9901SFilipe Manana 							last_dest_end,
38171c919a5eSMark Fasheh 							destoff, olen,
38181c919a5eSMark Fasheh 							no_time_update);
3819f82a9901SFilipe Manana 			if (ret)
382079787eaaSJeff Mahoney 				goto out;
38212c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
38222c463823SFilipe Manana 				break;
3823a22285a6SYan, Zheng 		}
3824b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3825df858e76SFilipe Manana 		key.offset = next_key_min_offset;
382669ae5e44SWang Xiaoguang 
382769ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
382869ae5e44SWang Xiaoguang 			ret = -EINTR;
382969ae5e44SWang Xiaoguang 			goto out;
383069ae5e44SWang Xiaoguang 		}
3831ae01a0abSYan Zheng 	}
3832f46b5a66SChristoph Hellwig 	ret = 0;
383332b7c687SMark Fasheh 
3834f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3835f82a9901SFilipe Manana 		/*
3836f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3837f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3838f82a9901SFilipe Manana 		 */
3839b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3840f82a9901SFilipe Manana 
3841f82a9901SFilipe Manana 		/*
3842f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3843f82a9901SFilipe Manana 		 * 1 - inode update
3844f82a9901SFilipe Manana 		 */
3845f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3846f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3847f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3848f82a9901SFilipe Manana 			goto out;
3849f82a9901SFilipe Manana 		}
3850f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3851f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3852f82a9901SFilipe Manana 		if (ret) {
3853f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
385466642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
3855f82a9901SFilipe Manana 			btrfs_end_transaction(trans, root);
3856f82a9901SFilipe Manana 			goto out;
3857f82a9901SFilipe Manana 		}
385814f59796SFilipe Manana 		clone_update_extent_map(inode, trans, NULL, last_dest_end,
385914f59796SFilipe Manana 					destoff + len - last_dest_end);
3860f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
38611c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3862f82a9901SFilipe Manana 	}
3863f82a9901SFilipe Manana 
3864f46b5a66SChristoph Hellwig out:
386532b7c687SMark Fasheh 	btrfs_free_path(path);
386615351955SDavid Sterba 	kvfree(buf);
386732b7c687SMark Fasheh 	return ret;
386832b7c687SMark Fasheh }
386932b7c687SMark Fasheh 
38703db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
387132b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
387232b7c687SMark Fasheh {
387354563d41SAl Viro 	struct inode *inode = file_inode(file);
38743db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
38750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
387632b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
387732b7c687SMark Fasheh 	int ret;
387832b7c687SMark Fasheh 	u64 len = olen;
38790b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
38803db11b2eSZach Brown 	int same_inode = src == inode;
388132b7c687SMark Fasheh 
388232b7c687SMark Fasheh 	/*
388332b7c687SMark Fasheh 	 * TODO:
388432b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
388532b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
388632b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
388732b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
388800fdf13aSLiu Bo 	 *
388900fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
389000fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
389132b7c687SMark Fasheh 	 */
389232b7c687SMark Fasheh 
389332b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
389432b7c687SMark Fasheh 		return -EROFS;
389532b7c687SMark Fasheh 
38963db11b2eSZach Brown 	if (file_src->f_path.mnt != file->f_path.mnt ||
38973db11b2eSZach Brown 	    src->i_sb != inode->i_sb)
38983db11b2eSZach Brown 		return -EXDEV;
389932b7c687SMark Fasheh 
390032b7c687SMark Fasheh 	/* don't make the dst file partly checksummed */
390132b7c687SMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
390232b7c687SMark Fasheh 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
39033db11b2eSZach Brown 		return -EINVAL;
390432b7c687SMark Fasheh 
390532b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
39063db11b2eSZach Brown 		return -EISDIR;
390732b7c687SMark Fasheh 
390832b7c687SMark Fasheh 	if (!same_inode) {
3909293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
391032b7c687SMark Fasheh 	} else {
39115955102cSAl Viro 		inode_lock(src);
391232b7c687SMark Fasheh 	}
391332b7c687SMark Fasheh 
391432b7c687SMark Fasheh 	/* determine range to clone */
391532b7c687SMark Fasheh 	ret = -EINVAL;
391632b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
391732b7c687SMark Fasheh 		goto out_unlock;
391832b7c687SMark Fasheh 	if (len == 0)
391932b7c687SMark Fasheh 		olen = len = src->i_size - off;
392032b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
392132b7c687SMark Fasheh 	if (off + len == src->i_size)
392232b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
392332b7c687SMark Fasheh 
3924ccccf3d6SFilipe Manana 	if (len == 0) {
3925ccccf3d6SFilipe Manana 		ret = 0;
3926ccccf3d6SFilipe Manana 		goto out_unlock;
3927ccccf3d6SFilipe Manana 	}
3928ccccf3d6SFilipe Manana 
392932b7c687SMark Fasheh 	/* verify the end result is block aligned */
393032b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
393132b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
393232b7c687SMark Fasheh 		goto out_unlock;
393332b7c687SMark Fasheh 
393432b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
393532b7c687SMark Fasheh 	if (same_inode) {
393632b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
393732b7c687SMark Fasheh 			goto out_unlock;
393832b7c687SMark Fasheh 	}
393932b7c687SMark Fasheh 
394032b7c687SMark Fasheh 	if (destoff > inode->i_size) {
394132b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
394232b7c687SMark Fasheh 		if (ret)
394332b7c687SMark Fasheh 			goto out_unlock;
394432b7c687SMark Fasheh 	}
394532b7c687SMark Fasheh 
3946c125b8bfSFilipe Manana 	/*
3947c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
3948c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
3949c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
3950c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
3951c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
3952c125b8bfSFilipe Manana 	 */
3953c125b8bfSFilipe Manana 	if (same_inode) {
3954c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3955c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
395632b7c687SMark Fasheh 
3957e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, lock_start, lock_len, true);
3958c125b8bfSFilipe Manana 	} else {
3959e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
3960e0bd70c6SFilipe Manana 					       true);
3961e0bd70c6SFilipe Manana 	}
3962e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3963e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3964e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3965e0bd70c6SFilipe Manana 		goto out_unlock;
3966c125b8bfSFilipe Manana 	}
396732b7c687SMark Fasheh 
39681c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
396932b7c687SMark Fasheh 
3970c125b8bfSFilipe Manana 	if (same_inode) {
3971c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3972c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
3973c125b8bfSFilipe Manana 
3974c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3975c125b8bfSFilipe Manana 	} else {
3976293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
3977c125b8bfSFilipe Manana 	}
3978c125b8bfSFilipe Manana 	/*
3979c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3980c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3981c125b8bfSFilipe Manana 	 */
398265bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
398309cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
398409cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
3985f46b5a66SChristoph Hellwig out_unlock:
3986293a8489SMark Fasheh 	if (!same_inode)
3987293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
3988293a8489SMark Fasheh 	else
39895955102cSAl Viro 		inode_unlock(src);
39903db11b2eSZach Brown 	return ret;
39913db11b2eSZach Brown }
39923db11b2eSZach Brown 
39933db11b2eSZach Brown ssize_t btrfs_copy_file_range(struct file *file_in, loff_t pos_in,
39943db11b2eSZach Brown 			      struct file *file_out, loff_t pos_out,
39953db11b2eSZach Brown 			      size_t len, unsigned int flags)
39963db11b2eSZach Brown {
39973db11b2eSZach Brown 	ssize_t ret;
39983db11b2eSZach Brown 
39993db11b2eSZach Brown 	ret = btrfs_clone_files(file_out, file_in, pos_in, len, pos_out);
40003db11b2eSZach Brown 	if (ret == 0)
40013db11b2eSZach Brown 		ret = len;
40023db11b2eSZach Brown 	return ret;
40033db11b2eSZach Brown }
40043db11b2eSZach Brown 
400504b38d60SChristoph Hellwig int btrfs_clone_file_range(struct file *src_file, loff_t off,
400604b38d60SChristoph Hellwig 		struct file *dst_file, loff_t destoff, u64 len)
40073db11b2eSZach Brown {
400804b38d60SChristoph Hellwig 	return btrfs_clone_files(dst_file, src_file, off, len, destoff);
4009c5c9cd4dSSage Weil }
4010c5c9cd4dSSage Weil 
4011f46b5a66SChristoph Hellwig /*
4012f46b5a66SChristoph Hellwig  * there are many ways the trans_start and trans_end ioctls can lead
4013f46b5a66SChristoph Hellwig  * to deadlocks.  They should only be used by applications that
4014f46b5a66SChristoph Hellwig  * basically own the machine, and have a very in depth understanding
4015f46b5a66SChristoph Hellwig  * of all the possible deadlocks and enospc problems.
4016f46b5a66SChristoph Hellwig  */
4017b2950863SChristoph Hellwig static long btrfs_ioctl_trans_start(struct file *file)
4018f46b5a66SChristoph Hellwig {
4019496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
40200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4021f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
4022f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
40231ab86aedSSage Weil 	int ret;
4024f46b5a66SChristoph Hellwig 
40251ab86aedSSage Weil 	ret = -EPERM;
4026df5b5520SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
4027f46b5a66SChristoph Hellwig 		goto out;
40281ab86aedSSage Weil 
40291ab86aedSSage Weil 	ret = -EINPROGRESS;
40301ab86aedSSage Weil 	if (file->private_data)
40311ab86aedSSage Weil 		goto out;
40329ca9ee09SSage Weil 
4033b83cc969SLi Zefan 	ret = -EROFS;
4034b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
4035b83cc969SLi Zefan 		goto out;
4036b83cc969SLi Zefan 
4037a561be71SAl Viro 	ret = mnt_want_write_file(file);
4038c146afadSYan Zheng 	if (ret)
4039c146afadSYan Zheng 		goto out;
4040c146afadSYan Zheng 
40410b246afaSJeff Mahoney 	atomic_inc(&fs_info->open_ioctl_trans);
40429ca9ee09SSage Weil 
4043f46b5a66SChristoph Hellwig 	ret = -ENOMEM;
40447a7eaa40SJosef Bacik 	trans = btrfs_start_ioctl_transaction(root);
4045abd30bb0STsutomu Itoh 	if (IS_ERR(trans))
40461ab86aedSSage Weil 		goto out_drop;
40471ab86aedSSage Weil 
40481ab86aedSSage Weil 	file->private_data = trans;
40491ab86aedSSage Weil 	return 0;
40501ab86aedSSage Weil 
40511ab86aedSSage Weil out_drop:
40520b246afaSJeff Mahoney 	atomic_dec(&fs_info->open_ioctl_trans);
40532a79f17eSAl Viro 	mnt_drop_write_file(file);
4054f46b5a66SChristoph Hellwig out:
4055f46b5a66SChristoph Hellwig 	return ret;
4056f46b5a66SChristoph Hellwig }
4057f46b5a66SChristoph Hellwig 
40586ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
40596ef5ed0dSJosef Bacik {
4060496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
40610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
40626ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
40636ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
40646ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
40656ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
40666ef5ed0dSJosef Bacik 	struct btrfs_path *path;
40676ef5ed0dSJosef Bacik 	struct btrfs_key location;
40686ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
40696ef5ed0dSJosef Bacik 	u64 objectid = 0;
40706ef5ed0dSJosef Bacik 	u64 dir_id;
40713c04ce01SMiao Xie 	int ret;
40726ef5ed0dSJosef Bacik 
40736ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
40746ef5ed0dSJosef Bacik 		return -EPERM;
40756ef5ed0dSJosef Bacik 
40763c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
40773c04ce01SMiao Xie 	if (ret)
40783c04ce01SMiao Xie 		return ret;
40793c04ce01SMiao Xie 
40803c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
40813c04ce01SMiao Xie 		ret = -EFAULT;
40823c04ce01SMiao Xie 		goto out;
40833c04ce01SMiao Xie 	}
40846ef5ed0dSJosef Bacik 
40856ef5ed0dSJosef Bacik 	if (!objectid)
40861cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
40876ef5ed0dSJosef Bacik 
40886ef5ed0dSJosef Bacik 	location.objectid = objectid;
40896ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
40906ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
40916ef5ed0dSJosef Bacik 
40920b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
40933c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
40943c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
40953c04ce01SMiao Xie 		goto out;
40963c04ce01SMiao Xie 	}
40976ef5ed0dSJosef Bacik 
40986ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
40993c04ce01SMiao Xie 	if (!path) {
41003c04ce01SMiao Xie 		ret = -ENOMEM;
41013c04ce01SMiao Xie 		goto out;
41023c04ce01SMiao Xie 	}
41036ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
41046ef5ed0dSJosef Bacik 
41056ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
410698d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
41076ef5ed0dSJosef Bacik 		btrfs_free_path(path);
41083c04ce01SMiao Xie 		ret = PTR_ERR(trans);
41093c04ce01SMiao Xie 		goto out;
41106ef5ed0dSJosef Bacik 	}
41116ef5ed0dSJosef Bacik 
41120b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
41130b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
41146ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
4115cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
41166ef5ed0dSJosef Bacik 		btrfs_free_path(path);
41176ef5ed0dSJosef Bacik 		btrfs_end_transaction(trans, root);
41180b246afaSJeff Mahoney 		btrfs_err(fs_info,
41195d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
41203c04ce01SMiao Xie 		ret = -ENOENT;
41213c04ce01SMiao Xie 		goto out;
41226ef5ed0dSJosef Bacik 	}
41236ef5ed0dSJosef Bacik 
41246ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
41256ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
41266ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
41276ef5ed0dSJosef Bacik 	btrfs_free_path(path);
41286ef5ed0dSJosef Bacik 
41290b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
41306ef5ed0dSJosef Bacik 	btrfs_end_transaction(trans, root);
41313c04ce01SMiao Xie out:
41323c04ce01SMiao Xie 	mnt_drop_write_file(file);
41333c04ce01SMiao Xie 	return ret;
41346ef5ed0dSJosef Bacik }
41356ef5ed0dSJosef Bacik 
41365af3e8ccSStefan Behrens void btrfs_get_block_group_info(struct list_head *groups_list,
4137bf5fc093SJosef Bacik 				struct btrfs_ioctl_space_info *space)
4138bf5fc093SJosef Bacik {
4139bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4140bf5fc093SJosef Bacik 
4141bf5fc093SJosef Bacik 	space->total_bytes = 0;
4142bf5fc093SJosef Bacik 	space->used_bytes = 0;
4143bf5fc093SJosef Bacik 	space->flags = 0;
4144bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4145bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4146bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4147bf5fc093SJosef Bacik 		space->used_bytes +=
4148bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4149bf5fc093SJosef Bacik 	}
4150bf5fc093SJosef Bacik }
4151bf5fc093SJosef Bacik 
41522ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
41532ff7e61eSJeff Mahoney 				   void __user *arg)
41541406e432SJosef Bacik {
41551406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
41561406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
41571406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
41587fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
415913f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
41601406e432SJosef Bacik 	struct btrfs_space_info *info;
4161bf5fc093SJosef Bacik 	u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
4162bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_SYSTEM,
4163bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_METADATA,
4164bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
4165bf5fc093SJosef Bacik 	int num_types = 4;
41667fde62bfSChris Mason 	int alloc_size;
41671406e432SJosef Bacik 	int ret = 0;
416851788b1bSDan Rosenberg 	u64 slot_count = 0;
4169bf5fc093SJosef Bacik 	int i, c;
41701406e432SJosef Bacik 
41711406e432SJosef Bacik 	if (copy_from_user(&space_args,
41721406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
41731406e432SJosef Bacik 			   sizeof(space_args)))
41741406e432SJosef Bacik 		return -EFAULT;
41751406e432SJosef Bacik 
4176bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4177bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4178bf5fc093SJosef Bacik 
4179bf5fc093SJosef Bacik 		info = NULL;
41807fde62bfSChris Mason 		rcu_read_lock();
41810b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4182bf5fc093SJosef Bacik 					list) {
4183bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4184bf5fc093SJosef Bacik 				info = tmp;
4185bf5fc093SJosef Bacik 				break;
4186bf5fc093SJosef Bacik 			}
4187bf5fc093SJosef Bacik 		}
41887fde62bfSChris Mason 		rcu_read_unlock();
41891406e432SJosef Bacik 
4190bf5fc093SJosef Bacik 		if (!info)
4191bf5fc093SJosef Bacik 			continue;
4192bf5fc093SJosef Bacik 
4193bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4194bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4195bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4196bf5fc093SJosef Bacik 				slot_count++;
4197bf5fc093SJosef Bacik 		}
4198bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4199bf5fc093SJosef Bacik 	}
4200bf5fc093SJosef Bacik 
420136523e95SDavid Sterba 	/*
420236523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
420336523e95SDavid Sterba 	 */
420436523e95SDavid Sterba 	slot_count++;
420536523e95SDavid Sterba 
42067fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
42077fde62bfSChris Mason 	if (space_args.space_slots == 0) {
42087fde62bfSChris Mason 		space_args.total_spaces = slot_count;
42097fde62bfSChris Mason 		goto out;
42107fde62bfSChris Mason 	}
4211bf5fc093SJosef Bacik 
421251788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4213bf5fc093SJosef Bacik 
42147fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4215bf5fc093SJosef Bacik 
42167fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
42177fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
42187fde62bfSChris Mason 	 */
421909cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
42207fde62bfSChris Mason 		return -ENOMEM;
42217fde62bfSChris Mason 
42227fde62bfSChris Mason 	space_args.total_spaces = 0;
42238d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
42247fde62bfSChris Mason 	if (!dest)
42257fde62bfSChris Mason 		return -ENOMEM;
42267fde62bfSChris Mason 	dest_orig = dest;
42277fde62bfSChris Mason 
42287fde62bfSChris Mason 	/* now we have a buffer to copy into */
4229bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4230bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4231bf5fc093SJosef Bacik 
423251788b1bSDan Rosenberg 		if (!slot_count)
423351788b1bSDan Rosenberg 			break;
423451788b1bSDan Rosenberg 
4235bf5fc093SJosef Bacik 		info = NULL;
42361406e432SJosef Bacik 		rcu_read_lock();
42370b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4238bf5fc093SJosef Bacik 					list) {
4239bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4240bf5fc093SJosef Bacik 				info = tmp;
42417fde62bfSChris Mason 				break;
4242bf5fc093SJosef Bacik 			}
4243bf5fc093SJosef Bacik 		}
4244bf5fc093SJosef Bacik 		rcu_read_unlock();
42457fde62bfSChris Mason 
4246bf5fc093SJosef Bacik 		if (!info)
4247bf5fc093SJosef Bacik 			continue;
4248bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4249bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4250bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
42515af3e8ccSStefan Behrens 				btrfs_get_block_group_info(
42525af3e8ccSStefan Behrens 					&info->block_groups[c], &space);
42537fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
42541406e432SJosef Bacik 				dest++;
42551406e432SJosef Bacik 				space_args.total_spaces++;
425651788b1bSDan Rosenberg 				slot_count--;
42571406e432SJosef Bacik 			}
425851788b1bSDan Rosenberg 			if (!slot_count)
425951788b1bSDan Rosenberg 				break;
4260bf5fc093SJosef Bacik 		}
4261bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4262bf5fc093SJosef Bacik 	}
42631406e432SJosef Bacik 
426436523e95SDavid Sterba 	/*
426536523e95SDavid Sterba 	 * Add global block reserve
426636523e95SDavid Sterba 	 */
426736523e95SDavid Sterba 	if (slot_count) {
42680b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
426936523e95SDavid Sterba 
427036523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
427136523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
427236523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
427336523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
427436523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
427536523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
427636523e95SDavid Sterba 		space_args.total_spaces++;
427736523e95SDavid Sterba 	}
427836523e95SDavid Sterba 
42792eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
42807fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
42817fde62bfSChris Mason 
42827fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
42837fde62bfSChris Mason 		ret = -EFAULT;
42847fde62bfSChris Mason 
42857fde62bfSChris Mason 	kfree(dest_orig);
42867fde62bfSChris Mason out:
42877fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
42881406e432SJosef Bacik 		ret = -EFAULT;
42891406e432SJosef Bacik 
42901406e432SJosef Bacik 	return ret;
42911406e432SJosef Bacik }
42921406e432SJosef Bacik 
4293f46b5a66SChristoph Hellwig /*
4294f46b5a66SChristoph Hellwig  * there are many ways the trans_start and trans_end ioctls can lead
4295f46b5a66SChristoph Hellwig  * to deadlocks.  They should only be used by applications that
4296f46b5a66SChristoph Hellwig  * basically own the machine, and have a very in depth understanding
4297f46b5a66SChristoph Hellwig  * of all the possible deadlocks and enospc problems.
4298f46b5a66SChristoph Hellwig  */
4299f46b5a66SChristoph Hellwig long btrfs_ioctl_trans_end(struct file *file)
4300f46b5a66SChristoph Hellwig {
4301496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4302f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
4303f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
4304f46b5a66SChristoph Hellwig 
4305f46b5a66SChristoph Hellwig 	trans = file->private_data;
43061ab86aedSSage Weil 	if (!trans)
43071ab86aedSSage Weil 		return -EINVAL;
4308b214107eSChristoph Hellwig 	file->private_data = NULL;
43099ca9ee09SSage Weil 
43101ab86aedSSage Weil 	btrfs_end_transaction(trans, root);
43111ab86aedSSage Weil 
4312a4abeea4SJosef Bacik 	atomic_dec(&root->fs_info->open_ioctl_trans);
43139ca9ee09SSage Weil 
43142a79f17eSAl Viro 	mnt_drop_write_file(file);
43151ab86aedSSage Weil 	return 0;
4316f46b5a66SChristoph Hellwig }
4317f46b5a66SChristoph Hellwig 
43189a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
43199a8c28beSMiao Xie 					    void __user *argp)
432046204592SSage Weil {
432146204592SSage Weil 	struct btrfs_trans_handle *trans;
432246204592SSage Weil 	u64 transid;
4323db5b493aSTsutomu Itoh 	int ret;
432446204592SSage Weil 
4325d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4326ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4327ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
432898d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4329ff7c1d33SMiao Xie 
4330ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4331ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4332ff7c1d33SMiao Xie 		goto out;
4333ff7c1d33SMiao Xie 	}
433446204592SSage Weil 	transid = trans->transid;
4335db5b493aSTsutomu Itoh 	ret = btrfs_commit_transaction_async(trans, root, 0);
43368b2b2d3cSTsutomu Itoh 	if (ret) {
43378b2b2d3cSTsutomu Itoh 		btrfs_end_transaction(trans, root);
4338db5b493aSTsutomu Itoh 		return ret;
43398b2b2d3cSTsutomu Itoh 	}
4340ff7c1d33SMiao Xie out:
434146204592SSage Weil 	if (argp)
434246204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
434346204592SSage Weil 			return -EFAULT;
434446204592SSage Weil 	return 0;
434546204592SSage Weil }
434646204592SSage Weil 
43472ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
43489a8c28beSMiao Xie 					   void __user *argp)
434946204592SSage Weil {
435046204592SSage Weil 	u64 transid;
435146204592SSage Weil 
435246204592SSage Weil 	if (argp) {
435346204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
435446204592SSage Weil 			return -EFAULT;
435546204592SSage Weil 	} else {
435646204592SSage Weil 		transid = 0;  /* current trans */
435746204592SSage Weil 	}
43582ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
435946204592SSage Weil }
436046204592SSage Weil 
4361b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4362475f6387SJan Schmidt {
43630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4364475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4365b8e95489SMiao Xie 	int ret;
4366475f6387SJan Schmidt 
4367475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4368475f6387SJan Schmidt 		return -EPERM;
4369475f6387SJan Schmidt 
4370475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4371475f6387SJan Schmidt 	if (IS_ERR(sa))
4372475f6387SJan Schmidt 		return PTR_ERR(sa);
4373475f6387SJan Schmidt 
4374b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4375b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4376b8e95489SMiao Xie 		if (ret)
4377b8e95489SMiao Xie 			goto out;
4378b8e95489SMiao Xie 	}
4379b8e95489SMiao Xie 
43800b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
438163a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
438263a212abSStefan Behrens 			      0);
4383475f6387SJan Schmidt 
4384475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4385475f6387SJan Schmidt 		ret = -EFAULT;
4386475f6387SJan Schmidt 
4387b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4388b8e95489SMiao Xie 		mnt_drop_write_file(file);
4389b8e95489SMiao Xie out:
4390475f6387SJan Schmidt 	kfree(sa);
4391475f6387SJan Schmidt 	return ret;
4392475f6387SJan Schmidt }
4393475f6387SJan Schmidt 
43942ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4395475f6387SJan Schmidt {
4396475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4397475f6387SJan Schmidt 		return -EPERM;
4398475f6387SJan Schmidt 
43992ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4400475f6387SJan Schmidt }
4401475f6387SJan Schmidt 
44022ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4403475f6387SJan Schmidt 				       void __user *arg)
4404475f6387SJan Schmidt {
4405475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4406475f6387SJan Schmidt 	int ret;
4407475f6387SJan Schmidt 
4408475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4409475f6387SJan Schmidt 		return -EPERM;
4410475f6387SJan Schmidt 
4411475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4412475f6387SJan Schmidt 	if (IS_ERR(sa))
4413475f6387SJan Schmidt 		return PTR_ERR(sa);
4414475f6387SJan Schmidt 
44152ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4416475f6387SJan Schmidt 
4417475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4418475f6387SJan Schmidt 		ret = -EFAULT;
4419475f6387SJan Schmidt 
4420475f6387SJan Schmidt 	kfree(sa);
4421475f6387SJan Schmidt 	return ret;
4422475f6387SJan Schmidt }
4423475f6387SJan Schmidt 
44242ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4425b27f7c0cSDavid Sterba 				      void __user *arg)
4426c11d2c23SStefan Behrens {
4427c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4428c11d2c23SStefan Behrens 	int ret;
4429c11d2c23SStefan Behrens 
4430c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4431c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4432c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4433c11d2c23SStefan Behrens 
4434b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4435b27f7c0cSDavid Sterba 		kfree(sa);
4436b27f7c0cSDavid Sterba 		return -EPERM;
4437b27f7c0cSDavid Sterba 	}
4438b27f7c0cSDavid Sterba 
44392ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4440c11d2c23SStefan Behrens 
4441c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4442c11d2c23SStefan Behrens 		ret = -EFAULT;
4443c11d2c23SStefan Behrens 
4444c11d2c23SStefan Behrens 	kfree(sa);
4445c11d2c23SStefan Behrens 	return ret;
4446c11d2c23SStefan Behrens }
4447c11d2c23SStefan Behrens 
44482ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
44492ff7e61eSJeff Mahoney 				    void __user *arg)
44503f6bcfbdSStefan Behrens {
44513f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
44523f6bcfbdSStefan Behrens 	int ret;
44533f6bcfbdSStefan Behrens 
44543f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
44553f6bcfbdSStefan Behrens 		return -EPERM;
44563f6bcfbdSStefan Behrens 
44573f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
44583f6bcfbdSStefan Behrens 	if (IS_ERR(p))
44593f6bcfbdSStefan Behrens 		return PTR_ERR(p);
44603f6bcfbdSStefan Behrens 
44613f6bcfbdSStefan Behrens 	switch (p->cmd) {
44623f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
44630b246afaSJeff Mahoney 		if (fs_info->sb->s_flags & MS_RDONLY) {
4464adfa97cbSIlya Dryomov 			ret = -EROFS;
4465adfa97cbSIlya Dryomov 			goto out;
4466adfa97cbSIlya Dryomov 		}
44673f6bcfbdSStefan Behrens 		if (atomic_xchg(
44680b246afaSJeff Mahoney 			&fs_info->mutually_exclusive_operation_running, 1)) {
4469e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
44703f6bcfbdSStefan Behrens 		} else {
44712ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
44723f6bcfbdSStefan Behrens 			atomic_set(
44730b246afaSJeff Mahoney 			 &fs_info->mutually_exclusive_operation_running, 0);
44743f6bcfbdSStefan Behrens 		}
44753f6bcfbdSStefan Behrens 		break;
44763f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
44770b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
44783f6bcfbdSStefan Behrens 		ret = 0;
44793f6bcfbdSStefan Behrens 		break;
44803f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
44810b246afaSJeff Mahoney 		ret = btrfs_dev_replace_cancel(fs_info, p);
44823f6bcfbdSStefan Behrens 		break;
44833f6bcfbdSStefan Behrens 	default:
44843f6bcfbdSStefan Behrens 		ret = -EINVAL;
44853f6bcfbdSStefan Behrens 		break;
44863f6bcfbdSStefan Behrens 	}
44873f6bcfbdSStefan Behrens 
44883f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
44893f6bcfbdSStefan Behrens 		ret = -EFAULT;
4490adfa97cbSIlya Dryomov out:
44913f6bcfbdSStefan Behrens 	kfree(p);
44923f6bcfbdSStefan Behrens 	return ret;
44933f6bcfbdSStefan Behrens }
44943f6bcfbdSStefan Behrens 
4495d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4496d7728c96SJan Schmidt {
4497d7728c96SJan Schmidt 	int ret = 0;
4498d7728c96SJan Schmidt 	int i;
4499740c3d22SChris Mason 	u64 rel_ptr;
4500d7728c96SJan Schmidt 	int size;
4501806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4502d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4503d7728c96SJan Schmidt 	struct btrfs_path *path;
4504d7728c96SJan Schmidt 
450582b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4506d7728c96SJan Schmidt 		return -EPERM;
4507d7728c96SJan Schmidt 
4508d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4509d7728c96SJan Schmidt 	if (!path) {
4510d7728c96SJan Schmidt 		ret = -ENOMEM;
4511d7728c96SJan Schmidt 		goto out;
4512d7728c96SJan Schmidt 	}
4513d7728c96SJan Schmidt 
4514d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4515d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4516d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4517d7728c96SJan Schmidt 		ipa = NULL;
4518d7728c96SJan Schmidt 		goto out;
4519d7728c96SJan Schmidt 	}
4520d7728c96SJan Schmidt 
4521d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4522d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4523d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4524d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4525d7728c96SJan Schmidt 		ipath = NULL;
4526d7728c96SJan Schmidt 		goto out;
4527d7728c96SJan Schmidt 	}
4528d7728c96SJan Schmidt 
4529d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4530d7728c96SJan Schmidt 	if (ret < 0)
4531d7728c96SJan Schmidt 		goto out;
4532d7728c96SJan Schmidt 
4533d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4534745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4535745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4536740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4537d7728c96SJan Schmidt 	}
4538d7728c96SJan Schmidt 
4539745c4d8eSJeff Mahoney 	ret = copy_to_user((void *)(unsigned long)ipa->fspath,
4540745c4d8eSJeff Mahoney 			   (void *)(unsigned long)ipath->fspath, size);
4541d7728c96SJan Schmidt 	if (ret) {
4542d7728c96SJan Schmidt 		ret = -EFAULT;
4543d7728c96SJan Schmidt 		goto out;
4544d7728c96SJan Schmidt 	}
4545d7728c96SJan Schmidt 
4546d7728c96SJan Schmidt out:
4547d7728c96SJan Schmidt 	btrfs_free_path(path);
4548d7728c96SJan Schmidt 	free_ipath(ipath);
4549d7728c96SJan Schmidt 	kfree(ipa);
4550d7728c96SJan Schmidt 
4551d7728c96SJan Schmidt 	return ret;
4552d7728c96SJan Schmidt }
4553d7728c96SJan Schmidt 
4554d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4555d7728c96SJan Schmidt {
4556d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4557d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4558d7728c96SJan Schmidt 
4559d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4560d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4561d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4562d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4563d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4564d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4565d7728c96SJan Schmidt 	} else {
4566d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4567d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4568d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4569d7728c96SJan Schmidt 	}
4570d7728c96SJan Schmidt 
4571d7728c96SJan Schmidt 	return 0;
4572d7728c96SJan Schmidt }
4573d7728c96SJan Schmidt 
45742ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4575d7728c96SJan Schmidt 					void __user *arg)
4576d7728c96SJan Schmidt {
4577d7728c96SJan Schmidt 	int ret = 0;
4578d7728c96SJan Schmidt 	int size;
4579d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4580d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4581d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4582d7728c96SJan Schmidt 
4583d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4584d7728c96SJan Schmidt 		return -EPERM;
4585d7728c96SJan Schmidt 
4586d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
45877b9ea627SShailendra Verma 	if (IS_ERR(loi))
45887b9ea627SShailendra Verma 		return PTR_ERR(loi);
4589d7728c96SJan Schmidt 
4590d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4591d7728c96SJan Schmidt 	if (!path) {
4592d7728c96SJan Schmidt 		ret = -ENOMEM;
4593d7728c96SJan Schmidt 		goto out;
4594d7728c96SJan Schmidt 	}
4595d7728c96SJan Schmidt 
4596ee22184bSByongho Lee 	size = min_t(u32, loi->size, SZ_64K);
4597d7728c96SJan Schmidt 	inodes = init_data_container(size);
4598d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4599d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4600d7728c96SJan Schmidt 		inodes = NULL;
4601d7728c96SJan Schmidt 		goto out;
4602d7728c96SJan Schmidt 	}
4603d7728c96SJan Schmidt 
46042ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4605df031f07SLiu Bo 					  build_ino_list, inodes);
4606df031f07SLiu Bo 	if (ret == -EINVAL)
4607d7728c96SJan Schmidt 		ret = -ENOENT;
4608d7728c96SJan Schmidt 	if (ret < 0)
4609d7728c96SJan Schmidt 		goto out;
4610d7728c96SJan Schmidt 
4611745c4d8eSJeff Mahoney 	ret = copy_to_user((void *)(unsigned long)loi->inodes,
4612745c4d8eSJeff Mahoney 			   (void *)(unsigned long)inodes, size);
4613d7728c96SJan Schmidt 	if (ret)
4614d7728c96SJan Schmidt 		ret = -EFAULT;
4615d7728c96SJan Schmidt 
4616d7728c96SJan Schmidt out:
4617d7728c96SJan Schmidt 	btrfs_free_path(path);
4618425d17a2SLiu Bo 	vfree(inodes);
4619d7728c96SJan Schmidt 	kfree(loi);
4620d7728c96SJan Schmidt 
4621d7728c96SJan Schmidt 	return ret;
4622d7728c96SJan Schmidt }
4623d7728c96SJan Schmidt 
462419a39dceSIlya Dryomov void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
4625c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4626c9e9f97bSIlya Dryomov {
4627c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4628c9e9f97bSIlya Dryomov 
4629c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4630c9e9f97bSIlya Dryomov 
4631837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_running))
4632837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4633837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4634837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4635a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4636a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4637837d5b6eSIlya Dryomov 
4638c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4639c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4640c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
464119a39dceSIlya Dryomov 
464219a39dceSIlya Dryomov 	if (lock) {
464319a39dceSIlya Dryomov 		spin_lock(&fs_info->balance_lock);
464419a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
464519a39dceSIlya Dryomov 		spin_unlock(&fs_info->balance_lock);
464619a39dceSIlya Dryomov 	} else {
464719a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
464819a39dceSIlya Dryomov 	}
4649c9e9f97bSIlya Dryomov }
4650c9e9f97bSIlya Dryomov 
46519ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4652c9e9f97bSIlya Dryomov {
4653496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4654c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4655c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4656c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4657ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4658c9e9f97bSIlya Dryomov 	int ret;
4659c9e9f97bSIlya Dryomov 
4660c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4661c9e9f97bSIlya Dryomov 		return -EPERM;
4662c9e9f97bSIlya Dryomov 
4663e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
46649ba1f6e4SLiu Bo 	if (ret)
46659ba1f6e4SLiu Bo 		return ret;
46669ba1f6e4SLiu Bo 
4667ed0fb78fSIlya Dryomov again:
4668ed0fb78fSIlya Dryomov 	if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
4669c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->volume_mutex);
4670c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4671ed0fb78fSIlya Dryomov 		need_unlock = true;
4672ed0fb78fSIlya Dryomov 		goto locked;
4673ed0fb78fSIlya Dryomov 	}
4674ed0fb78fSIlya Dryomov 
4675ed0fb78fSIlya Dryomov 	/*
467601327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4677ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4678ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4679ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4680ed0fb78fSIlya Dryomov 	 */
4681ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4682ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4683ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
4684ed0fb78fSIlya Dryomov 		if (!atomic_read(&fs_info->balance_running)) {
4685ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4686ed0fb78fSIlya Dryomov 			if (!mutex_trylock(&fs_info->volume_mutex))
4687ed0fb78fSIlya Dryomov 				goto again;
4688ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4689ed0fb78fSIlya Dryomov 
4690ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
4691ed0fb78fSIlya Dryomov 			    !atomic_read(&fs_info->balance_running)) {
4692ed0fb78fSIlya Dryomov 				/* this is (3) */
4693ed0fb78fSIlya Dryomov 				need_unlock = false;
4694ed0fb78fSIlya Dryomov 				goto locked;
4695ed0fb78fSIlya Dryomov 			}
4696ed0fb78fSIlya Dryomov 
4697ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4698ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->volume_mutex);
4699ed0fb78fSIlya Dryomov 			goto again;
4700ed0fb78fSIlya Dryomov 		} else {
4701ed0fb78fSIlya Dryomov 			/* this is (2) */
4702ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4703ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4704ed0fb78fSIlya Dryomov 			goto out;
4705ed0fb78fSIlya Dryomov 		}
4706ed0fb78fSIlya Dryomov 	} else {
4707ed0fb78fSIlya Dryomov 		/* this is (1) */
4708ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4709e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4710ed0fb78fSIlya Dryomov 		goto out;
4711ed0fb78fSIlya Dryomov 	}
4712ed0fb78fSIlya Dryomov 
4713ed0fb78fSIlya Dryomov locked:
4714ed0fb78fSIlya Dryomov 	BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
4715c9e9f97bSIlya Dryomov 
4716c9e9f97bSIlya Dryomov 	if (arg) {
4717c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4718c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4719c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4720ed0fb78fSIlya Dryomov 			goto out_unlock;
4721c9e9f97bSIlya Dryomov 		}
4722de322263SIlya Dryomov 
4723de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4724de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4725de322263SIlya Dryomov 				ret = -ENOTCONN;
4726de322263SIlya Dryomov 				goto out_bargs;
4727de322263SIlya Dryomov 			}
4728de322263SIlya Dryomov 
4729de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4730de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4731de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4732de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4733de322263SIlya Dryomov 
4734de322263SIlya Dryomov 			goto do_balance;
4735de322263SIlya Dryomov 		}
4736c9e9f97bSIlya Dryomov 	} else {
4737c9e9f97bSIlya Dryomov 		bargs = NULL;
4738c9e9f97bSIlya Dryomov 	}
4739c9e9f97bSIlya Dryomov 
4740ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4741837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4742837d5b6eSIlya Dryomov 		goto out_bargs;
4743837d5b6eSIlya Dryomov 	}
4744837d5b6eSIlya Dryomov 
47458d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4746c9e9f97bSIlya Dryomov 	if (!bctl) {
4747c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4748c9e9f97bSIlya Dryomov 		goto out_bargs;
4749c9e9f97bSIlya Dryomov 	}
4750c9e9f97bSIlya Dryomov 
4751c9e9f97bSIlya Dryomov 	bctl->fs_info = fs_info;
4752c9e9f97bSIlya Dryomov 	if (arg) {
4753c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4754c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4755c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4756c9e9f97bSIlya Dryomov 
4757c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4758f43ffb60SIlya Dryomov 	} else {
4759f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4760f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4761c9e9f97bSIlya Dryomov 	}
4762c9e9f97bSIlya Dryomov 
47638eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
47648eb93459SDavid Sterba 		ret = -EINVAL;
47650f89abf5SChristian Engelmayer 		goto out_bctl;
47668eb93459SDavid Sterba 	}
47678eb93459SDavid Sterba 
4768de322263SIlya Dryomov do_balance:
4769c9e9f97bSIlya Dryomov 	/*
4770ed0fb78fSIlya Dryomov 	 * Ownership of bctl and mutually_exclusive_operation_running
4771ed0fb78fSIlya Dryomov 	 * goes to to btrfs_balance.  bctl is freed in __cancel_balance,
4772ed0fb78fSIlya Dryomov 	 * or, if restriper was paused all the way until unmount, in
4773ed0fb78fSIlya Dryomov 	 * free_fs_info.  mutually_exclusive_operation_running is
4774ed0fb78fSIlya Dryomov 	 * cleared in __cancel_balance.
4775c9e9f97bSIlya Dryomov 	 */
4776ed0fb78fSIlya Dryomov 	need_unlock = false;
4777ed0fb78fSIlya Dryomov 
4778ed0fb78fSIlya Dryomov 	ret = btrfs_balance(bctl, bargs);
47790f89abf5SChristian Engelmayer 	bctl = NULL;
4780ed0fb78fSIlya Dryomov 
4781c9e9f97bSIlya Dryomov 	if (arg) {
4782c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4783c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4784c9e9f97bSIlya Dryomov 	}
4785c9e9f97bSIlya Dryomov 
47860f89abf5SChristian Engelmayer out_bctl:
47870f89abf5SChristian Engelmayer 	kfree(bctl);
4788c9e9f97bSIlya Dryomov out_bargs:
4789c9e9f97bSIlya Dryomov 	kfree(bargs);
4790ed0fb78fSIlya Dryomov out_unlock:
4791c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4792c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->volume_mutex);
4793ed0fb78fSIlya Dryomov 	if (need_unlock)
4794ed0fb78fSIlya Dryomov 		atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
4795ed0fb78fSIlya Dryomov out:
4796e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4797c9e9f97bSIlya Dryomov 	return ret;
4798c9e9f97bSIlya Dryomov }
4799c9e9f97bSIlya Dryomov 
48002ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4801837d5b6eSIlya Dryomov {
4802837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4803837d5b6eSIlya Dryomov 		return -EPERM;
4804837d5b6eSIlya Dryomov 
4805837d5b6eSIlya Dryomov 	switch (cmd) {
4806837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
48070b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4808a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
48090b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4810837d5b6eSIlya Dryomov 	}
4811837d5b6eSIlya Dryomov 
4812837d5b6eSIlya Dryomov 	return -EINVAL;
4813837d5b6eSIlya Dryomov }
4814837d5b6eSIlya Dryomov 
48152ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
481619a39dceSIlya Dryomov 					 void __user *arg)
481719a39dceSIlya Dryomov {
481819a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
481919a39dceSIlya Dryomov 	int ret = 0;
482019a39dceSIlya Dryomov 
482119a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
482219a39dceSIlya Dryomov 		return -EPERM;
482319a39dceSIlya Dryomov 
482419a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
482519a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
482619a39dceSIlya Dryomov 		ret = -ENOTCONN;
482719a39dceSIlya Dryomov 		goto out;
482819a39dceSIlya Dryomov 	}
482919a39dceSIlya Dryomov 
48308d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
483119a39dceSIlya Dryomov 	if (!bargs) {
483219a39dceSIlya Dryomov 		ret = -ENOMEM;
483319a39dceSIlya Dryomov 		goto out;
483419a39dceSIlya Dryomov 	}
483519a39dceSIlya Dryomov 
483619a39dceSIlya Dryomov 	update_ioctl_balance_args(fs_info, 1, bargs);
483719a39dceSIlya Dryomov 
483819a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
483919a39dceSIlya Dryomov 		ret = -EFAULT;
484019a39dceSIlya Dryomov 
484119a39dceSIlya Dryomov 	kfree(bargs);
484219a39dceSIlya Dryomov out:
484319a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
484419a39dceSIlya Dryomov 	return ret;
484519a39dceSIlya Dryomov }
484619a39dceSIlya Dryomov 
4847905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
48485d13a37bSArne Jansen {
48490b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48515d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
48525d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
48535d13a37bSArne Jansen 	int ret;
48545d13a37bSArne Jansen 	int err;
48555d13a37bSArne Jansen 
48565d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48575d13a37bSArne Jansen 		return -EPERM;
48585d13a37bSArne Jansen 
4859905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4860905b0ddaSMiao Xie 	if (ret)
4861905b0ddaSMiao Xie 		return ret;
48625d13a37bSArne Jansen 
48635d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4864905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4865905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4866905b0ddaSMiao Xie 		goto drop_write;
4867905b0ddaSMiao Xie 	}
48685d13a37bSArne Jansen 
48690b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
48700b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 2);
48715d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48725d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48735d13a37bSArne Jansen 		goto out;
48745d13a37bSArne Jansen 	}
48755d13a37bSArne Jansen 
48765d13a37bSArne Jansen 	switch (sa->cmd) {
48775d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
48780b246afaSJeff Mahoney 		ret = btrfs_quota_enable(trans, fs_info);
48795d13a37bSArne Jansen 		break;
48805d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
48810b246afaSJeff Mahoney 		ret = btrfs_quota_disable(trans, fs_info);
48825d13a37bSArne Jansen 		break;
48835d13a37bSArne Jansen 	default:
48845d13a37bSArne Jansen 		ret = -EINVAL;
48855d13a37bSArne Jansen 		break;
48865d13a37bSArne Jansen 	}
48875d13a37bSArne Jansen 
48880b246afaSJeff Mahoney 	err = btrfs_commit_transaction(trans, fs_info->tree_root);
48895d13a37bSArne Jansen 	if (err && !ret)
48905d13a37bSArne Jansen 		ret = err;
48915d13a37bSArne Jansen out:
48925d13a37bSArne Jansen 	kfree(sa);
48930b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4894905b0ddaSMiao Xie drop_write:
4895905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48965d13a37bSArne Jansen 	return ret;
48975d13a37bSArne Jansen }
48985d13a37bSArne Jansen 
4899905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
49005d13a37bSArne Jansen {
49010b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49020b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49030b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
49045d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
49055d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
49065d13a37bSArne Jansen 	int ret;
49075d13a37bSArne Jansen 	int err;
49085d13a37bSArne Jansen 
49095d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
49105d13a37bSArne Jansen 		return -EPERM;
49115d13a37bSArne Jansen 
4912905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4913905b0ddaSMiao Xie 	if (ret)
4914905b0ddaSMiao Xie 		return ret;
49155d13a37bSArne Jansen 
49165d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4917905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4918905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4919905b0ddaSMiao Xie 		goto drop_write;
4920905b0ddaSMiao Xie 	}
49215d13a37bSArne Jansen 
49225d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
49235d13a37bSArne Jansen 	if (IS_ERR(trans)) {
49245d13a37bSArne Jansen 		ret = PTR_ERR(trans);
49255d13a37bSArne Jansen 		goto out;
49265d13a37bSArne Jansen 	}
49275d13a37bSArne Jansen 
49285d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
49295d13a37bSArne Jansen 	if (sa->assign) {
49300b246afaSJeff Mahoney 		ret = btrfs_add_qgroup_relation(trans, fs_info,
49315d13a37bSArne Jansen 						sa->src, sa->dst);
49325d13a37bSArne Jansen 	} else {
49330b246afaSJeff Mahoney 		ret = btrfs_del_qgroup_relation(trans, fs_info,
49345d13a37bSArne Jansen 						sa->src, sa->dst);
49355d13a37bSArne Jansen 	}
49365d13a37bSArne Jansen 
4937e082f563SQu Wenruo 	/* update qgroup status and info */
49380b246afaSJeff Mahoney 	err = btrfs_run_qgroups(trans, fs_info);
4939e082f563SQu Wenruo 	if (err < 0)
49400b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4941ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
49425d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
49435d13a37bSArne Jansen 	if (err && !ret)
49445d13a37bSArne Jansen 		ret = err;
49455d13a37bSArne Jansen 
49465d13a37bSArne Jansen out:
49475d13a37bSArne Jansen 	kfree(sa);
4948905b0ddaSMiao Xie drop_write:
4949905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49505d13a37bSArne Jansen 	return ret;
49515d13a37bSArne Jansen }
49525d13a37bSArne Jansen 
4953905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
49545d13a37bSArne Jansen {
49550b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49570b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
49585d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
49595d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
49605d13a37bSArne Jansen 	int ret;
49615d13a37bSArne Jansen 	int err;
49625d13a37bSArne Jansen 
49635d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
49645d13a37bSArne Jansen 		return -EPERM;
49655d13a37bSArne Jansen 
4966905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4967905b0ddaSMiao Xie 	if (ret)
4968905b0ddaSMiao Xie 		return ret;
49695d13a37bSArne Jansen 
49705d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4971905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4972905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4973905b0ddaSMiao Xie 		goto drop_write;
4974905b0ddaSMiao Xie 	}
49755d13a37bSArne Jansen 
4976d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4977d86e56cfSMiao Xie 		ret = -EINVAL;
4978d86e56cfSMiao Xie 		goto out;
4979d86e56cfSMiao Xie 	}
4980d86e56cfSMiao Xie 
49815d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
49825d13a37bSArne Jansen 	if (IS_ERR(trans)) {
49835d13a37bSArne Jansen 		ret = PTR_ERR(trans);
49845d13a37bSArne Jansen 		goto out;
49855d13a37bSArne Jansen 	}
49865d13a37bSArne Jansen 
49875d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
49885d13a37bSArne Jansen 	if (sa->create) {
49890b246afaSJeff Mahoney 		ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
49905d13a37bSArne Jansen 	} else {
49910b246afaSJeff Mahoney 		ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
49925d13a37bSArne Jansen 	}
49935d13a37bSArne Jansen 
49945d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
49955d13a37bSArne Jansen 	if (err && !ret)
49965d13a37bSArne Jansen 		ret = err;
49975d13a37bSArne Jansen 
49985d13a37bSArne Jansen out:
49995d13a37bSArne Jansen 	kfree(sa);
5000905b0ddaSMiao Xie drop_write:
5001905b0ddaSMiao Xie 	mnt_drop_write_file(file);
50025d13a37bSArne Jansen 	return ret;
50035d13a37bSArne Jansen }
50045d13a37bSArne Jansen 
5005905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
50065d13a37bSArne Jansen {
50070b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50090b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
50105d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
50115d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
50125d13a37bSArne Jansen 	int ret;
50135d13a37bSArne Jansen 	int err;
50145d13a37bSArne Jansen 	u64 qgroupid;
50155d13a37bSArne Jansen 
50165d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
50175d13a37bSArne Jansen 		return -EPERM;
50185d13a37bSArne Jansen 
5019905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5020905b0ddaSMiao Xie 	if (ret)
5021905b0ddaSMiao Xie 		return ret;
50225d13a37bSArne Jansen 
50235d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5024905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5025905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5026905b0ddaSMiao Xie 		goto drop_write;
5027905b0ddaSMiao Xie 	}
50285d13a37bSArne Jansen 
50295d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
50305d13a37bSArne Jansen 	if (IS_ERR(trans)) {
50315d13a37bSArne Jansen 		ret = PTR_ERR(trans);
50325d13a37bSArne Jansen 		goto out;
50335d13a37bSArne Jansen 	}
50345d13a37bSArne Jansen 
50355d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
50365d13a37bSArne Jansen 	if (!qgroupid) {
50375d13a37bSArne Jansen 		/* take the current subvol as qgroup */
50385d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
50395d13a37bSArne Jansen 	}
50405d13a37bSArne Jansen 
50415d13a37bSArne Jansen 	/* FIXME: check if the IDs really exist */
50420b246afaSJeff Mahoney 	ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
50435d13a37bSArne Jansen 
50445d13a37bSArne Jansen 	err = btrfs_end_transaction(trans, root);
50455d13a37bSArne Jansen 	if (err && !ret)
50465d13a37bSArne Jansen 		ret = err;
50475d13a37bSArne Jansen 
50485d13a37bSArne Jansen out:
50495d13a37bSArne Jansen 	kfree(sa);
5050905b0ddaSMiao Xie drop_write:
5051905b0ddaSMiao Xie 	mnt_drop_write_file(file);
50525d13a37bSArne Jansen 	return ret;
50535d13a37bSArne Jansen }
50545d13a37bSArne Jansen 
50552f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
50562f232036SJan Schmidt {
50570b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50580b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50592f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
50602f232036SJan Schmidt 	int ret;
50612f232036SJan Schmidt 
50622f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
50632f232036SJan Schmidt 		return -EPERM;
50642f232036SJan Schmidt 
50652f232036SJan Schmidt 	ret = mnt_want_write_file(file);
50662f232036SJan Schmidt 	if (ret)
50672f232036SJan Schmidt 		return ret;
50682f232036SJan Schmidt 
50692f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
50702f232036SJan Schmidt 	if (IS_ERR(qsa)) {
50712f232036SJan Schmidt 		ret = PTR_ERR(qsa);
50722f232036SJan Schmidt 		goto drop_write;
50732f232036SJan Schmidt 	}
50742f232036SJan Schmidt 
50752f232036SJan Schmidt 	if (qsa->flags) {
50762f232036SJan Schmidt 		ret = -EINVAL;
50772f232036SJan Schmidt 		goto out;
50782f232036SJan Schmidt 	}
50792f232036SJan Schmidt 
50800b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
50812f232036SJan Schmidt 
50822f232036SJan Schmidt out:
50832f232036SJan Schmidt 	kfree(qsa);
50842f232036SJan Schmidt drop_write:
50852f232036SJan Schmidt 	mnt_drop_write_file(file);
50862f232036SJan Schmidt 	return ret;
50872f232036SJan Schmidt }
50882f232036SJan Schmidt 
50892f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
50902f232036SJan Schmidt {
50910b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50920b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50932f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
50942f232036SJan Schmidt 	int ret = 0;
50952f232036SJan Schmidt 
50962f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
50972f232036SJan Schmidt 		return -EPERM;
50982f232036SJan Schmidt 
50998d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
51002f232036SJan Schmidt 	if (!qsa)
51012f232036SJan Schmidt 		return -ENOMEM;
51022f232036SJan Schmidt 
51030b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
51042f232036SJan Schmidt 		qsa->flags = 1;
51050b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
51062f232036SJan Schmidt 	}
51072f232036SJan Schmidt 
51082f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
51092f232036SJan Schmidt 		ret = -EFAULT;
51102f232036SJan Schmidt 
51112f232036SJan Schmidt 	kfree(qsa);
51122f232036SJan Schmidt 	return ret;
51132f232036SJan Schmidt }
51142f232036SJan Schmidt 
511557254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
511657254b6eSJan Schmidt {
51170b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51180b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
511957254b6eSJan Schmidt 
512057254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
512157254b6eSJan Schmidt 		return -EPERM;
512257254b6eSJan Schmidt 
51230b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
512457254b6eSJan Schmidt }
512557254b6eSJan Schmidt 
5126abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
5127abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
51288ea05e3aSAlexander Block {
5129496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
51300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51318ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
51328ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
51338ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
5134c2050a45SDeepa Dinamani 	struct timespec ct = current_time(inode);
51358ea05e3aSAlexander Block 	int ret = 0;
5136dd5f9615SStefan Behrens 	int received_uuid_changed;
51378ea05e3aSAlexander Block 
5138bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
5139bd60ea0fSDavid Sterba 		return -EPERM;
5140bd60ea0fSDavid Sterba 
51418ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
51428ea05e3aSAlexander Block 	if (ret < 0)
51438ea05e3aSAlexander Block 		return ret;
51448ea05e3aSAlexander Block 
51450b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
51468ea05e3aSAlexander Block 
51478ea05e3aSAlexander Block 	if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
51488ea05e3aSAlexander Block 		ret = -EINVAL;
51498ea05e3aSAlexander Block 		goto out;
51508ea05e3aSAlexander Block 	}
51518ea05e3aSAlexander Block 
51528ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
51538ea05e3aSAlexander Block 		ret = -EROFS;
51548ea05e3aSAlexander Block 		goto out;
51558ea05e3aSAlexander Block 	}
51568ea05e3aSAlexander Block 
5157dd5f9615SStefan Behrens 	/*
5158dd5f9615SStefan Behrens 	 * 1 - root item
5159dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5160dd5f9615SStefan Behrens 	 */
5161dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
51628ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
51638ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
51648ea05e3aSAlexander Block 		trans = NULL;
51658ea05e3aSAlexander Block 		goto out;
51668ea05e3aSAlexander Block 	}
51678ea05e3aSAlexander Block 
51688ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
51698ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
51708ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
51718ea05e3aSAlexander Block 
5172dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5173dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5174dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5175dd5f9615SStefan Behrens 	    !btrfs_is_empty_uuid(root_item->received_uuid))
51760b246afaSJeff Mahoney 		btrfs_uuid_tree_rem(trans, fs_info, root_item->received_uuid,
5177dd5f9615SStefan Behrens 				    BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5178dd5f9615SStefan Behrens 				    root->root_key.objectid);
51798ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
51808ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
51818ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
51823cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
51833cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
51843cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
51853cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
51868ea05e3aSAlexander Block 
51870b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
51888ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
51898ea05e3aSAlexander Block 	if (ret < 0) {
51908ea05e3aSAlexander Block 		btrfs_end_transaction(trans, root);
51918ea05e3aSAlexander Block 		goto out;
5192dd5f9615SStefan Behrens 	}
5193dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
51940b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_add(trans, fs_info, sa->uuid,
5195dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5196dd5f9615SStefan Behrens 					  root->root_key.objectid);
5197dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
519866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
5199dd5f9615SStefan Behrens 			goto out;
5200dd5f9615SStefan Behrens 		}
5201dd5f9615SStefan Behrens 	}
52028ea05e3aSAlexander Block 	ret = btrfs_commit_transaction(trans, root);
5203dd5f9615SStefan Behrens 	if (ret < 0) {
520466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
52058ea05e3aSAlexander Block 		goto out;
52068ea05e3aSAlexander Block 	}
52078ea05e3aSAlexander Block 
5208abccd00fSHugo Mills out:
52090b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5210abccd00fSHugo Mills 	mnt_drop_write_file(file);
5211abccd00fSHugo Mills 	return ret;
5212abccd00fSHugo Mills }
5213abccd00fSHugo Mills 
5214abccd00fSHugo Mills #ifdef CONFIG_64BIT
5215abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5216abccd00fSHugo Mills 						void __user *arg)
5217abccd00fSHugo Mills {
5218abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5219abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5220abccd00fSHugo Mills 	int ret = 0;
5221abccd00fSHugo Mills 
5222abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
52237b9ea627SShailendra Verma 	if (IS_ERR(args32))
52247b9ea627SShailendra Verma 		return PTR_ERR(args32);
5225abccd00fSHugo Mills 
52268d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
522784dbeb87SDan Carpenter 	if (!args64) {
522884dbeb87SDan Carpenter 		ret = -ENOMEM;
5229abccd00fSHugo Mills 		goto out;
5230abccd00fSHugo Mills 	}
5231abccd00fSHugo Mills 
5232abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5233abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5234abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5235abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5236abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5237abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5238abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5239abccd00fSHugo Mills 	args64->flags = args32->flags;
5240abccd00fSHugo Mills 
5241abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5242abccd00fSHugo Mills 	if (ret)
5243abccd00fSHugo Mills 		goto out;
5244abccd00fSHugo Mills 
5245abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5246abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5247abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5248abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5249abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5250abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5251abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5252abccd00fSHugo Mills 	args32->flags = args64->flags;
5253abccd00fSHugo Mills 
5254abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5255abccd00fSHugo Mills 	if (ret)
5256abccd00fSHugo Mills 		ret = -EFAULT;
5257abccd00fSHugo Mills 
5258abccd00fSHugo Mills out:
5259abccd00fSHugo Mills 	kfree(args32);
5260abccd00fSHugo Mills 	kfree(args64);
5261abccd00fSHugo Mills 	return ret;
5262abccd00fSHugo Mills }
5263abccd00fSHugo Mills #endif
5264abccd00fSHugo Mills 
5265abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5266abccd00fSHugo Mills 					    void __user *arg)
5267abccd00fSHugo Mills {
5268abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5269abccd00fSHugo Mills 	int ret = 0;
5270abccd00fSHugo Mills 
5271abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
52727b9ea627SShailendra Verma 	if (IS_ERR(sa))
52737b9ea627SShailendra Verma 		return PTR_ERR(sa);
5274abccd00fSHugo Mills 
5275abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5276abccd00fSHugo Mills 
5277abccd00fSHugo Mills 	if (ret)
5278abccd00fSHugo Mills 		goto out;
5279abccd00fSHugo Mills 
52808ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
52818ea05e3aSAlexander Block 	if (ret)
52828ea05e3aSAlexander Block 		ret = -EFAULT;
52838ea05e3aSAlexander Block 
52848ea05e3aSAlexander Block out:
52858ea05e3aSAlexander Block 	kfree(sa);
52868ea05e3aSAlexander Block 	return ret;
52878ea05e3aSAlexander Block }
52888ea05e3aSAlexander Block 
5289867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5290867ab667Sjeff.liu {
52910b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52920b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5293a1b83ac5SAnand Jain 	size_t len;
5294867ab667Sjeff.liu 	int ret;
5295a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5296a1b83ac5SAnand Jain 
52970b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
52980b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
52990b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
5300a1b83ac5SAnand Jain 
5301a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5302867ab667Sjeff.liu 
5303867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
53040b246afaSJeff Mahoney 		btrfs_warn(fs_info,
53050b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
53060b246afaSJeff Mahoney 			   --len);
5307867ab667Sjeff.liu 	}
5308867ab667Sjeff.liu 
5309867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5310867ab667Sjeff.liu 
5311867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5312867ab667Sjeff.liu }
5313867ab667Sjeff.liu 
5314a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5315a8bfd4abSjeff.liu {
53160b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53180b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
53190b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
5320a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5321a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5322a8bfd4abSjeff.liu 	int ret;
5323a8bfd4abSjeff.liu 
5324a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5325a8bfd4abSjeff.liu 		return -EPERM;
5326a8bfd4abSjeff.liu 
5327a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5328a8bfd4abSjeff.liu 		return -EFAULT;
5329a8bfd4abSjeff.liu 
5330a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
53310b246afaSJeff Mahoney 		btrfs_err(fs_info,
53325d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5333a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5334a8bfd4abSjeff.liu 		return -EINVAL;
5335a8bfd4abSjeff.liu 	}
5336a8bfd4abSjeff.liu 
5337a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5338a8bfd4abSjeff.liu 	if (ret)
5339a8bfd4abSjeff.liu 		return ret;
5340a8bfd4abSjeff.liu 
5341a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5342a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5343a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5344a8bfd4abSjeff.liu 		goto out_unlock;
5345a8bfd4abSjeff.liu 	}
5346a8bfd4abSjeff.liu 
53470b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5348a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
53490b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
5350d0270acaSJeff Mahoney 	ret = btrfs_commit_transaction(trans, root);
5351a8bfd4abSjeff.liu 
5352a8bfd4abSjeff.liu out_unlock:
5353a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5354a8bfd4abSjeff.liu 	return ret;
5355a8bfd4abSjeff.liu }
5356a8bfd4abSjeff.liu 
53572eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
53582eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
53592eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
53602eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
53612eaa055fSJeff Mahoney 
5362d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
53632eaa055fSJeff Mahoney {
53644d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
53652eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
53662eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
53672eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
53682eaa055fSJeff Mahoney 	};
53692eaa055fSJeff Mahoney 
53702eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
53712eaa055fSJeff Mahoney 		return -EFAULT;
53722eaa055fSJeff Mahoney 
53732eaa055fSJeff Mahoney 	return 0;
53742eaa055fSJeff Mahoney }
53752eaa055fSJeff Mahoney 
53762eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
53772eaa055fSJeff Mahoney {
53780b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53800b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
53812eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
53822eaa055fSJeff Mahoney 
53832eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
53842eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
53852eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
53862eaa055fSJeff Mahoney 
53872eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
53882eaa055fSJeff Mahoney 		return -EFAULT;
53892eaa055fSJeff Mahoney 
53902eaa055fSJeff Mahoney 	return 0;
53912eaa055fSJeff Mahoney }
53922eaa055fSJeff Mahoney 
53932ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
53943b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
53952eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
53962eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
53972eaa055fSJeff Mahoney {
53983b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
53993b02a68aSJeff Mahoney 	char *names;
54002eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
54012eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
54022eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
54032eaa055fSJeff Mahoney 
54042eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
54052eaa055fSJeff Mahoney 	if (unsupported) {
54063b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
54073b02a68aSJeff Mahoney 		if (names) {
54080b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54093b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
54103b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
54113b02a68aSJeff Mahoney 			kfree(names);
54123b02a68aSJeff Mahoney 		} else
54130b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54142eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
54152eaa055fSJeff Mahoney 				   type, unsupported);
54162eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
54172eaa055fSJeff Mahoney 	}
54182eaa055fSJeff Mahoney 
54192eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
54202eaa055fSJeff Mahoney 	if (disallowed) {
54213b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
54223b02a68aSJeff Mahoney 		if (names) {
54230b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54243b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
54253b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
54263b02a68aSJeff Mahoney 			kfree(names);
54273b02a68aSJeff Mahoney 		} else
54280b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54292eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
54302eaa055fSJeff Mahoney 				   type, disallowed);
54312eaa055fSJeff Mahoney 		return -EPERM;
54322eaa055fSJeff Mahoney 	}
54332eaa055fSJeff Mahoney 
54342eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
54352eaa055fSJeff Mahoney 	if (disallowed) {
54363b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
54373b02a68aSJeff Mahoney 		if (names) {
54380b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54393b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
54403b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
54413b02a68aSJeff Mahoney 			kfree(names);
54423b02a68aSJeff Mahoney 		} else
54430b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54442eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
54452eaa055fSJeff Mahoney 				   type, disallowed);
54462eaa055fSJeff Mahoney 		return -EPERM;
54472eaa055fSJeff Mahoney 	}
54482eaa055fSJeff Mahoney 
54492eaa055fSJeff Mahoney 	return 0;
54502eaa055fSJeff Mahoney }
54512eaa055fSJeff Mahoney 
54522ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
54532ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
54542eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
54552eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
54562eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
54572eaa055fSJeff Mahoney 
54582eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
54592eaa055fSJeff Mahoney {
54600b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
54610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
54620b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
54630b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
54642eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
54652eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
54662eaa055fSJeff Mahoney 	u64 newflags;
54672eaa055fSJeff Mahoney 	int ret;
54682eaa055fSJeff Mahoney 
54692eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
54702eaa055fSJeff Mahoney 		return -EPERM;
54712eaa055fSJeff Mahoney 
54722eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
54732eaa055fSJeff Mahoney 		return -EFAULT;
54742eaa055fSJeff Mahoney 
54752eaa055fSJeff Mahoney 	/* Nothing to do */
54762eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
54772eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
54782eaa055fSJeff Mahoney 		return 0;
54792eaa055fSJeff Mahoney 
54802ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
54812eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
54822eaa055fSJeff Mahoney 	if (ret)
54832eaa055fSJeff Mahoney 		return ret;
54842eaa055fSJeff Mahoney 
54852ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
54862eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
54872eaa055fSJeff Mahoney 	if (ret)
54882eaa055fSJeff Mahoney 		return ret;
54892eaa055fSJeff Mahoney 
54902ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
54912eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
54922eaa055fSJeff Mahoney 	if (ret)
54932eaa055fSJeff Mahoney 		return ret;
54942eaa055fSJeff Mahoney 
54957ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
54967ab19625SDavid Sterba 	if (ret)
54977ab19625SDavid Sterba 		return ret;
54987ab19625SDavid Sterba 
54998051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
55007ab19625SDavid Sterba 	if (IS_ERR(trans)) {
55017ab19625SDavid Sterba 		ret = PTR_ERR(trans);
55027ab19625SDavid Sterba 		goto out_drop_write;
55037ab19625SDavid Sterba 	}
55042eaa055fSJeff Mahoney 
55050b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
55062eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
55072eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
55082eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
55092eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
55102eaa055fSJeff Mahoney 
55112eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
55122eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
55132eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
55142eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
55152eaa055fSJeff Mahoney 
55162eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
55172eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
55182eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
55192eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
55200b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
55212eaa055fSJeff Mahoney 
55227ab19625SDavid Sterba 	ret = btrfs_commit_transaction(trans, root);
55237ab19625SDavid Sterba out_drop_write:
55247ab19625SDavid Sterba 	mnt_drop_write_file(file);
55257ab19625SDavid Sterba 
55267ab19625SDavid Sterba 	return ret;
55272eaa055fSJeff Mahoney }
55282eaa055fSJeff Mahoney 
5529f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5530f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5531f46b5a66SChristoph Hellwig {
55320b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
55330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
55340b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
55354bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5536f46b5a66SChristoph Hellwig 
5537f46b5a66SChristoph Hellwig 	switch (cmd) {
55386cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
55396cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
55406cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
55416cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
55426cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
55436cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5544f7039b1dSLi Dongyang 	case FITRIM:
5545f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5546f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5547fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5548fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5549fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
55503de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5551fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
55526f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
55536f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
555476dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
555576dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
55560caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
55570caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
55580caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
55590caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
55606ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
55616ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5562f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
55631e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
55641e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
55651e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5566f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5567198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5568f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
55692ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5570f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5571da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
55726b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
55736b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5574475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
55752ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5576475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
55772ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5578f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
55799ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5580f46b5a66SChristoph Hellwig 	case BTRFS_IOC_TRANS_START:
5581f46b5a66SChristoph Hellwig 		return btrfs_ioctl_trans_start(file);
5582f46b5a66SChristoph Hellwig 	case BTRFS_IOC_TRANS_END:
5583f46b5a66SChristoph Hellwig 		return btrfs_ioctl_trans_end(file);
5584ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5585ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5586cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5587cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5588ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5589ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5590d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5591d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5592d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
55932ff7e61eSJeff Mahoney 		return btrfs_ioctl_logical_to_ino(fs_info, argp);
55941406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
55952ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
55969b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
55979b199859SFilipe David Borba Manana 		int ret;
55989b199859SFilipe David Borba Manana 
55990b246afaSJeff Mahoney 		ret = btrfs_start_delalloc_roots(fs_info, 0, -1);
56009b199859SFilipe David Borba Manana 		if (ret)
56019b199859SFilipe David Borba Manana 			return ret;
56020b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
56032fad4e83SDavid Sterba 		/*
56042fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
560501327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
56062fad4e83SDavid Sterba 		 * processing uncleaned subvols.
56072fad4e83SDavid Sterba 		 */
56080b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
56099b199859SFilipe David Borba Manana 		return ret;
56109b199859SFilipe David Borba Manana 	}
561146204592SSage Weil 	case BTRFS_IOC_START_SYNC:
56129a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
561346204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
56142ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5615475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5616b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5617475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
56182ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5619475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
56202ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5621c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
56229ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5623837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
56242ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
562519a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
56262ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
56278ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
56288ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5629abccd00fSHugo Mills #ifdef CONFIG_64BIT
5630abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5631abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5632abccd00fSHugo Mills #endif
563331db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
563431db9f7cSAlexander Block 		return btrfs_ioctl_send(file, argp);
5635c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
56362ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
56375d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5638905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
56395d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5640905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
56415d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5642905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
56435d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5644905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
56452f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
56462f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
56472f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
56482f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
564957254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
565057254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
56513f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
56522ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5653867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5654867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5655a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5656a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
56572eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5658d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
56592eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
56602eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
56612eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
56622eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5663f46b5a66SChristoph Hellwig 	}
5664f46b5a66SChristoph Hellwig 
5665f46b5a66SChristoph Hellwig 	return -ENOTTY;
5666f46b5a66SChristoph Hellwig }
56674c63c245SLuke Dashjr 
56684c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
56694c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
56704c63c245SLuke Dashjr {
56714c63c245SLuke Dashjr 	switch (cmd) {
56724c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
56734c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
56744c63c245SLuke Dashjr 		break;
56754c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
56764c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
56774c63c245SLuke Dashjr 		break;
56784c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
56794c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
56804c63c245SLuke Dashjr 		break;
56814c63c245SLuke Dashjr 	default:
56824c63c245SLuke Dashjr 		return -ENOIOCTLCMD;
56834c63c245SLuke Dashjr 	}
56844c63c245SLuke Dashjr 
56854c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
56864c63c245SLuke Dashjr }
56874c63c245SLuke Dashjr #endif
5688