xref: /openbmc/linux/fs/btrfs/ioctl.c (revision bea7eafd)
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>
40f54de068SDavid Sterba #include <linux/mm.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 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
1606cbff00fSChristoph Hellwig {
161496ad9aaSAl Viro 	struct btrfs_inode *ip = BTRFS_I(file_inode(file));
1626cbff00fSChristoph Hellwig 	unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
1636cbff00fSChristoph Hellwig 
1646cbff00fSChristoph Hellwig 	if (copy_to_user(arg, &flags, sizeof(flags)))
1656cbff00fSChristoph Hellwig 		return -EFAULT;
1666cbff00fSChristoph Hellwig 	return 0;
1676cbff00fSChristoph Hellwig }
1686cbff00fSChristoph Hellwig 
16975e7cb7fSLiu Bo static int check_flags(unsigned int flags)
17075e7cb7fSLiu Bo {
17175e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
17275e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
17375e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
174e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
175e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
17675e7cb7fSLiu Bo 		return -EOPNOTSUPP;
17775e7cb7fSLiu Bo 
17875e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
17975e7cb7fSLiu Bo 		return -EINVAL;
18075e7cb7fSLiu Bo 
18175e7cb7fSLiu Bo 	return 0;
18275e7cb7fSLiu Bo }
18375e7cb7fSLiu Bo 
1846cbff00fSChristoph Hellwig static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
1856cbff00fSChristoph Hellwig {
186496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
1870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1886cbff00fSChristoph Hellwig 	struct btrfs_inode *ip = BTRFS_I(inode);
1896cbff00fSChristoph Hellwig 	struct btrfs_root *root = ip->root;
1906cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
1916cbff00fSChristoph Hellwig 	unsigned int flags, oldflags;
1926cbff00fSChristoph Hellwig 	int ret;
193f062abf0SLi Zefan 	u64 ip_oldflags;
194f062abf0SLi Zefan 	unsigned int i_oldflags;
1957e97b8daSDavid Sterba 	umode_t mode;
1966cbff00fSChristoph Hellwig 
197bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
198bd60ea0fSDavid Sterba 		return -EPERM;
199bd60ea0fSDavid Sterba 
200b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
201b83cc969SLi Zefan 		return -EROFS;
202b83cc969SLi Zefan 
2036cbff00fSChristoph Hellwig 	if (copy_from_user(&flags, arg, sizeof(flags)))
2046cbff00fSChristoph Hellwig 		return -EFAULT;
2056cbff00fSChristoph Hellwig 
20675e7cb7fSLiu Bo 	ret = check_flags(flags);
20775e7cb7fSLiu Bo 	if (ret)
20875e7cb7fSLiu Bo 		return ret;
2096cbff00fSChristoph Hellwig 
210e7848683SJan Kara 	ret = mnt_want_write_file(file);
211e7848683SJan Kara 	if (ret)
212e7848683SJan Kara 		return ret;
213e7848683SJan Kara 
2145955102cSAl Viro 	inode_lock(inode);
2156cbff00fSChristoph Hellwig 
216f062abf0SLi Zefan 	ip_oldflags = ip->flags;
217f062abf0SLi Zefan 	i_oldflags = inode->i_flags;
2187e97b8daSDavid Sterba 	mode = inode->i_mode;
219f062abf0SLi Zefan 
2206cbff00fSChristoph Hellwig 	flags = btrfs_mask_flags(inode->i_mode, flags);
2216cbff00fSChristoph Hellwig 	oldflags = btrfs_flags_to_ioctl(ip->flags);
2226cbff00fSChristoph Hellwig 	if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
2236cbff00fSChristoph Hellwig 		if (!capable(CAP_LINUX_IMMUTABLE)) {
2246cbff00fSChristoph Hellwig 			ret = -EPERM;
2256cbff00fSChristoph Hellwig 			goto out_unlock;
2266cbff00fSChristoph Hellwig 		}
2276cbff00fSChristoph Hellwig 	}
2286cbff00fSChristoph Hellwig 
2296cbff00fSChristoph Hellwig 	if (flags & FS_SYNC_FL)
2306cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_SYNC;
2316cbff00fSChristoph Hellwig 	else
2326cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_SYNC;
2336cbff00fSChristoph Hellwig 	if (flags & FS_IMMUTABLE_FL)
2346cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_IMMUTABLE;
2356cbff00fSChristoph Hellwig 	else
2366cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_IMMUTABLE;
2376cbff00fSChristoph Hellwig 	if (flags & FS_APPEND_FL)
2386cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_APPEND;
2396cbff00fSChristoph Hellwig 	else
2406cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_APPEND;
2416cbff00fSChristoph Hellwig 	if (flags & FS_NODUMP_FL)
2426cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NODUMP;
2436cbff00fSChristoph Hellwig 	else
2446cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NODUMP;
2456cbff00fSChristoph Hellwig 	if (flags & FS_NOATIME_FL)
2466cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_NOATIME;
2476cbff00fSChristoph Hellwig 	else
2486cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_NOATIME;
2496cbff00fSChristoph Hellwig 	if (flags & FS_DIRSYNC_FL)
2506cbff00fSChristoph Hellwig 		ip->flags |= BTRFS_INODE_DIRSYNC;
2516cbff00fSChristoph Hellwig 	else
2526cbff00fSChristoph Hellwig 		ip->flags &= ~BTRFS_INODE_DIRSYNC;
2537e97b8daSDavid Sterba 	if (flags & FS_NOCOW_FL) {
2547e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2557e97b8daSDavid Sterba 			/*
2567e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2577e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2587e97b8daSDavid Sterba 			 * status of the file and will not set it.
2597e97b8daSDavid Sterba 			 */
2607e97b8daSDavid Sterba 			if (inode->i_size == 0)
2617e97b8daSDavid Sterba 				ip->flags |= BTRFS_INODE_NODATACOW
2627e97b8daSDavid Sterba 					   | BTRFS_INODE_NODATASUM;
2637e97b8daSDavid Sterba 		} else {
264e1e8fb6aSLi Zefan 			ip->flags |= BTRFS_INODE_NODATACOW;
2657e97b8daSDavid Sterba 		}
2667e97b8daSDavid Sterba 	} else {
2677e97b8daSDavid Sterba 		/*
26801327610SNicholas D Steeves 		 * Revert back under same assumptions as above
2697e97b8daSDavid Sterba 		 */
2707e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2717e97b8daSDavid Sterba 			if (inode->i_size == 0)
2727e97b8daSDavid Sterba 				ip->flags &= ~(BTRFS_INODE_NODATACOW
2737e97b8daSDavid Sterba 				             | BTRFS_INODE_NODATASUM);
2747e97b8daSDavid Sterba 		} else {
275e1e8fb6aSLi Zefan 			ip->flags &= ~BTRFS_INODE_NODATACOW;
2767e97b8daSDavid Sterba 		}
2777e97b8daSDavid Sterba 	}
2786cbff00fSChristoph Hellwig 
27975e7cb7fSLiu Bo 	/*
28075e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
28175e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
28275e7cb7fSLiu Bo 	 * things smaller.
28375e7cb7fSLiu Bo 	 */
28475e7cb7fSLiu Bo 	if (flags & FS_NOCOMP_FL) {
28575e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_COMPRESS;
28675e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_NOCOMPRESS;
28763541927SFilipe David Borba Manana 
28863541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
28963541927SFilipe David Borba Manana 		if (ret && ret != -ENODATA)
29063541927SFilipe David Borba Manana 			goto out_drop;
29175e7cb7fSLiu Bo 	} else if (flags & FS_COMPR_FL) {
29263541927SFilipe David Borba Manana 		const char *comp;
29363541927SFilipe David Borba Manana 
29475e7cb7fSLiu Bo 		ip->flags |= BTRFS_INODE_COMPRESS;
29575e7cb7fSLiu Bo 		ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
29663541927SFilipe David Borba Manana 
2970b246afaSJeff Mahoney 		if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
29863541927SFilipe David Borba Manana 			comp = "lzo";
29963541927SFilipe David Borba Manana 		else
30063541927SFilipe David Borba Manana 			comp = "zlib";
30163541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression",
30263541927SFilipe David Borba Manana 				     comp, strlen(comp), 0);
30363541927SFilipe David Borba Manana 		if (ret)
30463541927SFilipe David Borba Manana 			goto out_drop;
30563541927SFilipe David Borba Manana 
306ebcb904dSLi Zefan 	} else {
30778a017a2SFilipe Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
30878a017a2SFilipe Manana 		if (ret && ret != -ENODATA)
30978a017a2SFilipe Manana 			goto out_drop;
310ebcb904dSLi Zefan 		ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
31175e7cb7fSLiu Bo 	}
3126cbff00fSChristoph Hellwig 
3134da6f1a3SLi Zefan 	trans = btrfs_start_transaction(root, 1);
314f062abf0SLi Zefan 	if (IS_ERR(trans)) {
315f062abf0SLi Zefan 		ret = PTR_ERR(trans);
316f062abf0SLi Zefan 		goto out_drop;
317f062abf0SLi Zefan 	}
3186cbff00fSChristoph Hellwig 
319306424ccSLi Zefan 	btrfs_update_iflags(inode);
3200c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
321c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3226cbff00fSChristoph Hellwig 	ret = btrfs_update_inode(trans, root, inode);
3236cbff00fSChristoph Hellwig 
3243a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
325f062abf0SLi Zefan  out_drop:
326f062abf0SLi Zefan 	if (ret) {
327f062abf0SLi Zefan 		ip->flags = ip_oldflags;
328f062abf0SLi Zefan 		inode->i_flags = i_oldflags;
329f062abf0SLi Zefan 	}
3306cbff00fSChristoph Hellwig 
3316cbff00fSChristoph Hellwig  out_unlock:
3325955102cSAl Viro 	inode_unlock(inode);
333e7848683SJan Kara 	mnt_drop_write_file(file);
3342d4e6f6aSliubo 	return ret;
3356cbff00fSChristoph Hellwig }
3366cbff00fSChristoph Hellwig 
3376cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
3386cbff00fSChristoph Hellwig {
339496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
3406cbff00fSChristoph Hellwig 
3416cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
3426cbff00fSChristoph Hellwig }
343f46b5a66SChristoph Hellwig 
344f7039b1dSLi Dongyang static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
345f7039b1dSLi Dongyang {
3460b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
3470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
348f7039b1dSLi Dongyang 	struct btrfs_device *device;
349f7039b1dSLi Dongyang 	struct request_queue *q;
350f7039b1dSLi Dongyang 	struct fstrim_range range;
351f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
352f7039b1dSLi Dongyang 	u64 num_devices = 0;
353815745cfSAl Viro 	u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
354f7039b1dSLi Dongyang 	int ret;
355f7039b1dSLi Dongyang 
356f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
357f7039b1dSLi Dongyang 		return -EPERM;
358f7039b1dSLi Dongyang 
3591f78160cSXiao Guangrong 	rcu_read_lock();
3601f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
3611f78160cSXiao Guangrong 				dev_list) {
362f7039b1dSLi Dongyang 		if (!device->bdev)
363f7039b1dSLi Dongyang 			continue;
364f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
365f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
366f7039b1dSLi Dongyang 			num_devices++;
36750d0446eSSeraphime Kirkovski 			minlen = min_t(u64, q->limits.discard_granularity,
368f7039b1dSLi Dongyang 				     minlen);
369f7039b1dSLi Dongyang 		}
370f7039b1dSLi Dongyang 	}
3711f78160cSXiao Guangrong 	rcu_read_unlock();
372f4c697e6SLukas Czerner 
373f7039b1dSLi Dongyang 	if (!num_devices)
374f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
375f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
376f7039b1dSLi Dongyang 		return -EFAULT;
377e515c18bSLukas Czerner 	if (range.start > total_bytes ||
378e515c18bSLukas Czerner 	    range.len < fs_info->sb->s_blocksize)
379f4c697e6SLukas Czerner 		return -EINVAL;
380f7039b1dSLi Dongyang 
381f4c697e6SLukas Czerner 	range.len = min(range.len, total_bytes - range.start);
382f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
3832ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
384f7039b1dSLi Dongyang 	if (ret < 0)
385f7039b1dSLi Dongyang 		return ret;
386f7039b1dSLi Dongyang 
387f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
388f7039b1dSLi Dongyang 		return -EFAULT;
389f7039b1dSLi Dongyang 
390f7039b1dSLi Dongyang 	return 0;
391f7039b1dSLi Dongyang }
392f7039b1dSLi Dongyang 
393dd5f9615SStefan Behrens int btrfs_is_empty_uuid(u8 *uuid)
394dd5f9615SStefan Behrens {
39546e0f66aSChris Mason 	int i;
39646e0f66aSChris Mason 
39746e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
39846e0f66aSChris Mason 		if (uuid[i])
39946e0f66aSChris Mason 			return 0;
40046e0f66aSChris Mason 	}
40146e0f66aSChris Mason 	return 1;
402dd5f9615SStefan Behrens }
403dd5f9615SStefan Behrens 
404d5c12070SMiao Xie static noinline int create_subvol(struct inode *dir,
405cb8e7090SChristoph Hellwig 				  struct dentry *dentry,
40652f75f4fSDavid Sterba 				  const char *name, int namelen,
4076f72c7e2SArne Jansen 				  u64 *async_transid,
4088696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
409f46b5a66SChristoph Hellwig {
4100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
411f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
412f46b5a66SChristoph Hellwig 	struct btrfs_key key;
41349a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
414f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
415f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
416d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
41776dda93cSYan, Zheng 	struct btrfs_root *new_root;
418d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
419c2050a45SDeepa Dinamani 	struct timespec cur_time = current_time(dir);
4205662344bSTsutomu Itoh 	struct inode *inode;
421f46b5a66SChristoph Hellwig 	int ret;
422f46b5a66SChristoph Hellwig 	int err;
423f46b5a66SChristoph Hellwig 	u64 objectid;
424f46b5a66SChristoph Hellwig 	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
4253de4586cSChris Mason 	u64 index = 0;
426d5c12070SMiao Xie 	u64 qgroup_reserved;
4278ea05e3aSAlexander Block 	uuid_le new_uuid;
428f46b5a66SChristoph Hellwig 
42949a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
43049a3c4d9SDavid Sterba 	if (!root_item)
43149a3c4d9SDavid Sterba 		return -ENOMEM;
43249a3c4d9SDavid Sterba 
4330b246afaSJeff Mahoney 	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
4342fbe8c8aSAl Viro 	if (ret)
43549a3c4d9SDavid Sterba 		goto fail_free;
4366a912213SJosef Bacik 
437e09fe2d2SQu Wenruo 	/*
438e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
43901327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
440e09fe2d2SQu Wenruo 	 */
44149a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
44249a3c4d9SDavid Sterba 		ret = -ENOSPC;
44349a3c4d9SDavid Sterba 		goto fail_free;
44449a3c4d9SDavid Sterba 	}
445e09fe2d2SQu Wenruo 
446d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4479ed74f2dSJosef Bacik 	/*
448d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
449d5c12070SMiao Xie 	 * of create_snapshot().
4509ed74f2dSJosef Bacik 	 */
451d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
452dd5f9615SStefan Behrens 					       8, &qgroup_reserved, false);
453d5c12070SMiao Xie 	if (ret)
45449a3c4d9SDavid Sterba 		goto fail_free;
455f46b5a66SChristoph Hellwig 
456d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
457d5c12070SMiao Xie 	if (IS_ERR(trans)) {
458d5c12070SMiao Xie 		ret = PTR_ERR(trans);
4597775c818SDavid Sterba 		btrfs_subvolume_release_metadata(fs_info, &block_rsv);
46049a3c4d9SDavid Sterba 		goto fail_free;
461d5c12070SMiao Xie 	}
462d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
463d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
464f46b5a66SChristoph Hellwig 
4650b246afaSJeff Mahoney 	ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
4666f72c7e2SArne Jansen 	if (ret)
4676f72c7e2SArne Jansen 		goto fail;
4686f72c7e2SArne Jansen 
4694d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
4708e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
4718e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
4728e8a1e31SJosef Bacik 		goto fail;
4738e8a1e31SJosef Bacik 	}
474f46b5a66SChristoph Hellwig 
475b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
476f46b5a66SChristoph Hellwig 	btrfs_set_header_bytenr(leaf, leaf->start);
477f46b5a66SChristoph Hellwig 	btrfs_set_header_generation(leaf, trans->transid);
4785d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
479f46b5a66SChristoph Hellwig 	btrfs_set_header_owner(leaf, objectid);
480f46b5a66SChristoph Hellwig 
4810b246afaSJeff Mahoney 	write_extent_buffer_fsid(leaf, fs_info->fsid);
4820b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
483f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
484f46b5a66SChristoph Hellwig 
48549a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
4863cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
4873cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
4883cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
489da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
4900b246afaSJeff Mahoney 				     fs_info->nodesize);
4913cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
492f46b5a66SChristoph Hellwig 
49349a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
49449a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
4953cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
49608fe4db1SLi Zefan 
49749a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
49849a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
49949a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
50049a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
50149a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
50249a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
503f46b5a66SChristoph Hellwig 
50449a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
50549a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
5068ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
50749a3c4d9SDavid Sterba 	memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
50849a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
50949a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
51049a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
51149a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
51249a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
513f46b5a66SChristoph Hellwig 
514925baeddSChris Mason 	btrfs_tree_unlock(leaf);
515f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
516f46b5a66SChristoph Hellwig 	leaf = NULL;
517f46b5a66SChristoph Hellwig 
51849a3c4d9SDavid Sterba 	btrfs_set_root_dirid(root_item, new_dirid);
519f46b5a66SChristoph Hellwig 
520f46b5a66SChristoph Hellwig 	key.objectid = objectid;
5215d4f98a2SYan Zheng 	key.offset = 0;
522962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
5230b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
52449a3c4d9SDavid Sterba 				root_item);
525f46b5a66SChristoph Hellwig 	if (ret)
526f46b5a66SChristoph Hellwig 		goto fail;
527f46b5a66SChristoph Hellwig 
52876dda93cSYan, Zheng 	key.offset = (u64)-1;
5290b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &key);
53079787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
53179787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
53266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
53379787eaaSJeff Mahoney 		goto fail;
53479787eaaSJeff Mahoney 	}
53576dda93cSYan, Zheng 
53676dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
53776dda93cSYan, Zheng 
53863541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
539ce598979SMark Fasheh 	if (ret) {
540ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
54166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
542ce598979SMark Fasheh 		goto fail;
543ce598979SMark Fasheh 	}
544ce598979SMark Fasheh 
545f32e48e9SChandan Rajendra 	mutex_lock(&new_root->objectid_mutex);
546f32e48e9SChandan Rajendra 	new_root->highest_objectid = new_dirid;
547f32e48e9SChandan Rajendra 	mutex_unlock(&new_root->objectid_mutex);
548f32e48e9SChandan Rajendra 
549f46b5a66SChristoph Hellwig 	/*
550f46b5a66SChristoph Hellwig 	 * insert the directory item
551f46b5a66SChristoph Hellwig 	 */
552877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
55379787eaaSJeff Mahoney 	if (ret) {
55466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
55579787eaaSJeff Mahoney 		goto fail;
55679787eaaSJeff Mahoney 	}
5573de4586cSChris Mason 
5583de4586cSChris Mason 	ret = btrfs_insert_dir_item(trans, root,
5598e7611cfSNikolay Borisov 				    name, namelen, BTRFS_I(dir), &key,
5603de4586cSChris Mason 				    BTRFS_FT_DIR, index);
56179787eaaSJeff Mahoney 	if (ret) {
56266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
563f46b5a66SChristoph Hellwig 		goto fail;
56479787eaaSJeff Mahoney 	}
5650660b5afSChris Mason 
5666ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
56752c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
56852c26179SYan Zheng 	BUG_ON(ret);
56952c26179SYan Zheng 
5700b246afaSJeff Mahoney 	ret = btrfs_add_root_ref(trans, fs_info,
5714df27c4dSYan, Zheng 				 objectid, root->root_key.objectid,
5724a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
5730660b5afSChris Mason 	BUG_ON(ret);
5740660b5afSChris Mason 
5750b246afaSJeff Mahoney 	ret = btrfs_uuid_tree_add(trans, fs_info, root_item->uuid,
5766bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
577dd5f9615SStefan Behrens 	if (ret)
57866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
579dd5f9615SStefan Behrens 
580f46b5a66SChristoph Hellwig fail:
58149a3c4d9SDavid Sterba 	kfree(root_item);
582d5c12070SMiao Xie 	trans->block_rsv = NULL;
583d5c12070SMiao Xie 	trans->bytes_reserved = 0;
5847775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
585de6e8200SLiu Bo 
58672fd032eSSage Weil 	if (async_transid) {
58772fd032eSSage Weil 		*async_transid = trans->transid;
5883a45bb20SJeff Mahoney 		err = btrfs_commit_transaction_async(trans, 1);
58900d71c9cSMiao Xie 		if (err)
5903a45bb20SJeff Mahoney 			err = btrfs_commit_transaction(trans);
59172fd032eSSage Weil 	} else {
5923a45bb20SJeff Mahoney 		err = btrfs_commit_transaction(trans);
59372fd032eSSage Weil 	}
594f46b5a66SChristoph Hellwig 	if (err && !ret)
595f46b5a66SChristoph Hellwig 		ret = err;
5961a65e24bSChris Mason 
5975662344bSTsutomu Itoh 	if (!ret) {
5985662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
599de6e8200SLiu Bo 		if (IS_ERR(inode))
600de6e8200SLiu Bo 			return PTR_ERR(inode);
6015662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
6025662344bSTsutomu Itoh 	}
603f46b5a66SChristoph Hellwig 	return ret;
60449a3c4d9SDavid Sterba 
60549a3c4d9SDavid Sterba fail_free:
60649a3c4d9SDavid Sterba 	kfree(root_item);
60749a3c4d9SDavid Sterba 	return ret;
608f46b5a66SChristoph Hellwig }
609f46b5a66SChristoph Hellwig 
610ea14b57fSDavid Sterba static void btrfs_wait_for_no_snapshotting_writes(struct btrfs_root *root)
6118257b2dcSMiao Xie {
6128257b2dcSMiao Xie 	s64 writers;
6138257b2dcSMiao Xie 	DEFINE_WAIT(wait);
6148257b2dcSMiao Xie 
6158257b2dcSMiao Xie 	do {
6168257b2dcSMiao Xie 		prepare_to_wait(&root->subv_writers->wait, &wait,
6178257b2dcSMiao Xie 				TASK_UNINTERRUPTIBLE);
6188257b2dcSMiao Xie 
6198257b2dcSMiao Xie 		writers = percpu_counter_sum(&root->subv_writers->counter);
6208257b2dcSMiao Xie 		if (writers)
6218257b2dcSMiao Xie 			schedule();
6228257b2dcSMiao Xie 
6238257b2dcSMiao Xie 		finish_wait(&root->subv_writers->wait, &wait);
6248257b2dcSMiao Xie 	} while (writers);
6258257b2dcSMiao Xie }
6268257b2dcSMiao Xie 
627e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
62861d7e4cbSDavid Sterba 			   struct dentry *dentry,
629e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
630e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
631f46b5a66SChristoph Hellwig {
6320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6332e4bfab9SYan, Zheng 	struct inode *inode;
634f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
635f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
6362e4bfab9SYan, Zheng 	int ret;
637f46b5a66SChristoph Hellwig 
63827cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
639f46b5a66SChristoph Hellwig 		return -EINVAL;
640f46b5a66SChristoph Hellwig 
64123269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
642a1ee7362SDavid Sterba 	if (!pending_snapshot)
643a1ee7362SDavid Sterba 		return -ENOMEM;
644a1ee7362SDavid Sterba 
645b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
64623269bf5SDavid Sterba 			GFP_KERNEL);
6478546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
6488546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
649b0c0ea63SDavid Sterba 		ret = -ENOMEM;
650b0c0ea63SDavid Sterba 		goto free_pending;
651b0c0ea63SDavid Sterba 	}
652b0c0ea63SDavid Sterba 
653ea14b57fSDavid Sterba 	atomic_inc(&root->will_be_snapshotted);
6544e857c58SPeter Zijlstra 	smp_mb__after_atomic();
655ea14b57fSDavid Sterba 	btrfs_wait_for_no_snapshotting_writes(root);
6568257b2dcSMiao Xie 
6576a03843dSMiao Xie 	ret = btrfs_start_delalloc_inodes(root, 0);
6586a03843dSMiao Xie 	if (ret)
659a1ee7362SDavid Sterba 		goto dec_and_free;
6606a03843dSMiao Xie 
6616374e57aSChris Mason 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
6626a03843dSMiao Xie 
66366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
66466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
665d5c12070SMiao Xie 	/*
666d5c12070SMiao Xie 	 * 1 - parent dir inode
667d5c12070SMiao Xie 	 * 2 - dir entries
668d5c12070SMiao Xie 	 * 1 - root item
669d5c12070SMiao Xie 	 * 2 - root ref/backref
670d5c12070SMiao Xie 	 * 1 - root of snapshot
671dd5f9615SStefan Behrens 	 * 1 - UUID item
672d5c12070SMiao Xie 	 */
673d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
674dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
675ee3441b4SJeff Mahoney 					&pending_snapshot->qgroup_reserved,
676ee3441b4SJeff Mahoney 					false);
677d5c12070SMiao Xie 	if (ret)
678a1ee7362SDavid Sterba 		goto dec_and_free;
679d5c12070SMiao Xie 
680a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
681a22285a6SYan, Zheng 	pending_snapshot->root = root;
682b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
683e9662f70SMiao Xie 	pending_snapshot->dir = dir;
6848696c533SMiao Xie 	pending_snapshot->inherit = inherit;
685a22285a6SYan, Zheng 
686d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
687a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
688a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
689a22285a6SYan, Zheng 		goto fail;
690a22285a6SYan, Zheng 	}
691a22285a6SYan, Zheng 
6920b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
693a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
694a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
6950b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
69672fd032eSSage Weil 	if (async_transid) {
69772fd032eSSage Weil 		*async_transid = trans->transid;
6983a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction_async(trans, 1);
69900d71c9cSMiao Xie 		if (ret)
7003a45bb20SJeff Mahoney 			ret = btrfs_commit_transaction(trans);
70172fd032eSSage Weil 	} else {
7023a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
70372fd032eSSage Weil 	}
704aec8030aSMiao Xie 	if (ret)
705c37b2b62SJosef Bacik 		goto fail;
706a22285a6SYan, Zheng 
707a22285a6SYan, Zheng 	ret = pending_snapshot->error;
708f46b5a66SChristoph Hellwig 	if (ret)
7092e4bfab9SYan, Zheng 		goto fail;
710f46b5a66SChristoph Hellwig 
711d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
712d3797308SChris Mason 	if (ret)
713d3797308SChris Mason 		goto fail;
714d3797308SChris Mason 
7152b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
7162e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
7172e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
7182e4bfab9SYan, Zheng 		goto fail;
7192e4bfab9SYan, Zheng 	}
7205662344bSTsutomu Itoh 
7212e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
7222e4bfab9SYan, Zheng 	ret = 0;
7232e4bfab9SYan, Zheng fail:
7247775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
725a1ee7362SDavid Sterba dec_and_free:
726ea14b57fSDavid Sterba 	if (atomic_dec_and_test(&root->will_be_snapshotted))
727ea14b57fSDavid Sterba 		wake_up_atomic_t(&root->will_be_snapshotted);
728b0c0ea63SDavid Sterba free_pending:
729b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
7308546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
731a1ee7362SDavid Sterba 	kfree(pending_snapshot);
732a1ee7362SDavid Sterba 
733f46b5a66SChristoph Hellwig 	return ret;
734f46b5a66SChristoph Hellwig }
735f46b5a66SChristoph Hellwig 
7364260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
7374260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
7384260f7c7SSage Weil  *  whether the type of victim is right.
7394260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
7404260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
7414260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
7424260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
7434260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
7444260f7c7SSage Weil  *	a. be owner of dir, or
7454260f7c7SSage Weil  *	b. be owner of victim, or
7464260f7c7SSage Weil  *	c. have CAP_FOWNER capability
74701327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
7484260f7c7SSage Weil  *     links pointing to it.
7494260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
7504260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
7514260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
7524260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
7534260f7c7SSage Weil  *     nfs_async_unlink().
7544260f7c7SSage Weil  */
7554260f7c7SSage Weil 
7564260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
7574260f7c7SSage Weil {
7584260f7c7SSage Weil 	int error;
7594260f7c7SSage Weil 
7602b0143b5SDavid Howells 	if (d_really_is_negative(victim))
7614260f7c7SSage Weil 		return -ENOENT;
7624260f7c7SSage Weil 
7632b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
7644fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
7654260f7c7SSage Weil 
7664260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
7674260f7c7SSage Weil 	if (error)
7684260f7c7SSage Weil 		return error;
7694260f7c7SSage Weil 	if (IS_APPEND(dir))
7704260f7c7SSage Weil 		return -EPERM;
7712b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
7722b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
7734260f7c7SSage Weil 		return -EPERM;
7744260f7c7SSage Weil 	if (isdir) {
775e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
7764260f7c7SSage Weil 			return -ENOTDIR;
7774260f7c7SSage Weil 		if (IS_ROOT(victim))
7784260f7c7SSage Weil 			return -EBUSY;
779e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
7804260f7c7SSage Weil 		return -EISDIR;
7814260f7c7SSage Weil 	if (IS_DEADDIR(dir))
7824260f7c7SSage Weil 		return -ENOENT;
7834260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
7844260f7c7SSage Weil 		return -EBUSY;
7854260f7c7SSage Weil 	return 0;
7864260f7c7SSage Weil }
7874260f7c7SSage Weil 
788cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
789cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
790cb8e7090SChristoph Hellwig {
7912b0143b5SDavid Howells 	if (d_really_is_positive(child))
792cb8e7090SChristoph Hellwig 		return -EEXIST;
793cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
794cb8e7090SChristoph Hellwig 		return -ENOENT;
795cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
796cb8e7090SChristoph Hellwig }
797cb8e7090SChristoph Hellwig 
798cb8e7090SChristoph Hellwig /*
799cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
800cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
801cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
802cb8e7090SChristoph Hellwig  */
80392872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
80452f75f4fSDavid Sterba 				   const char *name, int namelen,
80572fd032eSSage Weil 				   struct btrfs_root *snap_src,
8066f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
8078696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
808cb8e7090SChristoph Hellwig {
8092b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
8100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
811cb8e7090SChristoph Hellwig 	struct dentry *dentry;
812cb8e7090SChristoph Hellwig 	int error;
813cb8e7090SChristoph Hellwig 
81400235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
81500235411SAl Viro 	if (error == -EINTR)
81600235411SAl Viro 		return error;
817cb8e7090SChristoph Hellwig 
818cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
819cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
820cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
821cb8e7090SChristoph Hellwig 		goto out_unlock;
822cb8e7090SChristoph Hellwig 
82376dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
824cb8e7090SChristoph Hellwig 	if (error)
825a874a63eSLiu Bo 		goto out_dput;
826cb8e7090SChristoph Hellwig 
8279c52057cSChris Mason 	/*
8289c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
8299c52057cSChris Mason 	 * check for them now when we can safely fail
8309c52057cSChris Mason 	 */
8319c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
8329c52057cSChris Mason 					       dir->i_ino, name,
8339c52057cSChris Mason 					       namelen);
8349c52057cSChris Mason 	if (error)
8359c52057cSChris Mason 		goto out_dput;
8369c52057cSChris Mason 
8370b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
83876dda93cSYan, Zheng 
83976dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
84076dda93cSYan, Zheng 		goto out_up_read;
84176dda93cSYan, Zheng 
8423de4586cSChris Mason 	if (snap_src) {
84361d7e4cbSDavid Sterba 		error = create_snapshot(snap_src, dir, dentry,
8446f72c7e2SArne Jansen 					async_transid, readonly, inherit);
8453de4586cSChris Mason 	} else {
846d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
847d5c12070SMiao Xie 				      async_transid, inherit);
8483de4586cSChris Mason 	}
84976dda93cSYan, Zheng 	if (!error)
85076dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
85176dda93cSYan, Zheng out_up_read:
8520b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
853cb8e7090SChristoph Hellwig out_dput:
854cb8e7090SChristoph Hellwig 	dput(dentry);
855cb8e7090SChristoph Hellwig out_unlock:
8565955102cSAl Viro 	inode_unlock(dir);
857cb8e7090SChristoph Hellwig 	return error;
858cb8e7090SChristoph Hellwig }
859cb8e7090SChristoph Hellwig 
8604cb5300bSChris Mason /*
8614cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
8624cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
8634cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
8644cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
8654cb5300bSChris Mason  * part of the file
8664cb5300bSChris Mason  */
867aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
8684cb5300bSChris Mason {
8694cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8704cb5300bSChris Mason 	struct extent_map *em = NULL;
8714cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8724cb5300bSChris Mason 	u64 end;
8734cb5300bSChris Mason 
8744cb5300bSChris Mason 	read_lock(&em_tree->lock);
87509cbfeafSKirill A. Shutemov 	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
8764cb5300bSChris Mason 	read_unlock(&em_tree->lock);
8774cb5300bSChris Mason 
8784cb5300bSChris Mason 	if (em) {
8794cb5300bSChris Mason 		end = extent_map_end(em);
8804cb5300bSChris Mason 		free_extent_map(em);
8814cb5300bSChris Mason 		if (end - offset > thresh)
8824cb5300bSChris Mason 			return 0;
8834cb5300bSChris Mason 	}
8844cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
8854cb5300bSChris Mason 	thresh /= 2;
8864cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
8874cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
8884cb5300bSChris Mason 	if (end >= thresh)
8894cb5300bSChris Mason 		return 0;
8904cb5300bSChris Mason 	return 1;
8914cb5300bSChris Mason }
8924cb5300bSChris Mason 
8934cb5300bSChris Mason /*
8944cb5300bSChris Mason  * helper function to walk through a file and find extents
8954cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
8964cb5300bSChris Mason  *
8974cb5300bSChris Mason  * This is used by the defragging code to find new and small
8984cb5300bSChris Mason  * extents
8994cb5300bSChris Mason  */
9004cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
9014cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
902aab110abSDavid Sterba 			    u64 *off, u32 thresh)
9034cb5300bSChris Mason {
9044cb5300bSChris Mason 	struct btrfs_path *path;
9054cb5300bSChris Mason 	struct btrfs_key min_key;
9064cb5300bSChris Mason 	struct extent_buffer *leaf;
9074cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
9084cb5300bSChris Mason 	int type;
9094cb5300bSChris Mason 	int ret;
9104a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
9114cb5300bSChris Mason 
9124cb5300bSChris Mason 	path = btrfs_alloc_path();
9134cb5300bSChris Mason 	if (!path)
9144cb5300bSChris Mason 		return -ENOMEM;
9154cb5300bSChris Mason 
916a4689d2bSDavid Sterba 	min_key.objectid = ino;
9174cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
9184cb5300bSChris Mason 	min_key.offset = *off;
9194cb5300bSChris Mason 
9204cb5300bSChris Mason 	while (1) {
9216174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
9224cb5300bSChris Mason 		if (ret != 0)
9234cb5300bSChris Mason 			goto none;
924f094c9bdSFilipe Manana process_slot:
925a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
9264cb5300bSChris Mason 			goto none;
9274cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
9284cb5300bSChris Mason 			goto none;
9294cb5300bSChris Mason 
9304cb5300bSChris Mason 		leaf = path->nodes[0];
9314cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
9324cb5300bSChris Mason 					struct btrfs_file_extent_item);
9334cb5300bSChris Mason 
9344cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
9354cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
9364cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
9374cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
9384cb5300bSChris Mason 			*off = min_key.offset;
9394cb5300bSChris Mason 			btrfs_free_path(path);
9404cb5300bSChris Mason 			return 0;
9414cb5300bSChris Mason 		}
9424cb5300bSChris Mason 
943f094c9bdSFilipe Manana 		path->slots[0]++;
944f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
945f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
946f094c9bdSFilipe Manana 			goto process_slot;
947f094c9bdSFilipe Manana 		}
948f094c9bdSFilipe Manana 
9494cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
9504cb5300bSChris Mason 			goto none;
9514cb5300bSChris Mason 
9524cb5300bSChris Mason 		min_key.offset++;
9534cb5300bSChris Mason 		btrfs_release_path(path);
9544cb5300bSChris Mason 	}
9554cb5300bSChris Mason none:
9564cb5300bSChris Mason 	btrfs_free_path(path);
9574cb5300bSChris Mason 	return -ENOENT;
9584cb5300bSChris Mason }
9594cb5300bSChris Mason 
9606c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
96117ce6ef8SLiu Bo {
96217ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
963940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9646c282eb4SLi Zefan 	struct extent_map *em;
96509cbfeafSKirill A. Shutemov 	u64 len = PAGE_SIZE;
966940100a4SChris Mason 
967940100a4SChris Mason 	/*
968940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
969940100a4SChris Mason 	 * the full extent lock
970940100a4SChris Mason 	 */
971940100a4SChris Mason 	read_lock(&em_tree->lock);
972940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
973940100a4SChris Mason 	read_unlock(&em_tree->lock);
974940100a4SChris Mason 
975940100a4SChris Mason 	if (!em) {
976308d9800SFilipe Manana 		struct extent_state *cached = NULL;
977308d9800SFilipe Manana 		u64 end = start + len - 1;
978308d9800SFilipe Manana 
979940100a4SChris Mason 		/* get the big lock and read metadata off disk */
980ff13db41SDavid Sterba 		lock_extent_bits(io_tree, start, end, &cached);
981fc4f21b1SNikolay Borisov 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
982308d9800SFilipe Manana 		unlock_extent_cached(io_tree, start, end, &cached, GFP_NOFS);
983940100a4SChris Mason 
9846cf8bfbfSDan Carpenter 		if (IS_ERR(em))
9856c282eb4SLi Zefan 			return NULL;
986940100a4SChris Mason 	}
987940100a4SChris Mason 
9886c282eb4SLi Zefan 	return em;
9896c282eb4SLi Zefan }
9906c282eb4SLi Zefan 
9916c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
9926c282eb4SLi Zefan {
9936c282eb4SLi Zefan 	struct extent_map *next;
9946c282eb4SLi Zefan 	bool ret = true;
9956c282eb4SLi Zefan 
9966c282eb4SLi Zefan 	/* this is the last extent */
9976c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
9986c282eb4SLi Zefan 		return false;
9996c282eb4SLi Zefan 
10006c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
1001e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1002e9512d72SChris Mason 		ret = false;
1003e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1004ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
10056c282eb4SLi Zefan 		ret = false;
10066c282eb4SLi Zefan 
10076c282eb4SLi Zefan 	free_extent_map(next);
10086c282eb4SLi Zefan 	return ret;
10096c282eb4SLi Zefan }
10106c282eb4SLi Zefan 
1011aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1012a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
1013a43a2111SAndrew Mahone 			       int compress)
10146c282eb4SLi Zefan {
10156c282eb4SLi Zefan 	struct extent_map *em;
10166c282eb4SLi Zefan 	int ret = 1;
10176c282eb4SLi Zefan 	bool next_mergeable = true;
10184a3560c4SLiu Bo 	bool prev_mergeable = true;
10196c282eb4SLi Zefan 
10206c282eb4SLi Zefan 	/*
10216c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
10226c282eb4SLi Zefan 	 * defragging it
10236c282eb4SLi Zefan 	 */
10246c282eb4SLi Zefan 	if (start < *defrag_end)
10256c282eb4SLi Zefan 		return 1;
10266c282eb4SLi Zefan 
10276c282eb4SLi Zefan 	*skip = 0;
10286c282eb4SLi Zefan 
10296c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
10306c282eb4SLi Zefan 	if (!em)
10316c282eb4SLi Zefan 		return 0;
10326c282eb4SLi Zefan 
1033940100a4SChris Mason 	/* this will cover holes, and inline extents */
103417ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1035940100a4SChris Mason 		ret = 0;
103617ce6ef8SLiu Bo 		goto out;
103717ce6ef8SLiu Bo 	}
103817ce6ef8SLiu Bo 
10394a3560c4SLiu Bo 	if (!*defrag_end)
10404a3560c4SLiu Bo 		prev_mergeable = false;
10414a3560c4SLiu Bo 
10426c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1043940100a4SChris Mason 	/*
10446c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
10456c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1046940100a4SChris Mason 	 */
1047a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
10484a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1049940100a4SChris Mason 		ret = 0;
105017ce6ef8SLiu Bo out:
1051940100a4SChris Mason 	/*
1052940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1053940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1054940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1055940100a4SChris Mason 	 *
1056940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1057940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1058940100a4SChris Mason 	 */
1059940100a4SChris Mason 	if (ret) {
1060940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1061940100a4SChris Mason 	} else {
1062940100a4SChris Mason 		*last_len = 0;
1063940100a4SChris Mason 		*skip = extent_map_end(em);
1064940100a4SChris Mason 		*defrag_end = 0;
1065940100a4SChris Mason 	}
1066940100a4SChris Mason 
1067940100a4SChris Mason 	free_extent_map(em);
1068940100a4SChris Mason 	return ret;
1069940100a4SChris Mason }
1070940100a4SChris Mason 
10714cb5300bSChris Mason /*
10724cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
10734cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
10744cb5300bSChris Mason  * to COW and defrag.
10754cb5300bSChris Mason  *
10764cb5300bSChris Mason  * It also makes sure the delalloc code has enough
10774cb5300bSChris Mason  * dirty data to avoid making new small extents as part
10784cb5300bSChris Mason  * of the defrag
10794cb5300bSChris Mason  *
10804cb5300bSChris Mason  * It's a good idea to start RA on this range
10814cb5300bSChris Mason  * before calling this.
10824cb5300bSChris Mason  */
10834cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
10844cb5300bSChris Mason 				    struct page **pages,
10854cb5300bSChris Mason 				    unsigned long start_index,
1086c41570c9SJustin Maggard 				    unsigned long num_pages)
1087f46b5a66SChristoph Hellwig {
10884cb5300bSChris Mason 	unsigned long file_end;
10894cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1090f46b5a66SChristoph Hellwig 	u64 page_start;
1091f46b5a66SChristoph Hellwig 	u64 page_end;
10921f12bd06SLiu Bo 	u64 page_cnt;
10934cb5300bSChris Mason 	int ret;
10944cb5300bSChris Mason 	int i;
10954cb5300bSChris Mason 	int i_done;
10964cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
10974cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1098600a45e1SMiao Xie 	struct extent_io_tree *tree;
1099364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
11003b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
11014cb5300bSChris Mason 
110209cbfeafSKirill A. Shutemov 	file_end = (isize - 1) >> PAGE_SHIFT;
11031f12bd06SLiu Bo 	if (!isize || start_index > file_end)
11041f12bd06SLiu Bo 		return 0;
11051f12bd06SLiu Bo 
11061f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
11074cb5300bSChris Mason 
1108364ecf36SQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
110909cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
111009cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
11114cb5300bSChris Mason 	if (ret)
11124cb5300bSChris Mason 		return ret;
11134cb5300bSChris Mason 	i_done = 0;
1114600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
11154cb5300bSChris Mason 
11164cb5300bSChris Mason 	/* step one, lock all the pages */
11171f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
11184cb5300bSChris Mason 		struct page *page;
1119600a45e1SMiao Xie again:
1120a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
11213b16a4e3SJosef Bacik 					   start_index + i, mask);
11224cb5300bSChris Mason 		if (!page)
11234cb5300bSChris Mason 			break;
11244cb5300bSChris Mason 
1125600a45e1SMiao Xie 		page_start = page_offset(page);
112609cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
1127600a45e1SMiao Xie 		while (1) {
1128308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1129ff13db41SDavid Sterba 					 &cached_state);
1130600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1131600a45e1SMiao Xie 							      page_start);
1132308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1133308d9800SFilipe Manana 					     &cached_state, GFP_NOFS);
1134600a45e1SMiao Xie 			if (!ordered)
1135600a45e1SMiao Xie 				break;
1136600a45e1SMiao Xie 
1137600a45e1SMiao Xie 			unlock_page(page);
1138600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1139600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1140600a45e1SMiao Xie 			lock_page(page);
11411f12bd06SLiu Bo 			/*
11421f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
11431f12bd06SLiu Bo 			 * it was released or not.
11441f12bd06SLiu Bo 			 */
11451f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
11461f12bd06SLiu Bo 				unlock_page(page);
114709cbfeafSKirill A. Shutemov 				put_page(page);
11481f12bd06SLiu Bo 				goto again;
11491f12bd06SLiu Bo 			}
1150600a45e1SMiao Xie 		}
1151600a45e1SMiao Xie 
11524cb5300bSChris Mason 		if (!PageUptodate(page)) {
11534cb5300bSChris Mason 			btrfs_readpage(NULL, page);
11544cb5300bSChris Mason 			lock_page(page);
11554cb5300bSChris Mason 			if (!PageUptodate(page)) {
11564cb5300bSChris Mason 				unlock_page(page);
115709cbfeafSKirill A. Shutemov 				put_page(page);
11584cb5300bSChris Mason 				ret = -EIO;
11594cb5300bSChris Mason 				break;
11604cb5300bSChris Mason 			}
11614cb5300bSChris Mason 		}
1162600a45e1SMiao Xie 
1163600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1164600a45e1SMiao Xie 			unlock_page(page);
116509cbfeafSKirill A. Shutemov 			put_page(page);
1166600a45e1SMiao Xie 			goto again;
1167600a45e1SMiao Xie 		}
1168600a45e1SMiao Xie 
11694cb5300bSChris Mason 		pages[i] = page;
11704cb5300bSChris Mason 		i_done++;
11714cb5300bSChris Mason 	}
11724cb5300bSChris Mason 	if (!i_done || ret)
11734cb5300bSChris Mason 		goto out;
11744cb5300bSChris Mason 
11754cb5300bSChris Mason 	if (!(inode->i_sb->s_flags & MS_ACTIVE))
11764cb5300bSChris Mason 		goto out;
11774cb5300bSChris Mason 
11784cb5300bSChris Mason 	/*
11794cb5300bSChris Mason 	 * so now we have a nice long stream of locked
11804cb5300bSChris Mason 	 * and up to date pages, lets wait on them
11814cb5300bSChris Mason 	 */
11824cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
11834cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
11844cb5300bSChris Mason 
11854cb5300bSChris Mason 	page_start = page_offset(pages[0]);
118609cbfeafSKirill A. Shutemov 	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
11874cb5300bSChris Mason 
11884cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1189ff13db41SDavid Sterba 			 page_start, page_end - 1, &cached_state);
11904cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
11914cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
11929e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
11939e8a4a8bSLiu Bo 			  &cached_state, GFP_NOFS);
11944cb5300bSChris Mason 
11951f12bd06SLiu Bo 	if (i_done != page_cnt) {
11969e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
11979e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
11989e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
1199bc42bda2SQu Wenruo 		btrfs_delalloc_release_space(inode, data_reserved,
120009cbfeafSKirill A. Shutemov 				start_index << PAGE_SHIFT,
120109cbfeafSKirill A. Shutemov 				(page_cnt - i_done) << PAGE_SHIFT);
12024cb5300bSChris Mason 	}
12034cb5300bSChris Mason 
12044cb5300bSChris Mason 
12059e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1206018ed4f7SDavid Sterba 			  &cached_state);
12074cb5300bSChris Mason 
12084cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
12094cb5300bSChris Mason 			     page_start, page_end - 1, &cached_state,
12104cb5300bSChris Mason 			     GFP_NOFS);
12114cb5300bSChris Mason 
12124cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12134cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
12144cb5300bSChris Mason 		ClearPageChecked(pages[i]);
12154cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
12164cb5300bSChris Mason 		set_page_dirty(pages[i]);
12174cb5300bSChris Mason 		unlock_page(pages[i]);
121809cbfeafSKirill A. Shutemov 		put_page(pages[i]);
12194cb5300bSChris Mason 	}
1220364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
12214cb5300bSChris Mason 	return i_done;
12224cb5300bSChris Mason out:
12234cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
12244cb5300bSChris Mason 		unlock_page(pages[i]);
122509cbfeafSKirill A. Shutemov 		put_page(pages[i]);
12264cb5300bSChris Mason 	}
1227bc42bda2SQu Wenruo 	btrfs_delalloc_release_space(inode, data_reserved,
122809cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
122909cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
1230364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
12314cb5300bSChris Mason 	return ret;
12324cb5300bSChris Mason 
12334cb5300bSChris Mason }
12344cb5300bSChris Mason 
12354cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
12364cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
12374cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
12384cb5300bSChris Mason {
12390b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
12404cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
12414cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
12424cb5300bSChris Mason 	unsigned long last_index;
1243151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1244940100a4SChris Mason 	u64 last_len = 0;
1245940100a4SChris Mason 	u64 skip = 0;
1246940100a4SChris Mason 	u64 defrag_end = 0;
12474cb5300bSChris Mason 	u64 newer_off = range->start;
1248f46b5a66SChristoph Hellwig 	unsigned long i;
1249008873eaSLi Zefan 	unsigned long ra_index = 0;
1250f46b5a66SChristoph Hellwig 	int ret;
12514cb5300bSChris Mason 	int defrag_count = 0;
12521a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1253aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
125409cbfeafSKirill A. Shutemov 	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1255c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
1256ee22184bSByongho Lee 	u64 new_align = ~((u64)SZ_128K - 1);
12574cb5300bSChris Mason 	struct page **pages = NULL;
12581e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
12594cb5300bSChris Mason 
12600abd5b17SLiu Bo 	if (isize == 0)
12610abd5b17SLiu Bo 		return 0;
12620abd5b17SLiu Bo 
12630abd5b17SLiu Bo 	if (range->start >= isize)
12640abd5b17SLiu Bo 		return -EINVAL;
12651a419d85SLi Zefan 
12661e2ef46dSDavid Sterba 	if (do_compress) {
12671a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
12681a419d85SLi Zefan 			return -EINVAL;
12691a419d85SLi Zefan 		if (range->compress_type)
12701a419d85SLi Zefan 			compress_type = range->compress_type;
12711a419d85SLi Zefan 	}
1272f46b5a66SChristoph Hellwig 
12730abd5b17SLiu Bo 	if (extent_thresh == 0)
1274ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1275f46b5a66SChristoph Hellwig 
12764cb5300bSChris Mason 	/*
12770a52d108SDavid Sterba 	 * If we were not given a file, allocate a readahead context. As
12780a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
12790a52d108SDavid Sterba 	 * we don't error out.
12804cb5300bSChris Mason 	 */
12814cb5300bSChris Mason 	if (!file) {
128263e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
12830a52d108SDavid Sterba 		if (ra)
12844cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
12854cb5300bSChris Mason 	} else {
12864cb5300bSChris Mason 		ra = &file->f_ra;
12874cb5300bSChris Mason 	}
12884cb5300bSChris Mason 
128963e727ecSDavid Sterba 	pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
12904cb5300bSChris Mason 	if (!pages) {
12914cb5300bSChris Mason 		ret = -ENOMEM;
12924cb5300bSChris Mason 		goto out_ra;
12934cb5300bSChris Mason 	}
12944cb5300bSChris Mason 
12954cb5300bSChris Mason 	/* find the last page to defrag */
12961e701a32SChris Mason 	if (range->start + range->len > range->start) {
1297151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
129809cbfeafSKirill A. Shutemov 			 range->start + range->len - 1) >> PAGE_SHIFT;
12991e701a32SChris Mason 	} else {
130009cbfeafSKirill A. Shutemov 		last_index = (isize - 1) >> PAGE_SHIFT;
13011e701a32SChris Mason 	}
13021e701a32SChris Mason 
13034cb5300bSChris Mason 	if (newer_than) {
13044cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
1305ee22184bSByongho Lee 				       &newer_off, SZ_64K);
13064cb5300bSChris Mason 		if (!ret) {
13074cb5300bSChris Mason 			range->start = newer_off;
13084cb5300bSChris Mason 			/*
13094cb5300bSChris Mason 			 * we always align our defrag to help keep
13104cb5300bSChris Mason 			 * the extents in the file evenly spaced
13114cb5300bSChris Mason 			 */
131209cbfeafSKirill A. Shutemov 			i = (newer_off & new_align) >> PAGE_SHIFT;
13134cb5300bSChris Mason 		} else
13144cb5300bSChris Mason 			goto out_ra;
13154cb5300bSChris Mason 	} else {
131609cbfeafSKirill A. Shutemov 		i = range->start >> PAGE_SHIFT;
13174cb5300bSChris Mason 	}
13184cb5300bSChris Mason 	if (!max_to_defrag)
1319070034bdSchandan 		max_to_defrag = last_index - i + 1;
13204cb5300bSChris Mason 
13212a0f7f57SLi Zefan 	/*
13222a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
13232a0f7f57SLi Zefan 	 * written sequentially.
13242a0f7f57SLi Zefan 	 */
13252a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
13262a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
13272a0f7f57SLi Zefan 
1328f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
132909cbfeafSKirill A. Shutemov 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
13304cb5300bSChris Mason 		/*
13314cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
13324cb5300bSChris Mason 		 * the FS
13334cb5300bSChris Mason 		 */
13344cb5300bSChris Mason 		if (!(inode->i_sb->s_flags & MS_ACTIVE))
13354cb5300bSChris Mason 			break;
13364cb5300bSChris Mason 
13370b246afaSJeff Mahoney 		if (btrfs_defrag_cancelled(fs_info)) {
13380b246afaSJeff Mahoney 			btrfs_debug(fs_info, "defrag_file cancelled");
1339210549ebSDavid Sterba 			ret = -EAGAIN;
1340210549ebSDavid Sterba 			break;
1341210549ebSDavid Sterba 		}
1342210549ebSDavid Sterba 
134309cbfeafSKirill A. Shutemov 		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
13446c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
13451e2ef46dSDavid Sterba 					 &defrag_end, do_compress)){
1346940100a4SChris Mason 			unsigned long next;
1347940100a4SChris Mason 			/*
1348940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1349940100a4SChris Mason 			 * bump our counter by the suggested amount
1350940100a4SChris Mason 			 */
135109cbfeafSKirill A. Shutemov 			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1352940100a4SChris Mason 			i = max(i + 1, next);
1353940100a4SChris Mason 			continue;
1354940100a4SChris Mason 		}
1355008873eaSLi Zefan 
1356008873eaSLi Zefan 		if (!newer_than) {
135709cbfeafSKirill A. Shutemov 			cluster = (PAGE_ALIGN(defrag_end) >>
135809cbfeafSKirill A. Shutemov 				   PAGE_SHIFT) - i;
1359008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1360008873eaSLi Zefan 		} else {
1361008873eaSLi Zefan 			cluster = max_cluster;
1362008873eaSLi Zefan 		}
1363008873eaSLi Zefan 
1364008873eaSLi Zefan 		if (i + cluster > ra_index) {
1365008873eaSLi Zefan 			ra_index = max(i, ra_index);
13660a52d108SDavid Sterba 			if (ra)
1367d3c0bab5SDavid Sterba 				page_cache_sync_readahead(inode->i_mapping, ra,
1368d3c0bab5SDavid Sterba 						file, ra_index, cluster);
1369e4826a5bSchandan 			ra_index += cluster;
1370008873eaSLi Zefan 		}
13714cb5300bSChris Mason 
13725955102cSAl Viro 		inode_lock(inode);
13731e2ef46dSDavid Sterba 		if (do_compress)
1374eec63c65SDavid Sterba 			BTRFS_I(inode)->defrag_compress = compress_type;
1375008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1376ecb8bea8SLiu Bo 		if (ret < 0) {
13775955102cSAl Viro 			inode_unlock(inode);
13784cb5300bSChris Mason 			goto out_ra;
1379ecb8bea8SLiu Bo 		}
13804cb5300bSChris Mason 
13814cb5300bSChris Mason 		defrag_count += ret;
1382d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
13835955102cSAl Viro 		inode_unlock(inode);
13844cb5300bSChris Mason 
13854cb5300bSChris Mason 		if (newer_than) {
13864cb5300bSChris Mason 			if (newer_off == (u64)-1)
13874cb5300bSChris Mason 				break;
13884cb5300bSChris Mason 
1389e1f041e1SLiu Bo 			if (ret > 0)
1390e1f041e1SLiu Bo 				i += ret;
1391e1f041e1SLiu Bo 
13924cb5300bSChris Mason 			newer_off = max(newer_off + 1,
139309cbfeafSKirill A. Shutemov 					(u64)i << PAGE_SHIFT);
13944cb5300bSChris Mason 
1395ee22184bSByongho Lee 			ret = find_new_extents(root, inode, newer_than,
1396ee22184bSByongho Lee 					       &newer_off, SZ_64K);
13974cb5300bSChris Mason 			if (!ret) {
13984cb5300bSChris Mason 				range->start = newer_off;
139909cbfeafSKirill A. Shutemov 				i = (newer_off & new_align) >> PAGE_SHIFT;
14004cb5300bSChris Mason 			} else {
14014cb5300bSChris Mason 				break;
1402940100a4SChris Mason 			}
14034cb5300bSChris Mason 		} else {
1404008873eaSLi Zefan 			if (ret > 0) {
1405cbcc8326SLi Zefan 				i += ret;
140609cbfeafSKirill A. Shutemov 				last_len += ret << PAGE_SHIFT;
1407008873eaSLi Zefan 			} else {
1408940100a4SChris Mason 				i++;
1409008873eaSLi Zefan 				last_len = 0;
1410008873eaSLi Zefan 			}
1411f46b5a66SChristoph Hellwig 		}
14124cb5300bSChris Mason 	}
1413f46b5a66SChristoph Hellwig 
1414dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
14151e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1416dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1417dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1418dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1419dec8ef90SFilipe Manana 	}
14201e701a32SChris Mason 
14211e2ef46dSDavid Sterba 	if (do_compress) {
14221e701a32SChris Mason 		/* the filemap_flush will queue IO into the worker threads, but
14231e701a32SChris Mason 		 * we have to make sure the IO is actually started and that
14241e701a32SChris Mason 		 * ordered extents get created before we return
14251e701a32SChris Mason 		 */
14260b246afaSJeff Mahoney 		atomic_inc(&fs_info->async_submit_draining);
14270b246afaSJeff Mahoney 		while (atomic_read(&fs_info->nr_async_submits) ||
14280b246afaSJeff Mahoney 		       atomic_read(&fs_info->async_delalloc_pages)) {
14290b246afaSJeff Mahoney 			wait_event(fs_info->async_submit_wait,
14300b246afaSJeff Mahoney 				   (atomic_read(&fs_info->nr_async_submits) == 0 &&
14310b246afaSJeff Mahoney 				    atomic_read(&fs_info->async_delalloc_pages) == 0));
14321e701a32SChris Mason 		}
14330b246afaSJeff Mahoney 		atomic_dec(&fs_info->async_submit_draining);
14341e701a32SChris Mason 	}
14351e701a32SChris Mason 
14361a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
14370b246afaSJeff Mahoney 		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
14381a419d85SLi Zefan 	}
14391a419d85SLi Zefan 
144060ccf82fSDiego Calleja 	ret = defrag_count;
1441940100a4SChris Mason 
14424cb5300bSChris Mason out_ra:
14431e2ef46dSDavid Sterba 	if (do_compress) {
14445955102cSAl Viro 		inode_lock(inode);
1445eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
14465955102cSAl Viro 		inode_unlock(inode);
1447633085c7SFilipe David Borba Manana 	}
14484cb5300bSChris Mason 	if (!file)
14494cb5300bSChris Mason 		kfree(ra);
14504cb5300bSChris Mason 	kfree(pages);
1451940100a4SChris Mason 	return ret;
1452f46b5a66SChristoph Hellwig }
1453f46b5a66SChristoph Hellwig 
1454198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
145576dda93cSYan, Zheng 					void __user *arg)
1456f46b5a66SChristoph Hellwig {
14570b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
14580b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1459f46b5a66SChristoph Hellwig 	u64 new_size;
1460f46b5a66SChristoph Hellwig 	u64 old_size;
1461f46b5a66SChristoph Hellwig 	u64 devid = 1;
14620b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1463f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1464f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1465f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1466f46b5a66SChristoph Hellwig 	char *sizestr;
14679a40f122SGui Hecheng 	char *retptr;
1468f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1469f46b5a66SChristoph Hellwig 	int ret = 0;
1470f46b5a66SChristoph Hellwig 	int mod = 0;
1471f46b5a66SChristoph Hellwig 
1472e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1473e441d54dSChris Mason 		return -EPERM;
1474e441d54dSChris Mason 
1475198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1476198605a8SMiao Xie 	if (ret)
1477198605a8SMiao Xie 		return ret;
1478198605a8SMiao Xie 
1479171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
148097547676SMiao Xie 		mnt_drop_write_file(file);
1481e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1482c9e9f97bSIlya Dryomov 	}
1483c9e9f97bSIlya Dryomov 
14840b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
1485dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1486c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1487c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1488c9e9f97bSIlya Dryomov 		goto out;
1489c9e9f97bSIlya Dryomov 	}
14905516e595SMark Fasheh 
14915516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1492f46b5a66SChristoph Hellwig 
1493f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1494f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1495f46b5a66SChristoph Hellwig 	if (devstr) {
1496f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1497f46b5a66SChristoph Hellwig 		*devstr = '\0';
1498f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
149958dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
150058dfae63SZhangZhen 		if (ret)
150158dfae63SZhangZhen 			goto out_free;
1502dfd79829SMiao Xie 		if (!devid) {
1503dfd79829SMiao Xie 			ret = -EINVAL;
1504dfd79829SMiao Xie 			goto out_free;
1505dfd79829SMiao Xie 		}
15060b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1507f46b5a66SChristoph Hellwig 	}
1508dba60f3fSMiao Xie 
15090b246afaSJeff Mahoney 	device = btrfs_find_device(fs_info, devid, NULL, NULL);
1510f46b5a66SChristoph Hellwig 	if (!device) {
15110b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1512c1c9ff7cSGeert Uytterhoeven 			   devid);
1513dfd79829SMiao Xie 		ret = -ENODEV;
1514c9e9f97bSIlya Dryomov 		goto out_free;
1515f46b5a66SChristoph Hellwig 	}
1516dba60f3fSMiao Xie 
1517dba60f3fSMiao Xie 	if (!device->writeable) {
15180b246afaSJeff Mahoney 		btrfs_info(fs_info,
1519efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1520c1c9ff7cSGeert Uytterhoeven 		       devid);
1521dfd79829SMiao Xie 		ret = -EPERM;
15224e42ae1bSLiu Bo 		goto out_free;
15234e42ae1bSLiu Bo 	}
15244e42ae1bSLiu Bo 
1525f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1526f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1527f46b5a66SChristoph Hellwig 	else {
1528f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1529f46b5a66SChristoph Hellwig 			mod = -1;
1530f46b5a66SChristoph Hellwig 			sizestr++;
1531f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1532f46b5a66SChristoph Hellwig 			mod = 1;
1533f46b5a66SChristoph Hellwig 			sizestr++;
1534f46b5a66SChristoph Hellwig 		}
15359a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
15369a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1537f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1538c9e9f97bSIlya Dryomov 			goto out_free;
1539f46b5a66SChristoph Hellwig 		}
1540f46b5a66SChristoph Hellwig 	}
1541f46b5a66SChristoph Hellwig 
154263a212abSStefan Behrens 	if (device->is_tgtdev_for_dev_replace) {
1543dfd79829SMiao Xie 		ret = -EPERM;
154463a212abSStefan Behrens 		goto out_free;
154563a212abSStefan Behrens 	}
154663a212abSStefan Behrens 
15477cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1548f46b5a66SChristoph Hellwig 
1549f46b5a66SChristoph Hellwig 	if (mod < 0) {
1550f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1551f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1552c9e9f97bSIlya Dryomov 			goto out_free;
1553f46b5a66SChristoph Hellwig 		}
1554f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1555f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1556eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1557902c68a4SGui Hecheng 			ret = -ERANGE;
1558eb8052e0SWenliang Fan 			goto out_free;
1559eb8052e0SWenliang Fan 		}
1560f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1561f46b5a66SChristoph Hellwig 	}
1562f46b5a66SChristoph Hellwig 
1563ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1564f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1565c9e9f97bSIlya Dryomov 		goto out_free;
1566f46b5a66SChristoph Hellwig 	}
1567f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1568f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1569c9e9f97bSIlya Dryomov 		goto out_free;
1570f46b5a66SChristoph Hellwig 	}
1571f46b5a66SChristoph Hellwig 
157247f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1573f46b5a66SChristoph Hellwig 
15740b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1575c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1576f46b5a66SChristoph Hellwig 
1577f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1578a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
157998d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
158098d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1581c9e9f97bSIlya Dryomov 			goto out_free;
158298d5dc13STsutomu Itoh 		}
1583f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
15843a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1585ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1586f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
15870253f40eSjeff.liu 	} /* equal, nothing need to do */
1588f46b5a66SChristoph Hellwig 
1589c9e9f97bSIlya Dryomov out_free:
1590f46b5a66SChristoph Hellwig 	kfree(vol_args);
1591c9e9f97bSIlya Dryomov out:
15920b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
1593171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
159418f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1595f46b5a66SChristoph Hellwig 	return ret;
1596f46b5a66SChristoph Hellwig }
1597f46b5a66SChristoph Hellwig 
159872fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
159952f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
16006f72c7e2SArne Jansen 				u64 *transid, bool readonly,
16018696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1602f46b5a66SChristoph Hellwig {
1603f46b5a66SChristoph Hellwig 	int namelen;
16043de4586cSChris Mason 	int ret = 0;
1605f46b5a66SChristoph Hellwig 
1606325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1607325c50e3SJeff Mahoney 		return -ENOTDIR;
1608325c50e3SJeff Mahoney 
1609a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1610a874a63eSLiu Bo 	if (ret)
1611a874a63eSLiu Bo 		goto out;
1612a874a63eSLiu Bo 
161372fd032eSSage Weil 	namelen = strlen(name);
161472fd032eSSage Weil 	if (strchr(name, '/')) {
1615f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1616a874a63eSLiu Bo 		goto out_drop_write;
1617f46b5a66SChristoph Hellwig 	}
1618f46b5a66SChristoph Hellwig 
161916780cabSChris Mason 	if (name[0] == '.' &&
162016780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
162116780cabSChris Mason 		ret = -EEXIST;
1622a874a63eSLiu Bo 		goto out_drop_write;
162316780cabSChris Mason 	}
162416780cabSChris Mason 
16253de4586cSChris Mason 	if (subvol) {
162672fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
16276f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1628cb8e7090SChristoph Hellwig 	} else {
16292903ff01SAl Viro 		struct fd src = fdget(fd);
16303de4586cSChris Mason 		struct inode *src_inode;
16312903ff01SAl Viro 		if (!src.file) {
16323de4586cSChris Mason 			ret = -EINVAL;
1633a874a63eSLiu Bo 			goto out_drop_write;
16343de4586cSChris Mason 		}
16353de4586cSChris Mason 
1636496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1637496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1638c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1639efe120a0SFrank Holton 				   "Snapshot src from another FS");
164023ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1641d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1642d0242061SDavid Sterba 			/*
1643d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1644d0242061SDavid Sterba 			 * are limited to own subvolumes only
1645d0242061SDavid Sterba 			 */
1646d0242061SDavid Sterba 			ret = -EPERM;
1647ecd18815SAl Viro 		} else {
164872fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
164972fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
16506f72c7e2SArne Jansen 					     transid, readonly, inherit);
1651ecd18815SAl Viro 		}
16522903ff01SAl Viro 		fdput(src);
1653cb8e7090SChristoph Hellwig 	}
1654a874a63eSLiu Bo out_drop_write:
1655a874a63eSLiu Bo 	mnt_drop_write_file(file);
1656f46b5a66SChristoph Hellwig out:
165772fd032eSSage Weil 	return ret;
165872fd032eSSage Weil }
165972fd032eSSage Weil 
166072fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1661fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
166272fd032eSSage Weil {
1663fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
166472fd032eSSage Weil 	int ret;
166572fd032eSSage Weil 
1666325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1667325c50e3SJeff Mahoney 		return -ENOTDIR;
1668325c50e3SJeff Mahoney 
1669fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1670fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1671fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1672fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1673fa0d2b9bSLi Zefan 
1674fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1675b83cc969SLi Zefan 					      vol_args->fd, subvol,
16766f72c7e2SArne Jansen 					      NULL, false, NULL);
1677fa0d2b9bSLi Zefan 
1678fa0d2b9bSLi Zefan 	kfree(vol_args);
1679fa0d2b9bSLi Zefan 	return ret;
1680fa0d2b9bSLi Zefan }
1681fa0d2b9bSLi Zefan 
1682fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1683fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1684fa0d2b9bSLi Zefan {
1685fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1686fa0d2b9bSLi Zefan 	int ret;
1687fdfb1e4fSLi Zefan 	u64 transid = 0;
1688fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1689b83cc969SLi Zefan 	bool readonly = false;
16906f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
169172fd032eSSage Weil 
1692325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1693325c50e3SJeff Mahoney 		return -ENOTDIR;
1694325c50e3SJeff Mahoney 
1695fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1696fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1697fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1698fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1699fdfb1e4fSLi Zefan 
1700b83cc969SLi Zefan 	if (vol_args->flags &
17016f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
17026f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1703b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1704c47ca32dSDan Carpenter 		goto free_args;
1705fdfb1e4fSLi Zefan 	}
1706fdfb1e4fSLi Zefan 
1707fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1708fdfb1e4fSLi Zefan 		ptr = &transid;
1709b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1710b83cc969SLi Zefan 		readonly = true;
17116f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
171209cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
17136f72c7e2SArne Jansen 			ret = -EINVAL;
1714c47ca32dSDan Carpenter 			goto free_args;
17156f72c7e2SArne Jansen 		}
17166f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
17176f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
17186f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1719c47ca32dSDan Carpenter 			goto free_args;
17206f72c7e2SArne Jansen 		}
17216f72c7e2SArne Jansen 	}
172275eaa0e2SSage Weil 
1723fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
17246f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
17258696c533SMiao Xie 					      readonly, inherit);
1726c47ca32dSDan Carpenter 	if (ret)
1727c47ca32dSDan Carpenter 		goto free_inherit;
172875eaa0e2SSage Weil 
1729c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1730fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1731c47ca32dSDan Carpenter 					transid),
1732c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
173375eaa0e2SSage Weil 		ret = -EFAULT;
1734c47ca32dSDan Carpenter 
1735c47ca32dSDan Carpenter free_inherit:
17366f72c7e2SArne Jansen 	kfree(inherit);
1737c47ca32dSDan Carpenter free_args:
1738c47ca32dSDan Carpenter 	kfree(vol_args);
1739f46b5a66SChristoph Hellwig 	return ret;
1740f46b5a66SChristoph Hellwig }
1741f46b5a66SChristoph Hellwig 
17420caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
17430caa102dSLi Zefan 						void __user *arg)
17440caa102dSLi Zefan {
1745496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17470caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17480caa102dSLi Zefan 	int ret = 0;
17490caa102dSLi Zefan 	u64 flags = 0;
17500caa102dSLi Zefan 
17514a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
17520caa102dSLi Zefan 		return -EINVAL;
17530caa102dSLi Zefan 
17540b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
17550caa102dSLi Zefan 	if (btrfs_root_readonly(root))
17560caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
17570b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
17580caa102dSLi Zefan 
17590caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
17600caa102dSLi Zefan 		ret = -EFAULT;
17610caa102dSLi Zefan 
17620caa102dSLi Zefan 	return ret;
17630caa102dSLi Zefan }
17640caa102dSLi Zefan 
17650caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
17660caa102dSLi Zefan 					      void __user *arg)
17670caa102dSLi Zefan {
1768496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
17690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
17700caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
17710caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
17720caa102dSLi Zefan 	u64 root_flags;
17730caa102dSLi Zefan 	u64 flags;
17740caa102dSLi Zefan 	int ret = 0;
17750caa102dSLi Zefan 
1776bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1777bd60ea0fSDavid Sterba 		return -EPERM;
1778bd60ea0fSDavid Sterba 
1779b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1780b9ca0664SLiu Bo 	if (ret)
1781b9ca0664SLiu Bo 		goto out;
17820caa102dSLi Zefan 
17834a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1784b9ca0664SLiu Bo 		ret = -EINVAL;
1785b9ca0664SLiu Bo 		goto out_drop_write;
1786b9ca0664SLiu Bo 	}
17870caa102dSLi Zefan 
1788b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1789b9ca0664SLiu Bo 		ret = -EFAULT;
1790b9ca0664SLiu Bo 		goto out_drop_write;
1791b9ca0664SLiu Bo 	}
17920caa102dSLi Zefan 
1793b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1794b9ca0664SLiu Bo 		ret = -EINVAL;
1795b9ca0664SLiu Bo 		goto out_drop_write;
1796b9ca0664SLiu Bo 	}
17970caa102dSLi Zefan 
1798b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1799b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1800b9ca0664SLiu Bo 		goto out_drop_write;
1801b9ca0664SLiu Bo 	}
18020caa102dSLi Zefan 
18030b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
18040caa102dSLi Zefan 
18050caa102dSLi Zefan 	/* nothing to do */
18060caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1807b9ca0664SLiu Bo 		goto out_drop_sem;
18080caa102dSLi Zefan 
18090caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
18102c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
18110caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
18120caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
18132c686537SDavid Sterba 	} else {
18142c686537SDavid Sterba 		/*
18152c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
18162c686537SDavid Sterba 		 * send
18172c686537SDavid Sterba 		 */
18182c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
18192c686537SDavid Sterba 		if (root->send_in_progress == 0) {
18200caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
18210caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
18222c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18232c686537SDavid Sterba 		} else {
18242c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
18250b246afaSJeff Mahoney 			btrfs_warn(fs_info,
18262c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
18272c686537SDavid Sterba 				   root->root_key.objectid);
18282c686537SDavid Sterba 			ret = -EPERM;
18292c686537SDavid Sterba 			goto out_drop_sem;
18302c686537SDavid Sterba 		}
18312c686537SDavid Sterba 	}
18320caa102dSLi Zefan 
18330caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
18340caa102dSLi Zefan 	if (IS_ERR(trans)) {
18350caa102dSLi Zefan 		ret = PTR_ERR(trans);
18360caa102dSLi Zefan 		goto out_reset;
18370caa102dSLi Zefan 	}
18380caa102dSLi Zefan 
18390b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
18400caa102dSLi Zefan 				&root->root_key, &root->root_item);
18410caa102dSLi Zefan 
18423a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
18430caa102dSLi Zefan out_reset:
18440caa102dSLi Zefan 	if (ret)
18450caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1846b9ca0664SLiu Bo out_drop_sem:
18470b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
1848b9ca0664SLiu Bo out_drop_write:
1849b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1850b9ca0664SLiu Bo out:
18510caa102dSLi Zefan 	return ret;
18520caa102dSLi Zefan }
18530caa102dSLi Zefan 
185476dda93cSYan, Zheng /*
185576dda93cSYan, Zheng  * helper to check if the subvolume references other subvolumes
185676dda93cSYan, Zheng  */
185776dda93cSYan, Zheng static noinline int may_destroy_subvol(struct btrfs_root *root)
185876dda93cSYan, Zheng {
18590b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
186076dda93cSYan, Zheng 	struct btrfs_path *path;
1861175a2b87SJosef Bacik 	struct btrfs_dir_item *di;
186276dda93cSYan, Zheng 	struct btrfs_key key;
1863175a2b87SJosef Bacik 	u64 dir_id;
186476dda93cSYan, Zheng 	int ret;
186576dda93cSYan, Zheng 
186676dda93cSYan, Zheng 	path = btrfs_alloc_path();
186776dda93cSYan, Zheng 	if (!path)
186876dda93cSYan, Zheng 		return -ENOMEM;
186976dda93cSYan, Zheng 
1870175a2b87SJosef Bacik 	/* Make sure this root isn't set as the default subvol */
18710b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
18720b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
1873175a2b87SJosef Bacik 				   dir_id, "default", 7, 0);
1874175a2b87SJosef Bacik 	if (di && !IS_ERR(di)) {
1875175a2b87SJosef Bacik 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1876175a2b87SJosef Bacik 		if (key.objectid == root->root_key.objectid) {
187772de6b53SGuangyu Sun 			ret = -EPERM;
18780b246afaSJeff Mahoney 			btrfs_err(fs_info,
18795d163e0eSJeff Mahoney 				  "deleting default subvolume %llu is not allowed",
18805d163e0eSJeff Mahoney 				  key.objectid);
1881175a2b87SJosef Bacik 			goto out;
1882175a2b87SJosef Bacik 		}
1883175a2b87SJosef Bacik 		btrfs_release_path(path);
1884175a2b87SJosef Bacik 	}
1885175a2b87SJosef Bacik 
188676dda93cSYan, Zheng 	key.objectid = root->root_key.objectid;
188776dda93cSYan, Zheng 	key.type = BTRFS_ROOT_REF_KEY;
188876dda93cSYan, Zheng 	key.offset = (u64)-1;
188976dda93cSYan, Zheng 
18900b246afaSJeff Mahoney 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
189176dda93cSYan, Zheng 	if (ret < 0)
189276dda93cSYan, Zheng 		goto out;
189376dda93cSYan, Zheng 	BUG_ON(ret == 0);
189476dda93cSYan, Zheng 
189576dda93cSYan, Zheng 	ret = 0;
189676dda93cSYan, Zheng 	if (path->slots[0] > 0) {
189776dda93cSYan, Zheng 		path->slots[0]--;
189876dda93cSYan, Zheng 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
189976dda93cSYan, Zheng 		if (key.objectid == root->root_key.objectid &&
190076dda93cSYan, Zheng 		    key.type == BTRFS_ROOT_REF_KEY)
190176dda93cSYan, Zheng 			ret = -ENOTEMPTY;
190276dda93cSYan, Zheng 	}
190376dda93cSYan, Zheng out:
190476dda93cSYan, Zheng 	btrfs_free_path(path);
190576dda93cSYan, Zheng 	return ret;
190676dda93cSYan, Zheng }
190776dda93cSYan, Zheng 
1908ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1909ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1910ac8e9819SChris Mason {
1911abc6e134SChris Mason 	struct btrfs_key test;
1912abc6e134SChris Mason 	int ret;
1913abc6e134SChris Mason 
1914abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1915abc6e134SChris Mason 	test.type = sk->min_type;
1916abc6e134SChris Mason 	test.offset = sk->min_offset;
1917abc6e134SChris Mason 
1918abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1919abc6e134SChris Mason 	if (ret < 0)
1920ac8e9819SChris Mason 		return 0;
1921abc6e134SChris Mason 
1922abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1923abc6e134SChris Mason 	test.type = sk->max_type;
1924abc6e134SChris Mason 	test.offset = sk->max_offset;
1925abc6e134SChris Mason 
1926abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1927abc6e134SChris Mason 	if (ret > 0)
1928ac8e9819SChris Mason 		return 0;
1929ac8e9819SChris Mason 	return 1;
1930ac8e9819SChris Mason }
1931ac8e9819SChris Mason 
1932df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
1933ac8e9819SChris Mason 			       struct btrfs_key *key,
1934ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
19359b6e817dSGerhard Heift 			       size_t *buf_size,
1936ba346b35SGerhard Heift 			       char __user *ubuf,
1937ac8e9819SChris Mason 			       unsigned long *sk_offset,
1938ac8e9819SChris Mason 			       int *num_found)
1939ac8e9819SChris Mason {
1940ac8e9819SChris Mason 	u64 found_transid;
1941ac8e9819SChris Mason 	struct extent_buffer *leaf;
1942ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
1943dd81d459SNaohiro Aota 	struct btrfs_key test;
1944ac8e9819SChris Mason 	unsigned long item_off;
1945ac8e9819SChris Mason 	unsigned long item_len;
1946ac8e9819SChris Mason 	int nritems;
1947ac8e9819SChris Mason 	int i;
1948ac8e9819SChris Mason 	int slot;
1949ac8e9819SChris Mason 	int ret = 0;
1950ac8e9819SChris Mason 
1951ac8e9819SChris Mason 	leaf = path->nodes[0];
1952ac8e9819SChris Mason 	slot = path->slots[0];
1953ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
1954ac8e9819SChris Mason 
1955ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
1956ac8e9819SChris Mason 		i = nritems;
1957ac8e9819SChris Mason 		goto advance_key;
1958ac8e9819SChris Mason 	}
1959ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
1960ac8e9819SChris Mason 
1961ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
1962ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
1963ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
1964ac8e9819SChris Mason 
196503b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
196603b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
196703b71c6cSGabriel de Perthuis 			continue;
196803b71c6cSGabriel de Perthuis 
19699b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
19708f5f6178SGerhard Heift 			if (*num_found) {
1971ac8e9819SChris Mason 				ret = 1;
19728f5f6178SGerhard Heift 				goto out;
19738f5f6178SGerhard Heift 			}
19748f5f6178SGerhard Heift 
19758f5f6178SGerhard Heift 			/*
19768f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
19778f5f6178SGerhard Heift 			 * handle -EOVERFLOW
19788f5f6178SGerhard Heift 			 */
19798f5f6178SGerhard Heift 
19809b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
1981ac8e9819SChris Mason 			item_len = 0;
19828f5f6178SGerhard Heift 			ret = -EOVERFLOW;
19838f5f6178SGerhard Heift 		}
1984ac8e9819SChris Mason 
19859b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
1986ac8e9819SChris Mason 			ret = 1;
198725c9bc2eSGerhard Heift 			goto out;
1988ac8e9819SChris Mason 		}
1989ac8e9819SChris Mason 
1990ac8e9819SChris Mason 		sh.objectid = key->objectid;
1991ac8e9819SChris Mason 		sh.offset = key->offset;
1992ac8e9819SChris Mason 		sh.type = key->type;
1993ac8e9819SChris Mason 		sh.len = item_len;
1994ac8e9819SChris Mason 		sh.transid = found_transid;
1995ac8e9819SChris Mason 
1996ac8e9819SChris Mason 		/* copy search result header */
1997ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
1998ba346b35SGerhard Heift 			ret = -EFAULT;
1999ba346b35SGerhard Heift 			goto out;
2000ba346b35SGerhard Heift 		}
2001ba346b35SGerhard Heift 
2002ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2003ac8e9819SChris Mason 
2004ac8e9819SChris Mason 		if (item_len) {
2005ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2006ac8e9819SChris Mason 			/* copy the item */
2007ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
2008ba346b35SGerhard Heift 						       item_off, item_len)) {
2009ba346b35SGerhard Heift 				ret = -EFAULT;
2010ba346b35SGerhard Heift 				goto out;
2011ba346b35SGerhard Heift 			}
2012ba346b35SGerhard Heift 
2013ac8e9819SChris Mason 			*sk_offset += item_len;
2014ac8e9819SChris Mason 		}
2015e2156867SHugo Mills 		(*num_found)++;
2016ac8e9819SChris Mason 
20178f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
20188f5f6178SGerhard Heift 			goto out;
20198f5f6178SGerhard Heift 
202025c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
202125c9bc2eSGerhard Heift 			ret = 1;
202225c9bc2eSGerhard Heift 			goto out;
202325c9bc2eSGerhard Heift 		}
2024ac8e9819SChris Mason 	}
2025ac8e9819SChris Mason advance_key:
2026ac8e9819SChris Mason 	ret = 0;
2027dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2028dd81d459SNaohiro Aota 	test.type = sk->max_type;
2029dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2030dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2031dd81d459SNaohiro Aota 		ret = 1;
2032dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2033abc6e134SChris Mason 		key->offset++;
2034dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2035abc6e134SChris Mason 		key->offset = 0;
2036abc6e134SChris Mason 		key->type++;
2037dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2038abc6e134SChris Mason 		key->offset = 0;
2039abc6e134SChris Mason 		key->type = 0;
2040abc6e134SChris Mason 		key->objectid++;
2041abc6e134SChris Mason 	} else
2042abc6e134SChris Mason 		ret = 1;
204325c9bc2eSGerhard Heift out:
2044ba346b35SGerhard Heift 	/*
2045ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2046ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2047ba346b35SGerhard Heift 	 *     * all items were found
2048ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2049ba346b35SGerhard Heift 	 *     leaf
2050ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2051ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2052ba346b35SGerhard Heift 	 */
2053ac8e9819SChris Mason 	return ret;
2054ac8e9819SChris Mason }
2055ac8e9819SChris Mason 
2056ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
205712544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
20589b6e817dSGerhard Heift 				 size_t *buf_size,
2059ba346b35SGerhard Heift 				 char __user *ubuf)
2060ac8e9819SChris Mason {
20610b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2062ac8e9819SChris Mason 	struct btrfs_root *root;
2063ac8e9819SChris Mason 	struct btrfs_key key;
2064ac8e9819SChris Mason 	struct btrfs_path *path;
2065ac8e9819SChris Mason 	int ret;
2066ac8e9819SChris Mason 	int num_found = 0;
2067ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2068ac8e9819SChris Mason 
20699b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
20709b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
207112544442SGerhard Heift 		return -EOVERFLOW;
20729b6e817dSGerhard Heift 	}
207312544442SGerhard Heift 
2074ac8e9819SChris Mason 	path = btrfs_alloc_path();
2075ac8e9819SChris Mason 	if (!path)
2076ac8e9819SChris Mason 		return -ENOMEM;
2077ac8e9819SChris Mason 
2078ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2079ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2080ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2081ac8e9819SChris Mason 	} else {
2082ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2083ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2084ac8e9819SChris Mason 		key.offset = (u64)-1;
2085ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2086ac8e9819SChris Mason 		if (IS_ERR(root)) {
2087ac8e9819SChris Mason 			btrfs_free_path(path);
2088ac8e9819SChris Mason 			return -ENOENT;
2089ac8e9819SChris Mason 		}
2090ac8e9819SChris Mason 	}
2091ac8e9819SChris Mason 
2092ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2093ac8e9819SChris Mason 	key.type = sk->min_type;
2094ac8e9819SChris Mason 	key.offset = sk->min_offset;
2095ac8e9819SChris Mason 
2096ac8e9819SChris Mason 	while (1) {
20976174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2098ac8e9819SChris Mason 		if (ret != 0) {
2099ac8e9819SChris Mason 			if (ret > 0)
2100ac8e9819SChris Mason 				ret = 0;
2101ac8e9819SChris Mason 			goto err;
2102ac8e9819SChris Mason 		}
2103df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2104ac8e9819SChris Mason 				 &sk_offset, &num_found);
2105b3b4aa74SDavid Sterba 		btrfs_release_path(path);
210625c9bc2eSGerhard Heift 		if (ret)
2107ac8e9819SChris Mason 			break;
2108ac8e9819SChris Mason 
2109ac8e9819SChris Mason 	}
21108f5f6178SGerhard Heift 	if (ret > 0)
2111ac8e9819SChris Mason 		ret = 0;
2112ac8e9819SChris Mason err:
2113ac8e9819SChris Mason 	sk->nr_items = num_found;
2114ac8e9819SChris Mason 	btrfs_free_path(path);
2115ac8e9819SChris Mason 	return ret;
2116ac8e9819SChris Mason }
2117ac8e9819SChris Mason 
2118ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2119ac8e9819SChris Mason 					   void __user *argp)
2120ac8e9819SChris Mason {
2121ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2122ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2123ac8e9819SChris Mason 	struct inode *inode;
2124ac8e9819SChris Mason 	int ret;
21259b6e817dSGerhard Heift 	size_t buf_size;
2126ac8e9819SChris Mason 
2127ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2128ac8e9819SChris Mason 		return -EPERM;
2129ac8e9819SChris Mason 
2130ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2131ac8e9819SChris Mason 
2132ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2133ba346b35SGerhard Heift 		return -EFAULT;
2134ba346b35SGerhard Heift 
2135ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2136ac8e9819SChris Mason 
2137496ad9aaSAl Viro 	inode = file_inode(file);
2138ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
21398f5f6178SGerhard Heift 
21408f5f6178SGerhard Heift 	/*
21418f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
21428f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
21438f5f6178SGerhard Heift 	 */
21448f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
21458f5f6178SGerhard Heift 		ret = 0;
21468f5f6178SGerhard Heift 
2147ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2148ac8e9819SChris Mason 		ret = -EFAULT;
2149ac8e9819SChris Mason 	return ret;
2150ac8e9819SChris Mason }
2151ac8e9819SChris Mason 
2152cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2153cc68a8a5SGerhard Heift 					       void __user *argp)
2154cc68a8a5SGerhard Heift {
2155cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2156cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2157cc68a8a5SGerhard Heift 	struct inode *inode;
2158cc68a8a5SGerhard Heift 	int ret;
2159cc68a8a5SGerhard Heift 	size_t buf_size;
2160ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2161cc68a8a5SGerhard Heift 
2162cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2163cc68a8a5SGerhard Heift 		return -EPERM;
2164cc68a8a5SGerhard Heift 
2165cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2166cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2167cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2168cc68a8a5SGerhard Heift 		return -EFAULT;
2169cc68a8a5SGerhard Heift 
2170cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2171cc68a8a5SGerhard Heift 
2172cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2173cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2174cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2175cc68a8a5SGerhard Heift 
2176cc68a8a5SGerhard Heift 	inode = file_inode(file);
2177cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2178cc68a8a5SGerhard Heift 			   (char *)(&uarg->buf[0]));
2179cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2180cc68a8a5SGerhard Heift 		ret = -EFAULT;
2181cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2182cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2183cc68a8a5SGerhard Heift 		ret = -EFAULT;
2184cc68a8a5SGerhard Heift 
218576dda93cSYan, Zheng 	return ret;
218676dda93cSYan, Zheng }
218776dda93cSYan, Zheng 
218898d377a0STARUISI Hiroaki /*
2189ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2190ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
219198d377a0STARUISI Hiroaki  */
219298d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
219398d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
219498d377a0STARUISI Hiroaki {
219598d377a0STARUISI Hiroaki 	struct btrfs_root *root;
219698d377a0STARUISI Hiroaki 	struct btrfs_key key;
2197ac8e9819SChris Mason 	char *ptr;
219898d377a0STARUISI Hiroaki 	int ret = -1;
219998d377a0STARUISI Hiroaki 	int slot;
220098d377a0STARUISI Hiroaki 	int len;
220198d377a0STARUISI Hiroaki 	int total_len = 0;
220298d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
220398d377a0STARUISI Hiroaki 	struct extent_buffer *l;
220498d377a0STARUISI Hiroaki 	struct btrfs_path *path;
220598d377a0STARUISI Hiroaki 
220698d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
220798d377a0STARUISI Hiroaki 		name[0]='\0';
220898d377a0STARUISI Hiroaki 		return 0;
220998d377a0STARUISI Hiroaki 	}
221098d377a0STARUISI Hiroaki 
221198d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
221298d377a0STARUISI Hiroaki 	if (!path)
221398d377a0STARUISI Hiroaki 		return -ENOMEM;
221498d377a0STARUISI Hiroaki 
2215ac8e9819SChris Mason 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
221698d377a0STARUISI Hiroaki 
221798d377a0STARUISI Hiroaki 	key.objectid = tree_id;
221898d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
221998d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
222098d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
222198d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2222f14d104dSDavid Sterba 		btrfs_err(info, "could not find root %llu", tree_id);
22238ad6fcabSChris Mason 		ret = -ENOENT;
22248ad6fcabSChris Mason 		goto out;
222598d377a0STARUISI Hiroaki 	}
222698d377a0STARUISI Hiroaki 
222798d377a0STARUISI Hiroaki 	key.objectid = dirid;
222898d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
22298ad6fcabSChris Mason 	key.offset = (u64)-1;
223098d377a0STARUISI Hiroaki 
223198d377a0STARUISI Hiroaki 	while (1) {
223298d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
223398d377a0STARUISI Hiroaki 		if (ret < 0)
223498d377a0STARUISI Hiroaki 			goto out;
223518674c6cSFilipe David Borba Manana 		else if (ret > 0) {
223618674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
223718674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
223818674c6cSFilipe David Borba Manana 			if (ret < 0)
223918674c6cSFilipe David Borba Manana 				goto out;
224018674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2241ac8e9819SChris Mason 				ret = -ENOENT;
224298d377a0STARUISI Hiroaki 				goto out;
2243ac8e9819SChris Mason 			}
224418674c6cSFilipe David Borba Manana 		}
224518674c6cSFilipe David Borba Manana 
224618674c6cSFilipe David Borba Manana 		l = path->nodes[0];
224718674c6cSFilipe David Borba Manana 		slot = path->slots[0];
224818674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
224998d377a0STARUISI Hiroaki 
225098d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
225198d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
225298d377a0STARUISI Hiroaki 		ptr -= len + 1;
225398d377a0STARUISI Hiroaki 		total_len += len + 1;
2254a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2255a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
225698d377a0STARUISI Hiroaki 			goto out;
2257a696cf35SFilipe David Borba Manana 		}
225898d377a0STARUISI Hiroaki 
225998d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
226098d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
226198d377a0STARUISI Hiroaki 
226298d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
226398d377a0STARUISI Hiroaki 			break;
226498d377a0STARUISI Hiroaki 
2265b3b4aa74SDavid Sterba 		btrfs_release_path(path);
226698d377a0STARUISI Hiroaki 		key.objectid = key.offset;
22678ad6fcabSChris Mason 		key.offset = (u64)-1;
226898d377a0STARUISI Hiroaki 		dirid = key.objectid;
226998d377a0STARUISI Hiroaki 	}
227077906a50SLi Zefan 	memmove(name, ptr, total_len);
227198d377a0STARUISI Hiroaki 	name[total_len] = '\0';
227298d377a0STARUISI Hiroaki 	ret = 0;
227398d377a0STARUISI Hiroaki out:
227498d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2275ac8e9819SChris Mason 	return ret;
2276ac8e9819SChris Mason }
2277ac8e9819SChris Mason 
2278ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2279ac8e9819SChris Mason 					   void __user *argp)
2280ac8e9819SChris Mason {
2281ac8e9819SChris Mason 	 struct btrfs_ioctl_ino_lookup_args *args;
2282ac8e9819SChris Mason 	 struct inode *inode;
228301b810b8SDavid Sterba 	int ret = 0;
2284ac8e9819SChris Mason 
22852354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
22862354d08fSJulia Lawall 	if (IS_ERR(args))
22872354d08fSJulia Lawall 		return PTR_ERR(args);
2288c2b96929SDan Carpenter 
2289496ad9aaSAl Viro 	inode = file_inode(file);
2290ac8e9819SChris Mason 
229101b810b8SDavid Sterba 	/*
229201b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
229301b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
229401b810b8SDavid Sterba 	 */
22951b53ac4dSChris Mason 	if (args->treeid == 0)
22961b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
22971b53ac4dSChris Mason 
229801b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
229901b810b8SDavid Sterba 		args->name[0] = 0;
230001b810b8SDavid Sterba 		goto out;
230101b810b8SDavid Sterba 	}
230201b810b8SDavid Sterba 
230301b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
230401b810b8SDavid Sterba 		ret = -EPERM;
230501b810b8SDavid Sterba 		goto out;
230601b810b8SDavid Sterba 	}
230701b810b8SDavid Sterba 
2308ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2309ac8e9819SChris Mason 					args->treeid, args->objectid,
2310ac8e9819SChris Mason 					args->name);
2311ac8e9819SChris Mason 
231201b810b8SDavid Sterba out:
2313ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2314ac8e9819SChris Mason 		ret = -EFAULT;
2315ac8e9819SChris Mason 
2316ac8e9819SChris Mason 	kfree(args);
231798d377a0STARUISI Hiroaki 	return ret;
231898d377a0STARUISI Hiroaki }
231998d377a0STARUISI Hiroaki 
232076dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
232176dda93cSYan, Zheng 					     void __user *arg)
232276dda93cSYan, Zheng {
232354563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
23240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
232576dda93cSYan, Zheng 	struct dentry *dentry;
23262b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
232776dda93cSYan, Zheng 	struct inode *inode;
232876dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
232976dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
233076dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
233176dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
2332c58aaad2SMiao Xie 	struct btrfs_block_rsv block_rsv;
2333521e0546SDavid Sterba 	u64 root_flags;
2334c58aaad2SMiao Xie 	u64 qgroup_reserved;
233576dda93cSYan, Zheng 	int namelen;
233676dda93cSYan, Zheng 	int ret;
233776dda93cSYan, Zheng 	int err = 0;
233876dda93cSYan, Zheng 
2339325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2340325c50e3SJeff Mahoney 		return -ENOTDIR;
2341325c50e3SJeff Mahoney 
234276dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
234376dda93cSYan, Zheng 	if (IS_ERR(vol_args))
234476dda93cSYan, Zheng 		return PTR_ERR(vol_args);
234576dda93cSYan, Zheng 
234676dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
234776dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
234876dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
234976dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
235076dda93cSYan, Zheng 		err = -EINVAL;
235176dda93cSYan, Zheng 		goto out;
235276dda93cSYan, Zheng 	}
235376dda93cSYan, Zheng 
2354a561be71SAl Viro 	err = mnt_want_write_file(file);
235576dda93cSYan, Zheng 	if (err)
235676dda93cSYan, Zheng 		goto out;
235776dda93cSYan, Zheng 
2358521e0546SDavid Sterba 
235900235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
236000235411SAl Viro 	if (err == -EINTR)
236100235411SAl Viro 		goto out_drop_write;
236276dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
236376dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
236476dda93cSYan, Zheng 		err = PTR_ERR(dentry);
236576dda93cSYan, Zheng 		goto out_unlock_dir;
236676dda93cSYan, Zheng 	}
236776dda93cSYan, Zheng 
23682b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
236976dda93cSYan, Zheng 		err = -ENOENT;
237076dda93cSYan, Zheng 		goto out_dput;
237176dda93cSYan, Zheng 	}
237276dda93cSYan, Zheng 
23732b0143b5SDavid Howells 	inode = d_inode(dentry);
23744260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
23754260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
23764260f7c7SSage Weil 		/*
23774260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
23784260f7c7SSage Weil 		 * option, when the user has write+exec access to the
23794260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
23804260f7c7SSage Weil 		 * allowed.
23814260f7c7SSage Weil 		 *
23824260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
23834260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
23844260f7c7SSage Weil 		 * otherwise be able to delete.
23854260f7c7SSage Weil 		 *
23864260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
23874260f7c7SSage Weil 		 * rmdir(2).
23884260f7c7SSage Weil 		 */
23894260f7c7SSage Weil 		err = -EPERM;
23900b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
23914260f7c7SSage Weil 			goto out_dput;
23924260f7c7SSage Weil 
23934260f7c7SSage Weil 		/*
23944260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
23954260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
23964260f7c7SSage Weil 		 * must be called on the dentry referencing the root
23974260f7c7SSage Weil 		 * of the subvol, not a random directory contained
23984260f7c7SSage Weil 		 * within it.
23994260f7c7SSage Weil 		 */
24004260f7c7SSage Weil 		err = -EINVAL;
24014260f7c7SSage Weil 		if (root == dest)
24024260f7c7SSage Weil 			goto out_dput;
24034260f7c7SSage Weil 
24044260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
24054260f7c7SSage Weil 		if (err)
24064260f7c7SSage Weil 			goto out_dput;
24075c39da5bSMiao Xie 	}
24084260f7c7SSage Weil 
24095c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
24104260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
24114260f7c7SSage Weil 	if (err)
24124260f7c7SSage Weil 		goto out_dput;
24134260f7c7SSage Weil 
24144a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
241576dda93cSYan, Zheng 		err = -EINVAL;
241676dda93cSYan, Zheng 		goto out_dput;
241776dda93cSYan, Zheng 	}
241876dda93cSYan, Zheng 
24195955102cSAl Viro 	inode_lock(inode);
2420521e0546SDavid Sterba 
2421521e0546SDavid Sterba 	/*
2422521e0546SDavid Sterba 	 * Don't allow to delete a subvolume with send in progress. This is
2423521e0546SDavid Sterba 	 * inside the i_mutex so the error handling that has to drop the bit
2424521e0546SDavid Sterba 	 * again is not run concurrently.
2425521e0546SDavid Sterba 	 */
2426521e0546SDavid Sterba 	spin_lock(&dest->root_item_lock);
2427c55bfa67SFilipe Manana 	root_flags = btrfs_root_flags(&dest->root_item);
2428c55bfa67SFilipe Manana 	if (dest->send_in_progress == 0) {
2429c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2430521e0546SDavid Sterba 				root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2431521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2432521e0546SDavid Sterba 	} else {
2433521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
24340b246afaSJeff Mahoney 		btrfs_warn(fs_info,
2435521e0546SDavid Sterba 			   "Attempt to delete subvolume %llu during send",
2436c55bfa67SFilipe Manana 			   dest->root_key.objectid);
2437521e0546SDavid Sterba 		err = -EPERM;
2438909e26dcSOmar Sandoval 		goto out_unlock_inode;
2439521e0546SDavid Sterba 	}
2440521e0546SDavid Sterba 
24410b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
244276dda93cSYan, Zheng 
244376dda93cSYan, Zheng 	err = may_destroy_subvol(dest);
244476dda93cSYan, Zheng 	if (err)
244576dda93cSYan, Zheng 		goto out_up_write;
244676dda93cSYan, Zheng 
2447c58aaad2SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2448c58aaad2SMiao Xie 	/*
2449c58aaad2SMiao Xie 	 * One for dir inode, two for dir entries, two for root
2450c58aaad2SMiao Xie 	 * ref/backref.
2451c58aaad2SMiao Xie 	 */
2452c58aaad2SMiao Xie 	err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2453ee3441b4SJeff Mahoney 					       5, &qgroup_reserved, true);
2454c58aaad2SMiao Xie 	if (err)
2455c58aaad2SMiao Xie 		goto out_up_write;
2456c58aaad2SMiao Xie 
2457a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 0);
2458a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
2459a22285a6SYan, Zheng 		err = PTR_ERR(trans);
2460c58aaad2SMiao Xie 		goto out_release;
2461a22285a6SYan, Zheng 	}
2462c58aaad2SMiao Xie 	trans->block_rsv = &block_rsv;
2463c58aaad2SMiao Xie 	trans->bytes_reserved = block_rsv.size;
2464a22285a6SYan, Zheng 
246543663557SNikolay Borisov 	btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
24662be63d5cSFilipe Manana 
246776dda93cSYan, Zheng 	ret = btrfs_unlink_subvol(trans, root, dir,
246876dda93cSYan, Zheng 				dest->root_key.objectid,
246976dda93cSYan, Zheng 				dentry->d_name.name,
247076dda93cSYan, Zheng 				dentry->d_name.len);
247179787eaaSJeff Mahoney 	if (ret) {
247279787eaaSJeff Mahoney 		err = ret;
247366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
247479787eaaSJeff Mahoney 		goto out_end_trans;
247579787eaaSJeff Mahoney 	}
247676dda93cSYan, Zheng 
247776dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, dest);
247876dda93cSYan, Zheng 
247976dda93cSYan, Zheng 	memset(&dest->root_item.drop_progress, 0,
248076dda93cSYan, Zheng 		sizeof(dest->root_item.drop_progress));
248176dda93cSYan, Zheng 	dest->root_item.drop_level = 0;
248276dda93cSYan, Zheng 	btrfs_set_root_refs(&dest->root_item, 0);
248376dda93cSYan, Zheng 
248427cdeb70SMiao Xie 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
248576dda93cSYan, Zheng 		ret = btrfs_insert_orphan_item(trans,
24860b246afaSJeff Mahoney 					fs_info->tree_root,
248776dda93cSYan, Zheng 					dest->root_key.objectid);
248879787eaaSJeff Mahoney 		if (ret) {
248966642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
249079787eaaSJeff Mahoney 			err = ret;
249179787eaaSJeff Mahoney 			goto out_end_trans;
2492d68fc57bSYan, Zheng 		}
249379787eaaSJeff Mahoney 	}
2494dd5f9615SStefan Behrens 
24950b246afaSJeff Mahoney 	ret = btrfs_uuid_tree_rem(trans, fs_info, dest->root_item.uuid,
24966bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL,
2497dd5f9615SStefan Behrens 				  dest->root_key.objectid);
2498dd5f9615SStefan Behrens 	if (ret && ret != -ENOENT) {
249966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
2500dd5f9615SStefan Behrens 		err = ret;
2501dd5f9615SStefan Behrens 		goto out_end_trans;
2502dd5f9615SStefan Behrens 	}
2503dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
25040b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_rem(trans, fs_info,
2505dd5f9615SStefan Behrens 					  dest->root_item.received_uuid,
2506dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2507dd5f9615SStefan Behrens 					  dest->root_key.objectid);
2508dd5f9615SStefan Behrens 		if (ret && ret != -ENOENT) {
250966642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
2510dd5f9615SStefan Behrens 			err = ret;
2511dd5f9615SStefan Behrens 			goto out_end_trans;
2512dd5f9615SStefan Behrens 		}
2513dd5f9615SStefan Behrens 	}
2514dd5f9615SStefan Behrens 
251579787eaaSJeff Mahoney out_end_trans:
2516c58aaad2SMiao Xie 	trans->block_rsv = NULL;
2517c58aaad2SMiao Xie 	trans->bytes_reserved = 0;
25183a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
251979787eaaSJeff Mahoney 	if (ret && !err)
252079787eaaSJeff Mahoney 		err = ret;
252176dda93cSYan, Zheng 	inode->i_flags |= S_DEAD;
2522c58aaad2SMiao Xie out_release:
25237775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
252476dda93cSYan, Zheng out_up_write:
25250b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
2526521e0546SDavid Sterba 	if (err) {
2527521e0546SDavid Sterba 		spin_lock(&dest->root_item_lock);
2528c55bfa67SFilipe Manana 		root_flags = btrfs_root_flags(&dest->root_item);
2529c55bfa67SFilipe Manana 		btrfs_set_root_flags(&dest->root_item,
2530521e0546SDavid Sterba 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2531521e0546SDavid Sterba 		spin_unlock(&dest->root_item_lock);
2532521e0546SDavid Sterba 	}
2533909e26dcSOmar Sandoval out_unlock_inode:
25345955102cSAl Viro 	inode_unlock(inode);
253576dda93cSYan, Zheng 	if (!err) {
253664ad6c48SOmar Sandoval 		d_invalidate(dentry);
253776dda93cSYan, Zheng 		btrfs_invalidate_inodes(dest);
253876dda93cSYan, Zheng 		d_delete(dentry);
253961155aa0SDavid Sterba 		ASSERT(dest->send_in_progress == 0);
2540fa6ac876SLiu Bo 
2541fa6ac876SLiu Bo 		/* the last ref */
254257cdc8dbSDavid Sterba 		if (dest->ino_cache_inode) {
254357cdc8dbSDavid Sterba 			iput(dest->ino_cache_inode);
254457cdc8dbSDavid Sterba 			dest->ino_cache_inode = NULL;
2545fa6ac876SLiu Bo 		}
254676dda93cSYan, Zheng 	}
254776dda93cSYan, Zheng out_dput:
254876dda93cSYan, Zheng 	dput(dentry);
254976dda93cSYan, Zheng out_unlock_dir:
25505955102cSAl Viro 	inode_unlock(dir);
255100235411SAl Viro out_drop_write:
25522a79f17eSAl Viro 	mnt_drop_write_file(file);
255376dda93cSYan, Zheng out:
255476dda93cSYan, Zheng 	kfree(vol_args);
255576dda93cSYan, Zheng 	return err;
255676dda93cSYan, Zheng }
255776dda93cSYan, Zheng 
25581e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2559f46b5a66SChristoph Hellwig {
2560496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2561f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
25621e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2563c146afadSYan Zheng 	int ret;
2564c146afadSYan Zheng 
256525122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
256625122d15SIlya Dryomov 	if (ret)
256725122d15SIlya Dryomov 		return ret;
2568b83cc969SLi Zefan 
256925122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
257025122d15SIlya Dryomov 		ret = -EROFS;
257125122d15SIlya Dryomov 		goto out;
25725ac00addSStefan Behrens 	}
2573f46b5a66SChristoph Hellwig 
2574f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2575f46b5a66SChristoph Hellwig 	case S_IFDIR:
2576e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2577e441d54dSChris Mason 			ret = -EPERM;
2578e441d54dSChris Mason 			goto out;
2579e441d54dSChris Mason 		}
2580de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
2581f46b5a66SChristoph Hellwig 		break;
2582f46b5a66SChristoph Hellwig 	case S_IFREG:
2583e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2584e441d54dSChris Mason 			ret = -EINVAL;
2585e441d54dSChris Mason 			goto out;
2586e441d54dSChris Mason 		}
25871e701a32SChris Mason 
25881e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
25891e701a32SChris Mason 		if (!range) {
25901e701a32SChris Mason 			ret = -ENOMEM;
25911e701a32SChris Mason 			goto out;
25921e701a32SChris Mason 		}
25931e701a32SChris Mason 
25941e701a32SChris Mason 		if (argp) {
25951e701a32SChris Mason 			if (copy_from_user(range, argp,
25961e701a32SChris Mason 					   sizeof(*range))) {
25971e701a32SChris Mason 				ret = -EFAULT;
25981e701a32SChris Mason 				kfree(range);
2599683be16eSDan Carpenter 				goto out;
26001e701a32SChris Mason 			}
26011e701a32SChris Mason 			/* compression requires us to start the IO */
26021e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
26031e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
26041e701a32SChris Mason 				range->extent_thresh = (u32)-1;
26051e701a32SChris Mason 			}
26061e701a32SChris Mason 		} else {
26071e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
26081e701a32SChris Mason 			range->len = (u64)-1;
26091e701a32SChris Mason 		}
2610496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
26114cb5300bSChris Mason 					range, 0, 0);
26124cb5300bSChris Mason 		if (ret > 0)
26134cb5300bSChris Mason 			ret = 0;
26141e701a32SChris Mason 		kfree(range);
2615f46b5a66SChristoph Hellwig 		break;
26168929ecfaSYan, Zheng 	default:
26178929ecfaSYan, Zheng 		ret = -EINVAL;
2618f46b5a66SChristoph Hellwig 	}
2619e441d54dSChris Mason out:
262025122d15SIlya Dryomov 	mnt_drop_write_file(file);
2621e441d54dSChris Mason 	return ret;
2622f46b5a66SChristoph Hellwig }
2623f46b5a66SChristoph Hellwig 
26242ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2625f46b5a66SChristoph Hellwig {
2626f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2627f46b5a66SChristoph Hellwig 	int ret;
2628f46b5a66SChristoph Hellwig 
2629e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2630e441d54dSChris Mason 		return -EPERM;
2631e441d54dSChris Mason 
2632171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2633e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2634c9e9f97bSIlya Dryomov 
26350b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
2636dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2637c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2638c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2639c9e9f97bSIlya Dryomov 		goto out;
2640c9e9f97bSIlya Dryomov 	}
2641f46b5a66SChristoph Hellwig 
26425516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
26432ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
2644f46b5a66SChristoph Hellwig 
264543d20761SAnand Jain 	if (!ret)
26460b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
264743d20761SAnand Jain 
2648f46b5a66SChristoph Hellwig 	kfree(vol_args);
2649c9e9f97bSIlya Dryomov out:
26500b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
2651171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2652f46b5a66SChristoph Hellwig 	return ret;
2653f46b5a66SChristoph Hellwig }
2654f46b5a66SChristoph Hellwig 
26556b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
2656f46b5a66SChristoph Hellwig {
26570b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
26580b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
26596b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
2660f46b5a66SChristoph Hellwig 	int ret;
2661f46b5a66SChristoph Hellwig 
2662e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2663e441d54dSChris Mason 		return -EPERM;
2664e441d54dSChris Mason 
2665da24927bSMiao Xie 	ret = mnt_want_write_file(file);
2666da24927bSMiao Xie 	if (ret)
2667da24927bSMiao Xie 		return ret;
2668c146afadSYan Zheng 
2669dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2670c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2671c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2672c47ca32dSDan Carpenter 		goto err_drop;
2673c9e9f97bSIlya Dryomov 	}
2674f46b5a66SChristoph Hellwig 
26756b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
2676735654eaSDavid Sterba 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED)
2677735654eaSDavid Sterba 		return -EOPNOTSUPP;
2678f46b5a66SChristoph Hellwig 
2679171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2680183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2681183860f6SAnand Jain 		goto out;
2682183860f6SAnand Jain 	}
2683183860f6SAnand Jain 
26840b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
2685735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
26862ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
26876b526ed7SAnand Jain 	} else {
26886b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
26892ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
26906b526ed7SAnand Jain 	}
26910b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
2692171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2693183860f6SAnand Jain 
26946b526ed7SAnand Jain 	if (!ret) {
2695735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
26960b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
26976b526ed7SAnand Jain 					vol_args->devid);
26986b526ed7SAnand Jain 		else
26990b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
27006b526ed7SAnand Jain 					vol_args->name);
27016b526ed7SAnand Jain 	}
2702183860f6SAnand Jain out:
2703183860f6SAnand Jain 	kfree(vol_args);
2704c47ca32dSDan Carpenter err_drop:
27054ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
2706f46b5a66SChristoph Hellwig 	return ret;
2707f46b5a66SChristoph Hellwig }
2708f46b5a66SChristoph Hellwig 
2709f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2710f46b5a66SChristoph Hellwig {
27110b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
27120b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2713f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2714f46b5a66SChristoph Hellwig 	int ret;
2715f46b5a66SChristoph Hellwig 
2716f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
2717f46b5a66SChristoph Hellwig 		return -EPERM;
2718f46b5a66SChristoph Hellwig 
2719f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
2720f46b5a66SChristoph Hellwig 	if (ret)
2721f46b5a66SChristoph Hellwig 		return ret;
2722f46b5a66SChristoph Hellwig 
2723171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2724f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
272558d7bbf8SDavid Sterba 		goto out_drop_write;
272658d7bbf8SDavid Sterba 	}
272758d7bbf8SDavid Sterba 
272858d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
272958d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
273058d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
2731f46b5a66SChristoph Hellwig 		goto out;
2732f46b5a66SChristoph Hellwig 	}
2733f46b5a66SChristoph Hellwig 
273458d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
27350b246afaSJeff Mahoney 	mutex_lock(&fs_info->volume_mutex);
27362ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
27370b246afaSJeff Mahoney 	mutex_unlock(&fs_info->volume_mutex);
2738f46b5a66SChristoph Hellwig 
2739f46b5a66SChristoph Hellwig 	if (!ret)
27400b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
2741f46b5a66SChristoph Hellwig 	kfree(vol_args);
274258d7bbf8SDavid Sterba out:
2743171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
274458d7bbf8SDavid Sterba out_drop_write:
2745f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
274658d7bbf8SDavid Sterba 
2747f46b5a66SChristoph Hellwig 	return ret;
2748f46b5a66SChristoph Hellwig }
2749f46b5a66SChristoph Hellwig 
27502ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
27512ff7e61eSJeff Mahoney 				void __user *arg)
2752475f6387SJan Schmidt {
2753027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
2754475f6387SJan Schmidt 	struct btrfs_device *device;
27550b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2756027ed2f0SLi Zefan 	int ret = 0;
2757475f6387SJan Schmidt 
2758027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2759027ed2f0SLi Zefan 	if (!fi_args)
2760027ed2f0SLi Zefan 		return -ENOMEM;
2761027ed2f0SLi Zefan 
2762f7171750SFilipe David Borba Manana 	mutex_lock(&fs_devices->device_list_mutex);
2763027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
27640b246afaSJeff Mahoney 	memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
2765475f6387SJan Schmidt 
2766d7641a49SByongho Lee 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
2767027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
2768027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
2769475f6387SJan Schmidt 	}
2770475f6387SJan Schmidt 	mutex_unlock(&fs_devices->device_list_mutex);
2771475f6387SJan Schmidt 
2772bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
2773bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
2774bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
277580a773fbSDavid Sterba 
2776027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2777027ed2f0SLi Zefan 		ret = -EFAULT;
2778475f6387SJan Schmidt 
2779027ed2f0SLi Zefan 	kfree(fi_args);
2780027ed2f0SLi Zefan 	return ret;
2781475f6387SJan Schmidt }
2782475f6387SJan Schmidt 
27832ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
27842ff7e61eSJeff Mahoney 				 void __user *arg)
2785475f6387SJan Schmidt {
2786475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
2787475f6387SJan Schmidt 	struct btrfs_device *dev;
27880b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2789475f6387SJan Schmidt 	int ret = 0;
2790475f6387SJan Schmidt 	char *s_uuid = NULL;
2791475f6387SJan Schmidt 
2792475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
2793475f6387SJan Schmidt 	if (IS_ERR(di_args))
2794475f6387SJan Schmidt 		return PTR_ERR(di_args);
2795475f6387SJan Schmidt 
2796dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
2797475f6387SJan Schmidt 		s_uuid = di_args->uuid;
2798475f6387SJan Schmidt 
2799475f6387SJan Schmidt 	mutex_lock(&fs_devices->device_list_mutex);
28000b246afaSJeff Mahoney 	dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
2801475f6387SJan Schmidt 
2802475f6387SJan Schmidt 	if (!dev) {
2803475f6387SJan Schmidt 		ret = -ENODEV;
2804475f6387SJan Schmidt 		goto out;
2805475f6387SJan Schmidt 	}
2806475f6387SJan Schmidt 
2807475f6387SJan Schmidt 	di_args->devid = dev->devid;
28087cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
28097cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2810475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2811a27202fbSJim Meyering 	if (dev->name) {
2812606686eeSJosef Bacik 		struct rcu_string *name;
2813606686eeSJosef Bacik 
2814606686eeSJosef Bacik 		rcu_read_lock();
2815606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
2816606686eeSJosef Bacik 		strncpy(di_args->path, name->str, sizeof(di_args->path));
2817606686eeSJosef Bacik 		rcu_read_unlock();
2818a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
2819a27202fbSJim Meyering 	} else {
282099ba55adSStefan Behrens 		di_args->path[0] = '\0';
2821a27202fbSJim Meyering 	}
2822475f6387SJan Schmidt 
2823475f6387SJan Schmidt out:
282455793c0dSDavid Sterba 	mutex_unlock(&fs_devices->device_list_mutex);
2825475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2826475f6387SJan Schmidt 		ret = -EFAULT;
2827475f6387SJan Schmidt 
2828475f6387SJan Schmidt 	kfree(di_args);
2829475f6387SJan Schmidt 	return ret;
2830475f6387SJan Schmidt }
2831475f6387SJan Schmidt 
2832f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2833416161dbSMark Fasheh {
2834416161dbSMark Fasheh 	struct page *page;
2835416161dbSMark Fasheh 
2836416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
2837416161dbSMark Fasheh 	if (!page)
283831314002SFilipe Manana 		return ERR_PTR(-ENOMEM);
2839416161dbSMark Fasheh 
2840416161dbSMark Fasheh 	if (!PageUptodate(page)) {
284131314002SFilipe Manana 		int ret;
284231314002SFilipe Manana 
284331314002SFilipe Manana 		ret = btrfs_readpage(NULL, page);
284431314002SFilipe Manana 		if (ret)
284531314002SFilipe Manana 			return ERR_PTR(ret);
2846416161dbSMark Fasheh 		lock_page(page);
2847416161dbSMark Fasheh 		if (!PageUptodate(page)) {
2848416161dbSMark Fasheh 			unlock_page(page);
284909cbfeafSKirill A. Shutemov 			put_page(page);
285031314002SFilipe Manana 			return ERR_PTR(-EIO);
2851416161dbSMark Fasheh 		}
285231314002SFilipe Manana 		if (page->mapping != inode->i_mapping) {
2853416161dbSMark Fasheh 			unlock_page(page);
285409cbfeafSKirill A. Shutemov 			put_page(page);
285531314002SFilipe Manana 			return ERR_PTR(-EAGAIN);
2856416161dbSMark Fasheh 		}
2857416161dbSMark Fasheh 	}
2858416161dbSMark Fasheh 
2859416161dbSMark Fasheh 	return page;
2860416161dbSMark Fasheh }
2861416161dbSMark Fasheh 
2862f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
2863f4414602SMark Fasheh 			       int num_pages, u64 off)
2864f4414602SMark Fasheh {
2865f4414602SMark Fasheh 	int i;
286609cbfeafSKirill A. Shutemov 	pgoff_t index = off >> PAGE_SHIFT;
2867f4414602SMark Fasheh 
2868f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
286931314002SFilipe Manana again:
2870f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
287131314002SFilipe Manana 		if (IS_ERR(pages[i])) {
287231314002SFilipe Manana 			int err = PTR_ERR(pages[i]);
287331314002SFilipe Manana 
287431314002SFilipe Manana 			if (err == -EAGAIN)
287531314002SFilipe Manana 				goto again;
287631314002SFilipe Manana 			pages[i] = NULL;
287731314002SFilipe Manana 			return err;
287831314002SFilipe Manana 		}
2879f4414602SMark Fasheh 	}
2880f4414602SMark Fasheh 	return 0;
2881f4414602SMark Fasheh }
2882f4414602SMark Fasheh 
2883e0bd70c6SFilipe Manana static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2884e0bd70c6SFilipe Manana 			     bool retry_range_locking)
288577fe20dcSMark Fasheh {
2886e0bd70c6SFilipe Manana 	/*
2887e0bd70c6SFilipe Manana 	 * Do any pending delalloc/csum calculations on inode, one way or
2888e0bd70c6SFilipe Manana 	 * another, and lock file content.
2889e0bd70c6SFilipe Manana 	 * The locking order is:
2890e0bd70c6SFilipe Manana 	 *
2891e0bd70c6SFilipe Manana 	 *   1) pages
2892e0bd70c6SFilipe Manana 	 *   2) range in the inode's io tree
2893e0bd70c6SFilipe Manana 	 */
289477fe20dcSMark Fasheh 	while (1) {
289577fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
289677fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
289777fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
289877fe20dcSMark Fasheh 							    off + len - 1);
2899ff5df9b8SFilipe Manana 		if ((!ordered ||
2900ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
2901ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
290277fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2903ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2904ff5df9b8SFilipe Manana 			if (ordered)
2905ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
290677fe20dcSMark Fasheh 			break;
2907ff5df9b8SFilipe Manana 		}
290877fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
290977fe20dcSMark Fasheh 		if (ordered)
291077fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
2911e0bd70c6SFilipe Manana 		if (!retry_range_locking)
2912e0bd70c6SFilipe Manana 			return -EAGAIN;
291377fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
291477fe20dcSMark Fasheh 	}
2915e0bd70c6SFilipe Manana 	return 0;
291677fe20dcSMark Fasheh }
291777fe20dcSMark Fasheh 
2918f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2919416161dbSMark Fasheh {
29205955102cSAl Viro 	inode_unlock(inode1);
29215955102cSAl Viro 	inode_unlock(inode2);
2922416161dbSMark Fasheh }
2923416161dbSMark Fasheh 
2924f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2925f4414602SMark Fasheh {
2926f4414602SMark Fasheh 	if (inode1 < inode2)
2927f4414602SMark Fasheh 		swap(inode1, inode2);
2928f4414602SMark Fasheh 
29295955102cSAl Viro 	inode_lock_nested(inode1, I_MUTEX_PARENT);
29305955102cSAl Viro 	inode_lock_nested(inode2, I_MUTEX_CHILD);
2931f4414602SMark Fasheh }
2932f4414602SMark Fasheh 
2933f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2934f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
2935f4414602SMark Fasheh {
2936f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2937f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2938f4414602SMark Fasheh }
2939f4414602SMark Fasheh 
2940e0bd70c6SFilipe Manana static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2941e0bd70c6SFilipe Manana 				    struct inode *inode2, u64 loff2, u64 len,
2942e0bd70c6SFilipe Manana 				    bool retry_range_locking)
2943416161dbSMark Fasheh {
2944e0bd70c6SFilipe Manana 	int ret;
2945e0bd70c6SFilipe Manana 
2946416161dbSMark Fasheh 	if (inode1 < inode2) {
2947416161dbSMark Fasheh 		swap(inode1, inode2);
2948416161dbSMark Fasheh 		swap(loff1, loff2);
2949416161dbSMark Fasheh 	}
2950e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2951e0bd70c6SFilipe Manana 	if (ret)
2952e0bd70c6SFilipe Manana 		return ret;
2953e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2954e0bd70c6SFilipe Manana 	if (ret)
2955e0bd70c6SFilipe Manana 		unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2956e0bd70c6SFilipe Manana 			      loff1 + len - 1);
2957e0bd70c6SFilipe Manana 	return ret;
2958416161dbSMark Fasheh }
2959f4414602SMark Fasheh 
2960f4414602SMark Fasheh struct cmp_pages {
2961f4414602SMark Fasheh 	int		num_pages;
2962f4414602SMark Fasheh 	struct page	**src_pages;
2963f4414602SMark Fasheh 	struct page	**dst_pages;
2964f4414602SMark Fasheh };
2965f4414602SMark Fasheh 
2966f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2967f4414602SMark Fasheh {
2968f4414602SMark Fasheh 	int i;
2969f4414602SMark Fasheh 	struct page *pg;
2970f4414602SMark Fasheh 
2971f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
2972f4414602SMark Fasheh 		pg = cmp->src_pages[i];
2973e0bd70c6SFilipe Manana 		if (pg) {
2974e0bd70c6SFilipe Manana 			unlock_page(pg);
297509cbfeafSKirill A. Shutemov 			put_page(pg);
2976e0bd70c6SFilipe Manana 		}
2977f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
2978e0bd70c6SFilipe Manana 		if (pg) {
2979e0bd70c6SFilipe Manana 			unlock_page(pg);
298009cbfeafSKirill A. Shutemov 			put_page(pg);
2981f4414602SMark Fasheh 		}
2982e0bd70c6SFilipe Manana 	}
2983f4414602SMark Fasheh 	kfree(cmp->src_pages);
2984f4414602SMark Fasheh 	kfree(cmp->dst_pages);
2985f4414602SMark Fasheh }
2986f4414602SMark Fasheh 
2987f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2988f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
2989f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
2990f4414602SMark Fasheh {
2991f4414602SMark Fasheh 	int ret;
299209cbfeafSKirill A. Shutemov 	int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
2993f4414602SMark Fasheh 	struct page **src_pgarr, **dst_pgarr;
2994f4414602SMark Fasheh 
2995f4414602SMark Fasheh 	/*
2996f4414602SMark Fasheh 	 * We must gather up all the pages before we initiate our
2997f4414602SMark Fasheh 	 * extent locking. We use an array for the page pointers. Size
2998f4414602SMark Fasheh 	 * of the array is bounded by len, which is in turn bounded by
2999f4414602SMark Fasheh 	 * BTRFS_MAX_DEDUPE_LEN.
3000f4414602SMark Fasheh 	 */
300166722f7cSDavid Sterba 	src_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
300266722f7cSDavid Sterba 	dst_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
3003f4414602SMark Fasheh 	if (!src_pgarr || !dst_pgarr) {
3004f4414602SMark Fasheh 		kfree(src_pgarr);
3005f4414602SMark Fasheh 		kfree(dst_pgarr);
3006f4414602SMark Fasheh 		return -ENOMEM;
3007f4414602SMark Fasheh 	}
3008f4414602SMark Fasheh 	cmp->num_pages = num_pages;
3009f4414602SMark Fasheh 	cmp->src_pages = src_pgarr;
3010f4414602SMark Fasheh 	cmp->dst_pages = dst_pgarr;
3011f4414602SMark Fasheh 
3012b1517622SFilipe Manana 	/*
3013b1517622SFilipe Manana 	 * If deduping ranges in the same inode, locking rules make it mandatory
3014b1517622SFilipe Manana 	 * to always lock pages in ascending order to avoid deadlocks with
3015b1517622SFilipe Manana 	 * concurrent tasks (such as starting writeback/delalloc).
3016b1517622SFilipe Manana 	 */
3017b1517622SFilipe Manana 	if (src == dst && dst_loff < loff) {
3018b1517622SFilipe Manana 		swap(src_pgarr, dst_pgarr);
3019b1517622SFilipe Manana 		swap(loff, dst_loff);
3020b1517622SFilipe Manana 	}
3021b1517622SFilipe Manana 
3022b1517622SFilipe Manana 	ret = gather_extent_pages(src, src_pgarr, cmp->num_pages, loff);
3023f4414602SMark Fasheh 	if (ret)
3024f4414602SMark Fasheh 		goto out;
3025f4414602SMark Fasheh 
3026b1517622SFilipe Manana 	ret = gather_extent_pages(dst, dst_pgarr, cmp->num_pages, dst_loff);
3027f4414602SMark Fasheh 
3028f4414602SMark Fasheh out:
3029f4414602SMark Fasheh 	if (ret)
3030f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
3031f4414602SMark Fasheh 	return 0;
3032416161dbSMark Fasheh }
3033416161dbSMark Fasheh 
30341a287cfeSDavid Sterba static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
3035416161dbSMark Fasheh {
3036416161dbSMark Fasheh 	int ret = 0;
3037f4414602SMark Fasheh 	int i;
3038416161dbSMark Fasheh 	struct page *src_page, *dst_page;
303909cbfeafSKirill A. Shutemov 	unsigned int cmp_len = PAGE_SIZE;
3040416161dbSMark Fasheh 	void *addr, *dst_addr;
3041416161dbSMark Fasheh 
3042f4414602SMark Fasheh 	i = 0;
3043416161dbSMark Fasheh 	while (len) {
304409cbfeafSKirill A. Shutemov 		if (len < PAGE_SIZE)
3045416161dbSMark Fasheh 			cmp_len = len;
3046416161dbSMark Fasheh 
3047f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
3048f4414602SMark Fasheh 
3049f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
3050f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
3051e0bd70c6SFilipe Manana 		ASSERT(PageLocked(src_page));
3052e0bd70c6SFilipe Manana 		ASSERT(PageLocked(dst_page));
3053f4414602SMark Fasheh 
3054416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
3055416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
3056416161dbSMark Fasheh 
3057416161dbSMark Fasheh 		flush_dcache_page(src_page);
3058416161dbSMark Fasheh 		flush_dcache_page(dst_page);
3059416161dbSMark Fasheh 
3060416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
30612b3909f8SDarrick J. Wong 			ret = -EBADE;
3062416161dbSMark Fasheh 
3063416161dbSMark Fasheh 		kunmap_atomic(addr);
3064416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
3065416161dbSMark Fasheh 
3066416161dbSMark Fasheh 		if (ret)
3067416161dbSMark Fasheh 			break;
3068416161dbSMark Fasheh 
3069416161dbSMark Fasheh 		len -= cmp_len;
3070f4414602SMark Fasheh 		i++;
3071416161dbSMark Fasheh 	}
3072416161dbSMark Fasheh 
3073416161dbSMark Fasheh 	return ret;
3074416161dbSMark Fasheh }
3075416161dbSMark Fasheh 
3076e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3077e1d227a4SMark Fasheh 				     u64 olen)
3078416161dbSMark Fasheh {
3079e1d227a4SMark Fasheh 	u64 len = *plen;
3080416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3081416161dbSMark Fasheh 
3082e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
3083416161dbSMark Fasheh 		return -EINVAL;
3084e1d227a4SMark Fasheh 
3085e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
3086e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
3087e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
3088e1d227a4SMark Fasheh 
3089416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
3090416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3091416161dbSMark Fasheh 		return -EINVAL;
3092416161dbSMark Fasheh 
3093416161dbSMark Fasheh 	return 0;
3094416161dbSMark Fasheh }
3095416161dbSMark Fasheh 
3096e1d227a4SMark Fasheh static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3097416161dbSMark Fasheh 			     struct inode *dst, u64 dst_loff)
3098416161dbSMark Fasheh {
3099416161dbSMark Fasheh 	int ret;
3100e1d227a4SMark Fasheh 	u64 len = olen;
3101f4414602SMark Fasheh 	struct cmp_pages cmp;
3102fc4badd9SOmar Sandoval 	bool same_inode = (src == dst);
31030efa9f48SMark Fasheh 	u64 same_lock_start = 0;
31040efa9f48SMark Fasheh 	u64 same_lock_len = 0;
3105416161dbSMark Fasheh 
3106113e8283SFilipe Manana 	if (len == 0)
3107113e8283SFilipe Manana 		return 0;
3108113e8283SFilipe Manana 
3109fc4badd9SOmar Sandoval 	if (same_inode)
31105955102cSAl Viro 		inode_lock(src);
3111fc4badd9SOmar Sandoval 	else
3112fc4badd9SOmar Sandoval 		btrfs_double_inode_lock(src, dst);
31130efa9f48SMark Fasheh 
31140efa9f48SMark Fasheh 	ret = extent_same_check_offsets(src, loff, &len, olen);
31150efa9f48SMark Fasheh 	if (ret)
31160efa9f48SMark Fasheh 		goto out_unlock;
3117fc4badd9SOmar Sandoval 
3118fc4badd9SOmar Sandoval 	ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3119f4dfe687SFilipe Manana 	if (ret)
3120f4dfe687SFilipe Manana 		goto out_unlock;
31210efa9f48SMark Fasheh 
3122fc4badd9SOmar Sandoval 	if (same_inode) {
31230efa9f48SMark Fasheh 		/*
31240efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
31250efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
31260efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
31270efa9f48SMark Fasheh 		 *
31280efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
31290efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
31300efa9f48SMark Fasheh 		 * reject the request.
31310efa9f48SMark Fasheh 		 *
31320efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
31330efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
31340efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
31350efa9f48SMark Fasheh 		 * i_size.
31360efa9f48SMark Fasheh 		 */
31370efa9f48SMark Fasheh 		if (len != olen) {
31380efa9f48SMark Fasheh 			ret = -EINVAL;
31390efa9f48SMark Fasheh 			goto out_unlock;
31400efa9f48SMark Fasheh 		}
31410efa9f48SMark Fasheh 
31420efa9f48SMark Fasheh 		/* Check for overlapping ranges */
31430efa9f48SMark Fasheh 		if (dst_loff + len > loff && dst_loff < loff + len) {
31440efa9f48SMark Fasheh 			ret = -EINVAL;
31450efa9f48SMark Fasheh 			goto out_unlock;
31460efa9f48SMark Fasheh 		}
31470efa9f48SMark Fasheh 
31480efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
31490efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
31500efa9f48SMark Fasheh 	}
3151416161dbSMark Fasheh 
3152416161dbSMark Fasheh 	/* don't make the dst file partly checksummed */
3153416161dbSMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3154416161dbSMark Fasheh 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3155416161dbSMark Fasheh 		ret = -EINVAL;
3156416161dbSMark Fasheh 		goto out_unlock;
3157416161dbSMark Fasheh 	}
3158416161dbSMark Fasheh 
3159e0bd70c6SFilipe Manana again:
3160f4414602SMark Fasheh 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3161f4414602SMark Fasheh 	if (ret)
3162f4414602SMark Fasheh 		goto out_unlock;
3163f4414602SMark Fasheh 
31640efa9f48SMark Fasheh 	if (same_inode)
3165e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, same_lock_start, same_lock_len,
3166e0bd70c6SFilipe Manana 					false);
31670efa9f48SMark Fasheh 	else
3168e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3169e0bd70c6SFilipe Manana 					       false);
3170e0bd70c6SFilipe Manana 	/*
3171e0bd70c6SFilipe Manana 	 * If one of the inodes has dirty pages in the respective range or
3172e0bd70c6SFilipe Manana 	 * ordered extents, we need to flush dellaloc and wait for all ordered
3173e0bd70c6SFilipe Manana 	 * extents in the range. We must unlock the pages and the ranges in the
3174e0bd70c6SFilipe Manana 	 * io trees to avoid deadlocks when flushing delalloc (requires locking
3175e0bd70c6SFilipe Manana 	 * pages) and when waiting for ordered extents to complete (they require
3176e0bd70c6SFilipe Manana 	 * range locking).
3177e0bd70c6SFilipe Manana 	 */
3178e0bd70c6SFilipe Manana 	if (ret == -EAGAIN) {
3179e0bd70c6SFilipe Manana 		/*
3180e0bd70c6SFilipe Manana 		 * Ranges in the io trees already unlocked. Now unlock all
3181e0bd70c6SFilipe Manana 		 * pages before waiting for all IO to complete.
3182e0bd70c6SFilipe Manana 		 */
3183e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
3184e0bd70c6SFilipe Manana 		if (same_inode) {
3185e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, same_lock_start,
3186e0bd70c6SFilipe Manana 						 same_lock_len);
3187e0bd70c6SFilipe Manana 		} else {
3188e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, loff, len);
3189e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(dst, dst_loff, len);
3190e0bd70c6SFilipe Manana 		}
3191e0bd70c6SFilipe Manana 		goto again;
3192e0bd70c6SFilipe Manana 	}
3193e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3194e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3195e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3196e0bd70c6SFilipe Manana 		btrfs_cmp_data_free(&cmp);
3197e0bd70c6SFilipe Manana 		return ret;
3198e0bd70c6SFilipe Manana 	}
3199f4414602SMark Fasheh 
3200207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
32011a287cfeSDavid Sterba 	ret = btrfs_cmp_data(olen, &cmp);
3202416161dbSMark Fasheh 	if (ret == 0)
32031c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3204416161dbSMark Fasheh 
32050efa9f48SMark Fasheh 	if (same_inode)
32060efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
32070efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
32080efa9f48SMark Fasheh 	else
3209f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3210f4414602SMark Fasheh 
3211f4414602SMark Fasheh 	btrfs_cmp_data_free(&cmp);
3212416161dbSMark Fasheh out_unlock:
32130efa9f48SMark Fasheh 	if (same_inode)
32145955102cSAl Viro 		inode_unlock(src);
32150efa9f48SMark Fasheh 	else
3216f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3217416161dbSMark Fasheh 
3218416161dbSMark Fasheh 	return ret;
3219416161dbSMark Fasheh }
3220416161dbSMark Fasheh 
3221ee22184bSByongho Lee #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3222416161dbSMark Fasheh 
32232b3909f8SDarrick J. Wong ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
32242b3909f8SDarrick J. Wong 				struct file *dst_file, u64 dst_loff)
3225416161dbSMark Fasheh {
32262b3909f8SDarrick J. Wong 	struct inode *src = file_inode(src_file);
32272b3909f8SDarrick J. Wong 	struct inode *dst = file_inode(dst_file);
3228416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
32292b3909f8SDarrick J. Wong 	ssize_t res;
3230416161dbSMark Fasheh 
32312b3909f8SDarrick J. Wong 	if (olen > BTRFS_MAX_DEDUPE_LEN)
32322b3909f8SDarrick J. Wong 		olen = BTRFS_MAX_DEDUPE_LEN;
3233416161dbSMark Fasheh 
323409cbfeafSKirill A. Shutemov 	if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3235416161dbSMark Fasheh 		/*
3236416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3237416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3238416161dbSMark Fasheh 		 * this situation without an update.
3239416161dbSMark Fasheh 		 */
32402b3909f8SDarrick J. Wong 		return -EINVAL;
3241416161dbSMark Fasheh 	}
3242416161dbSMark Fasheh 
32432b3909f8SDarrick J. Wong 	res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
32442b3909f8SDarrick J. Wong 	if (res)
32452b3909f8SDarrick J. Wong 		return res;
32462b3909f8SDarrick J. Wong 	return olen;
3247416161dbSMark Fasheh }
3248416161dbSMark Fasheh 
3249f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3250f82a9901SFilipe Manana 				     struct inode *inode,
3251f82a9901SFilipe Manana 				     u64 endoff,
3252f82a9901SFilipe Manana 				     const u64 destoff,
32531c919a5eSMark Fasheh 				     const u64 olen,
32541c919a5eSMark Fasheh 				     int no_time_update)
3255f82a9901SFilipe Manana {
3256f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3257f82a9901SFilipe Manana 	int ret;
3258f82a9901SFilipe Manana 
3259f82a9901SFilipe Manana 	inode_inc_iversion(inode);
32601c919a5eSMark Fasheh 	if (!no_time_update)
3261c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3262f82a9901SFilipe Manana 	/*
3263f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3264f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3265f82a9901SFilipe Manana 	 */
3266f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3267f82a9901SFilipe Manana 		endoff = destoff + olen;
3268f82a9901SFilipe Manana 	if (endoff > inode->i_size)
32696ef06d27SNikolay Borisov 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3270f82a9901SFilipe Manana 
3271f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3272f82a9901SFilipe Manana 	if (ret) {
327366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32743a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3275f82a9901SFilipe Manana 		goto out;
3276f82a9901SFilipe Manana 	}
32773a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
3278f82a9901SFilipe Manana out:
3279f82a9901SFilipe Manana 	return ret;
3280f82a9901SFilipe Manana }
3281f82a9901SFilipe Manana 
3282a2f392e4SNikolay Borisov static void clone_update_extent_map(struct btrfs_inode *inode,
32837ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
32847ffbb598SFilipe Manana 				    const struct btrfs_path *path,
32857ffbb598SFilipe Manana 				    const u64 hole_offset,
32867ffbb598SFilipe Manana 				    const u64 hole_len)
32877ffbb598SFilipe Manana {
3288a2f392e4SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
32897ffbb598SFilipe Manana 	struct extent_map *em;
32907ffbb598SFilipe Manana 	int ret;
32917ffbb598SFilipe Manana 
32927ffbb598SFilipe Manana 	em = alloc_extent_map();
32937ffbb598SFilipe Manana 	if (!em) {
3294a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
32957ffbb598SFilipe Manana 		return;
32967ffbb598SFilipe Manana 	}
32977ffbb598SFilipe Manana 
329814f59796SFilipe Manana 	if (path) {
329914f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
330014f59796SFilipe Manana 
330114f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
330214f59796SFilipe Manana 				    struct btrfs_file_extent_item);
3303a2f392e4SNikolay Borisov 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
33047ffbb598SFilipe Manana 		em->generation = -1;
33057ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
33067ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
33077ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3308a2f392e4SNikolay Borisov 					&inode->runtime_flags);
33097ffbb598SFilipe Manana 	} else {
33107ffbb598SFilipe Manana 		em->start = hole_offset;
33117ffbb598SFilipe Manana 		em->len = hole_len;
33127ffbb598SFilipe Manana 		em->ram_bytes = em->len;
33137ffbb598SFilipe Manana 		em->orig_start = hole_offset;
33147ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
33157ffbb598SFilipe Manana 		em->block_len = 0;
33167ffbb598SFilipe Manana 		em->orig_block_len = 0;
33177ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
33187ffbb598SFilipe Manana 		em->generation = trans->transid;
33197ffbb598SFilipe Manana 	}
33207ffbb598SFilipe Manana 
33217ffbb598SFilipe Manana 	while (1) {
33227ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
33237ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
33247ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
33257ffbb598SFilipe Manana 		if (ret != -EEXIST) {
33267ffbb598SFilipe Manana 			free_extent_map(em);
33277ffbb598SFilipe Manana 			break;
33287ffbb598SFilipe Manana 		}
3329a2f392e4SNikolay Borisov 		btrfs_drop_extent_cache(inode, em->start,
33307ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
33317ffbb598SFilipe Manana 	}
33327ffbb598SFilipe Manana 
3333ee39b432SDavid Sterba 	if (ret)
3334a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
33357ffbb598SFilipe Manana }
33367ffbb598SFilipe Manana 
33378039d87dSFilipe Manana /*
33388039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
33398039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
33408039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
33418039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
33428039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
33438039d87dSFilipe Manana  *
33448039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
33458039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
33468039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
33478039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
33488039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
33498039d87dSFilipe Manana  * i_mutex, which we are holding here).
33508039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
33518039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
33528039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
33538039d87dSFilipe Manana  *
33548039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
33558039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
33568039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
33578039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
33588039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
33598039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
33608039d87dSFilipe Manana  * the former.
33618039d87dSFilipe Manana  */
33624a0ab9d7SDavid Sterba static int clone_copy_inline_extent(struct inode *dst,
33638039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
33648039d87dSFilipe Manana 				    struct btrfs_path *path,
33658039d87dSFilipe Manana 				    struct btrfs_key *new_key,
33668039d87dSFilipe Manana 				    const u64 drop_start,
33678039d87dSFilipe Manana 				    const u64 datal,
33688039d87dSFilipe Manana 				    const u64 skip,
33698039d87dSFilipe Manana 				    const u64 size,
33708039d87dSFilipe Manana 				    char *inline_data)
33718039d87dSFilipe Manana {
33720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
33738039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
33748039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
33750b246afaSJeff Mahoney 				      fs_info->sectorsize);
33768039d87dSFilipe Manana 	int ret;
33778039d87dSFilipe Manana 	struct btrfs_key key;
33788039d87dSFilipe Manana 
33798039d87dSFilipe Manana 	if (new_key->offset > 0)
33808039d87dSFilipe Manana 		return -EOPNOTSUPP;
33818039d87dSFilipe Manana 
33824a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(dst));
33838039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
33848039d87dSFilipe Manana 	key.offset = 0;
33858039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
33868039d87dSFilipe Manana 	if (ret < 0) {
33878039d87dSFilipe Manana 		return ret;
33888039d87dSFilipe Manana 	} else if (ret > 0) {
33898039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
33908039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
33918039d87dSFilipe Manana 			if (ret < 0)
33928039d87dSFilipe Manana 				return ret;
33938039d87dSFilipe Manana 			else if (ret > 0)
33948039d87dSFilipe Manana 				goto copy_inline_extent;
33958039d87dSFilipe Manana 		}
33968039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
33974a0cc7caSNikolay Borisov 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
33988039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
33998039d87dSFilipe Manana 			ASSERT(key.offset > 0);
34008039d87dSFilipe Manana 			return -EOPNOTSUPP;
34018039d87dSFilipe Manana 		}
34028039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
34038039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
34048039d87dSFilipe Manana 		u64 ext_len;
34058039d87dSFilipe Manana 
34068039d87dSFilipe Manana 		/*
34078039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
34088039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
34098039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
34108039d87dSFilipe Manana 		 */
34118039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
34128039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
34138039d87dSFilipe Manana 		/*
34148039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
34158039d87dSFilipe Manana 		 * following it.
34168039d87dSFilipe Manana 		 */
34178039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
34188039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
34198039d87dSFilipe Manana 			goto copy_inline_extent;
34208039d87dSFilipe Manana 
34218039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
34228039d87dSFilipe Manana 		if (ext_len > aligned_end)
34238039d87dSFilipe Manana 			return -EOPNOTSUPP;
34248039d87dSFilipe Manana 
34258039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
34268039d87dSFilipe Manana 		if (ret < 0) {
34278039d87dSFilipe Manana 			return ret;
34288039d87dSFilipe Manana 		} else if (ret == 0) {
34298039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
34308039d87dSFilipe Manana 					      path->slots[0]);
34314a0cc7caSNikolay Borisov 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
34328039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
34338039d87dSFilipe Manana 				return -EOPNOTSUPP;
34348039d87dSFilipe Manana 		}
34358039d87dSFilipe Manana 	}
34368039d87dSFilipe Manana 
34378039d87dSFilipe Manana copy_inline_extent:
34388039d87dSFilipe Manana 	/*
34398039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
34408039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
34418039d87dSFilipe Manana 	 */
34428039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
34438039d87dSFilipe Manana 		/*
34448039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
34458039d87dSFilipe Manana 		 * This would require copying the data from the source inline
34468039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
34478039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
34488039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
34498039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
34508039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
34518039d87dSFilipe Manana 		 * inline extent).
34528039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
34538039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
34548039d87dSFilipe Manana 		 */
34558039d87dSFilipe Manana 		return -EOPNOTSUPP;
34568039d87dSFilipe Manana 	}
34578039d87dSFilipe Manana 
34588039d87dSFilipe Manana 	btrfs_release_path(path);
34598039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
34608039d87dSFilipe Manana 	if (ret)
34618039d87dSFilipe Manana 		return ret;
34628039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
34638039d87dSFilipe Manana 	if (ret)
34648039d87dSFilipe Manana 		return ret;
34658039d87dSFilipe Manana 
34668039d87dSFilipe Manana 	if (skip) {
34678039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
34688039d87dSFilipe Manana 
34698039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
34708039d87dSFilipe Manana 	}
34718039d87dSFilipe Manana 
34728039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
34738039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
34748039d87dSFilipe Manana 						  path->slots[0]),
34758039d87dSFilipe Manana 			    size);
34768039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
34778039d87dSFilipe Manana 
34788039d87dSFilipe Manana 	return 0;
34798039d87dSFilipe Manana }
34808039d87dSFilipe Manana 
348132b7c687SMark Fasheh /**
348232b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
348332b7c687SMark Fasheh  *
348432b7c687SMark Fasheh  * @src: Inode to clone from
348532b7c687SMark Fasheh  * @inode: Inode to clone to
348632b7c687SMark Fasheh  * @off: Offset within source to start clone from
348732b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
34881c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
348932b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
34901c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
349132b7c687SMark Fasheh  */
349232b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3493f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
34941c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3495f46b5a66SChristoph Hellwig {
34960b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3497f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
349832b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3499f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
350032b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
350132b7c687SMark Fasheh 	char *buf = NULL;
3502ae01a0abSYan Zheng 	struct btrfs_key key;
3503f46b5a66SChristoph Hellwig 	u32 nritems;
3504f46b5a66SChristoph Hellwig 	int slot;
3505ae01a0abSYan Zheng 	int ret;
3506f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3507f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3508ae01a0abSYan Zheng 
3509ae01a0abSYan Zheng 	ret = -ENOMEM;
3510752ade68SMichal Hocko 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3511ae01a0abSYan Zheng 	if (!buf)
351232b7c687SMark Fasheh 		return ret;
3513ae01a0abSYan Zheng 
3514ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3515ae01a0abSYan Zheng 	if (!path) {
351615351955SDavid Sterba 		kvfree(buf);
351732b7c687SMark Fasheh 		return ret;
3518ae01a0abSYan Zheng 	}
351932b7c687SMark Fasheh 
3520e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3521c5c9cd4dSSage Weil 	/* clone data */
35224a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(src));
3523ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
35242c463823SFilipe Manana 	key.offset = off;
3525f46b5a66SChristoph Hellwig 
3526f46b5a66SChristoph Hellwig 	while (1) {
3527de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3528df858e76SFilipe Manana 
3529f46b5a66SChristoph Hellwig 		/*
3530f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3531f46b5a66SChristoph Hellwig 		 * tree.
3532f46b5a66SChristoph Hellwig 		 */
3533e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3534362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3535362a20c5SDavid Sterba 				0, 0);
3536f46b5a66SChristoph Hellwig 		if (ret < 0)
3537f46b5a66SChristoph Hellwig 			goto out;
35382c463823SFilipe Manana 		/*
35392c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
35402c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
35412c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
35422c463823SFilipe Manana 		 */
35432c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
35442c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
35452c463823SFilipe Manana 					      path->slots[0] - 1);
35462c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
35472c463823SFilipe Manana 				path->slots[0]--;
35482c463823SFilipe Manana 		}
3549f46b5a66SChristoph Hellwig 
3550ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3551e4355f34SFilipe David Borba Manana process_slot:
3552ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3553362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3554f46b5a66SChristoph Hellwig 			if (ret < 0)
3555f46b5a66SChristoph Hellwig 				goto out;
3556f46b5a66SChristoph Hellwig 			if (ret > 0)
3557f46b5a66SChristoph Hellwig 				break;
3558ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3559f46b5a66SChristoph Hellwig 		}
3560f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3561f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3562f46b5a66SChristoph Hellwig 
3563ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3564962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
35654a0cc7caSNikolay Borisov 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3566f46b5a66SChristoph Hellwig 			break;
3567f46b5a66SChristoph Hellwig 
3568962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3569c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3570c5c9cd4dSSage Weil 			int type;
357131840ae1SZheng Yan 			u32 size;
357231840ae1SZheng Yan 			struct btrfs_key new_key;
3573c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3574c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3575c5c9cd4dSSage Weil 			u8 comp;
3576f82a9901SFilipe Manana 			u64 drop_start;
357731840ae1SZheng Yan 
3578c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3579c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3580c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3581c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3582c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3583c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3584d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3585d397712bSChris Mason 								      extent);
3586d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3587d397712bSChris Mason 								 extent);
3588c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3589d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3590d397712bSChris Mason 								    extent);
3591c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3592c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3593c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3594c5c9cd4dSSage Weil 								    extent);
3595c5c9cd4dSSage Weil 			}
359631840ae1SZheng Yan 
35972c463823SFilipe Manana 			/*
35982c463823SFilipe Manana 			 * The first search might have left us at an extent
35992c463823SFilipe Manana 			 * item that ends before our target range's start, can
36002c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
36012c463823SFilipe Manana 			 */
36022c463823SFilipe Manana 			if (key.offset + datal <= off) {
3603e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3604e4355f34SFilipe David Borba Manana 				goto process_slot;
36052c463823SFilipe Manana 			} else if (key.offset >= off + len) {
36062c463823SFilipe Manana 				break;
3607e4355f34SFilipe David Borba Manana 			}
3608df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3609e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3610e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3611e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3612e4355f34SFilipe David Borba Manana 					   size);
3613e4355f34SFilipe David Borba Manana 
3614e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3615e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3616c5c9cd4dSSage Weil 
361731840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
36184a0cc7caSNikolay Borisov 			new_key.objectid = btrfs_ino(BTRFS_I(inode));
36194d728ec7SLi Zefan 			if (off <= key.offset)
3620c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
36214d728ec7SLi Zefan 			else
36224d728ec7SLi Zefan 				new_key.offset = destoff;
3623c5c9cd4dSSage Weil 
3624b6f3409bSSage Weil 			/*
3625f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3626f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3627f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3628f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3629f82a9901SFilipe Manana 			 * partially overlaps it).
3630f82a9901SFilipe Manana 			 */
3631f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3632f82a9901SFilipe Manana 				drop_start = last_dest_end;
3633f82a9901SFilipe Manana 			else
3634f82a9901SFilipe Manana 				drop_start = new_key.offset;
3635f82a9901SFilipe Manana 
3636f82a9901SFilipe Manana 			/*
3637b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3638b6f3409bSSage Weil 			 * 1 - add new extent
3639b6f3409bSSage Weil 			 * 1 - inode update
3640b6f3409bSSage Weil 			 */
3641b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3642a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3643a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3644a22285a6SYan, Zheng 				goto out;
3645a22285a6SYan, Zheng 			}
3646a22285a6SYan, Zheng 
3647c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3648c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3649d72c0842SLi Zefan 				/*
3650d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3651d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3652d72c0842SLi Zefan 				 */
3653d72c0842SLi Zefan 
365493915584SAntonio Ospite 				/* subtract range b */
3655d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3656d72c0842SLi Zefan 					datal = off + len - key.offset;
3657d72c0842SLi Zefan 
365893915584SAntonio Ospite 				/* subtract range a */
3659a22285a6SYan, Zheng 				if (off > key.offset) {
3660a22285a6SYan, Zheng 					datao += off - key.offset;
3661a22285a6SYan, Zheng 					datal -= off - key.offset;
3662a22285a6SYan, Zheng 				}
3663a22285a6SYan, Zheng 
36645dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3665f82a9901SFilipe Manana 							 drop_start,
3666a22285a6SYan, Zheng 							 new_key.offset + datal,
36672671485dSJosef Bacik 							 1);
366879787eaaSJeff Mahoney 				if (ret) {
36693f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
367000fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
367166642832SJeff Mahoney 									ret);
36723a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
367379787eaaSJeff Mahoney 					goto out;
367479787eaaSJeff Mahoney 				}
3675a22285a6SYan, Zheng 
367631840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
367731840ae1SZheng Yan 							      &new_key, size);
367879787eaaSJeff Mahoney 				if (ret) {
367966642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
36803a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
368179787eaaSJeff Mahoney 					goto out;
368279787eaaSJeff Mahoney 				}
368331840ae1SZheng Yan 
368431840ae1SZheng Yan 				leaf = path->nodes[0];
368531840ae1SZheng Yan 				slot = path->slots[0];
368631840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
368731840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
368831840ae1SZheng Yan 					    size);
3689ae01a0abSYan Zheng 
3690f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3691f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3692c5c9cd4dSSage Weil 
3693c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3694c5c9cd4dSSage Weil 				if (!disko)
3695c5c9cd4dSSage Weil 					datao = 0;
3696c5c9cd4dSSage Weil 
3697c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3698c5c9cd4dSSage Weil 							     datao);
3699c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3700c5c9cd4dSSage Weil 								datal);
3701fcebe456SJosef Bacik 
3702c5c9cd4dSSage Weil 				if (disko) {
3703c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
37042ff7e61eSJeff Mahoney 					ret = btrfs_inc_extent_ref(trans,
37052ff7e61eSJeff Mahoney 							fs_info,
37065d4f98a2SYan Zheng 							disko, diskl, 0,
3707f46b5a66SChristoph Hellwig 							root->root_key.objectid,
37084a0cc7caSNikolay Borisov 							btrfs_ino(BTRFS_I(inode)),
3709b06c4bf5SFilipe Manana 							new_key.offset - datao);
371079787eaaSJeff Mahoney 					if (ret) {
371179787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
371279787eaaSJeff Mahoney 									ret);
37133a45bb20SJeff Mahoney 						btrfs_end_transaction(trans);
371479787eaaSJeff Mahoney 						goto out;
371579787eaaSJeff Mahoney 
371679787eaaSJeff Mahoney 					}
3717f46b5a66SChristoph Hellwig 				}
3718c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3719c5c9cd4dSSage Weil 				u64 skip = 0;
3720c5c9cd4dSSage Weil 				u64 trim = 0;
3721ed958762SFilipe Manana 
3722c5c9cd4dSSage Weil 				if (off > key.offset) {
3723c5c9cd4dSSage Weil 					skip = off - key.offset;
3724c5c9cd4dSSage Weil 					new_key.offset += skip;
372531840ae1SZheng Yan 				}
3726d397712bSChris Mason 
3727c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3728c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3729d397712bSChris Mason 
3730c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3731c5c9cd4dSSage Weil 					ret = -EINVAL;
37323a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
3733c5c9cd4dSSage Weil 					goto out;
373431840ae1SZheng Yan 				}
3735c5c9cd4dSSage Weil 				size -= skip + trim;
3736c5c9cd4dSSage Weil 				datal -= skip + trim;
3737a22285a6SYan, Zheng 
37384a0ab9d7SDavid Sterba 				ret = clone_copy_inline_extent(inode,
37398039d87dSFilipe Manana 							       trans, path,
37408039d87dSFilipe Manana 							       &new_key,
3741f82a9901SFilipe Manana 							       drop_start,
37428039d87dSFilipe Manana 							       datal,
37438039d87dSFilipe Manana 							       skip, size, buf);
374479787eaaSJeff Mahoney 				if (ret) {
37453f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
37463a29bc09SChris Mason 						btrfs_abort_transaction(trans,
374779787eaaSJeff Mahoney 									ret);
37483a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
374979787eaaSJeff Mahoney 					goto out;
375079787eaaSJeff Mahoney 				}
3751c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3752c5c9cd4dSSage Weil 				slot = path->slots[0];
3753c5c9cd4dSSage Weil 			}
3754c5c9cd4dSSage Weil 
37557ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
37567ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
3757a2f392e4SNikolay Borisov 				clone_update_extent_map(BTRFS_I(inode), trans,
375814f59796SFilipe Manana 						NULL, drop_start,
37597ffbb598SFilipe Manana 						new_key.offset - drop_start);
37607ffbb598SFilipe Manana 
3761a2f392e4SNikolay Borisov 			clone_update_extent_map(BTRFS_I(inode), trans,
3762a2f392e4SNikolay Borisov 					path, 0, 0);
37637ffbb598SFilipe Manana 
3764c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3765b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3766c5c9cd4dSSage Weil 
376762e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
37680b246afaSJeff Mahoney 					      fs_info->sectorsize);
3769f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3770f82a9901SFilipe Manana 							last_dest_end,
37711c919a5eSMark Fasheh 							destoff, olen,
37721c919a5eSMark Fasheh 							no_time_update);
3773f82a9901SFilipe Manana 			if (ret)
377479787eaaSJeff Mahoney 				goto out;
37752c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
37762c463823SFilipe Manana 				break;
3777a22285a6SYan, Zheng 		}
3778b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3779df858e76SFilipe Manana 		key.offset = next_key_min_offset;
378069ae5e44SWang Xiaoguang 
378169ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
378269ae5e44SWang Xiaoguang 			ret = -EINTR;
378369ae5e44SWang Xiaoguang 			goto out;
378469ae5e44SWang Xiaoguang 		}
3785ae01a0abSYan Zheng 	}
3786f46b5a66SChristoph Hellwig 	ret = 0;
378732b7c687SMark Fasheh 
3788f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3789f82a9901SFilipe Manana 		/*
3790f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3791f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3792f82a9901SFilipe Manana 		 */
3793b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3794f82a9901SFilipe Manana 
3795f82a9901SFilipe Manana 		/*
3796f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3797f82a9901SFilipe Manana 		 * 1 - inode update
3798f82a9901SFilipe Manana 		 */
3799f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3800f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3801f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3802f82a9901SFilipe Manana 			goto out;
3803f82a9901SFilipe Manana 		}
3804f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3805f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3806f82a9901SFilipe Manana 		if (ret) {
3807f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
380866642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
38093a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
3810f82a9901SFilipe Manana 			goto out;
3811f82a9901SFilipe Manana 		}
3812a2f392e4SNikolay Borisov 		clone_update_extent_map(BTRFS_I(inode), trans, NULL,
3813a2f392e4SNikolay Borisov 				last_dest_end,
381414f59796SFilipe Manana 				destoff + len - last_dest_end);
3815f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
38161c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3817f82a9901SFilipe Manana 	}
3818f82a9901SFilipe Manana 
3819f46b5a66SChristoph Hellwig out:
382032b7c687SMark Fasheh 	btrfs_free_path(path);
382115351955SDavid Sterba 	kvfree(buf);
382232b7c687SMark Fasheh 	return ret;
382332b7c687SMark Fasheh }
382432b7c687SMark Fasheh 
38253db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
382632b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
382732b7c687SMark Fasheh {
382854563d41SAl Viro 	struct inode *inode = file_inode(file);
38293db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
38300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
383132b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
383232b7c687SMark Fasheh 	int ret;
383332b7c687SMark Fasheh 	u64 len = olen;
38340b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
38353db11b2eSZach Brown 	int same_inode = src == inode;
383632b7c687SMark Fasheh 
383732b7c687SMark Fasheh 	/*
383832b7c687SMark Fasheh 	 * TODO:
383932b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
384032b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
384132b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
384232b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
384300fdf13aSLiu Bo 	 *
384400fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
384500fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
384632b7c687SMark Fasheh 	 */
384732b7c687SMark Fasheh 
384832b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
384932b7c687SMark Fasheh 		return -EROFS;
385032b7c687SMark Fasheh 
38513db11b2eSZach Brown 	if (file_src->f_path.mnt != file->f_path.mnt ||
38523db11b2eSZach Brown 	    src->i_sb != inode->i_sb)
38533db11b2eSZach Brown 		return -EXDEV;
385432b7c687SMark Fasheh 
385532b7c687SMark Fasheh 	/* don't make the dst file partly checksummed */
385632b7c687SMark Fasheh 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
385732b7c687SMark Fasheh 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
38583db11b2eSZach Brown 		return -EINVAL;
385932b7c687SMark Fasheh 
386032b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
38613db11b2eSZach Brown 		return -EISDIR;
386232b7c687SMark Fasheh 
386332b7c687SMark Fasheh 	if (!same_inode) {
3864293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
386532b7c687SMark Fasheh 	} else {
38665955102cSAl Viro 		inode_lock(src);
386732b7c687SMark Fasheh 	}
386832b7c687SMark Fasheh 
386932b7c687SMark Fasheh 	/* determine range to clone */
387032b7c687SMark Fasheh 	ret = -EINVAL;
387132b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
387232b7c687SMark Fasheh 		goto out_unlock;
387332b7c687SMark Fasheh 	if (len == 0)
387432b7c687SMark Fasheh 		olen = len = src->i_size - off;
387532b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
387632b7c687SMark Fasheh 	if (off + len == src->i_size)
387732b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
387832b7c687SMark Fasheh 
3879ccccf3d6SFilipe Manana 	if (len == 0) {
3880ccccf3d6SFilipe Manana 		ret = 0;
3881ccccf3d6SFilipe Manana 		goto out_unlock;
3882ccccf3d6SFilipe Manana 	}
3883ccccf3d6SFilipe Manana 
388432b7c687SMark Fasheh 	/* verify the end result is block aligned */
388532b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
388632b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
388732b7c687SMark Fasheh 		goto out_unlock;
388832b7c687SMark Fasheh 
388932b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
389032b7c687SMark Fasheh 	if (same_inode) {
389132b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
389232b7c687SMark Fasheh 			goto out_unlock;
389332b7c687SMark Fasheh 	}
389432b7c687SMark Fasheh 
389532b7c687SMark Fasheh 	if (destoff > inode->i_size) {
389632b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
389732b7c687SMark Fasheh 		if (ret)
389832b7c687SMark Fasheh 			goto out_unlock;
389932b7c687SMark Fasheh 	}
390032b7c687SMark Fasheh 
3901c125b8bfSFilipe Manana 	/*
3902c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
3903c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
3904c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
3905c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
3906c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
3907c125b8bfSFilipe Manana 	 */
3908c125b8bfSFilipe Manana 	if (same_inode) {
3909c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3910c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
391132b7c687SMark Fasheh 
3912e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, lock_start, lock_len, true);
3913c125b8bfSFilipe Manana 	} else {
3914e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
3915e0bd70c6SFilipe Manana 					       true);
3916e0bd70c6SFilipe Manana 	}
3917e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3918e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3919e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
3920e0bd70c6SFilipe Manana 		goto out_unlock;
3921c125b8bfSFilipe Manana 	}
392232b7c687SMark Fasheh 
39231c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
392432b7c687SMark Fasheh 
3925c125b8bfSFilipe Manana 	if (same_inode) {
3926c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
3927c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
3928c125b8bfSFilipe Manana 
3929c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3930c125b8bfSFilipe Manana 	} else {
3931293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
3932c125b8bfSFilipe Manana 	}
3933c125b8bfSFilipe Manana 	/*
3934c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3935c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3936c125b8bfSFilipe Manana 	 */
393765bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
393809cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
393909cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
3940f46b5a66SChristoph Hellwig out_unlock:
3941293a8489SMark Fasheh 	if (!same_inode)
3942293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
3943293a8489SMark Fasheh 	else
39445955102cSAl Viro 		inode_unlock(src);
39453db11b2eSZach Brown 	return ret;
39463db11b2eSZach Brown }
39473db11b2eSZach Brown 
394804b38d60SChristoph Hellwig int btrfs_clone_file_range(struct file *src_file, loff_t off,
394904b38d60SChristoph Hellwig 		struct file *dst_file, loff_t destoff, u64 len)
39503db11b2eSZach Brown {
395104b38d60SChristoph Hellwig 	return btrfs_clone_files(dst_file, src_file, off, len, destoff);
3952c5c9cd4dSSage Weil }
3953c5c9cd4dSSage Weil 
3954f46b5a66SChristoph Hellwig /*
3955f46b5a66SChristoph Hellwig  * there are many ways the trans_start and trans_end ioctls can lead
3956f46b5a66SChristoph Hellwig  * to deadlocks.  They should only be used by applications that
3957f46b5a66SChristoph Hellwig  * basically own the machine, and have a very in depth understanding
3958f46b5a66SChristoph Hellwig  * of all the possible deadlocks and enospc problems.
3959f46b5a66SChristoph Hellwig  */
3960b2950863SChristoph Hellwig static long btrfs_ioctl_trans_start(struct file *file)
3961f46b5a66SChristoph Hellwig {
3962496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
39630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3964f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
3965f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
396623b5ec74SJosef Bacik 	struct btrfs_file_private *private;
39671ab86aedSSage Weil 	int ret;
39683558d4f8SNikolay Borisov 	static bool warned = false;
3969f46b5a66SChristoph Hellwig 
39701ab86aedSSage Weil 	ret = -EPERM;
3971df5b5520SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
3972f46b5a66SChristoph Hellwig 		goto out;
39731ab86aedSSage Weil 
39743558d4f8SNikolay Borisov 	if (!warned) {
39753558d4f8SNikolay Borisov 		btrfs_warn(fs_info,
39763558d4f8SNikolay Borisov 			"Userspace transaction mechanism is considered "
39773558d4f8SNikolay Borisov 			"deprecated and slated to be removed in 4.17. "
39783558d4f8SNikolay Borisov 			"If you have a valid use case please "
39793558d4f8SNikolay Borisov 			"speak up on the mailing list");
39803558d4f8SNikolay Borisov 		WARN_ON(1);
39813558d4f8SNikolay Borisov 		warned = true;
39823558d4f8SNikolay Borisov 	}
39833558d4f8SNikolay Borisov 
39841ab86aedSSage Weil 	ret = -EINPROGRESS;
398523b5ec74SJosef Bacik 	private = file->private_data;
398623b5ec74SJosef Bacik 	if (private && private->trans)
39871ab86aedSSage Weil 		goto out;
398823b5ec74SJosef Bacik 	if (!private) {
398923b5ec74SJosef Bacik 		private = kzalloc(sizeof(struct btrfs_file_private),
399023b5ec74SJosef Bacik 				  GFP_KERNEL);
399123b5ec74SJosef Bacik 		if (!private)
399223b5ec74SJosef Bacik 			return -ENOMEM;
399323b5ec74SJosef Bacik 		file->private_data = private;
399423b5ec74SJosef Bacik 	}
39959ca9ee09SSage Weil 
3996b83cc969SLi Zefan 	ret = -EROFS;
3997b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
3998b83cc969SLi Zefan 		goto out;
3999b83cc969SLi Zefan 
4000a561be71SAl Viro 	ret = mnt_want_write_file(file);
4001c146afadSYan Zheng 	if (ret)
4002c146afadSYan Zheng 		goto out;
4003c146afadSYan Zheng 
40040b246afaSJeff Mahoney 	atomic_inc(&fs_info->open_ioctl_trans);
40059ca9ee09SSage Weil 
4006f46b5a66SChristoph Hellwig 	ret = -ENOMEM;
40077a7eaa40SJosef Bacik 	trans = btrfs_start_ioctl_transaction(root);
4008abd30bb0STsutomu Itoh 	if (IS_ERR(trans))
40091ab86aedSSage Weil 		goto out_drop;
40101ab86aedSSage Weil 
401123b5ec74SJosef Bacik 	private->trans = trans;
40121ab86aedSSage Weil 	return 0;
40131ab86aedSSage Weil 
40141ab86aedSSage Weil out_drop:
40150b246afaSJeff Mahoney 	atomic_dec(&fs_info->open_ioctl_trans);
40162a79f17eSAl Viro 	mnt_drop_write_file(file);
4017f46b5a66SChristoph Hellwig out:
4018f46b5a66SChristoph Hellwig 	return ret;
4019f46b5a66SChristoph Hellwig }
4020f46b5a66SChristoph Hellwig 
40216ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
40226ef5ed0dSJosef Bacik {
4023496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
40240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
40256ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
40266ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
40276ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
40286ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
40296ef5ed0dSJosef Bacik 	struct btrfs_path *path;
40306ef5ed0dSJosef Bacik 	struct btrfs_key location;
40316ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
40326ef5ed0dSJosef Bacik 	u64 objectid = 0;
40336ef5ed0dSJosef Bacik 	u64 dir_id;
40343c04ce01SMiao Xie 	int ret;
40356ef5ed0dSJosef Bacik 
40366ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
40376ef5ed0dSJosef Bacik 		return -EPERM;
40386ef5ed0dSJosef Bacik 
40393c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
40403c04ce01SMiao Xie 	if (ret)
40413c04ce01SMiao Xie 		return ret;
40423c04ce01SMiao Xie 
40433c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
40443c04ce01SMiao Xie 		ret = -EFAULT;
40453c04ce01SMiao Xie 		goto out;
40463c04ce01SMiao Xie 	}
40476ef5ed0dSJosef Bacik 
40486ef5ed0dSJosef Bacik 	if (!objectid)
40491cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
40506ef5ed0dSJosef Bacik 
40516ef5ed0dSJosef Bacik 	location.objectid = objectid;
40526ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
40536ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
40546ef5ed0dSJosef Bacik 
40550b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
40563c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
40573c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
40583c04ce01SMiao Xie 		goto out;
40593c04ce01SMiao Xie 	}
40606ef5ed0dSJosef Bacik 
40616ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
40623c04ce01SMiao Xie 	if (!path) {
40633c04ce01SMiao Xie 		ret = -ENOMEM;
40643c04ce01SMiao Xie 		goto out;
40653c04ce01SMiao Xie 	}
40666ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
40676ef5ed0dSJosef Bacik 
40686ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
406998d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
40706ef5ed0dSJosef Bacik 		btrfs_free_path(path);
40713c04ce01SMiao Xie 		ret = PTR_ERR(trans);
40723c04ce01SMiao Xie 		goto out;
40736ef5ed0dSJosef Bacik 	}
40746ef5ed0dSJosef Bacik 
40750b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
40760b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
40776ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
4078cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
40796ef5ed0dSJosef Bacik 		btrfs_free_path(path);
40803a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
40810b246afaSJeff Mahoney 		btrfs_err(fs_info,
40825d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
40833c04ce01SMiao Xie 		ret = -ENOENT;
40843c04ce01SMiao Xie 		goto out;
40856ef5ed0dSJosef Bacik 	}
40866ef5ed0dSJosef Bacik 
40876ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
40886ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
40896ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
40906ef5ed0dSJosef Bacik 	btrfs_free_path(path);
40916ef5ed0dSJosef Bacik 
40920b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
40933a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
40943c04ce01SMiao Xie out:
40953c04ce01SMiao Xie 	mnt_drop_write_file(file);
40963c04ce01SMiao Xie 	return ret;
40976ef5ed0dSJosef Bacik }
40986ef5ed0dSJosef Bacik 
40995af3e8ccSStefan Behrens void btrfs_get_block_group_info(struct list_head *groups_list,
4100bf5fc093SJosef Bacik 				struct btrfs_ioctl_space_info *space)
4101bf5fc093SJosef Bacik {
4102bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4103bf5fc093SJosef Bacik 
4104bf5fc093SJosef Bacik 	space->total_bytes = 0;
4105bf5fc093SJosef Bacik 	space->used_bytes = 0;
4106bf5fc093SJosef Bacik 	space->flags = 0;
4107bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4108bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4109bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4110bf5fc093SJosef Bacik 		space->used_bytes +=
4111bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4112bf5fc093SJosef Bacik 	}
4113bf5fc093SJosef Bacik }
4114bf5fc093SJosef Bacik 
41152ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
41162ff7e61eSJeff Mahoney 				   void __user *arg)
41171406e432SJosef Bacik {
41181406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
41191406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
41201406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
41217fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
412213f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
41231406e432SJosef Bacik 	struct btrfs_space_info *info;
4124bf5fc093SJosef Bacik 	u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
4125bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_SYSTEM,
4126bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_METADATA,
4127bf5fc093SJosef Bacik 		       BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
4128bf5fc093SJosef Bacik 	int num_types = 4;
41297fde62bfSChris Mason 	int alloc_size;
41301406e432SJosef Bacik 	int ret = 0;
413151788b1bSDan Rosenberg 	u64 slot_count = 0;
4132bf5fc093SJosef Bacik 	int i, c;
41331406e432SJosef Bacik 
41341406e432SJosef Bacik 	if (copy_from_user(&space_args,
41351406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
41361406e432SJosef Bacik 			   sizeof(space_args)))
41371406e432SJosef Bacik 		return -EFAULT;
41381406e432SJosef Bacik 
4139bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4140bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4141bf5fc093SJosef Bacik 
4142bf5fc093SJosef Bacik 		info = NULL;
41437fde62bfSChris Mason 		rcu_read_lock();
41440b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4145bf5fc093SJosef Bacik 					list) {
4146bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4147bf5fc093SJosef Bacik 				info = tmp;
4148bf5fc093SJosef Bacik 				break;
4149bf5fc093SJosef Bacik 			}
4150bf5fc093SJosef Bacik 		}
41517fde62bfSChris Mason 		rcu_read_unlock();
41521406e432SJosef Bacik 
4153bf5fc093SJosef Bacik 		if (!info)
4154bf5fc093SJosef Bacik 			continue;
4155bf5fc093SJosef Bacik 
4156bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4157bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4158bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4159bf5fc093SJosef Bacik 				slot_count++;
4160bf5fc093SJosef Bacik 		}
4161bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4162bf5fc093SJosef Bacik 	}
4163bf5fc093SJosef Bacik 
416436523e95SDavid Sterba 	/*
416536523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
416636523e95SDavid Sterba 	 */
416736523e95SDavid Sterba 	slot_count++;
416836523e95SDavid Sterba 
41697fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
41707fde62bfSChris Mason 	if (space_args.space_slots == 0) {
41717fde62bfSChris Mason 		space_args.total_spaces = slot_count;
41727fde62bfSChris Mason 		goto out;
41737fde62bfSChris Mason 	}
4174bf5fc093SJosef Bacik 
417551788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4176bf5fc093SJosef Bacik 
41777fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4178bf5fc093SJosef Bacik 
41797fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
41807fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
41817fde62bfSChris Mason 	 */
418209cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
41837fde62bfSChris Mason 		return -ENOMEM;
41847fde62bfSChris Mason 
41857fde62bfSChris Mason 	space_args.total_spaces = 0;
41868d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
41877fde62bfSChris Mason 	if (!dest)
41887fde62bfSChris Mason 		return -ENOMEM;
41897fde62bfSChris Mason 	dest_orig = dest;
41907fde62bfSChris Mason 
41917fde62bfSChris Mason 	/* now we have a buffer to copy into */
4192bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4193bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4194bf5fc093SJosef Bacik 
419551788b1bSDan Rosenberg 		if (!slot_count)
419651788b1bSDan Rosenberg 			break;
419751788b1bSDan Rosenberg 
4198bf5fc093SJosef Bacik 		info = NULL;
41991406e432SJosef Bacik 		rcu_read_lock();
42000b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4201bf5fc093SJosef Bacik 					list) {
4202bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4203bf5fc093SJosef Bacik 				info = tmp;
42047fde62bfSChris Mason 				break;
4205bf5fc093SJosef Bacik 			}
4206bf5fc093SJosef Bacik 		}
4207bf5fc093SJosef Bacik 		rcu_read_unlock();
42087fde62bfSChris Mason 
4209bf5fc093SJosef Bacik 		if (!info)
4210bf5fc093SJosef Bacik 			continue;
4211bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4212bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4213bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
42145af3e8ccSStefan Behrens 				btrfs_get_block_group_info(
42155af3e8ccSStefan Behrens 					&info->block_groups[c], &space);
42167fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
42171406e432SJosef Bacik 				dest++;
42181406e432SJosef Bacik 				space_args.total_spaces++;
421951788b1bSDan Rosenberg 				slot_count--;
42201406e432SJosef Bacik 			}
422151788b1bSDan Rosenberg 			if (!slot_count)
422251788b1bSDan Rosenberg 				break;
4223bf5fc093SJosef Bacik 		}
4224bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4225bf5fc093SJosef Bacik 	}
42261406e432SJosef Bacik 
422736523e95SDavid Sterba 	/*
422836523e95SDavid Sterba 	 * Add global block reserve
422936523e95SDavid Sterba 	 */
423036523e95SDavid Sterba 	if (slot_count) {
42310b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
423236523e95SDavid Sterba 
423336523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
423436523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
423536523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
423636523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
423736523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
423836523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
423936523e95SDavid Sterba 		space_args.total_spaces++;
424036523e95SDavid Sterba 	}
424136523e95SDavid Sterba 
42422eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
42437fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
42447fde62bfSChris Mason 
42457fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
42467fde62bfSChris Mason 		ret = -EFAULT;
42477fde62bfSChris Mason 
42487fde62bfSChris Mason 	kfree(dest_orig);
42497fde62bfSChris Mason out:
42507fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
42511406e432SJosef Bacik 		ret = -EFAULT;
42521406e432SJosef Bacik 
42531406e432SJosef Bacik 	return ret;
42541406e432SJosef Bacik }
42551406e432SJosef Bacik 
4256f46b5a66SChristoph Hellwig /*
4257f46b5a66SChristoph Hellwig  * there are many ways the trans_start and trans_end ioctls can lead
4258f46b5a66SChristoph Hellwig  * to deadlocks.  They should only be used by applications that
4259f46b5a66SChristoph Hellwig  * basically own the machine, and have a very in depth understanding
4260f46b5a66SChristoph Hellwig  * of all the possible deadlocks and enospc problems.
4261f46b5a66SChristoph Hellwig  */
4262f46b5a66SChristoph Hellwig long btrfs_ioctl_trans_end(struct file *file)
4263f46b5a66SChristoph Hellwig {
4264496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4265f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
426623b5ec74SJosef Bacik 	struct btrfs_file_private *private = file->private_data;
4267f46b5a66SChristoph Hellwig 
426823b5ec74SJosef Bacik 	if (!private || !private->trans)
42691ab86aedSSage Weil 		return -EINVAL;
42709ca9ee09SSage Weil 
427123b5ec74SJosef Bacik 	btrfs_end_transaction(private->trans);
427223b5ec74SJosef Bacik 	private->trans = NULL;
42731ab86aedSSage Weil 
4274a4abeea4SJosef Bacik 	atomic_dec(&root->fs_info->open_ioctl_trans);
42759ca9ee09SSage Weil 
42762a79f17eSAl Viro 	mnt_drop_write_file(file);
42771ab86aedSSage Weil 	return 0;
4278f46b5a66SChristoph Hellwig }
4279f46b5a66SChristoph Hellwig 
42809a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
42819a8c28beSMiao Xie 					    void __user *argp)
428246204592SSage Weil {
428346204592SSage Weil 	struct btrfs_trans_handle *trans;
428446204592SSage Weil 	u64 transid;
4285db5b493aSTsutomu Itoh 	int ret;
428646204592SSage Weil 
4287d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4288ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4289ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
429098d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4291ff7c1d33SMiao Xie 
4292ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4293ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4294ff7c1d33SMiao Xie 		goto out;
4295ff7c1d33SMiao Xie 	}
429646204592SSage Weil 	transid = trans->transid;
42973a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction_async(trans, 0);
42988b2b2d3cSTsutomu Itoh 	if (ret) {
42993a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
4300db5b493aSTsutomu Itoh 		return ret;
43018b2b2d3cSTsutomu Itoh 	}
4302ff7c1d33SMiao Xie out:
430346204592SSage Weil 	if (argp)
430446204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
430546204592SSage Weil 			return -EFAULT;
430646204592SSage Weil 	return 0;
430746204592SSage Weil }
430846204592SSage Weil 
43092ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
43109a8c28beSMiao Xie 					   void __user *argp)
431146204592SSage Weil {
431246204592SSage Weil 	u64 transid;
431346204592SSage Weil 
431446204592SSage Weil 	if (argp) {
431546204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
431646204592SSage Weil 			return -EFAULT;
431746204592SSage Weil 	} else {
431846204592SSage Weil 		transid = 0;  /* current trans */
431946204592SSage Weil 	}
43202ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
432146204592SSage Weil }
432246204592SSage Weil 
4323b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4324475f6387SJan Schmidt {
43250b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4326475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4327b8e95489SMiao Xie 	int ret;
4328475f6387SJan Schmidt 
4329475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4330475f6387SJan Schmidt 		return -EPERM;
4331475f6387SJan Schmidt 
4332475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4333475f6387SJan Schmidt 	if (IS_ERR(sa))
4334475f6387SJan Schmidt 		return PTR_ERR(sa);
4335475f6387SJan Schmidt 
4336b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4337b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4338b8e95489SMiao Xie 		if (ret)
4339b8e95489SMiao Xie 			goto out;
4340b8e95489SMiao Xie 	}
4341b8e95489SMiao Xie 
43420b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
434363a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
434463a212abSStefan Behrens 			      0);
4345475f6387SJan Schmidt 
4346475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4347475f6387SJan Schmidt 		ret = -EFAULT;
4348475f6387SJan Schmidt 
4349b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4350b8e95489SMiao Xie 		mnt_drop_write_file(file);
4351b8e95489SMiao Xie out:
4352475f6387SJan Schmidt 	kfree(sa);
4353475f6387SJan Schmidt 	return ret;
4354475f6387SJan Schmidt }
4355475f6387SJan Schmidt 
43562ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4357475f6387SJan Schmidt {
4358475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4359475f6387SJan Schmidt 		return -EPERM;
4360475f6387SJan Schmidt 
43612ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4362475f6387SJan Schmidt }
4363475f6387SJan Schmidt 
43642ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4365475f6387SJan Schmidt 				       void __user *arg)
4366475f6387SJan Schmidt {
4367475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4368475f6387SJan Schmidt 	int ret;
4369475f6387SJan Schmidt 
4370475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4371475f6387SJan Schmidt 		return -EPERM;
4372475f6387SJan Schmidt 
4373475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4374475f6387SJan Schmidt 	if (IS_ERR(sa))
4375475f6387SJan Schmidt 		return PTR_ERR(sa);
4376475f6387SJan Schmidt 
43772ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4378475f6387SJan Schmidt 
4379475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4380475f6387SJan Schmidt 		ret = -EFAULT;
4381475f6387SJan Schmidt 
4382475f6387SJan Schmidt 	kfree(sa);
4383475f6387SJan Schmidt 	return ret;
4384475f6387SJan Schmidt }
4385475f6387SJan Schmidt 
43862ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4387b27f7c0cSDavid Sterba 				      void __user *arg)
4388c11d2c23SStefan Behrens {
4389c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4390c11d2c23SStefan Behrens 	int ret;
4391c11d2c23SStefan Behrens 
4392c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4393c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4394c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4395c11d2c23SStefan Behrens 
4396b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4397b27f7c0cSDavid Sterba 		kfree(sa);
4398b27f7c0cSDavid Sterba 		return -EPERM;
4399b27f7c0cSDavid Sterba 	}
4400b27f7c0cSDavid Sterba 
44012ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4402c11d2c23SStefan Behrens 
4403c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4404c11d2c23SStefan Behrens 		ret = -EFAULT;
4405c11d2c23SStefan Behrens 
4406c11d2c23SStefan Behrens 	kfree(sa);
4407c11d2c23SStefan Behrens 	return ret;
4408c11d2c23SStefan Behrens }
4409c11d2c23SStefan Behrens 
44102ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
44112ff7e61eSJeff Mahoney 				    void __user *arg)
44123f6bcfbdSStefan Behrens {
44133f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
44143f6bcfbdSStefan Behrens 	int ret;
44153f6bcfbdSStefan Behrens 
44163f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
44173f6bcfbdSStefan Behrens 		return -EPERM;
44183f6bcfbdSStefan Behrens 
44193f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
44203f6bcfbdSStefan Behrens 	if (IS_ERR(p))
44213f6bcfbdSStefan Behrens 		return PTR_ERR(p);
44223f6bcfbdSStefan Behrens 
44233f6bcfbdSStefan Behrens 	switch (p->cmd) {
44243f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
44250b246afaSJeff Mahoney 		if (fs_info->sb->s_flags & MS_RDONLY) {
4426adfa97cbSIlya Dryomov 			ret = -EROFS;
4427adfa97cbSIlya Dryomov 			goto out;
4428adfa97cbSIlya Dryomov 		}
4429171938e5SDavid Sterba 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4430e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
44313f6bcfbdSStefan Behrens 		} else {
44322ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4433171938e5SDavid Sterba 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
44343f6bcfbdSStefan Behrens 		}
44353f6bcfbdSStefan Behrens 		break;
44363f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
44370b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
44383f6bcfbdSStefan Behrens 		ret = 0;
44393f6bcfbdSStefan Behrens 		break;
44403f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
44410b246afaSJeff Mahoney 		ret = btrfs_dev_replace_cancel(fs_info, p);
44423f6bcfbdSStefan Behrens 		break;
44433f6bcfbdSStefan Behrens 	default:
44443f6bcfbdSStefan Behrens 		ret = -EINVAL;
44453f6bcfbdSStefan Behrens 		break;
44463f6bcfbdSStefan Behrens 	}
44473f6bcfbdSStefan Behrens 
44483f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
44493f6bcfbdSStefan Behrens 		ret = -EFAULT;
4450adfa97cbSIlya Dryomov out:
44513f6bcfbdSStefan Behrens 	kfree(p);
44523f6bcfbdSStefan Behrens 	return ret;
44533f6bcfbdSStefan Behrens }
44543f6bcfbdSStefan Behrens 
4455d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4456d7728c96SJan Schmidt {
4457d7728c96SJan Schmidt 	int ret = 0;
4458d7728c96SJan Schmidt 	int i;
4459740c3d22SChris Mason 	u64 rel_ptr;
4460d7728c96SJan Schmidt 	int size;
4461806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4462d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4463d7728c96SJan Schmidt 	struct btrfs_path *path;
4464d7728c96SJan Schmidt 
446582b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4466d7728c96SJan Schmidt 		return -EPERM;
4467d7728c96SJan Schmidt 
4468d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4469d7728c96SJan Schmidt 	if (!path) {
4470d7728c96SJan Schmidt 		ret = -ENOMEM;
4471d7728c96SJan Schmidt 		goto out;
4472d7728c96SJan Schmidt 	}
4473d7728c96SJan Schmidt 
4474d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4475d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4476d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4477d7728c96SJan Schmidt 		ipa = NULL;
4478d7728c96SJan Schmidt 		goto out;
4479d7728c96SJan Schmidt 	}
4480d7728c96SJan Schmidt 
4481d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4482d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4483d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4484d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4485d7728c96SJan Schmidt 		ipath = NULL;
4486d7728c96SJan Schmidt 		goto out;
4487d7728c96SJan Schmidt 	}
4488d7728c96SJan Schmidt 
4489d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4490d7728c96SJan Schmidt 	if (ret < 0)
4491d7728c96SJan Schmidt 		goto out;
4492d7728c96SJan Schmidt 
4493d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4494745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4495745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4496740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4497d7728c96SJan Schmidt 	}
4498d7728c96SJan Schmidt 
4499745c4d8eSJeff Mahoney 	ret = copy_to_user((void *)(unsigned long)ipa->fspath,
4500745c4d8eSJeff Mahoney 			   (void *)(unsigned long)ipath->fspath, size);
4501d7728c96SJan Schmidt 	if (ret) {
4502d7728c96SJan Schmidt 		ret = -EFAULT;
4503d7728c96SJan Schmidt 		goto out;
4504d7728c96SJan Schmidt 	}
4505d7728c96SJan Schmidt 
4506d7728c96SJan Schmidt out:
4507d7728c96SJan Schmidt 	btrfs_free_path(path);
4508d7728c96SJan Schmidt 	free_ipath(ipath);
4509d7728c96SJan Schmidt 	kfree(ipa);
4510d7728c96SJan Schmidt 
4511d7728c96SJan Schmidt 	return ret;
4512d7728c96SJan Schmidt }
4513d7728c96SJan Schmidt 
4514d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4515d7728c96SJan Schmidt {
4516d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4517d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4518d7728c96SJan Schmidt 
4519d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4520d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4521d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4522d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4523d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4524d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4525d7728c96SJan Schmidt 	} else {
4526d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4527d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4528d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4529d7728c96SJan Schmidt 	}
4530d7728c96SJan Schmidt 
4531d7728c96SJan Schmidt 	return 0;
4532d7728c96SJan Schmidt }
4533d7728c96SJan Schmidt 
45342ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4535d7728c96SJan Schmidt 					void __user *arg)
4536d7728c96SJan Schmidt {
4537d7728c96SJan Schmidt 	int ret = 0;
4538d7728c96SJan Schmidt 	int size;
4539d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4540d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4541d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4542d7728c96SJan Schmidt 
4543d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4544d7728c96SJan Schmidt 		return -EPERM;
4545d7728c96SJan Schmidt 
4546d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
45477b9ea627SShailendra Verma 	if (IS_ERR(loi))
45487b9ea627SShailendra Verma 		return PTR_ERR(loi);
4549d7728c96SJan Schmidt 
4550d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4551d7728c96SJan Schmidt 	if (!path) {
4552d7728c96SJan Schmidt 		ret = -ENOMEM;
4553d7728c96SJan Schmidt 		goto out;
4554d7728c96SJan Schmidt 	}
4555d7728c96SJan Schmidt 
4556ee22184bSByongho Lee 	size = min_t(u32, loi->size, SZ_64K);
4557d7728c96SJan Schmidt 	inodes = init_data_container(size);
4558d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4559d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4560d7728c96SJan Schmidt 		inodes = NULL;
4561d7728c96SJan Schmidt 		goto out;
4562d7728c96SJan Schmidt 	}
4563d7728c96SJan Schmidt 
45642ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4565df031f07SLiu Bo 					  build_ino_list, inodes);
4566df031f07SLiu Bo 	if (ret == -EINVAL)
4567d7728c96SJan Schmidt 		ret = -ENOENT;
4568d7728c96SJan Schmidt 	if (ret < 0)
4569d7728c96SJan Schmidt 		goto out;
4570d7728c96SJan Schmidt 
4571745c4d8eSJeff Mahoney 	ret = copy_to_user((void *)(unsigned long)loi->inodes,
4572745c4d8eSJeff Mahoney 			   (void *)(unsigned long)inodes, size);
4573d7728c96SJan Schmidt 	if (ret)
4574d7728c96SJan Schmidt 		ret = -EFAULT;
4575d7728c96SJan Schmidt 
4576d7728c96SJan Schmidt out:
4577d7728c96SJan Schmidt 	btrfs_free_path(path);
4578f54de068SDavid Sterba 	kvfree(inodes);
4579d7728c96SJan Schmidt 	kfree(loi);
4580d7728c96SJan Schmidt 
4581d7728c96SJan Schmidt 	return ret;
4582d7728c96SJan Schmidt }
4583d7728c96SJan Schmidt 
458419a39dceSIlya Dryomov void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
4585c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4586c9e9f97bSIlya Dryomov {
4587c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4588c9e9f97bSIlya Dryomov 
4589c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4590c9e9f97bSIlya Dryomov 
4591837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_running))
4592837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4593837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4594837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4595a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4596a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4597837d5b6eSIlya Dryomov 
4598c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4599c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4600c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
460119a39dceSIlya Dryomov 
460219a39dceSIlya Dryomov 	if (lock) {
460319a39dceSIlya Dryomov 		spin_lock(&fs_info->balance_lock);
460419a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
460519a39dceSIlya Dryomov 		spin_unlock(&fs_info->balance_lock);
460619a39dceSIlya Dryomov 	} else {
460719a39dceSIlya Dryomov 		memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
460819a39dceSIlya Dryomov 	}
4609c9e9f97bSIlya Dryomov }
4610c9e9f97bSIlya Dryomov 
46119ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4612c9e9f97bSIlya Dryomov {
4613496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4614c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4615c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4616c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4617ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4618c9e9f97bSIlya Dryomov 	int ret;
4619c9e9f97bSIlya Dryomov 
4620c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4621c9e9f97bSIlya Dryomov 		return -EPERM;
4622c9e9f97bSIlya Dryomov 
4623e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
46249ba1f6e4SLiu Bo 	if (ret)
46259ba1f6e4SLiu Bo 		return ret;
46269ba1f6e4SLiu Bo 
4627ed0fb78fSIlya Dryomov again:
4628171938e5SDavid Sterba 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4629c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->volume_mutex);
4630c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4631ed0fb78fSIlya Dryomov 		need_unlock = true;
4632ed0fb78fSIlya Dryomov 		goto locked;
4633ed0fb78fSIlya Dryomov 	}
4634ed0fb78fSIlya Dryomov 
4635ed0fb78fSIlya Dryomov 	/*
463601327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4637ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4638ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4639ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4640ed0fb78fSIlya Dryomov 	 */
4641ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4642ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4643ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
4644ed0fb78fSIlya Dryomov 		if (!atomic_read(&fs_info->balance_running)) {
4645ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4646ed0fb78fSIlya Dryomov 			if (!mutex_trylock(&fs_info->volume_mutex))
4647ed0fb78fSIlya Dryomov 				goto again;
4648ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4649ed0fb78fSIlya Dryomov 
4650ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
4651ed0fb78fSIlya Dryomov 			    !atomic_read(&fs_info->balance_running)) {
4652ed0fb78fSIlya Dryomov 				/* this is (3) */
4653ed0fb78fSIlya Dryomov 				need_unlock = false;
4654ed0fb78fSIlya Dryomov 				goto locked;
4655ed0fb78fSIlya Dryomov 			}
4656ed0fb78fSIlya Dryomov 
4657ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4658ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->volume_mutex);
4659ed0fb78fSIlya Dryomov 			goto again;
4660ed0fb78fSIlya Dryomov 		} else {
4661ed0fb78fSIlya Dryomov 			/* this is (2) */
4662ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4663ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4664ed0fb78fSIlya Dryomov 			goto out;
4665ed0fb78fSIlya Dryomov 		}
4666ed0fb78fSIlya Dryomov 	} else {
4667ed0fb78fSIlya Dryomov 		/* this is (1) */
4668ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4669e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4670ed0fb78fSIlya Dryomov 		goto out;
4671ed0fb78fSIlya Dryomov 	}
4672ed0fb78fSIlya Dryomov 
4673ed0fb78fSIlya Dryomov locked:
4674171938e5SDavid Sterba 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4675c9e9f97bSIlya Dryomov 
4676c9e9f97bSIlya Dryomov 	if (arg) {
4677c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4678c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4679c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4680ed0fb78fSIlya Dryomov 			goto out_unlock;
4681c9e9f97bSIlya Dryomov 		}
4682de322263SIlya Dryomov 
4683de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4684de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4685de322263SIlya Dryomov 				ret = -ENOTCONN;
4686de322263SIlya Dryomov 				goto out_bargs;
4687de322263SIlya Dryomov 			}
4688de322263SIlya Dryomov 
4689de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4690de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4691de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4692de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4693de322263SIlya Dryomov 
4694de322263SIlya Dryomov 			goto do_balance;
4695de322263SIlya Dryomov 		}
4696c9e9f97bSIlya Dryomov 	} else {
4697c9e9f97bSIlya Dryomov 		bargs = NULL;
4698c9e9f97bSIlya Dryomov 	}
4699c9e9f97bSIlya Dryomov 
4700ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4701837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4702837d5b6eSIlya Dryomov 		goto out_bargs;
4703837d5b6eSIlya Dryomov 	}
4704837d5b6eSIlya Dryomov 
47058d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4706c9e9f97bSIlya Dryomov 	if (!bctl) {
4707c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4708c9e9f97bSIlya Dryomov 		goto out_bargs;
4709c9e9f97bSIlya Dryomov 	}
4710c9e9f97bSIlya Dryomov 
4711c9e9f97bSIlya Dryomov 	bctl->fs_info = fs_info;
4712c9e9f97bSIlya Dryomov 	if (arg) {
4713c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4714c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4715c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4716c9e9f97bSIlya Dryomov 
4717c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4718f43ffb60SIlya Dryomov 	} else {
4719f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4720f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4721c9e9f97bSIlya Dryomov 	}
4722c9e9f97bSIlya Dryomov 
47238eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
47248eb93459SDavid Sterba 		ret = -EINVAL;
47250f89abf5SChristian Engelmayer 		goto out_bctl;
47268eb93459SDavid Sterba 	}
47278eb93459SDavid Sterba 
4728de322263SIlya Dryomov do_balance:
4729c9e9f97bSIlya Dryomov 	/*
4730171938e5SDavid Sterba 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP
4731ed0fb78fSIlya Dryomov 	 * goes to to btrfs_balance.  bctl is freed in __cancel_balance,
4732ed0fb78fSIlya Dryomov 	 * or, if restriper was paused all the way until unmount, in
4733171938e5SDavid Sterba 	 * free_fs_info.  The flag is cleared in __cancel_balance.
4734c9e9f97bSIlya Dryomov 	 */
4735ed0fb78fSIlya Dryomov 	need_unlock = false;
4736ed0fb78fSIlya Dryomov 
4737ed0fb78fSIlya Dryomov 	ret = btrfs_balance(bctl, bargs);
47380f89abf5SChristian Engelmayer 	bctl = NULL;
4739ed0fb78fSIlya Dryomov 
4740c9e9f97bSIlya Dryomov 	if (arg) {
4741c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4742c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4743c9e9f97bSIlya Dryomov 	}
4744c9e9f97bSIlya Dryomov 
47450f89abf5SChristian Engelmayer out_bctl:
47460f89abf5SChristian Engelmayer 	kfree(bctl);
4747c9e9f97bSIlya Dryomov out_bargs:
4748c9e9f97bSIlya Dryomov 	kfree(bargs);
4749ed0fb78fSIlya Dryomov out_unlock:
4750c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4751c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->volume_mutex);
4752ed0fb78fSIlya Dryomov 	if (need_unlock)
4753171938e5SDavid Sterba 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4754ed0fb78fSIlya Dryomov out:
4755e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4756c9e9f97bSIlya Dryomov 	return ret;
4757c9e9f97bSIlya Dryomov }
4758c9e9f97bSIlya Dryomov 
47592ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4760837d5b6eSIlya Dryomov {
4761837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4762837d5b6eSIlya Dryomov 		return -EPERM;
4763837d5b6eSIlya Dryomov 
4764837d5b6eSIlya Dryomov 	switch (cmd) {
4765837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
47660b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4767a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
47680b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4769837d5b6eSIlya Dryomov 	}
4770837d5b6eSIlya Dryomov 
4771837d5b6eSIlya Dryomov 	return -EINVAL;
4772837d5b6eSIlya Dryomov }
4773837d5b6eSIlya Dryomov 
47742ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
477519a39dceSIlya Dryomov 					 void __user *arg)
477619a39dceSIlya Dryomov {
477719a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
477819a39dceSIlya Dryomov 	int ret = 0;
477919a39dceSIlya Dryomov 
478019a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
478119a39dceSIlya Dryomov 		return -EPERM;
478219a39dceSIlya Dryomov 
478319a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
478419a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
478519a39dceSIlya Dryomov 		ret = -ENOTCONN;
478619a39dceSIlya Dryomov 		goto out;
478719a39dceSIlya Dryomov 	}
478819a39dceSIlya Dryomov 
47898d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
479019a39dceSIlya Dryomov 	if (!bargs) {
479119a39dceSIlya Dryomov 		ret = -ENOMEM;
479219a39dceSIlya Dryomov 		goto out;
479319a39dceSIlya Dryomov 	}
479419a39dceSIlya Dryomov 
479519a39dceSIlya Dryomov 	update_ioctl_balance_args(fs_info, 1, bargs);
479619a39dceSIlya Dryomov 
479719a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
479819a39dceSIlya Dryomov 		ret = -EFAULT;
479919a39dceSIlya Dryomov 
480019a39dceSIlya Dryomov 	kfree(bargs);
480119a39dceSIlya Dryomov out:
480219a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
480319a39dceSIlya Dryomov 	return ret;
480419a39dceSIlya Dryomov }
480519a39dceSIlya Dryomov 
4806905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
48075d13a37bSArne Jansen {
48080b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48105d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
48115d13a37bSArne Jansen 	struct btrfs_trans_handle *trans = NULL;
48125d13a37bSArne Jansen 	int ret;
48135d13a37bSArne Jansen 	int err;
48145d13a37bSArne Jansen 
48155d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48165d13a37bSArne Jansen 		return -EPERM;
48175d13a37bSArne Jansen 
4818905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4819905b0ddaSMiao Xie 	if (ret)
4820905b0ddaSMiao Xie 		return ret;
48215d13a37bSArne Jansen 
48225d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4823905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4824905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4825905b0ddaSMiao Xie 		goto drop_write;
4826905b0ddaSMiao Xie 	}
48275d13a37bSArne Jansen 
48280b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
48290b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 2);
48305d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48315d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48325d13a37bSArne Jansen 		goto out;
48335d13a37bSArne Jansen 	}
48345d13a37bSArne Jansen 
48355d13a37bSArne Jansen 	switch (sa->cmd) {
48365d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
48370b246afaSJeff Mahoney 		ret = btrfs_quota_enable(trans, fs_info);
48385d13a37bSArne Jansen 		break;
48395d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
48400b246afaSJeff Mahoney 		ret = btrfs_quota_disable(trans, fs_info);
48415d13a37bSArne Jansen 		break;
48425d13a37bSArne Jansen 	default:
48435d13a37bSArne Jansen 		ret = -EINVAL;
48445d13a37bSArne Jansen 		break;
48455d13a37bSArne Jansen 	}
48465d13a37bSArne Jansen 
48473a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
48485d13a37bSArne Jansen 	if (err && !ret)
48495d13a37bSArne Jansen 		ret = err;
48505d13a37bSArne Jansen out:
48515d13a37bSArne Jansen 	kfree(sa);
48520b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4853905b0ddaSMiao Xie drop_write:
4854905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48555d13a37bSArne Jansen 	return ret;
48565d13a37bSArne Jansen }
48575d13a37bSArne Jansen 
4858905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
48595d13a37bSArne Jansen {
48600b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48620b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
48635d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
48645d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48655d13a37bSArne Jansen 	int ret;
48665d13a37bSArne Jansen 	int err;
48675d13a37bSArne Jansen 
48685d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48695d13a37bSArne Jansen 		return -EPERM;
48705d13a37bSArne Jansen 
4871905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4872905b0ddaSMiao Xie 	if (ret)
4873905b0ddaSMiao Xie 		return ret;
48745d13a37bSArne Jansen 
48755d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4876905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4877905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4878905b0ddaSMiao Xie 		goto drop_write;
4879905b0ddaSMiao Xie 	}
48805d13a37bSArne Jansen 
48815d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
48825d13a37bSArne Jansen 	if (IS_ERR(trans)) {
48835d13a37bSArne Jansen 		ret = PTR_ERR(trans);
48845d13a37bSArne Jansen 		goto out;
48855d13a37bSArne Jansen 	}
48865d13a37bSArne Jansen 
48875d13a37bSArne Jansen 	if (sa->assign) {
48880b246afaSJeff Mahoney 		ret = btrfs_add_qgroup_relation(trans, fs_info,
48895d13a37bSArne Jansen 						sa->src, sa->dst);
48905d13a37bSArne Jansen 	} else {
48910b246afaSJeff Mahoney 		ret = btrfs_del_qgroup_relation(trans, fs_info,
48925d13a37bSArne Jansen 						sa->src, sa->dst);
48935d13a37bSArne Jansen 	}
48945d13a37bSArne Jansen 
4895e082f563SQu Wenruo 	/* update qgroup status and info */
48960b246afaSJeff Mahoney 	err = btrfs_run_qgroups(trans, fs_info);
4897e082f563SQu Wenruo 	if (err < 0)
48980b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4899ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
49003a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
49015d13a37bSArne Jansen 	if (err && !ret)
49025d13a37bSArne Jansen 		ret = err;
49035d13a37bSArne Jansen 
49045d13a37bSArne Jansen out:
49055d13a37bSArne Jansen 	kfree(sa);
4906905b0ddaSMiao Xie drop_write:
4907905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49085d13a37bSArne Jansen 	return ret;
49095d13a37bSArne Jansen }
49105d13a37bSArne Jansen 
4911905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
49125d13a37bSArne Jansen {
49130b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49150b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
49165d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
49175d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
49185d13a37bSArne Jansen 	int ret;
49195d13a37bSArne Jansen 	int err;
49205d13a37bSArne Jansen 
49215d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
49225d13a37bSArne Jansen 		return -EPERM;
49235d13a37bSArne Jansen 
4924905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4925905b0ddaSMiao Xie 	if (ret)
4926905b0ddaSMiao Xie 		return ret;
49275d13a37bSArne Jansen 
49285d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4929905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4930905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4931905b0ddaSMiao Xie 		goto drop_write;
4932905b0ddaSMiao Xie 	}
49335d13a37bSArne Jansen 
4934d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4935d86e56cfSMiao Xie 		ret = -EINVAL;
4936d86e56cfSMiao Xie 		goto out;
4937d86e56cfSMiao Xie 	}
4938d86e56cfSMiao Xie 
49395d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
49405d13a37bSArne Jansen 	if (IS_ERR(trans)) {
49415d13a37bSArne Jansen 		ret = PTR_ERR(trans);
49425d13a37bSArne Jansen 		goto out;
49435d13a37bSArne Jansen 	}
49445d13a37bSArne Jansen 
49455d13a37bSArne Jansen 	if (sa->create) {
49460b246afaSJeff Mahoney 		ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
49475d13a37bSArne Jansen 	} else {
49480b246afaSJeff Mahoney 		ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
49495d13a37bSArne Jansen 	}
49505d13a37bSArne Jansen 
49513a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
49525d13a37bSArne Jansen 	if (err && !ret)
49535d13a37bSArne Jansen 		ret = err;
49545d13a37bSArne Jansen 
49555d13a37bSArne Jansen out:
49565d13a37bSArne Jansen 	kfree(sa);
4957905b0ddaSMiao Xie drop_write:
4958905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49595d13a37bSArne Jansen 	return ret;
49605d13a37bSArne Jansen }
49615d13a37bSArne Jansen 
4962905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
49635d13a37bSArne Jansen {
49640b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
49660b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
49675d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
49685d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
49695d13a37bSArne Jansen 	int ret;
49705d13a37bSArne Jansen 	int err;
49715d13a37bSArne Jansen 	u64 qgroupid;
49725d13a37bSArne Jansen 
49735d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
49745d13a37bSArne Jansen 		return -EPERM;
49755d13a37bSArne Jansen 
4976905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4977905b0ddaSMiao Xie 	if (ret)
4978905b0ddaSMiao Xie 		return ret;
49795d13a37bSArne Jansen 
49805d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4981905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4982905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4983905b0ddaSMiao Xie 		goto drop_write;
4984905b0ddaSMiao Xie 	}
49855d13a37bSArne Jansen 
49865d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
49875d13a37bSArne Jansen 	if (IS_ERR(trans)) {
49885d13a37bSArne Jansen 		ret = PTR_ERR(trans);
49895d13a37bSArne Jansen 		goto out;
49905d13a37bSArne Jansen 	}
49915d13a37bSArne Jansen 
49925d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
49935d13a37bSArne Jansen 	if (!qgroupid) {
49945d13a37bSArne Jansen 		/* take the current subvol as qgroup */
49955d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
49965d13a37bSArne Jansen 	}
49975d13a37bSArne Jansen 
49980b246afaSJeff Mahoney 	ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
49995d13a37bSArne Jansen 
50003a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
50015d13a37bSArne Jansen 	if (err && !ret)
50025d13a37bSArne Jansen 		ret = err;
50035d13a37bSArne Jansen 
50045d13a37bSArne Jansen out:
50055d13a37bSArne Jansen 	kfree(sa);
5006905b0ddaSMiao Xie drop_write:
5007905b0ddaSMiao Xie 	mnt_drop_write_file(file);
50085d13a37bSArne Jansen 	return ret;
50095d13a37bSArne Jansen }
50105d13a37bSArne Jansen 
50112f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
50122f232036SJan Schmidt {
50130b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50152f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
50162f232036SJan Schmidt 	int ret;
50172f232036SJan Schmidt 
50182f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
50192f232036SJan Schmidt 		return -EPERM;
50202f232036SJan Schmidt 
50212f232036SJan Schmidt 	ret = mnt_want_write_file(file);
50222f232036SJan Schmidt 	if (ret)
50232f232036SJan Schmidt 		return ret;
50242f232036SJan Schmidt 
50252f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
50262f232036SJan Schmidt 	if (IS_ERR(qsa)) {
50272f232036SJan Schmidt 		ret = PTR_ERR(qsa);
50282f232036SJan Schmidt 		goto drop_write;
50292f232036SJan Schmidt 	}
50302f232036SJan Schmidt 
50312f232036SJan Schmidt 	if (qsa->flags) {
50322f232036SJan Schmidt 		ret = -EINVAL;
50332f232036SJan Schmidt 		goto out;
50342f232036SJan Schmidt 	}
50352f232036SJan Schmidt 
50360b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
50372f232036SJan Schmidt 
50382f232036SJan Schmidt out:
50392f232036SJan Schmidt 	kfree(qsa);
50402f232036SJan Schmidt drop_write:
50412f232036SJan Schmidt 	mnt_drop_write_file(file);
50422f232036SJan Schmidt 	return ret;
50432f232036SJan Schmidt }
50442f232036SJan Schmidt 
50452f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
50462f232036SJan Schmidt {
50470b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50480b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50492f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
50502f232036SJan Schmidt 	int ret = 0;
50512f232036SJan Schmidt 
50522f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
50532f232036SJan Schmidt 		return -EPERM;
50542f232036SJan Schmidt 
50558d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
50562f232036SJan Schmidt 	if (!qsa)
50572f232036SJan Schmidt 		return -ENOMEM;
50582f232036SJan Schmidt 
50590b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
50602f232036SJan Schmidt 		qsa->flags = 1;
50610b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
50622f232036SJan Schmidt 	}
50632f232036SJan Schmidt 
50642f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
50652f232036SJan Schmidt 		ret = -EFAULT;
50662f232036SJan Schmidt 
50672f232036SJan Schmidt 	kfree(qsa);
50682f232036SJan Schmidt 	return ret;
50692f232036SJan Schmidt }
50702f232036SJan Schmidt 
507157254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
507257254b6eSJan Schmidt {
50730b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50740b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
507557254b6eSJan Schmidt 
507657254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
507757254b6eSJan Schmidt 		return -EPERM;
507857254b6eSJan Schmidt 
50790b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
508057254b6eSJan Schmidt }
508157254b6eSJan Schmidt 
5082abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
5083abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
50848ea05e3aSAlexander Block {
5085496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
50860b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50878ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
50888ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
50898ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
5090c2050a45SDeepa Dinamani 	struct timespec ct = current_time(inode);
50918ea05e3aSAlexander Block 	int ret = 0;
5092dd5f9615SStefan Behrens 	int received_uuid_changed;
50938ea05e3aSAlexander Block 
5094bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
5095bd60ea0fSDavid Sterba 		return -EPERM;
5096bd60ea0fSDavid Sterba 
50978ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
50988ea05e3aSAlexander Block 	if (ret < 0)
50998ea05e3aSAlexander Block 		return ret;
51008ea05e3aSAlexander Block 
51010b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
51028ea05e3aSAlexander Block 
51034a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
51048ea05e3aSAlexander Block 		ret = -EINVAL;
51058ea05e3aSAlexander Block 		goto out;
51068ea05e3aSAlexander Block 	}
51078ea05e3aSAlexander Block 
51088ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
51098ea05e3aSAlexander Block 		ret = -EROFS;
51108ea05e3aSAlexander Block 		goto out;
51118ea05e3aSAlexander Block 	}
51128ea05e3aSAlexander Block 
5113dd5f9615SStefan Behrens 	/*
5114dd5f9615SStefan Behrens 	 * 1 - root item
5115dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5116dd5f9615SStefan Behrens 	 */
5117dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
51188ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
51198ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
51208ea05e3aSAlexander Block 		trans = NULL;
51218ea05e3aSAlexander Block 		goto out;
51228ea05e3aSAlexander Block 	}
51238ea05e3aSAlexander Block 
51248ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
51258ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
51268ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
51278ea05e3aSAlexander Block 
5128dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5129dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5130dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5131dd5f9615SStefan Behrens 	    !btrfs_is_empty_uuid(root_item->received_uuid))
51320b246afaSJeff Mahoney 		btrfs_uuid_tree_rem(trans, fs_info, root_item->received_uuid,
5133dd5f9615SStefan Behrens 				    BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5134dd5f9615SStefan Behrens 				    root->root_key.objectid);
51358ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
51368ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
51378ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
51383cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
51393cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
51403cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
51413cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
51428ea05e3aSAlexander Block 
51430b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
51448ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
51458ea05e3aSAlexander Block 	if (ret < 0) {
51463a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
51478ea05e3aSAlexander Block 		goto out;
5148dd5f9615SStefan Behrens 	}
5149dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
51500b246afaSJeff Mahoney 		ret = btrfs_uuid_tree_add(trans, fs_info, sa->uuid,
5151dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5152dd5f9615SStefan Behrens 					  root->root_key.objectid);
5153dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
515466642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
5155dd5f9615SStefan Behrens 			goto out;
5156dd5f9615SStefan Behrens 		}
5157dd5f9615SStefan Behrens 	}
51583a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5159dd5f9615SStefan Behrens 	if (ret < 0) {
516066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
51618ea05e3aSAlexander Block 		goto out;
51628ea05e3aSAlexander Block 	}
51638ea05e3aSAlexander Block 
5164abccd00fSHugo Mills out:
51650b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5166abccd00fSHugo Mills 	mnt_drop_write_file(file);
5167abccd00fSHugo Mills 	return ret;
5168abccd00fSHugo Mills }
5169abccd00fSHugo Mills 
5170abccd00fSHugo Mills #ifdef CONFIG_64BIT
5171abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5172abccd00fSHugo Mills 						void __user *arg)
5173abccd00fSHugo Mills {
5174abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5175abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5176abccd00fSHugo Mills 	int ret = 0;
5177abccd00fSHugo Mills 
5178abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
51797b9ea627SShailendra Verma 	if (IS_ERR(args32))
51807b9ea627SShailendra Verma 		return PTR_ERR(args32);
5181abccd00fSHugo Mills 
51828d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
518384dbeb87SDan Carpenter 	if (!args64) {
518484dbeb87SDan Carpenter 		ret = -ENOMEM;
5185abccd00fSHugo Mills 		goto out;
5186abccd00fSHugo Mills 	}
5187abccd00fSHugo Mills 
5188abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5189abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5190abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5191abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5192abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5193abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5194abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5195abccd00fSHugo Mills 	args64->flags = args32->flags;
5196abccd00fSHugo Mills 
5197abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5198abccd00fSHugo Mills 	if (ret)
5199abccd00fSHugo Mills 		goto out;
5200abccd00fSHugo Mills 
5201abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5202abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5203abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5204abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5205abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5206abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5207abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5208abccd00fSHugo Mills 	args32->flags = args64->flags;
5209abccd00fSHugo Mills 
5210abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5211abccd00fSHugo Mills 	if (ret)
5212abccd00fSHugo Mills 		ret = -EFAULT;
5213abccd00fSHugo Mills 
5214abccd00fSHugo Mills out:
5215abccd00fSHugo Mills 	kfree(args32);
5216abccd00fSHugo Mills 	kfree(args64);
5217abccd00fSHugo Mills 	return ret;
5218abccd00fSHugo Mills }
5219abccd00fSHugo Mills #endif
5220abccd00fSHugo Mills 
5221abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5222abccd00fSHugo Mills 					    void __user *arg)
5223abccd00fSHugo Mills {
5224abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5225abccd00fSHugo Mills 	int ret = 0;
5226abccd00fSHugo Mills 
5227abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
52287b9ea627SShailendra Verma 	if (IS_ERR(sa))
52297b9ea627SShailendra Verma 		return PTR_ERR(sa);
5230abccd00fSHugo Mills 
5231abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5232abccd00fSHugo Mills 
5233abccd00fSHugo Mills 	if (ret)
5234abccd00fSHugo Mills 		goto out;
5235abccd00fSHugo Mills 
52368ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
52378ea05e3aSAlexander Block 	if (ret)
52388ea05e3aSAlexander Block 		ret = -EFAULT;
52398ea05e3aSAlexander Block 
52408ea05e3aSAlexander Block out:
52418ea05e3aSAlexander Block 	kfree(sa);
52428ea05e3aSAlexander Block 	return ret;
52438ea05e3aSAlexander Block }
52448ea05e3aSAlexander Block 
5245867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5246867ab667Sjeff.liu {
52470b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52480b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5249a1b83ac5SAnand Jain 	size_t len;
5250867ab667Sjeff.liu 	int ret;
5251a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5252a1b83ac5SAnand Jain 
52530b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
52540b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
52550b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
5256a1b83ac5SAnand Jain 
5257a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5258867ab667Sjeff.liu 
5259867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
52600b246afaSJeff Mahoney 		btrfs_warn(fs_info,
52610b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
52620b246afaSJeff Mahoney 			   --len);
5263867ab667Sjeff.liu 	}
5264867ab667Sjeff.liu 
5265867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5266867ab667Sjeff.liu 
5267867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5268867ab667Sjeff.liu }
5269867ab667Sjeff.liu 
5270a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5271a8bfd4abSjeff.liu {
52720b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52740b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
52750b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
5276a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5277a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5278a8bfd4abSjeff.liu 	int ret;
5279a8bfd4abSjeff.liu 
5280a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5281a8bfd4abSjeff.liu 		return -EPERM;
5282a8bfd4abSjeff.liu 
5283a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5284a8bfd4abSjeff.liu 		return -EFAULT;
5285a8bfd4abSjeff.liu 
5286a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
52870b246afaSJeff Mahoney 		btrfs_err(fs_info,
52885d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5289a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5290a8bfd4abSjeff.liu 		return -EINVAL;
5291a8bfd4abSjeff.liu 	}
5292a8bfd4abSjeff.liu 
5293a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5294a8bfd4abSjeff.liu 	if (ret)
5295a8bfd4abSjeff.liu 		return ret;
5296a8bfd4abSjeff.liu 
5297a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5298a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5299a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5300a8bfd4abSjeff.liu 		goto out_unlock;
5301a8bfd4abSjeff.liu 	}
5302a8bfd4abSjeff.liu 
53030b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5304a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
53050b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
53063a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5307a8bfd4abSjeff.liu 
5308a8bfd4abSjeff.liu out_unlock:
5309a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5310a8bfd4abSjeff.liu 	return ret;
5311a8bfd4abSjeff.liu }
5312a8bfd4abSjeff.liu 
53132eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
53142eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
53152eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
53162eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
53172eaa055fSJeff Mahoney 
5318d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
53192eaa055fSJeff Mahoney {
53204d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
53212eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
53222eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
53232eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
53242eaa055fSJeff Mahoney 	};
53252eaa055fSJeff Mahoney 
53262eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
53272eaa055fSJeff Mahoney 		return -EFAULT;
53282eaa055fSJeff Mahoney 
53292eaa055fSJeff Mahoney 	return 0;
53302eaa055fSJeff Mahoney }
53312eaa055fSJeff Mahoney 
53322eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
53332eaa055fSJeff Mahoney {
53340b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53360b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
53372eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
53382eaa055fSJeff Mahoney 
53392eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
53402eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
53412eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
53422eaa055fSJeff Mahoney 
53432eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
53442eaa055fSJeff Mahoney 		return -EFAULT;
53452eaa055fSJeff Mahoney 
53462eaa055fSJeff Mahoney 	return 0;
53472eaa055fSJeff Mahoney }
53482eaa055fSJeff Mahoney 
53492ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
53503b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
53512eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
53522eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
53532eaa055fSJeff Mahoney {
53543b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
53553b02a68aSJeff Mahoney 	char *names;
53562eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
53572eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
53582eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
53592eaa055fSJeff Mahoney 
53602eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
53612eaa055fSJeff Mahoney 	if (unsupported) {
53623b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
53633b02a68aSJeff Mahoney 		if (names) {
53640b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53653b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
53663b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
53673b02a68aSJeff Mahoney 			kfree(names);
53683b02a68aSJeff Mahoney 		} else
53690b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53702eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
53712eaa055fSJeff Mahoney 				   type, unsupported);
53722eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
53732eaa055fSJeff Mahoney 	}
53742eaa055fSJeff Mahoney 
53752eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
53762eaa055fSJeff Mahoney 	if (disallowed) {
53773b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
53783b02a68aSJeff Mahoney 		if (names) {
53790b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53803b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
53813b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
53823b02a68aSJeff Mahoney 			kfree(names);
53833b02a68aSJeff Mahoney 		} else
53840b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53852eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
53862eaa055fSJeff Mahoney 				   type, disallowed);
53872eaa055fSJeff Mahoney 		return -EPERM;
53882eaa055fSJeff Mahoney 	}
53892eaa055fSJeff Mahoney 
53902eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
53912eaa055fSJeff Mahoney 	if (disallowed) {
53923b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
53933b02a68aSJeff Mahoney 		if (names) {
53940b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53953b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
53963b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
53973b02a68aSJeff Mahoney 			kfree(names);
53983b02a68aSJeff Mahoney 		} else
53990b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54002eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
54012eaa055fSJeff Mahoney 				   type, disallowed);
54022eaa055fSJeff Mahoney 		return -EPERM;
54032eaa055fSJeff Mahoney 	}
54042eaa055fSJeff Mahoney 
54052eaa055fSJeff Mahoney 	return 0;
54062eaa055fSJeff Mahoney }
54072eaa055fSJeff Mahoney 
54082ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
54092ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
54102eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
54112eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
54122eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
54132eaa055fSJeff Mahoney 
54142eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
54152eaa055fSJeff Mahoney {
54160b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
54170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
54180b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
54190b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
54202eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
54212eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
54222eaa055fSJeff Mahoney 	u64 newflags;
54232eaa055fSJeff Mahoney 	int ret;
54242eaa055fSJeff Mahoney 
54252eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
54262eaa055fSJeff Mahoney 		return -EPERM;
54272eaa055fSJeff Mahoney 
54282eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
54292eaa055fSJeff Mahoney 		return -EFAULT;
54302eaa055fSJeff Mahoney 
54312eaa055fSJeff Mahoney 	/* Nothing to do */
54322eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
54332eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
54342eaa055fSJeff Mahoney 		return 0;
54352eaa055fSJeff Mahoney 
54362ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
54372eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
54382eaa055fSJeff Mahoney 	if (ret)
54392eaa055fSJeff Mahoney 		return ret;
54402eaa055fSJeff Mahoney 
54412ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
54422eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
54432eaa055fSJeff Mahoney 	if (ret)
54442eaa055fSJeff Mahoney 		return ret;
54452eaa055fSJeff Mahoney 
54462ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
54472eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
54482eaa055fSJeff Mahoney 	if (ret)
54492eaa055fSJeff Mahoney 		return ret;
54502eaa055fSJeff Mahoney 
54517ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
54527ab19625SDavid Sterba 	if (ret)
54537ab19625SDavid Sterba 		return ret;
54547ab19625SDavid Sterba 
54558051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
54567ab19625SDavid Sterba 	if (IS_ERR(trans)) {
54577ab19625SDavid Sterba 		ret = PTR_ERR(trans);
54587ab19625SDavid Sterba 		goto out_drop_write;
54597ab19625SDavid Sterba 	}
54602eaa055fSJeff Mahoney 
54610b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
54622eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
54632eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
54642eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
54652eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
54662eaa055fSJeff Mahoney 
54672eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
54682eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
54692eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
54702eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
54712eaa055fSJeff Mahoney 
54722eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
54732eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
54742eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
54752eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
54760b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
54772eaa055fSJeff Mahoney 
54783a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
54797ab19625SDavid Sterba out_drop_write:
54807ab19625SDavid Sterba 	mnt_drop_write_file(file);
54817ab19625SDavid Sterba 
54827ab19625SDavid Sterba 	return ret;
54832eaa055fSJeff Mahoney }
54842eaa055fSJeff Mahoney 
5485f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5486f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5487f46b5a66SChristoph Hellwig {
54880b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
54890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
54900b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
54914bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5492f46b5a66SChristoph Hellwig 
5493f46b5a66SChristoph Hellwig 	switch (cmd) {
54946cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
54956cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
54966cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
54976cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
54986cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
54996cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5500f7039b1dSLi Dongyang 	case FITRIM:
5501f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5502f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5503fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5504fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5505fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
55063de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5507fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
55086f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
55096f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
551076dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
551176dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
55120caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
55130caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
55140caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
55150caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
55166ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
55176ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5518f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
55191e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
55201e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
55211e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5522f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5523198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5524f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
55252ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5526f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5527da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
55286b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
55296b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5530475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
55312ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5532475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
55332ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5534f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
55359ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5536f46b5a66SChristoph Hellwig 	case BTRFS_IOC_TRANS_START:
5537f46b5a66SChristoph Hellwig 		return btrfs_ioctl_trans_start(file);
5538f46b5a66SChristoph Hellwig 	case BTRFS_IOC_TRANS_END:
5539f46b5a66SChristoph Hellwig 		return btrfs_ioctl_trans_end(file);
5540ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5541ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5542cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5543cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5544ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5545ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5546d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5547d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5548d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
55492ff7e61eSJeff Mahoney 		return btrfs_ioctl_logical_to_ino(fs_info, argp);
55501406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
55512ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
55529b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
55539b199859SFilipe David Borba Manana 		int ret;
55549b199859SFilipe David Borba Manana 
55550b246afaSJeff Mahoney 		ret = btrfs_start_delalloc_roots(fs_info, 0, -1);
55569b199859SFilipe David Borba Manana 		if (ret)
55579b199859SFilipe David Borba Manana 			return ret;
55580b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
55592fad4e83SDavid Sterba 		/*
55602fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
556101327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
55622fad4e83SDavid Sterba 		 * processing uncleaned subvols.
55632fad4e83SDavid Sterba 		 */
55640b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
55659b199859SFilipe David Borba Manana 		return ret;
55669b199859SFilipe David Borba Manana 	}
556746204592SSage Weil 	case BTRFS_IOC_START_SYNC:
55689a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
556946204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
55702ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5571475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5572b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5573475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
55742ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5575475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
55762ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5577c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
55789ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5579837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
55802ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
558119a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
55822ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
55838ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
55848ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5585abccd00fSHugo Mills #ifdef CONFIG_64BIT
5586abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5587abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5588abccd00fSHugo Mills #endif
558931db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
559031db9f7cSAlexander Block 		return btrfs_ioctl_send(file, argp);
5591c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
55922ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
55935d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5594905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
55955d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5596905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
55975d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5598905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
55995d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5600905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
56012f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
56022f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
56032f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
56042f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
560557254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
560657254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
56073f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
56082ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5609867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5610867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5611a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5612a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
56132eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5614d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
56152eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
56162eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
56172eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
56182eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5619f46b5a66SChristoph Hellwig 	}
5620f46b5a66SChristoph Hellwig 
5621f46b5a66SChristoph Hellwig 	return -ENOTTY;
5622f46b5a66SChristoph Hellwig }
56234c63c245SLuke Dashjr 
56244c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
56254c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
56264c63c245SLuke Dashjr {
56272a362249SJeff Mahoney 	/*
56282a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
56292a362249SJeff Mahoney 	 * handling is necessary.
56302a362249SJeff Mahoney 	 */
56314c63c245SLuke Dashjr 	switch (cmd) {
56324c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
56334c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
56344c63c245SLuke Dashjr 		break;
56354c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
56364c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
56374c63c245SLuke Dashjr 		break;
56384c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
56394c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
56404c63c245SLuke Dashjr 		break;
56414c63c245SLuke Dashjr 	}
56424c63c245SLuke Dashjr 
56434c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
56444c63c245SLuke Dashjr }
56454c63c245SLuke Dashjr #endif
5646