xref: /openbmc/linux/fs/btrfs/ioctl.c (revision 3efbee1d)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
2f46b5a66SChristoph Hellwig /*
3f46b5a66SChristoph Hellwig  * Copyright (C) 2007 Oracle.  All rights reserved.
4f46b5a66SChristoph Hellwig  */
5f46b5a66SChristoph Hellwig 
6f46b5a66SChristoph Hellwig #include <linux/kernel.h>
7f46b5a66SChristoph Hellwig #include <linux/bio.h>
8f46b5a66SChristoph Hellwig #include <linux/file.h>
9f46b5a66SChristoph Hellwig #include <linux/fs.h>
10cb8e7090SChristoph Hellwig #include <linux/fsnotify.h>
11f46b5a66SChristoph Hellwig #include <linux/pagemap.h>
12f46b5a66SChristoph Hellwig #include <linux/highmem.h>
13f46b5a66SChristoph Hellwig #include <linux/time.h>
14f46b5a66SChristoph Hellwig #include <linux/string.h>
15f46b5a66SChristoph Hellwig #include <linux/backing-dev.h>
16cb8e7090SChristoph Hellwig #include <linux/mount.h>
17cb8e7090SChristoph Hellwig #include <linux/namei.h>
18f46b5a66SChristoph Hellwig #include <linux/writeback.h>
19f46b5a66SChristoph Hellwig #include <linux/compat.h>
20cb8e7090SChristoph Hellwig #include <linux/security.h>
21f46b5a66SChristoph Hellwig #include <linux/xattr.h>
22f54de068SDavid Sterba #include <linux/mm.h>
235a0e3ad6STejun Heo #include <linux/slab.h>
24f7039b1dSLi Dongyang #include <linux/blkdev.h>
258ea05e3aSAlexander Block #include <linux/uuid.h>
2655e301fdSFilipe Brandenburger #include <linux/btrfs.h>
27416161dbSMark Fasheh #include <linux/uaccess.h>
28ae5e165dSJeff Layton #include <linux/iversion.h>
29f46b5a66SChristoph Hellwig #include "ctree.h"
30f46b5a66SChristoph Hellwig #include "disk-io.h"
31f46b5a66SChristoph Hellwig #include "transaction.h"
32f46b5a66SChristoph Hellwig #include "btrfs_inode.h"
33f46b5a66SChristoph Hellwig #include "print-tree.h"
34f46b5a66SChristoph Hellwig #include "volumes.h"
35925baeddSChris Mason #include "locking.h"
36581bb050SLi Zefan #include "inode-map.h"
37d7728c96SJan Schmidt #include "backref.h"
38606686eeSJosef Bacik #include "rcu-string.h"
3931db9f7cSAlexander Block #include "send.h"
403f6bcfbdSStefan Behrens #include "dev-replace.h"
4163541927SFilipe David Borba Manana #include "props.h"
423b02a68aSJeff Mahoney #include "sysfs.h"
43fcebe456SJosef Bacik #include "qgroup.h"
441ec9a1aeSFilipe Manana #include "tree-log.h"
45ebb8765bSAnand Jain #include "compression.h"
46f46b5a66SChristoph Hellwig 
47abccd00fSHugo Mills #ifdef CONFIG_64BIT
48abccd00fSHugo Mills /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
49abccd00fSHugo Mills  * structures are incorrect, as the timespec structure from userspace
50abccd00fSHugo Mills  * is 4 bytes too small. We define these alternatives here to teach
51abccd00fSHugo Mills  * the kernel about the 32-bit struct packing.
52abccd00fSHugo Mills  */
53abccd00fSHugo Mills struct btrfs_ioctl_timespec_32 {
54abccd00fSHugo Mills 	__u64 sec;
55abccd00fSHugo Mills 	__u32 nsec;
56abccd00fSHugo Mills } __attribute__ ((__packed__));
57abccd00fSHugo Mills 
58abccd00fSHugo Mills struct btrfs_ioctl_received_subvol_args_32 {
59abccd00fSHugo Mills 	char	uuid[BTRFS_UUID_SIZE];	/* in */
60abccd00fSHugo Mills 	__u64	stransid;		/* in */
61abccd00fSHugo Mills 	__u64	rtransid;		/* out */
62abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 stime; /* in */
63abccd00fSHugo Mills 	struct btrfs_ioctl_timespec_32 rtime; /* out */
64abccd00fSHugo Mills 	__u64	flags;			/* in */
65abccd00fSHugo Mills 	__u64	reserved[16];		/* in */
66abccd00fSHugo Mills } __attribute__ ((__packed__));
67abccd00fSHugo Mills 
68abccd00fSHugo Mills #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
69abccd00fSHugo Mills 				struct btrfs_ioctl_received_subvol_args_32)
70abccd00fSHugo Mills #endif
71abccd00fSHugo Mills 
722351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
732351f431SJosef Bacik struct btrfs_ioctl_send_args_32 {
742351f431SJosef Bacik 	__s64 send_fd;			/* in */
752351f431SJosef Bacik 	__u64 clone_sources_count;	/* in */
762351f431SJosef Bacik 	compat_uptr_t clone_sources;	/* in */
772351f431SJosef Bacik 	__u64 parent_root;		/* in */
782351f431SJosef Bacik 	__u64 flags;			/* in */
792351f431SJosef Bacik 	__u64 reserved[4];		/* in */
802351f431SJosef Bacik } __attribute__ ((__packed__));
812351f431SJosef Bacik 
822351f431SJosef Bacik #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
832351f431SJosef Bacik 			       struct btrfs_ioctl_send_args_32)
842351f431SJosef Bacik #endif
85abccd00fSHugo Mills 
86416161dbSMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
871c919a5eSMark Fasheh 		       u64 off, u64 olen, u64 olen_aligned, u64 destoff,
881c919a5eSMark Fasheh 		       int no_time_update);
89416161dbSMark Fasheh 
906cbff00fSChristoph Hellwig /* Mask out flags that are inappropriate for the given type of inode. */
911905a0f7SDavid Sterba static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
921905a0f7SDavid Sterba 		unsigned int flags)
936cbff00fSChristoph Hellwig {
941905a0f7SDavid Sterba 	if (S_ISDIR(inode->i_mode))
956cbff00fSChristoph Hellwig 		return flags;
961905a0f7SDavid Sterba 	else if (S_ISREG(inode->i_mode))
976cbff00fSChristoph Hellwig 		return flags & ~FS_DIRSYNC_FL;
986cbff00fSChristoph Hellwig 	else
996cbff00fSChristoph Hellwig 		return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
1006cbff00fSChristoph Hellwig }
101f46b5a66SChristoph Hellwig 
1026cbff00fSChristoph Hellwig /*
103a157d4fdSDavid Sterba  * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
104a157d4fdSDavid Sterba  * ioctl.
1056cbff00fSChristoph Hellwig  */
106a157d4fdSDavid Sterba static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags)
1076cbff00fSChristoph Hellwig {
1086cbff00fSChristoph Hellwig 	unsigned int iflags = 0;
1096cbff00fSChristoph Hellwig 
1106cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_SYNC)
1116cbff00fSChristoph Hellwig 		iflags |= FS_SYNC_FL;
1126cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_IMMUTABLE)
1136cbff00fSChristoph Hellwig 		iflags |= FS_IMMUTABLE_FL;
1146cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_APPEND)
1156cbff00fSChristoph Hellwig 		iflags |= FS_APPEND_FL;
1166cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NODUMP)
1176cbff00fSChristoph Hellwig 		iflags |= FS_NODUMP_FL;
1186cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_NOATIME)
1196cbff00fSChristoph Hellwig 		iflags |= FS_NOATIME_FL;
1206cbff00fSChristoph Hellwig 	if (flags & BTRFS_INODE_DIRSYNC)
1216cbff00fSChristoph Hellwig 		iflags |= FS_DIRSYNC_FL;
122d0092bddSLi Zefan 	if (flags & BTRFS_INODE_NODATACOW)
123d0092bddSLi Zefan 		iflags |= FS_NOCOW_FL;
124d0092bddSLi Zefan 
12513f48dc9SSatoru Takeuchi 	if (flags & BTRFS_INODE_NOCOMPRESS)
126d0092bddSLi Zefan 		iflags |= FS_NOCOMP_FL;
12713f48dc9SSatoru Takeuchi 	else if (flags & BTRFS_INODE_COMPRESS)
12813f48dc9SSatoru Takeuchi 		iflags |= FS_COMPR_FL;
1296cbff00fSChristoph Hellwig 
1306cbff00fSChristoph Hellwig 	return iflags;
1316cbff00fSChristoph Hellwig }
1326cbff00fSChristoph Hellwig 
1336cbff00fSChristoph Hellwig /*
1346cbff00fSChristoph Hellwig  * Update inode->i_flags based on the btrfs internal flags.
1356cbff00fSChristoph Hellwig  */
1367b6a221eSDavid Sterba void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
1376cbff00fSChristoph Hellwig {
1385c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
1393cc79392SFilipe Manana 	unsigned int new_fl = 0;
1406cbff00fSChristoph Hellwig 
1415c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_SYNC)
1423cc79392SFilipe Manana 		new_fl |= S_SYNC;
1435c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_IMMUTABLE)
1443cc79392SFilipe Manana 		new_fl |= S_IMMUTABLE;
1455c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_APPEND)
1463cc79392SFilipe Manana 		new_fl |= S_APPEND;
1475c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_NOATIME)
1483cc79392SFilipe Manana 		new_fl |= S_NOATIME;
1495c57b8b6SDavid Sterba 	if (binode->flags & BTRFS_INODE_DIRSYNC)
1503cc79392SFilipe Manana 		new_fl |= S_DIRSYNC;
1513cc79392SFilipe Manana 
1523cc79392SFilipe Manana 	set_mask_bits(&inode->i_flags,
1533cc79392SFilipe Manana 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
1543cc79392SFilipe Manana 		      new_fl);
1556cbff00fSChristoph Hellwig }
1566cbff00fSChristoph Hellwig 
1576cbff00fSChristoph Hellwig static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
1586cbff00fSChristoph Hellwig {
1595c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(file_inode(file));
1605c57b8b6SDavid Sterba 	unsigned int flags = btrfs_inode_flags_to_fsflags(binode->flags);
1616cbff00fSChristoph Hellwig 
1626cbff00fSChristoph Hellwig 	if (copy_to_user(arg, &flags, sizeof(flags)))
1636cbff00fSChristoph Hellwig 		return -EFAULT;
1646cbff00fSChristoph Hellwig 	return 0;
1656cbff00fSChristoph Hellwig }
1666cbff00fSChristoph Hellwig 
1675ba76abfSDavid Sterba /* Check if @flags are a supported and valid set of FS_*_FL flags */
1685ba76abfSDavid Sterba static int check_fsflags(unsigned int flags)
16975e7cb7fSLiu Bo {
17075e7cb7fSLiu Bo 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
17175e7cb7fSLiu Bo 		      FS_NOATIME_FL | FS_NODUMP_FL | \
17275e7cb7fSLiu Bo 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
173e1e8fb6aSLi Zefan 		      FS_NOCOMP_FL | FS_COMPR_FL |
174e1e8fb6aSLi Zefan 		      FS_NOCOW_FL))
17575e7cb7fSLiu Bo 		return -EOPNOTSUPP;
17675e7cb7fSLiu Bo 
17775e7cb7fSLiu Bo 	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
17875e7cb7fSLiu Bo 		return -EINVAL;
17975e7cb7fSLiu Bo 
18075e7cb7fSLiu Bo 	return 0;
18175e7cb7fSLiu Bo }
18275e7cb7fSLiu Bo 
1836cbff00fSChristoph Hellwig static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
1846cbff00fSChristoph Hellwig {
185496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
1860b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1875c57b8b6SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
1885c57b8b6SDavid Sterba 	struct btrfs_root *root = binode->root;
1896cbff00fSChristoph Hellwig 	struct btrfs_trans_handle *trans;
1905c57b8b6SDavid Sterba 	unsigned int fsflags, old_fsflags;
1916cbff00fSChristoph Hellwig 	int ret;
1925c57b8b6SDavid Sterba 	u64 old_flags;
1935c57b8b6SDavid Sterba 	unsigned int old_i_flags;
1947e97b8daSDavid Sterba 	umode_t mode;
1956cbff00fSChristoph Hellwig 
196bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
197bd60ea0fSDavid Sterba 		return -EPERM;
198bd60ea0fSDavid Sterba 
199b83cc969SLi Zefan 	if (btrfs_root_readonly(root))
200b83cc969SLi Zefan 		return -EROFS;
201b83cc969SLi Zefan 
2025c57b8b6SDavid Sterba 	if (copy_from_user(&fsflags, arg, sizeof(fsflags)))
2036cbff00fSChristoph Hellwig 		return -EFAULT;
2046cbff00fSChristoph Hellwig 
2055c57b8b6SDavid Sterba 	ret = check_fsflags(fsflags);
20675e7cb7fSLiu Bo 	if (ret)
20775e7cb7fSLiu Bo 		return ret;
2086cbff00fSChristoph Hellwig 
209e7848683SJan Kara 	ret = mnt_want_write_file(file);
210e7848683SJan Kara 	if (ret)
211e7848683SJan Kara 		return ret;
212e7848683SJan Kara 
2135955102cSAl Viro 	inode_lock(inode);
2146cbff00fSChristoph Hellwig 
2155c57b8b6SDavid Sterba 	old_flags = binode->flags;
2165c57b8b6SDavid Sterba 	old_i_flags = inode->i_flags;
2177e97b8daSDavid Sterba 	mode = inode->i_mode;
218f062abf0SLi Zefan 
2195c57b8b6SDavid Sterba 	fsflags = btrfs_mask_fsflags_for_type(inode, fsflags);
2205c57b8b6SDavid Sterba 	old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags);
2215c57b8b6SDavid Sterba 	if ((fsflags ^ old_fsflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
2226cbff00fSChristoph Hellwig 		if (!capable(CAP_LINUX_IMMUTABLE)) {
2236cbff00fSChristoph Hellwig 			ret = -EPERM;
2246cbff00fSChristoph Hellwig 			goto out_unlock;
2256cbff00fSChristoph Hellwig 		}
2266cbff00fSChristoph Hellwig 	}
2276cbff00fSChristoph Hellwig 
2285c57b8b6SDavid Sterba 	if (fsflags & FS_SYNC_FL)
2295c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_SYNC;
2306cbff00fSChristoph Hellwig 	else
2315c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_SYNC;
2325c57b8b6SDavid Sterba 	if (fsflags & FS_IMMUTABLE_FL)
2335c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_IMMUTABLE;
2346cbff00fSChristoph Hellwig 	else
2355c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_IMMUTABLE;
2365c57b8b6SDavid Sterba 	if (fsflags & FS_APPEND_FL)
2375c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_APPEND;
2386cbff00fSChristoph Hellwig 	else
2395c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_APPEND;
2405c57b8b6SDavid Sterba 	if (fsflags & FS_NODUMP_FL)
2415c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_NODUMP;
2426cbff00fSChristoph Hellwig 	else
2435c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NODUMP;
2445c57b8b6SDavid Sterba 	if (fsflags & FS_NOATIME_FL)
2455c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_NOATIME;
2466cbff00fSChristoph Hellwig 	else
2475c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NOATIME;
2485c57b8b6SDavid Sterba 	if (fsflags & FS_DIRSYNC_FL)
2495c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_DIRSYNC;
2506cbff00fSChristoph Hellwig 	else
2515c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_DIRSYNC;
2525c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOW_FL) {
2537e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2547e97b8daSDavid Sterba 			/*
2557e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2567e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2577e97b8daSDavid Sterba 			 * status of the file and will not set it.
2587e97b8daSDavid Sterba 			 */
2597e97b8daSDavid Sterba 			if (inode->i_size == 0)
2605c57b8b6SDavid Sterba 				binode->flags |= BTRFS_INODE_NODATACOW
2617e97b8daSDavid Sterba 					      | BTRFS_INODE_NODATASUM;
2627e97b8daSDavid Sterba 		} else {
2635c57b8b6SDavid Sterba 			binode->flags |= BTRFS_INODE_NODATACOW;
2647e97b8daSDavid Sterba 		}
2657e97b8daSDavid Sterba 	} else {
2667e97b8daSDavid Sterba 		/*
26701327610SNicholas D Steeves 		 * Revert back under same assumptions as above
2687e97b8daSDavid Sterba 		 */
2697e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2707e97b8daSDavid Sterba 			if (inode->i_size == 0)
2715c57b8b6SDavid Sterba 				binode->flags &= ~(BTRFS_INODE_NODATACOW
2727e97b8daSDavid Sterba 				             | BTRFS_INODE_NODATASUM);
2737e97b8daSDavid Sterba 		} else {
2745c57b8b6SDavid Sterba 			binode->flags &= ~BTRFS_INODE_NODATACOW;
2757e97b8daSDavid Sterba 		}
2767e97b8daSDavid Sterba 	}
2776cbff00fSChristoph Hellwig 
27875e7cb7fSLiu Bo 	/*
27975e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
28075e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
28175e7cb7fSLiu Bo 	 * things smaller.
28275e7cb7fSLiu Bo 	 */
2835c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOMP_FL) {
2845c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_COMPRESS;
2855c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_NOCOMPRESS;
28663541927SFilipe David Borba Manana 
28763541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
28863541927SFilipe David Borba Manana 		if (ret && ret != -ENODATA)
28963541927SFilipe David Borba Manana 			goto out_drop;
2905c57b8b6SDavid Sterba 	} else if (fsflags & FS_COMPR_FL) {
29163541927SFilipe David Borba Manana 		const char *comp;
29263541927SFilipe David Borba Manana 
2935c57b8b6SDavid Sterba 		binode->flags |= BTRFS_INODE_COMPRESS;
2945c57b8b6SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NOCOMPRESS;
29563541927SFilipe David Borba Manana 
29693370509SDavid Sterba 		comp = btrfs_compress_type2str(fs_info->compress_type);
29793370509SDavid Sterba 		if (!comp || comp[0] == 0)
29893370509SDavid Sterba 			comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
29993370509SDavid Sterba 
30063541927SFilipe David Borba Manana 		ret = btrfs_set_prop(inode, "btrfs.compression",
30163541927SFilipe David Borba Manana 				     comp, strlen(comp), 0);
30263541927SFilipe David Borba Manana 		if (ret)
30363541927SFilipe David Borba Manana 			goto out_drop;
30463541927SFilipe David Borba Manana 
305ebcb904dSLi Zefan 	} else {
30678a017a2SFilipe Manana 		ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
30778a017a2SFilipe Manana 		if (ret && ret != -ENODATA)
30878a017a2SFilipe Manana 			goto out_drop;
3095c57b8b6SDavid Sterba 		binode->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
31075e7cb7fSLiu Bo 	}
3116cbff00fSChristoph Hellwig 
3124da6f1a3SLi Zefan 	trans = btrfs_start_transaction(root, 1);
313f062abf0SLi Zefan 	if (IS_ERR(trans)) {
314f062abf0SLi Zefan 		ret = PTR_ERR(trans);
315f062abf0SLi Zefan 		goto out_drop;
316f062abf0SLi Zefan 	}
3176cbff00fSChristoph Hellwig 
3187b6a221eSDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
3190c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
320c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3216cbff00fSChristoph Hellwig 	ret = btrfs_update_inode(trans, root, inode);
3226cbff00fSChristoph Hellwig 
3233a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
324f062abf0SLi Zefan  out_drop:
325f062abf0SLi Zefan 	if (ret) {
3265c57b8b6SDavid Sterba 		binode->flags = old_flags;
3275c57b8b6SDavid Sterba 		inode->i_flags = old_i_flags;
328f062abf0SLi Zefan 	}
3296cbff00fSChristoph Hellwig 
3306cbff00fSChristoph Hellwig  out_unlock:
3315955102cSAl Viro 	inode_unlock(inode);
332e7848683SJan Kara 	mnt_drop_write_file(file);
3332d4e6f6aSliubo 	return ret;
3346cbff00fSChristoph Hellwig }
3356cbff00fSChristoph Hellwig 
33619f93b3cSDavid Sterba /*
33719f93b3cSDavid Sterba  * Translate btrfs internal inode flags to xflags as expected by the
33819f93b3cSDavid Sterba  * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are
33919f93b3cSDavid Sterba  * silently dropped.
34019f93b3cSDavid Sterba  */
34119f93b3cSDavid Sterba static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags)
34219f93b3cSDavid Sterba {
34319f93b3cSDavid Sterba 	unsigned int xflags = 0;
34419f93b3cSDavid Sterba 
34519f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_APPEND)
34619f93b3cSDavid Sterba 		xflags |= FS_XFLAG_APPEND;
34719f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_IMMUTABLE)
34819f93b3cSDavid Sterba 		xflags |= FS_XFLAG_IMMUTABLE;
34919f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_NOATIME)
35019f93b3cSDavid Sterba 		xflags |= FS_XFLAG_NOATIME;
35119f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_NODUMP)
35219f93b3cSDavid Sterba 		xflags |= FS_XFLAG_NODUMP;
35319f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_SYNC)
35419f93b3cSDavid Sterba 		xflags |= FS_XFLAG_SYNC;
35519f93b3cSDavid Sterba 
35619f93b3cSDavid Sterba 	return xflags;
35719f93b3cSDavid Sterba }
35819f93b3cSDavid Sterba 
35919f93b3cSDavid Sterba /* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */
36019f93b3cSDavid Sterba static int check_xflags(unsigned int flags)
36119f93b3cSDavid Sterba {
36219f93b3cSDavid Sterba 	if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME |
36319f93b3cSDavid Sterba 		      FS_XFLAG_NODUMP | FS_XFLAG_SYNC))
36419f93b3cSDavid Sterba 		return -EOPNOTSUPP;
36519f93b3cSDavid Sterba 	return 0;
36619f93b3cSDavid Sterba }
36719f93b3cSDavid Sterba 
368e4202ac9SDavid Sterba /*
369e4202ac9SDavid Sterba  * Set the xflags from the internal inode flags. The remaining items of fsxattr
370e4202ac9SDavid Sterba  * are zeroed.
371e4202ac9SDavid Sterba  */
372e4202ac9SDavid Sterba static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg)
373e4202ac9SDavid Sterba {
374e4202ac9SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(file_inode(file));
375e4202ac9SDavid Sterba 	struct fsxattr fa;
376e4202ac9SDavid Sterba 
377e4202ac9SDavid Sterba 	memset(&fa, 0, sizeof(fa));
378e4202ac9SDavid Sterba 	fa.fsx_xflags = btrfs_inode_flags_to_xflags(binode->flags);
379e4202ac9SDavid Sterba 
380e4202ac9SDavid Sterba 	if (copy_to_user(arg, &fa, sizeof(fa)))
381e4202ac9SDavid Sterba 		return -EFAULT;
382e4202ac9SDavid Sterba 
383e4202ac9SDavid Sterba 	return 0;
384e4202ac9SDavid Sterba }
385e4202ac9SDavid Sterba 
386025f2121SDavid Sterba static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg)
387025f2121SDavid Sterba {
388025f2121SDavid Sterba 	struct inode *inode = file_inode(file);
389025f2121SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
390025f2121SDavid Sterba 	struct btrfs_root *root = binode->root;
391025f2121SDavid Sterba 	struct btrfs_trans_handle *trans;
392025f2121SDavid Sterba 	struct fsxattr fa;
393025f2121SDavid Sterba 	unsigned old_flags;
394025f2121SDavid Sterba 	unsigned old_i_flags;
395025f2121SDavid Sterba 	int ret = 0;
396025f2121SDavid Sterba 
397025f2121SDavid Sterba 	if (!inode_owner_or_capable(inode))
398025f2121SDavid Sterba 		return -EPERM;
399025f2121SDavid Sterba 
400025f2121SDavid Sterba 	if (btrfs_root_readonly(root))
401025f2121SDavid Sterba 		return -EROFS;
402025f2121SDavid Sterba 
403025f2121SDavid Sterba 	memset(&fa, 0, sizeof(fa));
404025f2121SDavid Sterba 	if (copy_from_user(&fa, arg, sizeof(fa)))
405025f2121SDavid Sterba 		return -EFAULT;
406025f2121SDavid Sterba 
407025f2121SDavid Sterba 	ret = check_xflags(fa.fsx_xflags);
408025f2121SDavid Sterba 	if (ret)
409025f2121SDavid Sterba 		return ret;
410025f2121SDavid Sterba 
411025f2121SDavid Sterba 	if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0)
412025f2121SDavid Sterba 		return -EOPNOTSUPP;
413025f2121SDavid Sterba 
414025f2121SDavid Sterba 	ret = mnt_want_write_file(file);
415025f2121SDavid Sterba 	if (ret)
416025f2121SDavid Sterba 		return ret;
417025f2121SDavid Sterba 
418025f2121SDavid Sterba 	inode_lock(inode);
419025f2121SDavid Sterba 
420025f2121SDavid Sterba 	old_flags = binode->flags;
421025f2121SDavid Sterba 	old_i_flags = inode->i_flags;
422025f2121SDavid Sterba 
423025f2121SDavid Sterba 	/* We need the capabilities to change append-only or immutable inode */
424025f2121SDavid Sterba 	if (((old_flags & (BTRFS_INODE_APPEND | BTRFS_INODE_IMMUTABLE)) ||
425025f2121SDavid Sterba 	     (fa.fsx_xflags & (FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE))) &&
426025f2121SDavid Sterba 	    !capable(CAP_LINUX_IMMUTABLE)) {
427025f2121SDavid Sterba 		ret = -EPERM;
428025f2121SDavid Sterba 		goto out_unlock;
429025f2121SDavid Sterba 	}
430025f2121SDavid Sterba 
431025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_SYNC)
432025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_SYNC;
433025f2121SDavid Sterba 	else
434025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_SYNC;
435025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE)
436025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_IMMUTABLE;
437025f2121SDavid Sterba 	else
438025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_IMMUTABLE;
439025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_APPEND)
440025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_APPEND;
441025f2121SDavid Sterba 	else
442025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_APPEND;
443025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_NODUMP)
444025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_NODUMP;
445025f2121SDavid Sterba 	else
446025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NODUMP;
447025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_NOATIME)
448025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_NOATIME;
449025f2121SDavid Sterba 	else
450025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NOATIME;
451025f2121SDavid Sterba 
452025f2121SDavid Sterba 	/* 1 item for the inode */
453025f2121SDavid Sterba 	trans = btrfs_start_transaction(root, 1);
454025f2121SDavid Sterba 	if (IS_ERR(trans)) {
455025f2121SDavid Sterba 		ret = PTR_ERR(trans);
456025f2121SDavid Sterba 		goto out_unlock;
457025f2121SDavid Sterba 	}
458025f2121SDavid Sterba 
459025f2121SDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
460025f2121SDavid Sterba 	inode_inc_iversion(inode);
461025f2121SDavid Sterba 	inode->i_ctime = current_time(inode);
462025f2121SDavid Sterba 	ret = btrfs_update_inode(trans, root, inode);
463025f2121SDavid Sterba 
464025f2121SDavid Sterba 	btrfs_end_transaction(trans);
465025f2121SDavid Sterba 
466025f2121SDavid Sterba out_unlock:
467025f2121SDavid Sterba 	if (ret) {
468025f2121SDavid Sterba 		binode->flags = old_flags;
469025f2121SDavid Sterba 		inode->i_flags = old_i_flags;
470025f2121SDavid Sterba 	}
471025f2121SDavid Sterba 
472025f2121SDavid Sterba 	inode_unlock(inode);
473025f2121SDavid Sterba 	mnt_drop_write_file(file);
474025f2121SDavid Sterba 
475025f2121SDavid Sterba 	return ret;
476025f2121SDavid Sterba }
477025f2121SDavid Sterba 
4786cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
4796cbff00fSChristoph Hellwig {
480496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4816cbff00fSChristoph Hellwig 
4826cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
4836cbff00fSChristoph Hellwig }
484f46b5a66SChristoph Hellwig 
485f7039b1dSLi Dongyang static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
486f7039b1dSLi Dongyang {
4870b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
4880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
489f7039b1dSLi Dongyang 	struct btrfs_device *device;
490f7039b1dSLi Dongyang 	struct request_queue *q;
491f7039b1dSLi Dongyang 	struct fstrim_range range;
492f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
493f7039b1dSLi Dongyang 	u64 num_devices = 0;
494815745cfSAl Viro 	u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
495f7039b1dSLi Dongyang 	int ret;
496f7039b1dSLi Dongyang 
497f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
498f7039b1dSLi Dongyang 		return -EPERM;
499f7039b1dSLi Dongyang 
5001f78160cSXiao Guangrong 	rcu_read_lock();
5011f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
5021f78160cSXiao Guangrong 				dev_list) {
503f7039b1dSLi Dongyang 		if (!device->bdev)
504f7039b1dSLi Dongyang 			continue;
505f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
506f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
507f7039b1dSLi Dongyang 			num_devices++;
50850d0446eSSeraphime Kirkovski 			minlen = min_t(u64, q->limits.discard_granularity,
509f7039b1dSLi Dongyang 				     minlen);
510f7039b1dSLi Dongyang 		}
511f7039b1dSLi Dongyang 	}
5121f78160cSXiao Guangrong 	rcu_read_unlock();
513f4c697e6SLukas Czerner 
514f7039b1dSLi Dongyang 	if (!num_devices)
515f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
516f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
517f7039b1dSLi Dongyang 		return -EFAULT;
518e515c18bSLukas Czerner 	if (range.start > total_bytes ||
519e515c18bSLukas Czerner 	    range.len < fs_info->sb->s_blocksize)
520f4c697e6SLukas Czerner 		return -EINVAL;
521f7039b1dSLi Dongyang 
522f4c697e6SLukas Czerner 	range.len = min(range.len, total_bytes - range.start);
523f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
5242ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
525f7039b1dSLi Dongyang 	if (ret < 0)
526f7039b1dSLi Dongyang 		return ret;
527f7039b1dSLi Dongyang 
528f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
529f7039b1dSLi Dongyang 		return -EFAULT;
530f7039b1dSLi Dongyang 
531f7039b1dSLi Dongyang 	return 0;
532f7039b1dSLi Dongyang }
533f7039b1dSLi Dongyang 
534dd5f9615SStefan Behrens int btrfs_is_empty_uuid(u8 *uuid)
535dd5f9615SStefan Behrens {
53646e0f66aSChris Mason 	int i;
53746e0f66aSChris Mason 
53846e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
53946e0f66aSChris Mason 		if (uuid[i])
54046e0f66aSChris Mason 			return 0;
54146e0f66aSChris Mason 	}
54246e0f66aSChris Mason 	return 1;
543dd5f9615SStefan Behrens }
544dd5f9615SStefan Behrens 
545d5c12070SMiao Xie static noinline int create_subvol(struct inode *dir,
546cb8e7090SChristoph Hellwig 				  struct dentry *dentry,
54752f75f4fSDavid Sterba 				  const char *name, int namelen,
5486f72c7e2SArne Jansen 				  u64 *async_transid,
5498696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
550f46b5a66SChristoph Hellwig {
5510b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
552f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
553f46b5a66SChristoph Hellwig 	struct btrfs_key key;
55449a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
555f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
556f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
557d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
55876dda93cSYan, Zheng 	struct btrfs_root *new_root;
559d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
56095582b00SDeepa Dinamani 	struct timespec64 cur_time = current_time(dir);
5615662344bSTsutomu Itoh 	struct inode *inode;
562f46b5a66SChristoph Hellwig 	int ret;
563f46b5a66SChristoph Hellwig 	int err;
564f46b5a66SChristoph Hellwig 	u64 objectid;
565f46b5a66SChristoph Hellwig 	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
5663de4586cSChris Mason 	u64 index = 0;
5678ea05e3aSAlexander Block 	uuid_le new_uuid;
568f46b5a66SChristoph Hellwig 
56949a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
57049a3c4d9SDavid Sterba 	if (!root_item)
57149a3c4d9SDavid Sterba 		return -ENOMEM;
57249a3c4d9SDavid Sterba 
5730b246afaSJeff Mahoney 	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
5742fbe8c8aSAl Viro 	if (ret)
57549a3c4d9SDavid Sterba 		goto fail_free;
5766a912213SJosef Bacik 
577e09fe2d2SQu Wenruo 	/*
578e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
57901327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
580e09fe2d2SQu Wenruo 	 */
58149a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
58249a3c4d9SDavid Sterba 		ret = -ENOSPC;
58349a3c4d9SDavid Sterba 		goto fail_free;
58449a3c4d9SDavid Sterba 	}
585e09fe2d2SQu Wenruo 
586d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
5879ed74f2dSJosef Bacik 	/*
588d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
589d5c12070SMiao Xie 	 * of create_snapshot().
5909ed74f2dSJosef Bacik 	 */
591c4c129dbSGu JinXiang 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
592d5c12070SMiao Xie 	if (ret)
59349a3c4d9SDavid Sterba 		goto fail_free;
594f46b5a66SChristoph Hellwig 
595d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
596d5c12070SMiao Xie 	if (IS_ERR(trans)) {
597d5c12070SMiao Xie 		ret = PTR_ERR(trans);
5987775c818SDavid Sterba 		btrfs_subvolume_release_metadata(fs_info, &block_rsv);
59949a3c4d9SDavid Sterba 		goto fail_free;
600d5c12070SMiao Xie 	}
601d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
602d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
603f46b5a66SChristoph Hellwig 
6040b246afaSJeff Mahoney 	ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
6056f72c7e2SArne Jansen 	if (ret)
6066f72c7e2SArne Jansen 		goto fail;
6076f72c7e2SArne Jansen 
6084d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
6098e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
6108e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
6118e8a1e31SJosef Bacik 		goto fail;
6128e8a1e31SJosef Bacik 	}
613f46b5a66SChristoph Hellwig 
614f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
615f46b5a66SChristoph Hellwig 
61649a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
6173cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
6183cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
6193cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
620da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
6210b246afaSJeff Mahoney 				     fs_info->nodesize);
6223cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
623f46b5a66SChristoph Hellwig 
62449a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
62549a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
6263cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
62708fe4db1SLi Zefan 
62849a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
62949a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
63049a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
63149a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
63249a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
63349a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
634f46b5a66SChristoph Hellwig 
63549a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
63649a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
6378ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
63849a3c4d9SDavid Sterba 	memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
63949a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
64049a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
64149a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
64249a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
64349a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
644f46b5a66SChristoph Hellwig 
645925baeddSChris Mason 	btrfs_tree_unlock(leaf);
646f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
647f46b5a66SChristoph Hellwig 	leaf = NULL;
648f46b5a66SChristoph Hellwig 
64949a3c4d9SDavid Sterba 	btrfs_set_root_dirid(root_item, new_dirid);
650f46b5a66SChristoph Hellwig 
651f46b5a66SChristoph Hellwig 	key.objectid = objectid;
6525d4f98a2SYan Zheng 	key.offset = 0;
653962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
6540b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
65549a3c4d9SDavid Sterba 				root_item);
656f46b5a66SChristoph Hellwig 	if (ret)
657f46b5a66SChristoph Hellwig 		goto fail;
658f46b5a66SChristoph Hellwig 
65976dda93cSYan, Zheng 	key.offset = (u64)-1;
6600b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &key);
66179787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
66279787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
66366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
66479787eaaSJeff Mahoney 		goto fail;
66579787eaaSJeff Mahoney 	}
66676dda93cSYan, Zheng 
66776dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
66876dda93cSYan, Zheng 
66963541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
670ce598979SMark Fasheh 	if (ret) {
671ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
67266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
673ce598979SMark Fasheh 		goto fail;
674ce598979SMark Fasheh 	}
675ce598979SMark Fasheh 
676f32e48e9SChandan Rajendra 	mutex_lock(&new_root->objectid_mutex);
677f32e48e9SChandan Rajendra 	new_root->highest_objectid = new_dirid;
678f32e48e9SChandan Rajendra 	mutex_unlock(&new_root->objectid_mutex);
679f32e48e9SChandan Rajendra 
680f46b5a66SChristoph Hellwig 	/*
681f46b5a66SChristoph Hellwig 	 * insert the directory item
682f46b5a66SChristoph Hellwig 	 */
683877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
68479787eaaSJeff Mahoney 	if (ret) {
68566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
68679787eaaSJeff Mahoney 		goto fail;
68779787eaaSJeff Mahoney 	}
6883de4586cSChris Mason 
6893de4586cSChris Mason 	ret = btrfs_insert_dir_item(trans, root,
6908e7611cfSNikolay Borisov 				    name, namelen, BTRFS_I(dir), &key,
6913de4586cSChris Mason 				    BTRFS_FT_DIR, index);
69279787eaaSJeff Mahoney 	if (ret) {
69366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
694f46b5a66SChristoph Hellwig 		goto fail;
69579787eaaSJeff Mahoney 	}
6960660b5afSChris Mason 
6976ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
69852c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
69952c26179SYan Zheng 	BUG_ON(ret);
70052c26179SYan Zheng 
7010b246afaSJeff Mahoney 	ret = btrfs_add_root_ref(trans, fs_info,
7024df27c4dSYan, Zheng 				 objectid, root->root_key.objectid,
7034a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
7040660b5afSChris Mason 	BUG_ON(ret);
7050660b5afSChris Mason 
706cdb345a8SLu Fengqi 	ret = btrfs_uuid_tree_add(trans, root_item->uuid,
7076bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
708dd5f9615SStefan Behrens 	if (ret)
70966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
710dd5f9615SStefan Behrens 
711f46b5a66SChristoph Hellwig fail:
71249a3c4d9SDavid Sterba 	kfree(root_item);
713d5c12070SMiao Xie 	trans->block_rsv = NULL;
714d5c12070SMiao Xie 	trans->bytes_reserved = 0;
7157775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
716de6e8200SLiu Bo 
71772fd032eSSage Weil 	if (async_transid) {
71872fd032eSSage Weil 		*async_transid = trans->transid;
7193a45bb20SJeff Mahoney 		err = btrfs_commit_transaction_async(trans, 1);
72000d71c9cSMiao Xie 		if (err)
7213a45bb20SJeff Mahoney 			err = btrfs_commit_transaction(trans);
72272fd032eSSage Weil 	} else {
7233a45bb20SJeff Mahoney 		err = btrfs_commit_transaction(trans);
72472fd032eSSage Weil 	}
725f46b5a66SChristoph Hellwig 	if (err && !ret)
726f46b5a66SChristoph Hellwig 		ret = err;
7271a65e24bSChris Mason 
7285662344bSTsutomu Itoh 	if (!ret) {
7295662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
730de6e8200SLiu Bo 		if (IS_ERR(inode))
731de6e8200SLiu Bo 			return PTR_ERR(inode);
7325662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
7335662344bSTsutomu Itoh 	}
734f46b5a66SChristoph Hellwig 	return ret;
73549a3c4d9SDavid Sterba 
73649a3c4d9SDavid Sterba fail_free:
73749a3c4d9SDavid Sterba 	kfree(root_item);
73849a3c4d9SDavid Sterba 	return ret;
739f46b5a66SChristoph Hellwig }
740f46b5a66SChristoph Hellwig 
741e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
74261d7e4cbSDavid Sterba 			   struct dentry *dentry,
743e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
744e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
745f46b5a66SChristoph Hellwig {
7460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
7472e4bfab9SYan, Zheng 	struct inode *inode;
748f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
749f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
7502e4bfab9SYan, Zheng 	int ret;
751f46b5a66SChristoph Hellwig 
75227cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
753f46b5a66SChristoph Hellwig 		return -EINVAL;
754f46b5a66SChristoph Hellwig 
75523269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
756a1ee7362SDavid Sterba 	if (!pending_snapshot)
757a1ee7362SDavid Sterba 		return -ENOMEM;
758a1ee7362SDavid Sterba 
759b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
76023269bf5SDavid Sterba 			GFP_KERNEL);
7618546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
7628546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
763b0c0ea63SDavid Sterba 		ret = -ENOMEM;
764b0c0ea63SDavid Sterba 		goto free_pending;
765b0c0ea63SDavid Sterba 	}
766b0c0ea63SDavid Sterba 
767ea14b57fSDavid Sterba 	atomic_inc(&root->will_be_snapshotted);
7684e857c58SPeter Zijlstra 	smp_mb__after_atomic();
76945bac0f3SLiu Bo 	/* wait for no snapshot writes */
77045bac0f3SLiu Bo 	wait_event(root->subv_writers->wait,
77145bac0f3SLiu Bo 		   percpu_counter_sum(&root->subv_writers->counter) == 0);
7728257b2dcSMiao Xie 
77376f32e24SNikolay Borisov 	ret = btrfs_start_delalloc_inodes(root);
7746a03843dSMiao Xie 	if (ret)
775a1ee7362SDavid Sterba 		goto dec_and_free;
7766a03843dSMiao Xie 
7776374e57aSChris Mason 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
7786a03843dSMiao Xie 
77966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
78066d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
781d5c12070SMiao Xie 	/*
782d5c12070SMiao Xie 	 * 1 - parent dir inode
783d5c12070SMiao Xie 	 * 2 - dir entries
784d5c12070SMiao Xie 	 * 1 - root item
785d5c12070SMiao Xie 	 * 2 - root ref/backref
786d5c12070SMiao Xie 	 * 1 - root of snapshot
787dd5f9615SStefan Behrens 	 * 1 - UUID item
788d5c12070SMiao Xie 	 */
789d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
790dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
791ee3441b4SJeff Mahoney 					false);
792d5c12070SMiao Xie 	if (ret)
793a1ee7362SDavid Sterba 		goto dec_and_free;
794d5c12070SMiao Xie 
795a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
796a22285a6SYan, Zheng 	pending_snapshot->root = root;
797b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
798e9662f70SMiao Xie 	pending_snapshot->dir = dir;
7998696c533SMiao Xie 	pending_snapshot->inherit = inherit;
800a22285a6SYan, Zheng 
801d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
802a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
803a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
804a22285a6SYan, Zheng 		goto fail;
805a22285a6SYan, Zheng 	}
806a22285a6SYan, Zheng 
8070b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
808a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
809a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
8100b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
81172fd032eSSage Weil 	if (async_transid) {
81272fd032eSSage Weil 		*async_transid = trans->transid;
8133a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction_async(trans, 1);
81400d71c9cSMiao Xie 		if (ret)
8153a45bb20SJeff Mahoney 			ret = btrfs_commit_transaction(trans);
81672fd032eSSage Weil 	} else {
8173a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
81872fd032eSSage Weil 	}
819aec8030aSMiao Xie 	if (ret)
820c37b2b62SJosef Bacik 		goto fail;
821a22285a6SYan, Zheng 
822a22285a6SYan, Zheng 	ret = pending_snapshot->error;
823f46b5a66SChristoph Hellwig 	if (ret)
8242e4bfab9SYan, Zheng 		goto fail;
825f46b5a66SChristoph Hellwig 
826d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
827d3797308SChris Mason 	if (ret)
828d3797308SChris Mason 		goto fail;
829d3797308SChris Mason 
8302b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
8312e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
8322e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
8332e4bfab9SYan, Zheng 		goto fail;
8342e4bfab9SYan, Zheng 	}
8355662344bSTsutomu Itoh 
8362e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
8372e4bfab9SYan, Zheng 	ret = 0;
8382e4bfab9SYan, Zheng fail:
8397775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
840a1ee7362SDavid Sterba dec_and_free:
841ea14b57fSDavid Sterba 	if (atomic_dec_and_test(&root->will_be_snapshotted))
8424625956aSPeter Zijlstra 		wake_up_var(&root->will_be_snapshotted);
843b0c0ea63SDavid Sterba free_pending:
844b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
8458546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
846a1ee7362SDavid Sterba 	kfree(pending_snapshot);
847a1ee7362SDavid Sterba 
848f46b5a66SChristoph Hellwig 	return ret;
849f46b5a66SChristoph Hellwig }
850f46b5a66SChristoph Hellwig 
8514260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
8524260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
8534260f7c7SSage Weil  *  whether the type of victim is right.
8544260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
8554260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
8564260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
8574260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
8584260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
8594260f7c7SSage Weil  *	a. be owner of dir, or
8604260f7c7SSage Weil  *	b. be owner of victim, or
8614260f7c7SSage Weil  *	c. have CAP_FOWNER capability
86201327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
8634260f7c7SSage Weil  *     links pointing to it.
8644260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
8654260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
8664260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
8674260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
8684260f7c7SSage Weil  *     nfs_async_unlink().
8694260f7c7SSage Weil  */
8704260f7c7SSage Weil 
8714260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
8724260f7c7SSage Weil {
8734260f7c7SSage Weil 	int error;
8744260f7c7SSage Weil 
8752b0143b5SDavid Howells 	if (d_really_is_negative(victim))
8764260f7c7SSage Weil 		return -ENOENT;
8774260f7c7SSage Weil 
8782b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
8794fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
8804260f7c7SSage Weil 
8814260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
8824260f7c7SSage Weil 	if (error)
8834260f7c7SSage Weil 		return error;
8844260f7c7SSage Weil 	if (IS_APPEND(dir))
8854260f7c7SSage Weil 		return -EPERM;
8862b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
8872b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
8884260f7c7SSage Weil 		return -EPERM;
8894260f7c7SSage Weil 	if (isdir) {
890e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
8914260f7c7SSage Weil 			return -ENOTDIR;
8924260f7c7SSage Weil 		if (IS_ROOT(victim))
8934260f7c7SSage Weil 			return -EBUSY;
894e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
8954260f7c7SSage Weil 		return -EISDIR;
8964260f7c7SSage Weil 	if (IS_DEADDIR(dir))
8974260f7c7SSage Weil 		return -ENOENT;
8984260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
8994260f7c7SSage Weil 		return -EBUSY;
9004260f7c7SSage Weil 	return 0;
9014260f7c7SSage Weil }
9024260f7c7SSage Weil 
903cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
904cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
905cb8e7090SChristoph Hellwig {
9062b0143b5SDavid Howells 	if (d_really_is_positive(child))
907cb8e7090SChristoph Hellwig 		return -EEXIST;
908cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
909cb8e7090SChristoph Hellwig 		return -ENOENT;
910cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
911cb8e7090SChristoph Hellwig }
912cb8e7090SChristoph Hellwig 
913cb8e7090SChristoph Hellwig /*
914cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
915cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
916cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
917cb8e7090SChristoph Hellwig  */
91892872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
91952f75f4fSDavid Sterba 				   const char *name, int namelen,
92072fd032eSSage Weil 				   struct btrfs_root *snap_src,
9216f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
9228696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
923cb8e7090SChristoph Hellwig {
9242b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
9250b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
926cb8e7090SChristoph Hellwig 	struct dentry *dentry;
927cb8e7090SChristoph Hellwig 	int error;
928cb8e7090SChristoph Hellwig 
92900235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
93000235411SAl Viro 	if (error == -EINTR)
93100235411SAl Viro 		return error;
932cb8e7090SChristoph Hellwig 
933cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
934cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
935cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
936cb8e7090SChristoph Hellwig 		goto out_unlock;
937cb8e7090SChristoph Hellwig 
93876dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
939cb8e7090SChristoph Hellwig 	if (error)
940a874a63eSLiu Bo 		goto out_dput;
941cb8e7090SChristoph Hellwig 
9429c52057cSChris Mason 	/*
9439c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
9449c52057cSChris Mason 	 * check for them now when we can safely fail
9459c52057cSChris Mason 	 */
9469c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
9479c52057cSChris Mason 					       dir->i_ino, name,
9489c52057cSChris Mason 					       namelen);
9499c52057cSChris Mason 	if (error)
9509c52057cSChris Mason 		goto out_dput;
9519c52057cSChris Mason 
9520b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
95376dda93cSYan, Zheng 
95476dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
95576dda93cSYan, Zheng 		goto out_up_read;
95676dda93cSYan, Zheng 
9573de4586cSChris Mason 	if (snap_src) {
95861d7e4cbSDavid Sterba 		error = create_snapshot(snap_src, dir, dentry,
9596f72c7e2SArne Jansen 					async_transid, readonly, inherit);
9603de4586cSChris Mason 	} else {
961d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
962d5c12070SMiao Xie 				      async_transid, inherit);
9633de4586cSChris Mason 	}
96476dda93cSYan, Zheng 	if (!error)
96576dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
96676dda93cSYan, Zheng out_up_read:
9670b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
968cb8e7090SChristoph Hellwig out_dput:
969cb8e7090SChristoph Hellwig 	dput(dentry);
970cb8e7090SChristoph Hellwig out_unlock:
9715955102cSAl Viro 	inode_unlock(dir);
972cb8e7090SChristoph Hellwig 	return error;
973cb8e7090SChristoph Hellwig }
974cb8e7090SChristoph Hellwig 
9754cb5300bSChris Mason /*
9764cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
9774cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
9784cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
9794cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
9804cb5300bSChris Mason  * part of the file
9814cb5300bSChris Mason  */
982aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
9834cb5300bSChris Mason {
9844cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9854cb5300bSChris Mason 	struct extent_map *em = NULL;
9864cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9874cb5300bSChris Mason 	u64 end;
9884cb5300bSChris Mason 
9894cb5300bSChris Mason 	read_lock(&em_tree->lock);
99009cbfeafSKirill A. Shutemov 	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
9914cb5300bSChris Mason 	read_unlock(&em_tree->lock);
9924cb5300bSChris Mason 
9934cb5300bSChris Mason 	if (em) {
9944cb5300bSChris Mason 		end = extent_map_end(em);
9954cb5300bSChris Mason 		free_extent_map(em);
9964cb5300bSChris Mason 		if (end - offset > thresh)
9974cb5300bSChris Mason 			return 0;
9984cb5300bSChris Mason 	}
9994cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
10004cb5300bSChris Mason 	thresh /= 2;
10014cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
10024cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
10034cb5300bSChris Mason 	if (end >= thresh)
10044cb5300bSChris Mason 		return 0;
10054cb5300bSChris Mason 	return 1;
10064cb5300bSChris Mason }
10074cb5300bSChris Mason 
10084cb5300bSChris Mason /*
10094cb5300bSChris Mason  * helper function to walk through a file and find extents
10104cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
10114cb5300bSChris Mason  *
10124cb5300bSChris Mason  * This is used by the defragging code to find new and small
10134cb5300bSChris Mason  * extents
10144cb5300bSChris Mason  */
10154cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
10164cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
1017aab110abSDavid Sterba 			    u64 *off, u32 thresh)
10184cb5300bSChris Mason {
10194cb5300bSChris Mason 	struct btrfs_path *path;
10204cb5300bSChris Mason 	struct btrfs_key min_key;
10214cb5300bSChris Mason 	struct extent_buffer *leaf;
10224cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
10234cb5300bSChris Mason 	int type;
10244cb5300bSChris Mason 	int ret;
10254a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
10264cb5300bSChris Mason 
10274cb5300bSChris Mason 	path = btrfs_alloc_path();
10284cb5300bSChris Mason 	if (!path)
10294cb5300bSChris Mason 		return -ENOMEM;
10304cb5300bSChris Mason 
1031a4689d2bSDavid Sterba 	min_key.objectid = ino;
10324cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
10334cb5300bSChris Mason 	min_key.offset = *off;
10344cb5300bSChris Mason 
10354cb5300bSChris Mason 	while (1) {
10366174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
10374cb5300bSChris Mason 		if (ret != 0)
10384cb5300bSChris Mason 			goto none;
1039f094c9bdSFilipe Manana process_slot:
1040a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
10414cb5300bSChris Mason 			goto none;
10424cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
10434cb5300bSChris Mason 			goto none;
10444cb5300bSChris Mason 
10454cb5300bSChris Mason 		leaf = path->nodes[0];
10464cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
10474cb5300bSChris Mason 					struct btrfs_file_extent_item);
10484cb5300bSChris Mason 
10494cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
10504cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
10514cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
10524cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
10534cb5300bSChris Mason 			*off = min_key.offset;
10544cb5300bSChris Mason 			btrfs_free_path(path);
10554cb5300bSChris Mason 			return 0;
10564cb5300bSChris Mason 		}
10574cb5300bSChris Mason 
1058f094c9bdSFilipe Manana 		path->slots[0]++;
1059f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
1060f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1061f094c9bdSFilipe Manana 			goto process_slot;
1062f094c9bdSFilipe Manana 		}
1063f094c9bdSFilipe Manana 
10644cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
10654cb5300bSChris Mason 			goto none;
10664cb5300bSChris Mason 
10674cb5300bSChris Mason 		min_key.offset++;
10684cb5300bSChris Mason 		btrfs_release_path(path);
10694cb5300bSChris Mason 	}
10704cb5300bSChris Mason none:
10714cb5300bSChris Mason 	btrfs_free_path(path);
10724cb5300bSChris Mason 	return -ENOENT;
10734cb5300bSChris Mason }
10744cb5300bSChris Mason 
10756c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
107617ce6ef8SLiu Bo {
107717ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1078940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10796c282eb4SLi Zefan 	struct extent_map *em;
108009cbfeafSKirill A. Shutemov 	u64 len = PAGE_SIZE;
1081940100a4SChris Mason 
1082940100a4SChris Mason 	/*
1083940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
1084940100a4SChris Mason 	 * the full extent lock
1085940100a4SChris Mason 	 */
1086940100a4SChris Mason 	read_lock(&em_tree->lock);
1087940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
1088940100a4SChris Mason 	read_unlock(&em_tree->lock);
1089940100a4SChris Mason 
1090940100a4SChris Mason 	if (!em) {
1091308d9800SFilipe Manana 		struct extent_state *cached = NULL;
1092308d9800SFilipe Manana 		u64 end = start + len - 1;
1093308d9800SFilipe Manana 
1094940100a4SChris Mason 		/* get the big lock and read metadata off disk */
1095ff13db41SDavid Sterba 		lock_extent_bits(io_tree, start, end, &cached);
1096fc4f21b1SNikolay Borisov 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1097e43bbe5eSDavid Sterba 		unlock_extent_cached(io_tree, start, end, &cached);
1098940100a4SChris Mason 
10996cf8bfbfSDan Carpenter 		if (IS_ERR(em))
11006c282eb4SLi Zefan 			return NULL;
1101940100a4SChris Mason 	}
1102940100a4SChris Mason 
11036c282eb4SLi Zefan 	return em;
11046c282eb4SLi Zefan }
11056c282eb4SLi Zefan 
11066c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
11076c282eb4SLi Zefan {
11086c282eb4SLi Zefan 	struct extent_map *next;
11096c282eb4SLi Zefan 	bool ret = true;
11106c282eb4SLi Zefan 
11116c282eb4SLi Zefan 	/* this is the last extent */
11126c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
11136c282eb4SLi Zefan 		return false;
11146c282eb4SLi Zefan 
11156c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
1116e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1117e9512d72SChris Mason 		ret = false;
1118e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1119ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
11206c282eb4SLi Zefan 		ret = false;
11216c282eb4SLi Zefan 
11226c282eb4SLi Zefan 	free_extent_map(next);
11236c282eb4SLi Zefan 	return ret;
11246c282eb4SLi Zefan }
11256c282eb4SLi Zefan 
1126aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1127a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
1128a43a2111SAndrew Mahone 			       int compress)
11296c282eb4SLi Zefan {
11306c282eb4SLi Zefan 	struct extent_map *em;
11316c282eb4SLi Zefan 	int ret = 1;
11326c282eb4SLi Zefan 	bool next_mergeable = true;
11334a3560c4SLiu Bo 	bool prev_mergeable = true;
11346c282eb4SLi Zefan 
11356c282eb4SLi Zefan 	/*
11366c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
11376c282eb4SLi Zefan 	 * defragging it
11386c282eb4SLi Zefan 	 */
11396c282eb4SLi Zefan 	if (start < *defrag_end)
11406c282eb4SLi Zefan 		return 1;
11416c282eb4SLi Zefan 
11426c282eb4SLi Zefan 	*skip = 0;
11436c282eb4SLi Zefan 
11446c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
11456c282eb4SLi Zefan 	if (!em)
11466c282eb4SLi Zefan 		return 0;
11476c282eb4SLi Zefan 
1148940100a4SChris Mason 	/* this will cover holes, and inline extents */
114917ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1150940100a4SChris Mason 		ret = 0;
115117ce6ef8SLiu Bo 		goto out;
115217ce6ef8SLiu Bo 	}
115317ce6ef8SLiu Bo 
11544a3560c4SLiu Bo 	if (!*defrag_end)
11554a3560c4SLiu Bo 		prev_mergeable = false;
11564a3560c4SLiu Bo 
11576c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1158940100a4SChris Mason 	/*
11596c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
11606c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1161940100a4SChris Mason 	 */
1162a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
11634a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1164940100a4SChris Mason 		ret = 0;
116517ce6ef8SLiu Bo out:
1166940100a4SChris Mason 	/*
1167940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1168940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1169940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1170940100a4SChris Mason 	 *
1171940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1172940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1173940100a4SChris Mason 	 */
1174940100a4SChris Mason 	if (ret) {
1175940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1176940100a4SChris Mason 	} else {
1177940100a4SChris Mason 		*last_len = 0;
1178940100a4SChris Mason 		*skip = extent_map_end(em);
1179940100a4SChris Mason 		*defrag_end = 0;
1180940100a4SChris Mason 	}
1181940100a4SChris Mason 
1182940100a4SChris Mason 	free_extent_map(em);
1183940100a4SChris Mason 	return ret;
1184940100a4SChris Mason }
1185940100a4SChris Mason 
11864cb5300bSChris Mason /*
11874cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
11884cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
11894cb5300bSChris Mason  * to COW and defrag.
11904cb5300bSChris Mason  *
11914cb5300bSChris Mason  * It also makes sure the delalloc code has enough
11924cb5300bSChris Mason  * dirty data to avoid making new small extents as part
11934cb5300bSChris Mason  * of the defrag
11944cb5300bSChris Mason  *
11954cb5300bSChris Mason  * It's a good idea to start RA on this range
11964cb5300bSChris Mason  * before calling this.
11974cb5300bSChris Mason  */
11984cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
11994cb5300bSChris Mason 				    struct page **pages,
12004cb5300bSChris Mason 				    unsigned long start_index,
1201c41570c9SJustin Maggard 				    unsigned long num_pages)
1202f46b5a66SChristoph Hellwig {
12034cb5300bSChris Mason 	unsigned long file_end;
12044cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1205f46b5a66SChristoph Hellwig 	u64 page_start;
1206f46b5a66SChristoph Hellwig 	u64 page_end;
12071f12bd06SLiu Bo 	u64 page_cnt;
12084cb5300bSChris Mason 	int ret;
12094cb5300bSChris Mason 	int i;
12104cb5300bSChris Mason 	int i_done;
12114cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
12124cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1213600a45e1SMiao Xie 	struct extent_io_tree *tree;
1214364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
12153b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
12164cb5300bSChris Mason 
121709cbfeafSKirill A. Shutemov 	file_end = (isize - 1) >> PAGE_SHIFT;
12181f12bd06SLiu Bo 	if (!isize || start_index > file_end)
12191f12bd06SLiu Bo 		return 0;
12201f12bd06SLiu Bo 
12211f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
12224cb5300bSChris Mason 
1223364ecf36SQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
122409cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
122509cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
12264cb5300bSChris Mason 	if (ret)
12274cb5300bSChris Mason 		return ret;
12284cb5300bSChris Mason 	i_done = 0;
1229600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
12304cb5300bSChris Mason 
12314cb5300bSChris Mason 	/* step one, lock all the pages */
12321f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
12334cb5300bSChris Mason 		struct page *page;
1234600a45e1SMiao Xie again:
1235a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
12363b16a4e3SJosef Bacik 					   start_index + i, mask);
12374cb5300bSChris Mason 		if (!page)
12384cb5300bSChris Mason 			break;
12394cb5300bSChris Mason 
1240600a45e1SMiao Xie 		page_start = page_offset(page);
124109cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
1242600a45e1SMiao Xie 		while (1) {
1243308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1244ff13db41SDavid Sterba 					 &cached_state);
1245600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1246600a45e1SMiao Xie 							      page_start);
1247308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1248e43bbe5eSDavid Sterba 					     &cached_state);
1249600a45e1SMiao Xie 			if (!ordered)
1250600a45e1SMiao Xie 				break;
1251600a45e1SMiao Xie 
1252600a45e1SMiao Xie 			unlock_page(page);
1253600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1254600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1255600a45e1SMiao Xie 			lock_page(page);
12561f12bd06SLiu Bo 			/*
12571f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
12581f12bd06SLiu Bo 			 * it was released or not.
12591f12bd06SLiu Bo 			 */
12601f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
12611f12bd06SLiu Bo 				unlock_page(page);
126209cbfeafSKirill A. Shutemov 				put_page(page);
12631f12bd06SLiu Bo 				goto again;
12641f12bd06SLiu Bo 			}
1265600a45e1SMiao Xie 		}
1266600a45e1SMiao Xie 
12674cb5300bSChris Mason 		if (!PageUptodate(page)) {
12684cb5300bSChris Mason 			btrfs_readpage(NULL, page);
12694cb5300bSChris Mason 			lock_page(page);
12704cb5300bSChris Mason 			if (!PageUptodate(page)) {
12714cb5300bSChris Mason 				unlock_page(page);
127209cbfeafSKirill A. Shutemov 				put_page(page);
12734cb5300bSChris Mason 				ret = -EIO;
12744cb5300bSChris Mason 				break;
12754cb5300bSChris Mason 			}
12764cb5300bSChris Mason 		}
1277600a45e1SMiao Xie 
1278600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1279600a45e1SMiao Xie 			unlock_page(page);
128009cbfeafSKirill A. Shutemov 			put_page(page);
1281600a45e1SMiao Xie 			goto again;
1282600a45e1SMiao Xie 		}
1283600a45e1SMiao Xie 
12844cb5300bSChris Mason 		pages[i] = page;
12854cb5300bSChris Mason 		i_done++;
12864cb5300bSChris Mason 	}
12874cb5300bSChris Mason 	if (!i_done || ret)
12884cb5300bSChris Mason 		goto out;
12894cb5300bSChris Mason 
12901751e8a6SLinus Torvalds 	if (!(inode->i_sb->s_flags & SB_ACTIVE))
12914cb5300bSChris Mason 		goto out;
12924cb5300bSChris Mason 
12934cb5300bSChris Mason 	/*
12944cb5300bSChris Mason 	 * so now we have a nice long stream of locked
12954cb5300bSChris Mason 	 * and up to date pages, lets wait on them
12964cb5300bSChris Mason 	 */
12974cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
12984cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
12994cb5300bSChris Mason 
13004cb5300bSChris Mason 	page_start = page_offset(pages[0]);
130109cbfeafSKirill A. Shutemov 	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
13024cb5300bSChris Mason 
13034cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1304ff13db41SDavid Sterba 			 page_start, page_end - 1, &cached_state);
13054cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
13064cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
13079e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1308ae0f1625SDavid Sterba 			  &cached_state);
13094cb5300bSChris Mason 
13101f12bd06SLiu Bo 	if (i_done != page_cnt) {
13119e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
13129e0baf60SJosef Bacik 		BTRFS_I(inode)->outstanding_extents++;
13139e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
1314bc42bda2SQu Wenruo 		btrfs_delalloc_release_space(inode, data_reserved,
131509cbfeafSKirill A. Shutemov 				start_index << PAGE_SHIFT,
131643b18595SQu Wenruo 				(page_cnt - i_done) << PAGE_SHIFT, true);
13174cb5300bSChris Mason 	}
13184cb5300bSChris Mason 
13194cb5300bSChris Mason 
13209e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1321018ed4f7SDavid Sterba 			  &cached_state);
13224cb5300bSChris Mason 
13234cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1324e43bbe5eSDavid Sterba 			     page_start, page_end - 1, &cached_state);
13254cb5300bSChris Mason 
13264cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
13274cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
13284cb5300bSChris Mason 		ClearPageChecked(pages[i]);
13294cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
13304cb5300bSChris Mason 		set_page_dirty(pages[i]);
13314cb5300bSChris Mason 		unlock_page(pages[i]);
133209cbfeafSKirill A. Shutemov 		put_page(pages[i]);
13334cb5300bSChris Mason 	}
133443b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
133543b18595SQu Wenruo 				       false);
1336364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
13374cb5300bSChris Mason 	return i_done;
13384cb5300bSChris Mason out:
13394cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
13404cb5300bSChris Mason 		unlock_page(pages[i]);
134109cbfeafSKirill A. Shutemov 		put_page(pages[i]);
13424cb5300bSChris Mason 	}
1343bc42bda2SQu Wenruo 	btrfs_delalloc_release_space(inode, data_reserved,
134409cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
134543b18595SQu Wenruo 			page_cnt << PAGE_SHIFT, true);
134643b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
134743b18595SQu Wenruo 				       true);
1348364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
13494cb5300bSChris Mason 	return ret;
13504cb5300bSChris Mason 
13514cb5300bSChris Mason }
13524cb5300bSChris Mason 
13534cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
13544cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
13554cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
13564cb5300bSChris Mason {
13570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
13584cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
13594cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
13604cb5300bSChris Mason 	unsigned long last_index;
1361151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1362940100a4SChris Mason 	u64 last_len = 0;
1363940100a4SChris Mason 	u64 skip = 0;
1364940100a4SChris Mason 	u64 defrag_end = 0;
13654cb5300bSChris Mason 	u64 newer_off = range->start;
1366f46b5a66SChristoph Hellwig 	unsigned long i;
1367008873eaSLi Zefan 	unsigned long ra_index = 0;
1368f46b5a66SChristoph Hellwig 	int ret;
13694cb5300bSChris Mason 	int defrag_count = 0;
13701a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1371aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
137209cbfeafSKirill A. Shutemov 	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1373c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
1374ee22184bSByongho Lee 	u64 new_align = ~((u64)SZ_128K - 1);
13754cb5300bSChris Mason 	struct page **pages = NULL;
13761e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
13774cb5300bSChris Mason 
13780abd5b17SLiu Bo 	if (isize == 0)
13790abd5b17SLiu Bo 		return 0;
13800abd5b17SLiu Bo 
13810abd5b17SLiu Bo 	if (range->start >= isize)
13820abd5b17SLiu Bo 		return -EINVAL;
13831a419d85SLi Zefan 
13841e2ef46dSDavid Sterba 	if (do_compress) {
13851a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
13861a419d85SLi Zefan 			return -EINVAL;
13871a419d85SLi Zefan 		if (range->compress_type)
13881a419d85SLi Zefan 			compress_type = range->compress_type;
13891a419d85SLi Zefan 	}
1390f46b5a66SChristoph Hellwig 
13910abd5b17SLiu Bo 	if (extent_thresh == 0)
1392ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1393f46b5a66SChristoph Hellwig 
13944cb5300bSChris Mason 	/*
13950a52d108SDavid Sterba 	 * If we were not given a file, allocate a readahead context. As
13960a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
13970a52d108SDavid Sterba 	 * we don't error out.
13984cb5300bSChris Mason 	 */
13994cb5300bSChris Mason 	if (!file) {
140063e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
14010a52d108SDavid Sterba 		if (ra)
14024cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
14034cb5300bSChris Mason 	} else {
14044cb5300bSChris Mason 		ra = &file->f_ra;
14054cb5300bSChris Mason 	}
14064cb5300bSChris Mason 
140763e727ecSDavid Sterba 	pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
14084cb5300bSChris Mason 	if (!pages) {
14094cb5300bSChris Mason 		ret = -ENOMEM;
14104cb5300bSChris Mason 		goto out_ra;
14114cb5300bSChris Mason 	}
14124cb5300bSChris Mason 
14134cb5300bSChris Mason 	/* find the last page to defrag */
14141e701a32SChris Mason 	if (range->start + range->len > range->start) {
1415151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
141609cbfeafSKirill A. Shutemov 			 range->start + range->len - 1) >> PAGE_SHIFT;
14171e701a32SChris Mason 	} else {
141809cbfeafSKirill A. Shutemov 		last_index = (isize - 1) >> PAGE_SHIFT;
14191e701a32SChris Mason 	}
14201e701a32SChris Mason 
14214cb5300bSChris Mason 	if (newer_than) {
14224cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
1423ee22184bSByongho Lee 				       &newer_off, SZ_64K);
14244cb5300bSChris Mason 		if (!ret) {
14254cb5300bSChris Mason 			range->start = newer_off;
14264cb5300bSChris Mason 			/*
14274cb5300bSChris Mason 			 * we always align our defrag to help keep
14284cb5300bSChris Mason 			 * the extents in the file evenly spaced
14294cb5300bSChris Mason 			 */
143009cbfeafSKirill A. Shutemov 			i = (newer_off & new_align) >> PAGE_SHIFT;
14314cb5300bSChris Mason 		} else
14324cb5300bSChris Mason 			goto out_ra;
14334cb5300bSChris Mason 	} else {
143409cbfeafSKirill A. Shutemov 		i = range->start >> PAGE_SHIFT;
14354cb5300bSChris Mason 	}
14364cb5300bSChris Mason 	if (!max_to_defrag)
1437070034bdSchandan 		max_to_defrag = last_index - i + 1;
14384cb5300bSChris Mason 
14392a0f7f57SLi Zefan 	/*
14402a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
14412a0f7f57SLi Zefan 	 * written sequentially.
14422a0f7f57SLi Zefan 	 */
14432a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
14442a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
14452a0f7f57SLi Zefan 
1446f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
144709cbfeafSKirill A. Shutemov 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
14484cb5300bSChris Mason 		/*
14494cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
14504cb5300bSChris Mason 		 * the FS
14514cb5300bSChris Mason 		 */
14521751e8a6SLinus Torvalds 		if (!(inode->i_sb->s_flags & SB_ACTIVE))
14534cb5300bSChris Mason 			break;
14544cb5300bSChris Mason 
14550b246afaSJeff Mahoney 		if (btrfs_defrag_cancelled(fs_info)) {
14560b246afaSJeff Mahoney 			btrfs_debug(fs_info, "defrag_file cancelled");
1457210549ebSDavid Sterba 			ret = -EAGAIN;
1458210549ebSDavid Sterba 			break;
1459210549ebSDavid Sterba 		}
1460210549ebSDavid Sterba 
146109cbfeafSKirill A. Shutemov 		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
14626c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
14631e2ef46dSDavid Sterba 					 &defrag_end, do_compress)){
1464940100a4SChris Mason 			unsigned long next;
1465940100a4SChris Mason 			/*
1466940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1467940100a4SChris Mason 			 * bump our counter by the suggested amount
1468940100a4SChris Mason 			 */
146909cbfeafSKirill A. Shutemov 			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1470940100a4SChris Mason 			i = max(i + 1, next);
1471940100a4SChris Mason 			continue;
1472940100a4SChris Mason 		}
1473008873eaSLi Zefan 
1474008873eaSLi Zefan 		if (!newer_than) {
147509cbfeafSKirill A. Shutemov 			cluster = (PAGE_ALIGN(defrag_end) >>
147609cbfeafSKirill A. Shutemov 				   PAGE_SHIFT) - i;
1477008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1478008873eaSLi Zefan 		} else {
1479008873eaSLi Zefan 			cluster = max_cluster;
1480008873eaSLi Zefan 		}
1481008873eaSLi Zefan 
1482008873eaSLi Zefan 		if (i + cluster > ra_index) {
1483008873eaSLi Zefan 			ra_index = max(i, ra_index);
14840a52d108SDavid Sterba 			if (ra)
1485d3c0bab5SDavid Sterba 				page_cache_sync_readahead(inode->i_mapping, ra,
1486d3c0bab5SDavid Sterba 						file, ra_index, cluster);
1487e4826a5bSchandan 			ra_index += cluster;
1488008873eaSLi Zefan 		}
14894cb5300bSChris Mason 
14905955102cSAl Viro 		inode_lock(inode);
14911e2ef46dSDavid Sterba 		if (do_compress)
1492eec63c65SDavid Sterba 			BTRFS_I(inode)->defrag_compress = compress_type;
1493008873eaSLi Zefan 		ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1494ecb8bea8SLiu Bo 		if (ret < 0) {
14955955102cSAl Viro 			inode_unlock(inode);
14964cb5300bSChris Mason 			goto out_ra;
1497ecb8bea8SLiu Bo 		}
14984cb5300bSChris Mason 
14994cb5300bSChris Mason 		defrag_count += ret;
1500d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
15015955102cSAl Viro 		inode_unlock(inode);
15024cb5300bSChris Mason 
15034cb5300bSChris Mason 		if (newer_than) {
15044cb5300bSChris Mason 			if (newer_off == (u64)-1)
15054cb5300bSChris Mason 				break;
15064cb5300bSChris Mason 
1507e1f041e1SLiu Bo 			if (ret > 0)
1508e1f041e1SLiu Bo 				i += ret;
1509e1f041e1SLiu Bo 
15104cb5300bSChris Mason 			newer_off = max(newer_off + 1,
151109cbfeafSKirill A. Shutemov 					(u64)i << PAGE_SHIFT);
15124cb5300bSChris Mason 
1513ee22184bSByongho Lee 			ret = find_new_extents(root, inode, newer_than,
1514ee22184bSByongho Lee 					       &newer_off, SZ_64K);
15154cb5300bSChris Mason 			if (!ret) {
15164cb5300bSChris Mason 				range->start = newer_off;
151709cbfeafSKirill A. Shutemov 				i = (newer_off & new_align) >> PAGE_SHIFT;
15184cb5300bSChris Mason 			} else {
15194cb5300bSChris Mason 				break;
1520940100a4SChris Mason 			}
15214cb5300bSChris Mason 		} else {
1522008873eaSLi Zefan 			if (ret > 0) {
1523cbcc8326SLi Zefan 				i += ret;
152409cbfeafSKirill A. Shutemov 				last_len += ret << PAGE_SHIFT;
1525008873eaSLi Zefan 			} else {
1526940100a4SChris Mason 				i++;
1527008873eaSLi Zefan 				last_len = 0;
1528008873eaSLi Zefan 			}
1529f46b5a66SChristoph Hellwig 		}
15304cb5300bSChris Mason 	}
1531f46b5a66SChristoph Hellwig 
1532dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
15331e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1534dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1535dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1536dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1537dec8ef90SFilipe Manana 	}
15381e701a32SChris Mason 
15391a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
15400b246afaSJeff Mahoney 		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
15415c1aab1dSNick Terrell 	} else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
15425c1aab1dSNick Terrell 		btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
15431a419d85SLi Zefan 	}
15441a419d85SLi Zefan 
154560ccf82fSDiego Calleja 	ret = defrag_count;
1546940100a4SChris Mason 
15474cb5300bSChris Mason out_ra:
15481e2ef46dSDavid Sterba 	if (do_compress) {
15495955102cSAl Viro 		inode_lock(inode);
1550eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
15515955102cSAl Viro 		inode_unlock(inode);
1552633085c7SFilipe David Borba Manana 	}
15534cb5300bSChris Mason 	if (!file)
15544cb5300bSChris Mason 		kfree(ra);
15554cb5300bSChris Mason 	kfree(pages);
1556940100a4SChris Mason 	return ret;
1557f46b5a66SChristoph Hellwig }
1558f46b5a66SChristoph Hellwig 
1559198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
156076dda93cSYan, Zheng 					void __user *arg)
1561f46b5a66SChristoph Hellwig {
15620b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
15630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1564f46b5a66SChristoph Hellwig 	u64 new_size;
1565f46b5a66SChristoph Hellwig 	u64 old_size;
1566f46b5a66SChristoph Hellwig 	u64 devid = 1;
15670b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1568f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1569f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1570f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1571f46b5a66SChristoph Hellwig 	char *sizestr;
15729a40f122SGui Hecheng 	char *retptr;
1573f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1574f46b5a66SChristoph Hellwig 	int ret = 0;
1575f46b5a66SChristoph Hellwig 	int mod = 0;
1576f46b5a66SChristoph Hellwig 
1577e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1578e441d54dSChris Mason 		return -EPERM;
1579e441d54dSChris Mason 
1580198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1581198605a8SMiao Xie 	if (ret)
1582198605a8SMiao Xie 		return ret;
1583198605a8SMiao Xie 
1584171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
158597547676SMiao Xie 		mnt_drop_write_file(file);
1586e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1587c9e9f97bSIlya Dryomov 	}
1588c9e9f97bSIlya Dryomov 
1589dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1590c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1591c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1592c9e9f97bSIlya Dryomov 		goto out;
1593c9e9f97bSIlya Dryomov 	}
15945516e595SMark Fasheh 
15955516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1596f46b5a66SChristoph Hellwig 
1597f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1598f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1599f46b5a66SChristoph Hellwig 	if (devstr) {
1600f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1601f46b5a66SChristoph Hellwig 		*devstr = '\0';
1602f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
160358dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
160458dfae63SZhangZhen 		if (ret)
160558dfae63SZhangZhen 			goto out_free;
1606dfd79829SMiao Xie 		if (!devid) {
1607dfd79829SMiao Xie 			ret = -EINVAL;
1608dfd79829SMiao Xie 			goto out_free;
1609dfd79829SMiao Xie 		}
16100b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1611f46b5a66SChristoph Hellwig 	}
1612dba60f3fSMiao Xie 
16130b246afaSJeff Mahoney 	device = btrfs_find_device(fs_info, devid, NULL, NULL);
1614f46b5a66SChristoph Hellwig 	if (!device) {
16150b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1616c1c9ff7cSGeert Uytterhoeven 			   devid);
1617dfd79829SMiao Xie 		ret = -ENODEV;
1618c9e9f97bSIlya Dryomov 		goto out_free;
1619f46b5a66SChristoph Hellwig 	}
1620dba60f3fSMiao Xie 
1621ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
16220b246afaSJeff Mahoney 		btrfs_info(fs_info,
1623efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1624c1c9ff7cSGeert Uytterhoeven 		       devid);
1625dfd79829SMiao Xie 		ret = -EPERM;
16264e42ae1bSLiu Bo 		goto out_free;
16274e42ae1bSLiu Bo 	}
16284e42ae1bSLiu Bo 
1629f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1630f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1631f46b5a66SChristoph Hellwig 	else {
1632f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1633f46b5a66SChristoph Hellwig 			mod = -1;
1634f46b5a66SChristoph Hellwig 			sizestr++;
1635f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1636f46b5a66SChristoph Hellwig 			mod = 1;
1637f46b5a66SChristoph Hellwig 			sizestr++;
1638f46b5a66SChristoph Hellwig 		}
16399a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
16409a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1641f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1642c9e9f97bSIlya Dryomov 			goto out_free;
1643f46b5a66SChristoph Hellwig 		}
1644f46b5a66SChristoph Hellwig 	}
1645f46b5a66SChristoph Hellwig 
1646401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1647dfd79829SMiao Xie 		ret = -EPERM;
164863a212abSStefan Behrens 		goto out_free;
164963a212abSStefan Behrens 	}
165063a212abSStefan Behrens 
16517cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1652f46b5a66SChristoph Hellwig 
1653f46b5a66SChristoph Hellwig 	if (mod < 0) {
1654f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1655f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1656c9e9f97bSIlya Dryomov 			goto out_free;
1657f46b5a66SChristoph Hellwig 		}
1658f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1659f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1660eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1661902c68a4SGui Hecheng 			ret = -ERANGE;
1662eb8052e0SWenliang Fan 			goto out_free;
1663eb8052e0SWenliang Fan 		}
1664f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1665f46b5a66SChristoph Hellwig 	}
1666f46b5a66SChristoph Hellwig 
1667ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1668f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1669c9e9f97bSIlya Dryomov 		goto out_free;
1670f46b5a66SChristoph Hellwig 	}
1671f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1672f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1673c9e9f97bSIlya Dryomov 		goto out_free;
1674f46b5a66SChristoph Hellwig 	}
1675f46b5a66SChristoph Hellwig 
167647f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1677f46b5a66SChristoph Hellwig 
16780b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1679c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1680f46b5a66SChristoph Hellwig 
1681f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1682a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
168398d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
168498d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1685c9e9f97bSIlya Dryomov 			goto out_free;
168698d5dc13STsutomu Itoh 		}
1687f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
16883a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1689ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1690f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
16910253f40eSjeff.liu 	} /* equal, nothing need to do */
1692f46b5a66SChristoph Hellwig 
1693c9e9f97bSIlya Dryomov out_free:
1694f46b5a66SChristoph Hellwig 	kfree(vol_args);
1695c9e9f97bSIlya Dryomov out:
1696171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
169718f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1698f46b5a66SChristoph Hellwig 	return ret;
1699f46b5a66SChristoph Hellwig }
1700f46b5a66SChristoph Hellwig 
170172fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
170252f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
17036f72c7e2SArne Jansen 				u64 *transid, bool readonly,
17048696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1705f46b5a66SChristoph Hellwig {
1706f46b5a66SChristoph Hellwig 	int namelen;
17073de4586cSChris Mason 	int ret = 0;
1708f46b5a66SChristoph Hellwig 
1709325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1710325c50e3SJeff Mahoney 		return -ENOTDIR;
1711325c50e3SJeff Mahoney 
1712a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1713a874a63eSLiu Bo 	if (ret)
1714a874a63eSLiu Bo 		goto out;
1715a874a63eSLiu Bo 
171672fd032eSSage Weil 	namelen = strlen(name);
171772fd032eSSage Weil 	if (strchr(name, '/')) {
1718f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1719a874a63eSLiu Bo 		goto out_drop_write;
1720f46b5a66SChristoph Hellwig 	}
1721f46b5a66SChristoph Hellwig 
172216780cabSChris Mason 	if (name[0] == '.' &&
172316780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
172416780cabSChris Mason 		ret = -EEXIST;
1725a874a63eSLiu Bo 		goto out_drop_write;
172616780cabSChris Mason 	}
172716780cabSChris Mason 
17283de4586cSChris Mason 	if (subvol) {
172972fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
17306f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1731cb8e7090SChristoph Hellwig 	} else {
17322903ff01SAl Viro 		struct fd src = fdget(fd);
17333de4586cSChris Mason 		struct inode *src_inode;
17342903ff01SAl Viro 		if (!src.file) {
17353de4586cSChris Mason 			ret = -EINVAL;
1736a874a63eSLiu Bo 			goto out_drop_write;
17373de4586cSChris Mason 		}
17383de4586cSChris Mason 
1739496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1740496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1741c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1742efe120a0SFrank Holton 				   "Snapshot src from another FS");
174323ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1744d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1745d0242061SDavid Sterba 			/*
1746d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1747d0242061SDavid Sterba 			 * are limited to own subvolumes only
1748d0242061SDavid Sterba 			 */
1749d0242061SDavid Sterba 			ret = -EPERM;
1750ecd18815SAl Viro 		} else {
175172fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
175272fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
17536f72c7e2SArne Jansen 					     transid, readonly, inherit);
1754ecd18815SAl Viro 		}
17552903ff01SAl Viro 		fdput(src);
1756cb8e7090SChristoph Hellwig 	}
1757a874a63eSLiu Bo out_drop_write:
1758a874a63eSLiu Bo 	mnt_drop_write_file(file);
1759f46b5a66SChristoph Hellwig out:
176072fd032eSSage Weil 	return ret;
176172fd032eSSage Weil }
176272fd032eSSage Weil 
176372fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1764fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
176572fd032eSSage Weil {
1766fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
176772fd032eSSage Weil 	int ret;
176872fd032eSSage Weil 
1769325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1770325c50e3SJeff Mahoney 		return -ENOTDIR;
1771325c50e3SJeff Mahoney 
1772fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1773fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1774fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1775fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1776fa0d2b9bSLi Zefan 
1777fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1778b83cc969SLi Zefan 					      vol_args->fd, subvol,
17796f72c7e2SArne Jansen 					      NULL, false, NULL);
1780fa0d2b9bSLi Zefan 
1781fa0d2b9bSLi Zefan 	kfree(vol_args);
1782fa0d2b9bSLi Zefan 	return ret;
1783fa0d2b9bSLi Zefan }
1784fa0d2b9bSLi Zefan 
1785fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1786fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1787fa0d2b9bSLi Zefan {
1788fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1789fa0d2b9bSLi Zefan 	int ret;
1790fdfb1e4fSLi Zefan 	u64 transid = 0;
1791fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1792b83cc969SLi Zefan 	bool readonly = false;
17936f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
179472fd032eSSage Weil 
1795325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1796325c50e3SJeff Mahoney 		return -ENOTDIR;
1797325c50e3SJeff Mahoney 
1798fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1799fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1800fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1801fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1802fdfb1e4fSLi Zefan 
1803b83cc969SLi Zefan 	if (vol_args->flags &
18046f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
18056f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1806b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1807c47ca32dSDan Carpenter 		goto free_args;
1808fdfb1e4fSLi Zefan 	}
1809fdfb1e4fSLi Zefan 
1810fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1811fdfb1e4fSLi Zefan 		ptr = &transid;
1812b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1813b83cc969SLi Zefan 		readonly = true;
18146f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
181509cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
18166f72c7e2SArne Jansen 			ret = -EINVAL;
1817c47ca32dSDan Carpenter 			goto free_args;
18186f72c7e2SArne Jansen 		}
18196f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
18206f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
18216f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1822c47ca32dSDan Carpenter 			goto free_args;
18236f72c7e2SArne Jansen 		}
18246f72c7e2SArne Jansen 	}
182575eaa0e2SSage Weil 
1826fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
18276f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
18288696c533SMiao Xie 					      readonly, inherit);
1829c47ca32dSDan Carpenter 	if (ret)
1830c47ca32dSDan Carpenter 		goto free_inherit;
183175eaa0e2SSage Weil 
1832c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1833fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1834c47ca32dSDan Carpenter 					transid),
1835c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
183675eaa0e2SSage Weil 		ret = -EFAULT;
1837c47ca32dSDan Carpenter 
1838c47ca32dSDan Carpenter free_inherit:
18396f72c7e2SArne Jansen 	kfree(inherit);
1840c47ca32dSDan Carpenter free_args:
1841c47ca32dSDan Carpenter 	kfree(vol_args);
1842f46b5a66SChristoph Hellwig 	return ret;
1843f46b5a66SChristoph Hellwig }
1844f46b5a66SChristoph Hellwig 
18450caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
18460caa102dSLi Zefan 						void __user *arg)
18470caa102dSLi Zefan {
1848496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18500caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
18510caa102dSLi Zefan 	int ret = 0;
18520caa102dSLi Zefan 	u64 flags = 0;
18530caa102dSLi Zefan 
18544a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
18550caa102dSLi Zefan 		return -EINVAL;
18560caa102dSLi Zefan 
18570b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
18580caa102dSLi Zefan 	if (btrfs_root_readonly(root))
18590caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
18600b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
18610caa102dSLi Zefan 
18620caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
18630caa102dSLi Zefan 		ret = -EFAULT;
18640caa102dSLi Zefan 
18650caa102dSLi Zefan 	return ret;
18660caa102dSLi Zefan }
18670caa102dSLi Zefan 
18680caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
18690caa102dSLi Zefan 					      void __user *arg)
18700caa102dSLi Zefan {
1871496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18730caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
18740caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
18750caa102dSLi Zefan 	u64 root_flags;
18760caa102dSLi Zefan 	u64 flags;
18770caa102dSLi Zefan 	int ret = 0;
18780caa102dSLi Zefan 
1879bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1880bd60ea0fSDavid Sterba 		return -EPERM;
1881bd60ea0fSDavid Sterba 
1882b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1883b9ca0664SLiu Bo 	if (ret)
1884b9ca0664SLiu Bo 		goto out;
18850caa102dSLi Zefan 
18864a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1887b9ca0664SLiu Bo 		ret = -EINVAL;
1888b9ca0664SLiu Bo 		goto out_drop_write;
1889b9ca0664SLiu Bo 	}
18900caa102dSLi Zefan 
1891b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1892b9ca0664SLiu Bo 		ret = -EFAULT;
1893b9ca0664SLiu Bo 		goto out_drop_write;
1894b9ca0664SLiu Bo 	}
18950caa102dSLi Zefan 
1896b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1897b9ca0664SLiu Bo 		ret = -EINVAL;
1898b9ca0664SLiu Bo 		goto out_drop_write;
1899b9ca0664SLiu Bo 	}
19000caa102dSLi Zefan 
1901b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1902b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1903b9ca0664SLiu Bo 		goto out_drop_write;
1904b9ca0664SLiu Bo 	}
19050caa102dSLi Zefan 
19060b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
19070caa102dSLi Zefan 
19080caa102dSLi Zefan 	/* nothing to do */
19090caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1910b9ca0664SLiu Bo 		goto out_drop_sem;
19110caa102dSLi Zefan 
19120caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
19132c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
19140caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
19150caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
19162c686537SDavid Sterba 	} else {
19172c686537SDavid Sterba 		/*
19182c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
19192c686537SDavid Sterba 		 * send
19202c686537SDavid Sterba 		 */
19212c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
19222c686537SDavid Sterba 		if (root->send_in_progress == 0) {
19230caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
19240caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
19252c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19262c686537SDavid Sterba 		} else {
19272c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19280b246afaSJeff Mahoney 			btrfs_warn(fs_info,
19292c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
19302c686537SDavid Sterba 				   root->root_key.objectid);
19312c686537SDavid Sterba 			ret = -EPERM;
19322c686537SDavid Sterba 			goto out_drop_sem;
19332c686537SDavid Sterba 		}
19342c686537SDavid Sterba 	}
19350caa102dSLi Zefan 
19360caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
19370caa102dSLi Zefan 	if (IS_ERR(trans)) {
19380caa102dSLi Zefan 		ret = PTR_ERR(trans);
19390caa102dSLi Zefan 		goto out_reset;
19400caa102dSLi Zefan 	}
19410caa102dSLi Zefan 
19420b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
19430caa102dSLi Zefan 				&root->root_key, &root->root_item);
19449417ebc8SNikolay Borisov 	if (ret < 0) {
19459417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
19469417ebc8SNikolay Borisov 		goto out_reset;
19479417ebc8SNikolay Borisov 	}
19480caa102dSLi Zefan 
19499417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
19509417ebc8SNikolay Borisov 
19510caa102dSLi Zefan out_reset:
19520caa102dSLi Zefan 	if (ret)
19530caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1954b9ca0664SLiu Bo out_drop_sem:
19550b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
1956b9ca0664SLiu Bo out_drop_write:
1957b9ca0664SLiu Bo 	mnt_drop_write_file(file);
1958b9ca0664SLiu Bo out:
19590caa102dSLi Zefan 	return ret;
19600caa102dSLi Zefan }
19610caa102dSLi Zefan 
1962ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
1963ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
1964ac8e9819SChris Mason {
1965abc6e134SChris Mason 	struct btrfs_key test;
1966abc6e134SChris Mason 	int ret;
1967abc6e134SChris Mason 
1968abc6e134SChris Mason 	test.objectid = sk->min_objectid;
1969abc6e134SChris Mason 	test.type = sk->min_type;
1970abc6e134SChris Mason 	test.offset = sk->min_offset;
1971abc6e134SChris Mason 
1972abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1973abc6e134SChris Mason 	if (ret < 0)
1974ac8e9819SChris Mason 		return 0;
1975abc6e134SChris Mason 
1976abc6e134SChris Mason 	test.objectid = sk->max_objectid;
1977abc6e134SChris Mason 	test.type = sk->max_type;
1978abc6e134SChris Mason 	test.offset = sk->max_offset;
1979abc6e134SChris Mason 
1980abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
1981abc6e134SChris Mason 	if (ret > 0)
1982ac8e9819SChris Mason 		return 0;
1983ac8e9819SChris Mason 	return 1;
1984ac8e9819SChris Mason }
1985ac8e9819SChris Mason 
1986df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
1987ac8e9819SChris Mason 			       struct btrfs_key *key,
1988ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
19899b6e817dSGerhard Heift 			       size_t *buf_size,
1990ba346b35SGerhard Heift 			       char __user *ubuf,
1991ac8e9819SChris Mason 			       unsigned long *sk_offset,
1992ac8e9819SChris Mason 			       int *num_found)
1993ac8e9819SChris Mason {
1994ac8e9819SChris Mason 	u64 found_transid;
1995ac8e9819SChris Mason 	struct extent_buffer *leaf;
1996ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
1997dd81d459SNaohiro Aota 	struct btrfs_key test;
1998ac8e9819SChris Mason 	unsigned long item_off;
1999ac8e9819SChris Mason 	unsigned long item_len;
2000ac8e9819SChris Mason 	int nritems;
2001ac8e9819SChris Mason 	int i;
2002ac8e9819SChris Mason 	int slot;
2003ac8e9819SChris Mason 	int ret = 0;
2004ac8e9819SChris Mason 
2005ac8e9819SChris Mason 	leaf = path->nodes[0];
2006ac8e9819SChris Mason 	slot = path->slots[0];
2007ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
2008ac8e9819SChris Mason 
2009ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
2010ac8e9819SChris Mason 		i = nritems;
2011ac8e9819SChris Mason 		goto advance_key;
2012ac8e9819SChris Mason 	}
2013ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
2014ac8e9819SChris Mason 
2015ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
2016ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
2017ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
2018ac8e9819SChris Mason 
201903b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
202003b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
202103b71c6cSGabriel de Perthuis 			continue;
202203b71c6cSGabriel de Perthuis 
20239b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
20248f5f6178SGerhard Heift 			if (*num_found) {
2025ac8e9819SChris Mason 				ret = 1;
20268f5f6178SGerhard Heift 				goto out;
20278f5f6178SGerhard Heift 			}
20288f5f6178SGerhard Heift 
20298f5f6178SGerhard Heift 			/*
20308f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
20318f5f6178SGerhard Heift 			 * handle -EOVERFLOW
20328f5f6178SGerhard Heift 			 */
20338f5f6178SGerhard Heift 
20349b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
2035ac8e9819SChris Mason 			item_len = 0;
20368f5f6178SGerhard Heift 			ret = -EOVERFLOW;
20378f5f6178SGerhard Heift 		}
2038ac8e9819SChris Mason 
20399b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2040ac8e9819SChris Mason 			ret = 1;
204125c9bc2eSGerhard Heift 			goto out;
2042ac8e9819SChris Mason 		}
2043ac8e9819SChris Mason 
2044ac8e9819SChris Mason 		sh.objectid = key->objectid;
2045ac8e9819SChris Mason 		sh.offset = key->offset;
2046ac8e9819SChris Mason 		sh.type = key->type;
2047ac8e9819SChris Mason 		sh.len = item_len;
2048ac8e9819SChris Mason 		sh.transid = found_transid;
2049ac8e9819SChris Mason 
2050ac8e9819SChris Mason 		/* copy search result header */
2051ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2052ba346b35SGerhard Heift 			ret = -EFAULT;
2053ba346b35SGerhard Heift 			goto out;
2054ba346b35SGerhard Heift 		}
2055ba346b35SGerhard Heift 
2056ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2057ac8e9819SChris Mason 
2058ac8e9819SChris Mason 		if (item_len) {
2059ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2060ac8e9819SChris Mason 			/* copy the item */
2061ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
2062ba346b35SGerhard Heift 						       item_off, item_len)) {
2063ba346b35SGerhard Heift 				ret = -EFAULT;
2064ba346b35SGerhard Heift 				goto out;
2065ba346b35SGerhard Heift 			}
2066ba346b35SGerhard Heift 
2067ac8e9819SChris Mason 			*sk_offset += item_len;
2068ac8e9819SChris Mason 		}
2069e2156867SHugo Mills 		(*num_found)++;
2070ac8e9819SChris Mason 
20718f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
20728f5f6178SGerhard Heift 			goto out;
20738f5f6178SGerhard Heift 
207425c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
207525c9bc2eSGerhard Heift 			ret = 1;
207625c9bc2eSGerhard Heift 			goto out;
207725c9bc2eSGerhard Heift 		}
2078ac8e9819SChris Mason 	}
2079ac8e9819SChris Mason advance_key:
2080ac8e9819SChris Mason 	ret = 0;
2081dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2082dd81d459SNaohiro Aota 	test.type = sk->max_type;
2083dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2084dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2085dd81d459SNaohiro Aota 		ret = 1;
2086dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2087abc6e134SChris Mason 		key->offset++;
2088dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2089abc6e134SChris Mason 		key->offset = 0;
2090abc6e134SChris Mason 		key->type++;
2091dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2092abc6e134SChris Mason 		key->offset = 0;
2093abc6e134SChris Mason 		key->type = 0;
2094abc6e134SChris Mason 		key->objectid++;
2095abc6e134SChris Mason 	} else
2096abc6e134SChris Mason 		ret = 1;
209725c9bc2eSGerhard Heift out:
2098ba346b35SGerhard Heift 	/*
2099ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2100ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2101ba346b35SGerhard Heift 	 *     * all items were found
2102ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2103ba346b35SGerhard Heift 	 *     leaf
2104ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2105ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2106ba346b35SGerhard Heift 	 */
2107ac8e9819SChris Mason 	return ret;
2108ac8e9819SChris Mason }
2109ac8e9819SChris Mason 
2110ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
211112544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
21129b6e817dSGerhard Heift 				 size_t *buf_size,
2113ba346b35SGerhard Heift 				 char __user *ubuf)
2114ac8e9819SChris Mason {
21150b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2116ac8e9819SChris Mason 	struct btrfs_root *root;
2117ac8e9819SChris Mason 	struct btrfs_key key;
2118ac8e9819SChris Mason 	struct btrfs_path *path;
2119ac8e9819SChris Mason 	int ret;
2120ac8e9819SChris Mason 	int num_found = 0;
2121ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2122ac8e9819SChris Mason 
21239b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
21249b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
212512544442SGerhard Heift 		return -EOVERFLOW;
21269b6e817dSGerhard Heift 	}
212712544442SGerhard Heift 
2128ac8e9819SChris Mason 	path = btrfs_alloc_path();
2129ac8e9819SChris Mason 	if (!path)
2130ac8e9819SChris Mason 		return -ENOMEM;
2131ac8e9819SChris Mason 
2132ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2133ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2134ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2135ac8e9819SChris Mason 	} else {
2136ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2137ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2138ac8e9819SChris Mason 		key.offset = (u64)-1;
2139ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2140ac8e9819SChris Mason 		if (IS_ERR(root)) {
2141ac8e9819SChris Mason 			btrfs_free_path(path);
2142ad1e3d56SMisono Tomohiro 			return PTR_ERR(root);
2143ac8e9819SChris Mason 		}
2144ac8e9819SChris Mason 	}
2145ac8e9819SChris Mason 
2146ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2147ac8e9819SChris Mason 	key.type = sk->min_type;
2148ac8e9819SChris Mason 	key.offset = sk->min_offset;
2149ac8e9819SChris Mason 
2150ac8e9819SChris Mason 	while (1) {
21516174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2152ac8e9819SChris Mason 		if (ret != 0) {
2153ac8e9819SChris Mason 			if (ret > 0)
2154ac8e9819SChris Mason 				ret = 0;
2155ac8e9819SChris Mason 			goto err;
2156ac8e9819SChris Mason 		}
2157df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2158ac8e9819SChris Mason 				 &sk_offset, &num_found);
2159b3b4aa74SDavid Sterba 		btrfs_release_path(path);
216025c9bc2eSGerhard Heift 		if (ret)
2161ac8e9819SChris Mason 			break;
2162ac8e9819SChris Mason 
2163ac8e9819SChris Mason 	}
21648f5f6178SGerhard Heift 	if (ret > 0)
2165ac8e9819SChris Mason 		ret = 0;
2166ac8e9819SChris Mason err:
2167ac8e9819SChris Mason 	sk->nr_items = num_found;
2168ac8e9819SChris Mason 	btrfs_free_path(path);
2169ac8e9819SChris Mason 	return ret;
2170ac8e9819SChris Mason }
2171ac8e9819SChris Mason 
2172ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2173ac8e9819SChris Mason 					   void __user *argp)
2174ac8e9819SChris Mason {
2175ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2176ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2177ac8e9819SChris Mason 	struct inode *inode;
2178ac8e9819SChris Mason 	int ret;
21799b6e817dSGerhard Heift 	size_t buf_size;
2180ac8e9819SChris Mason 
2181ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2182ac8e9819SChris Mason 		return -EPERM;
2183ac8e9819SChris Mason 
2184ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2185ac8e9819SChris Mason 
2186ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2187ba346b35SGerhard Heift 		return -EFAULT;
2188ba346b35SGerhard Heift 
2189ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2190ac8e9819SChris Mason 
2191496ad9aaSAl Viro 	inode = file_inode(file);
2192ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
21938f5f6178SGerhard Heift 
21948f5f6178SGerhard Heift 	/*
21958f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
21968f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
21978f5f6178SGerhard Heift 	 */
21988f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
21998f5f6178SGerhard Heift 		ret = 0;
22008f5f6178SGerhard Heift 
2201ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2202ac8e9819SChris Mason 		ret = -EFAULT;
2203ac8e9819SChris Mason 	return ret;
2204ac8e9819SChris Mason }
2205ac8e9819SChris Mason 
2206cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2207cc68a8a5SGerhard Heift 					       void __user *argp)
2208cc68a8a5SGerhard Heift {
2209cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2210cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2211cc68a8a5SGerhard Heift 	struct inode *inode;
2212cc68a8a5SGerhard Heift 	int ret;
2213cc68a8a5SGerhard Heift 	size_t buf_size;
2214ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2215cc68a8a5SGerhard Heift 
2216cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2217cc68a8a5SGerhard Heift 		return -EPERM;
2218cc68a8a5SGerhard Heift 
2219cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2220cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2221cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2222cc68a8a5SGerhard Heift 		return -EFAULT;
2223cc68a8a5SGerhard Heift 
2224cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2225cc68a8a5SGerhard Heift 
2226cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2227cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2228cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2229cc68a8a5SGerhard Heift 
2230cc68a8a5SGerhard Heift 	inode = file_inode(file);
2231cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2232718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2233cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2234cc68a8a5SGerhard Heift 		ret = -EFAULT;
2235cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2236cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2237cc68a8a5SGerhard Heift 		ret = -EFAULT;
2238cc68a8a5SGerhard Heift 
223976dda93cSYan, Zheng 	return ret;
224076dda93cSYan, Zheng }
224176dda93cSYan, Zheng 
224298d377a0STARUISI Hiroaki /*
2243ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2244ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
224598d377a0STARUISI Hiroaki  */
224698d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
224798d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
224898d377a0STARUISI Hiroaki {
224998d377a0STARUISI Hiroaki 	struct btrfs_root *root;
225098d377a0STARUISI Hiroaki 	struct btrfs_key key;
2251ac8e9819SChris Mason 	char *ptr;
225298d377a0STARUISI Hiroaki 	int ret = -1;
225398d377a0STARUISI Hiroaki 	int slot;
225498d377a0STARUISI Hiroaki 	int len;
225598d377a0STARUISI Hiroaki 	int total_len = 0;
225698d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
225798d377a0STARUISI Hiroaki 	struct extent_buffer *l;
225898d377a0STARUISI Hiroaki 	struct btrfs_path *path;
225998d377a0STARUISI Hiroaki 
226098d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
226198d377a0STARUISI Hiroaki 		name[0]='\0';
226298d377a0STARUISI Hiroaki 		return 0;
226398d377a0STARUISI Hiroaki 	}
226498d377a0STARUISI Hiroaki 
226598d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
226698d377a0STARUISI Hiroaki 	if (!path)
226798d377a0STARUISI Hiroaki 		return -ENOMEM;
226898d377a0STARUISI Hiroaki 
2269c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
227098d377a0STARUISI Hiroaki 
227198d377a0STARUISI Hiroaki 	key.objectid = tree_id;
227298d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
227398d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
227498d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
227598d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2276ad1e3d56SMisono Tomohiro 		ret = PTR_ERR(root);
22778ad6fcabSChris Mason 		goto out;
227898d377a0STARUISI Hiroaki 	}
227998d377a0STARUISI Hiroaki 
228098d377a0STARUISI Hiroaki 	key.objectid = dirid;
228198d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
22828ad6fcabSChris Mason 	key.offset = (u64)-1;
228398d377a0STARUISI Hiroaki 
228498d377a0STARUISI Hiroaki 	while (1) {
228598d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
228698d377a0STARUISI Hiroaki 		if (ret < 0)
228798d377a0STARUISI Hiroaki 			goto out;
228818674c6cSFilipe David Borba Manana 		else if (ret > 0) {
228918674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
229018674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
229118674c6cSFilipe David Borba Manana 			if (ret < 0)
229218674c6cSFilipe David Borba Manana 				goto out;
229318674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2294ac8e9819SChris Mason 				ret = -ENOENT;
229598d377a0STARUISI Hiroaki 				goto out;
2296ac8e9819SChris Mason 			}
229718674c6cSFilipe David Borba Manana 		}
229818674c6cSFilipe David Borba Manana 
229918674c6cSFilipe David Borba Manana 		l = path->nodes[0];
230018674c6cSFilipe David Borba Manana 		slot = path->slots[0];
230118674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
230298d377a0STARUISI Hiroaki 
230398d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
230498d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
230598d377a0STARUISI Hiroaki 		ptr -= len + 1;
230698d377a0STARUISI Hiroaki 		total_len += len + 1;
2307a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2308a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
230998d377a0STARUISI Hiroaki 			goto out;
2310a696cf35SFilipe David Borba Manana 		}
231198d377a0STARUISI Hiroaki 
231298d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
231398d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
231498d377a0STARUISI Hiroaki 
231598d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
231698d377a0STARUISI Hiroaki 			break;
231798d377a0STARUISI Hiroaki 
2318b3b4aa74SDavid Sterba 		btrfs_release_path(path);
231998d377a0STARUISI Hiroaki 		key.objectid = key.offset;
23208ad6fcabSChris Mason 		key.offset = (u64)-1;
232198d377a0STARUISI Hiroaki 		dirid = key.objectid;
232298d377a0STARUISI Hiroaki 	}
232377906a50SLi Zefan 	memmove(name, ptr, total_len);
232498d377a0STARUISI Hiroaki 	name[total_len] = '\0';
232598d377a0STARUISI Hiroaki 	ret = 0;
232698d377a0STARUISI Hiroaki out:
232798d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2328ac8e9819SChris Mason 	return ret;
2329ac8e9819SChris Mason }
2330ac8e9819SChris Mason 
233123d0b79dSTomohiro Misono static int btrfs_search_path_in_tree_user(struct inode *inode,
233223d0b79dSTomohiro Misono 				struct btrfs_ioctl_ino_lookup_user_args *args)
233323d0b79dSTomohiro Misono {
233423d0b79dSTomohiro Misono 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
233523d0b79dSTomohiro Misono 	struct super_block *sb = inode->i_sb;
233623d0b79dSTomohiro Misono 	struct btrfs_key upper_limit = BTRFS_I(inode)->location;
233723d0b79dSTomohiro Misono 	u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
233823d0b79dSTomohiro Misono 	u64 dirid = args->dirid;
233923d0b79dSTomohiro Misono 	unsigned long item_off;
234023d0b79dSTomohiro Misono 	unsigned long item_len;
234123d0b79dSTomohiro Misono 	struct btrfs_inode_ref *iref;
234223d0b79dSTomohiro Misono 	struct btrfs_root_ref *rref;
234323d0b79dSTomohiro Misono 	struct btrfs_root *root;
234423d0b79dSTomohiro Misono 	struct btrfs_path *path;
234523d0b79dSTomohiro Misono 	struct btrfs_key key, key2;
234623d0b79dSTomohiro Misono 	struct extent_buffer *leaf;
234723d0b79dSTomohiro Misono 	struct inode *temp_inode;
234823d0b79dSTomohiro Misono 	char *ptr;
234923d0b79dSTomohiro Misono 	int slot;
235023d0b79dSTomohiro Misono 	int len;
235123d0b79dSTomohiro Misono 	int total_len = 0;
235223d0b79dSTomohiro Misono 	int ret;
235323d0b79dSTomohiro Misono 
235423d0b79dSTomohiro Misono 	path = btrfs_alloc_path();
235523d0b79dSTomohiro Misono 	if (!path)
235623d0b79dSTomohiro Misono 		return -ENOMEM;
235723d0b79dSTomohiro Misono 
235823d0b79dSTomohiro Misono 	/*
235923d0b79dSTomohiro Misono 	 * If the bottom subvolume does not exist directly under upper_limit,
236023d0b79dSTomohiro Misono 	 * construct the path in from the bottom up.
236123d0b79dSTomohiro Misono 	 */
236223d0b79dSTomohiro Misono 	if (dirid != upper_limit.objectid) {
236323d0b79dSTomohiro Misono 		ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
236423d0b79dSTomohiro Misono 
236523d0b79dSTomohiro Misono 		key.objectid = treeid;
236623d0b79dSTomohiro Misono 		key.type = BTRFS_ROOT_ITEM_KEY;
236723d0b79dSTomohiro Misono 		key.offset = (u64)-1;
236823d0b79dSTomohiro Misono 		root = btrfs_read_fs_root_no_name(fs_info, &key);
236923d0b79dSTomohiro Misono 		if (IS_ERR(root)) {
237023d0b79dSTomohiro Misono 			ret = PTR_ERR(root);
237123d0b79dSTomohiro Misono 			goto out;
237223d0b79dSTomohiro Misono 		}
237323d0b79dSTomohiro Misono 
237423d0b79dSTomohiro Misono 		key.objectid = dirid;
237523d0b79dSTomohiro Misono 		key.type = BTRFS_INODE_REF_KEY;
237623d0b79dSTomohiro Misono 		key.offset = (u64)-1;
237723d0b79dSTomohiro Misono 		while (1) {
237823d0b79dSTomohiro Misono 			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
237923d0b79dSTomohiro Misono 			if (ret < 0) {
238023d0b79dSTomohiro Misono 				goto out;
238123d0b79dSTomohiro Misono 			} else if (ret > 0) {
238223d0b79dSTomohiro Misono 				ret = btrfs_previous_item(root, path, dirid,
238323d0b79dSTomohiro Misono 							  BTRFS_INODE_REF_KEY);
238423d0b79dSTomohiro Misono 				if (ret < 0) {
238523d0b79dSTomohiro Misono 					goto out;
238623d0b79dSTomohiro Misono 				} else if (ret > 0) {
238723d0b79dSTomohiro Misono 					ret = -ENOENT;
238823d0b79dSTomohiro Misono 					goto out;
238923d0b79dSTomohiro Misono 				}
239023d0b79dSTomohiro Misono 			}
239123d0b79dSTomohiro Misono 
239223d0b79dSTomohiro Misono 			leaf = path->nodes[0];
239323d0b79dSTomohiro Misono 			slot = path->slots[0];
239423d0b79dSTomohiro Misono 			btrfs_item_key_to_cpu(leaf, &key, slot);
239523d0b79dSTomohiro Misono 
239623d0b79dSTomohiro Misono 			iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
239723d0b79dSTomohiro Misono 			len = btrfs_inode_ref_name_len(leaf, iref);
239823d0b79dSTomohiro Misono 			ptr -= len + 1;
239923d0b79dSTomohiro Misono 			total_len += len + 1;
240023d0b79dSTomohiro Misono 			if (ptr < args->path) {
240123d0b79dSTomohiro Misono 				ret = -ENAMETOOLONG;
240223d0b79dSTomohiro Misono 				goto out;
240323d0b79dSTomohiro Misono 			}
240423d0b79dSTomohiro Misono 
240523d0b79dSTomohiro Misono 			*(ptr + len) = '/';
240623d0b79dSTomohiro Misono 			read_extent_buffer(leaf, ptr,
240723d0b79dSTomohiro Misono 					(unsigned long)(iref + 1), len);
240823d0b79dSTomohiro Misono 
240923d0b79dSTomohiro Misono 			/* Check the read+exec permission of this directory */
241023d0b79dSTomohiro Misono 			ret = btrfs_previous_item(root, path, dirid,
241123d0b79dSTomohiro Misono 						  BTRFS_INODE_ITEM_KEY);
241223d0b79dSTomohiro Misono 			if (ret < 0) {
241323d0b79dSTomohiro Misono 				goto out;
241423d0b79dSTomohiro Misono 			} else if (ret > 0) {
241523d0b79dSTomohiro Misono 				ret = -ENOENT;
241623d0b79dSTomohiro Misono 				goto out;
241723d0b79dSTomohiro Misono 			}
241823d0b79dSTomohiro Misono 
241923d0b79dSTomohiro Misono 			leaf = path->nodes[0];
242023d0b79dSTomohiro Misono 			slot = path->slots[0];
242123d0b79dSTomohiro Misono 			btrfs_item_key_to_cpu(leaf, &key2, slot);
242223d0b79dSTomohiro Misono 			if (key2.objectid != dirid) {
242323d0b79dSTomohiro Misono 				ret = -ENOENT;
242423d0b79dSTomohiro Misono 				goto out;
242523d0b79dSTomohiro Misono 			}
242623d0b79dSTomohiro Misono 
242723d0b79dSTomohiro Misono 			temp_inode = btrfs_iget(sb, &key2, root, NULL);
24283ca57bd6SMisono Tomohiro 			if (IS_ERR(temp_inode)) {
24293ca57bd6SMisono Tomohiro 				ret = PTR_ERR(temp_inode);
24303ca57bd6SMisono Tomohiro 				goto out;
24313ca57bd6SMisono Tomohiro 			}
243223d0b79dSTomohiro Misono 			ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC);
243323d0b79dSTomohiro Misono 			iput(temp_inode);
243423d0b79dSTomohiro Misono 			if (ret) {
243523d0b79dSTomohiro Misono 				ret = -EACCES;
243623d0b79dSTomohiro Misono 				goto out;
243723d0b79dSTomohiro Misono 			}
243823d0b79dSTomohiro Misono 
243923d0b79dSTomohiro Misono 			if (key.offset == upper_limit.objectid)
244023d0b79dSTomohiro Misono 				break;
244123d0b79dSTomohiro Misono 			if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
244223d0b79dSTomohiro Misono 				ret = -EACCES;
244323d0b79dSTomohiro Misono 				goto out;
244423d0b79dSTomohiro Misono 			}
244523d0b79dSTomohiro Misono 
244623d0b79dSTomohiro Misono 			btrfs_release_path(path);
244723d0b79dSTomohiro Misono 			key.objectid = key.offset;
244823d0b79dSTomohiro Misono 			key.offset = (u64)-1;
244923d0b79dSTomohiro Misono 			dirid = key.objectid;
245023d0b79dSTomohiro Misono 		}
245123d0b79dSTomohiro Misono 
245223d0b79dSTomohiro Misono 		memmove(args->path, ptr, total_len);
245323d0b79dSTomohiro Misono 		args->path[total_len] = '\0';
245423d0b79dSTomohiro Misono 		btrfs_release_path(path);
245523d0b79dSTomohiro Misono 	}
245623d0b79dSTomohiro Misono 
245723d0b79dSTomohiro Misono 	/* Get the bottom subvolume's name from ROOT_REF */
245823d0b79dSTomohiro Misono 	root = fs_info->tree_root;
245923d0b79dSTomohiro Misono 	key.objectid = treeid;
246023d0b79dSTomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
246123d0b79dSTomohiro Misono 	key.offset = args->treeid;
246223d0b79dSTomohiro Misono 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
246323d0b79dSTomohiro Misono 	if (ret < 0) {
246423d0b79dSTomohiro Misono 		goto out;
246523d0b79dSTomohiro Misono 	} else if (ret > 0) {
246623d0b79dSTomohiro Misono 		ret = -ENOENT;
246723d0b79dSTomohiro Misono 		goto out;
246823d0b79dSTomohiro Misono 	}
246923d0b79dSTomohiro Misono 
247023d0b79dSTomohiro Misono 	leaf = path->nodes[0];
247123d0b79dSTomohiro Misono 	slot = path->slots[0];
247223d0b79dSTomohiro Misono 	btrfs_item_key_to_cpu(leaf, &key, slot);
247323d0b79dSTomohiro Misono 
247423d0b79dSTomohiro Misono 	item_off = btrfs_item_ptr_offset(leaf, slot);
247523d0b79dSTomohiro Misono 	item_len = btrfs_item_size_nr(leaf, slot);
247623d0b79dSTomohiro Misono 	/* Check if dirid in ROOT_REF corresponds to passed dirid */
247723d0b79dSTomohiro Misono 	rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
247823d0b79dSTomohiro Misono 	if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
247923d0b79dSTomohiro Misono 		ret = -EINVAL;
248023d0b79dSTomohiro Misono 		goto out;
248123d0b79dSTomohiro Misono 	}
248223d0b79dSTomohiro Misono 
248323d0b79dSTomohiro Misono 	/* Copy subvolume's name */
248423d0b79dSTomohiro Misono 	item_off += sizeof(struct btrfs_root_ref);
248523d0b79dSTomohiro Misono 	item_len -= sizeof(struct btrfs_root_ref);
248623d0b79dSTomohiro Misono 	read_extent_buffer(leaf, args->name, item_off, item_len);
248723d0b79dSTomohiro Misono 	args->name[item_len] = 0;
248823d0b79dSTomohiro Misono 
248923d0b79dSTomohiro Misono out:
249023d0b79dSTomohiro Misono 	btrfs_free_path(path);
249123d0b79dSTomohiro Misono 	return ret;
249223d0b79dSTomohiro Misono }
249323d0b79dSTomohiro Misono 
2494ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2495ac8e9819SChris Mason 					   void __user *argp)
2496ac8e9819SChris Mason {
2497ac8e9819SChris Mason 	struct btrfs_ioctl_ino_lookup_args *args;
2498ac8e9819SChris Mason 	struct inode *inode;
249901b810b8SDavid Sterba 	int ret = 0;
2500ac8e9819SChris Mason 
25012354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
25022354d08fSJulia Lawall 	if (IS_ERR(args))
25032354d08fSJulia Lawall 		return PTR_ERR(args);
2504c2b96929SDan Carpenter 
2505496ad9aaSAl Viro 	inode = file_inode(file);
2506ac8e9819SChris Mason 
250701b810b8SDavid Sterba 	/*
250801b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
250901b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
251001b810b8SDavid Sterba 	 */
25111b53ac4dSChris Mason 	if (args->treeid == 0)
25121b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
25131b53ac4dSChris Mason 
251401b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
251501b810b8SDavid Sterba 		args->name[0] = 0;
251601b810b8SDavid Sterba 		goto out;
251701b810b8SDavid Sterba 	}
251801b810b8SDavid Sterba 
251901b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
252001b810b8SDavid Sterba 		ret = -EPERM;
252101b810b8SDavid Sterba 		goto out;
252201b810b8SDavid Sterba 	}
252301b810b8SDavid Sterba 
2524ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2525ac8e9819SChris Mason 					args->treeid, args->objectid,
2526ac8e9819SChris Mason 					args->name);
2527ac8e9819SChris Mason 
252801b810b8SDavid Sterba out:
2529ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2530ac8e9819SChris Mason 		ret = -EFAULT;
2531ac8e9819SChris Mason 
2532ac8e9819SChris Mason 	kfree(args);
253398d377a0STARUISI Hiroaki 	return ret;
253498d377a0STARUISI Hiroaki }
253598d377a0STARUISI Hiroaki 
253623d0b79dSTomohiro Misono /*
253723d0b79dSTomohiro Misono  * Version of ino_lookup ioctl (unprivileged)
253823d0b79dSTomohiro Misono  *
253923d0b79dSTomohiro Misono  * The main differences from ino_lookup ioctl are:
254023d0b79dSTomohiro Misono  *
254123d0b79dSTomohiro Misono  *   1. Read + Exec permission will be checked using inode_permission() during
254223d0b79dSTomohiro Misono  *      path construction. -EACCES will be returned in case of failure.
254323d0b79dSTomohiro Misono  *   2. Path construction will be stopped at the inode number which corresponds
254423d0b79dSTomohiro Misono  *      to the fd with which this ioctl is called. If constructed path does not
254523d0b79dSTomohiro Misono  *      exist under fd's inode, -EACCES will be returned.
254623d0b79dSTomohiro Misono  *   3. The name of bottom subvolume is also searched and filled.
254723d0b79dSTomohiro Misono  */
254823d0b79dSTomohiro Misono static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
254923d0b79dSTomohiro Misono {
255023d0b79dSTomohiro Misono 	struct btrfs_ioctl_ino_lookup_user_args *args;
255123d0b79dSTomohiro Misono 	struct inode *inode;
255223d0b79dSTomohiro Misono 	int ret;
255323d0b79dSTomohiro Misono 
255423d0b79dSTomohiro Misono 	args = memdup_user(argp, sizeof(*args));
255523d0b79dSTomohiro Misono 	if (IS_ERR(args))
255623d0b79dSTomohiro Misono 		return PTR_ERR(args);
255723d0b79dSTomohiro Misono 
255823d0b79dSTomohiro Misono 	inode = file_inode(file);
255923d0b79dSTomohiro Misono 
256023d0b79dSTomohiro Misono 	if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
256123d0b79dSTomohiro Misono 	    BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
256223d0b79dSTomohiro Misono 		/*
256323d0b79dSTomohiro Misono 		 * The subvolume does not exist under fd with which this is
256423d0b79dSTomohiro Misono 		 * called
256523d0b79dSTomohiro Misono 		 */
256623d0b79dSTomohiro Misono 		kfree(args);
256723d0b79dSTomohiro Misono 		return -EACCES;
256823d0b79dSTomohiro Misono 	}
256923d0b79dSTomohiro Misono 
257023d0b79dSTomohiro Misono 	ret = btrfs_search_path_in_tree_user(inode, args);
257123d0b79dSTomohiro Misono 
257223d0b79dSTomohiro Misono 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
257323d0b79dSTomohiro Misono 		ret = -EFAULT;
257423d0b79dSTomohiro Misono 
257523d0b79dSTomohiro Misono 	kfree(args);
257623d0b79dSTomohiro Misono 	return ret;
257723d0b79dSTomohiro Misono }
257823d0b79dSTomohiro Misono 
2579b64ec075STomohiro Misono /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2580b64ec075STomohiro Misono static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2581b64ec075STomohiro Misono {
2582b64ec075STomohiro Misono 	struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2583b64ec075STomohiro Misono 	struct btrfs_fs_info *fs_info;
2584b64ec075STomohiro Misono 	struct btrfs_root *root;
2585b64ec075STomohiro Misono 	struct btrfs_path *path;
2586b64ec075STomohiro Misono 	struct btrfs_key key;
2587b64ec075STomohiro Misono 	struct btrfs_root_item *root_item;
2588b64ec075STomohiro Misono 	struct btrfs_root_ref *rref;
2589b64ec075STomohiro Misono 	struct extent_buffer *leaf;
2590b64ec075STomohiro Misono 	unsigned long item_off;
2591b64ec075STomohiro Misono 	unsigned long item_len;
2592b64ec075STomohiro Misono 	struct inode *inode;
2593b64ec075STomohiro Misono 	int slot;
2594b64ec075STomohiro Misono 	int ret = 0;
2595b64ec075STomohiro Misono 
2596b64ec075STomohiro Misono 	path = btrfs_alloc_path();
2597b64ec075STomohiro Misono 	if (!path)
2598b64ec075STomohiro Misono 		return -ENOMEM;
2599b64ec075STomohiro Misono 
2600b64ec075STomohiro Misono 	subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2601b64ec075STomohiro Misono 	if (!subvol_info) {
2602b64ec075STomohiro Misono 		btrfs_free_path(path);
2603b64ec075STomohiro Misono 		return -ENOMEM;
2604b64ec075STomohiro Misono 	}
2605b64ec075STomohiro Misono 
2606b64ec075STomohiro Misono 	inode = file_inode(file);
2607b64ec075STomohiro Misono 	fs_info = BTRFS_I(inode)->root->fs_info;
2608b64ec075STomohiro Misono 
2609b64ec075STomohiro Misono 	/* Get root_item of inode's subvolume */
2610b64ec075STomohiro Misono 	key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2611b64ec075STomohiro Misono 	key.type = BTRFS_ROOT_ITEM_KEY;
2612b64ec075STomohiro Misono 	key.offset = (u64)-1;
2613b64ec075STomohiro Misono 	root = btrfs_read_fs_root_no_name(fs_info, &key);
2614b64ec075STomohiro Misono 	if (IS_ERR(root)) {
2615b64ec075STomohiro Misono 		ret = PTR_ERR(root);
2616b64ec075STomohiro Misono 		goto out;
2617b64ec075STomohiro Misono 	}
2618b64ec075STomohiro Misono 	root_item = &root->root_item;
2619b64ec075STomohiro Misono 
2620b64ec075STomohiro Misono 	subvol_info->treeid = key.objectid;
2621b64ec075STomohiro Misono 
2622b64ec075STomohiro Misono 	subvol_info->generation = btrfs_root_generation(root_item);
2623b64ec075STomohiro Misono 	subvol_info->flags = btrfs_root_flags(root_item);
2624b64ec075STomohiro Misono 
2625b64ec075STomohiro Misono 	memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2626b64ec075STomohiro Misono 	memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2627b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2628b64ec075STomohiro Misono 	memcpy(subvol_info->received_uuid, root_item->received_uuid,
2629b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2630b64ec075STomohiro Misono 
2631b64ec075STomohiro Misono 	subvol_info->ctransid = btrfs_root_ctransid(root_item);
2632b64ec075STomohiro Misono 	subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2633b64ec075STomohiro Misono 	subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2634b64ec075STomohiro Misono 
2635b64ec075STomohiro Misono 	subvol_info->otransid = btrfs_root_otransid(root_item);
2636b64ec075STomohiro Misono 	subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2637b64ec075STomohiro Misono 	subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2638b64ec075STomohiro Misono 
2639b64ec075STomohiro Misono 	subvol_info->stransid = btrfs_root_stransid(root_item);
2640b64ec075STomohiro Misono 	subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2641b64ec075STomohiro Misono 	subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2642b64ec075STomohiro Misono 
2643b64ec075STomohiro Misono 	subvol_info->rtransid = btrfs_root_rtransid(root_item);
2644b64ec075STomohiro Misono 	subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2645b64ec075STomohiro Misono 	subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2646b64ec075STomohiro Misono 
2647b64ec075STomohiro Misono 	if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2648b64ec075STomohiro Misono 		/* Search root tree for ROOT_BACKREF of this subvolume */
2649b64ec075STomohiro Misono 		root = fs_info->tree_root;
2650b64ec075STomohiro Misono 
2651b64ec075STomohiro Misono 		key.type = BTRFS_ROOT_BACKREF_KEY;
2652b64ec075STomohiro Misono 		key.offset = 0;
2653b64ec075STomohiro Misono 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2654b64ec075STomohiro Misono 		if (ret < 0) {
2655b64ec075STomohiro Misono 			goto out;
2656b64ec075STomohiro Misono 		} else if (path->slots[0] >=
2657b64ec075STomohiro Misono 			   btrfs_header_nritems(path->nodes[0])) {
2658b64ec075STomohiro Misono 			ret = btrfs_next_leaf(root, path);
2659b64ec075STomohiro Misono 			if (ret < 0) {
2660b64ec075STomohiro Misono 				goto out;
2661b64ec075STomohiro Misono 			} else if (ret > 0) {
2662b64ec075STomohiro Misono 				ret = -EUCLEAN;
2663b64ec075STomohiro Misono 				goto out;
2664b64ec075STomohiro Misono 			}
2665b64ec075STomohiro Misono 		}
2666b64ec075STomohiro Misono 
2667b64ec075STomohiro Misono 		leaf = path->nodes[0];
2668b64ec075STomohiro Misono 		slot = path->slots[0];
2669b64ec075STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
2670b64ec075STomohiro Misono 		if (key.objectid == subvol_info->treeid &&
2671b64ec075STomohiro Misono 		    key.type == BTRFS_ROOT_BACKREF_KEY) {
2672b64ec075STomohiro Misono 			subvol_info->parent_id = key.offset;
2673b64ec075STomohiro Misono 
2674b64ec075STomohiro Misono 			rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2675b64ec075STomohiro Misono 			subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2676b64ec075STomohiro Misono 
2677b64ec075STomohiro Misono 			item_off = btrfs_item_ptr_offset(leaf, slot)
2678b64ec075STomohiro Misono 					+ sizeof(struct btrfs_root_ref);
2679b64ec075STomohiro Misono 			item_len = btrfs_item_size_nr(leaf, slot)
2680b64ec075STomohiro Misono 					- sizeof(struct btrfs_root_ref);
2681b64ec075STomohiro Misono 			read_extent_buffer(leaf, subvol_info->name,
2682b64ec075STomohiro Misono 					   item_off, item_len);
2683b64ec075STomohiro Misono 		} else {
2684b64ec075STomohiro Misono 			ret = -ENOENT;
2685b64ec075STomohiro Misono 			goto out;
2686b64ec075STomohiro Misono 		}
2687b64ec075STomohiro Misono 	}
2688b64ec075STomohiro Misono 
2689b64ec075STomohiro Misono 	if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2690b64ec075STomohiro Misono 		ret = -EFAULT;
2691b64ec075STomohiro Misono 
2692b64ec075STomohiro Misono out:
2693b64ec075STomohiro Misono 	btrfs_free_path(path);
2694b64ec075STomohiro Misono 	kzfree(subvol_info);
2695b64ec075STomohiro Misono 	return ret;
2696b64ec075STomohiro Misono }
2697b64ec075STomohiro Misono 
269842e4b520STomohiro Misono /*
269942e4b520STomohiro Misono  * Return ROOT_REF information of the subvolume containing this inode
270042e4b520STomohiro Misono  * except the subvolume name.
270142e4b520STomohiro Misono  */
270242e4b520STomohiro Misono static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
270342e4b520STomohiro Misono {
270442e4b520STomohiro Misono 	struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
270542e4b520STomohiro Misono 	struct btrfs_root_ref *rref;
270642e4b520STomohiro Misono 	struct btrfs_root *root;
270742e4b520STomohiro Misono 	struct btrfs_path *path;
270842e4b520STomohiro Misono 	struct btrfs_key key;
270942e4b520STomohiro Misono 	struct extent_buffer *leaf;
271042e4b520STomohiro Misono 	struct inode *inode;
271142e4b520STomohiro Misono 	u64 objectid;
271242e4b520STomohiro Misono 	int slot;
271342e4b520STomohiro Misono 	int ret;
271442e4b520STomohiro Misono 	u8 found;
271542e4b520STomohiro Misono 
271642e4b520STomohiro Misono 	path = btrfs_alloc_path();
271742e4b520STomohiro Misono 	if (!path)
271842e4b520STomohiro Misono 		return -ENOMEM;
271942e4b520STomohiro Misono 
272042e4b520STomohiro Misono 	rootrefs = memdup_user(argp, sizeof(*rootrefs));
272142e4b520STomohiro Misono 	if (IS_ERR(rootrefs)) {
272242e4b520STomohiro Misono 		btrfs_free_path(path);
272342e4b520STomohiro Misono 		return PTR_ERR(rootrefs);
272442e4b520STomohiro Misono 	}
272542e4b520STomohiro Misono 
272642e4b520STomohiro Misono 	inode = file_inode(file);
272742e4b520STomohiro Misono 	root = BTRFS_I(inode)->root->fs_info->tree_root;
272842e4b520STomohiro Misono 	objectid = BTRFS_I(inode)->root->root_key.objectid;
272942e4b520STomohiro Misono 
273042e4b520STomohiro Misono 	key.objectid = objectid;
273142e4b520STomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
273242e4b520STomohiro Misono 	key.offset = rootrefs->min_treeid;
273342e4b520STomohiro Misono 	found = 0;
273442e4b520STomohiro Misono 
273542e4b520STomohiro Misono 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
273642e4b520STomohiro Misono 	if (ret < 0) {
273742e4b520STomohiro Misono 		goto out;
273842e4b520STomohiro Misono 	} else if (path->slots[0] >=
273942e4b520STomohiro Misono 		   btrfs_header_nritems(path->nodes[0])) {
274042e4b520STomohiro Misono 		ret = btrfs_next_leaf(root, path);
274142e4b520STomohiro Misono 		if (ret < 0) {
274242e4b520STomohiro Misono 			goto out;
274342e4b520STomohiro Misono 		} else if (ret > 0) {
274442e4b520STomohiro Misono 			ret = -EUCLEAN;
274542e4b520STomohiro Misono 			goto out;
274642e4b520STomohiro Misono 		}
274742e4b520STomohiro Misono 	}
274842e4b520STomohiro Misono 	while (1) {
274942e4b520STomohiro Misono 		leaf = path->nodes[0];
275042e4b520STomohiro Misono 		slot = path->slots[0];
275142e4b520STomohiro Misono 
275242e4b520STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
275342e4b520STomohiro Misono 		if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
275442e4b520STomohiro Misono 			ret = 0;
275542e4b520STomohiro Misono 			goto out;
275642e4b520STomohiro Misono 		}
275742e4b520STomohiro Misono 
275842e4b520STomohiro Misono 		if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
275942e4b520STomohiro Misono 			ret = -EOVERFLOW;
276042e4b520STomohiro Misono 			goto out;
276142e4b520STomohiro Misono 		}
276242e4b520STomohiro Misono 
276342e4b520STomohiro Misono 		rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
276442e4b520STomohiro Misono 		rootrefs->rootref[found].treeid = key.offset;
276542e4b520STomohiro Misono 		rootrefs->rootref[found].dirid =
276642e4b520STomohiro Misono 				  btrfs_root_ref_dirid(leaf, rref);
276742e4b520STomohiro Misono 		found++;
276842e4b520STomohiro Misono 
276942e4b520STomohiro Misono 		ret = btrfs_next_item(root, path);
277042e4b520STomohiro Misono 		if (ret < 0) {
277142e4b520STomohiro Misono 			goto out;
277242e4b520STomohiro Misono 		} else if (ret > 0) {
277342e4b520STomohiro Misono 			ret = -EUCLEAN;
277442e4b520STomohiro Misono 			goto out;
277542e4b520STomohiro Misono 		}
277642e4b520STomohiro Misono 	}
277742e4b520STomohiro Misono 
277842e4b520STomohiro Misono out:
277942e4b520STomohiro Misono 	if (!ret || ret == -EOVERFLOW) {
278042e4b520STomohiro Misono 		rootrefs->num_items = found;
278142e4b520STomohiro Misono 		/* update min_treeid for next search */
278242e4b520STomohiro Misono 		if (found)
278342e4b520STomohiro Misono 			rootrefs->min_treeid =
278442e4b520STomohiro Misono 				rootrefs->rootref[found - 1].treeid + 1;
278542e4b520STomohiro Misono 		if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
278642e4b520STomohiro Misono 			ret = -EFAULT;
278742e4b520STomohiro Misono 	}
278842e4b520STomohiro Misono 
278942e4b520STomohiro Misono 	kfree(rootrefs);
279042e4b520STomohiro Misono 	btrfs_free_path(path);
279142e4b520STomohiro Misono 
279242e4b520STomohiro Misono 	return ret;
279342e4b520STomohiro Misono }
279442e4b520STomohiro Misono 
279576dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
279676dda93cSYan, Zheng 					     void __user *arg)
279776dda93cSYan, Zheng {
279854563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
27990b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
280076dda93cSYan, Zheng 	struct dentry *dentry;
28012b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
280276dda93cSYan, Zheng 	struct inode *inode;
280376dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
280476dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
280576dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
280676dda93cSYan, Zheng 	int namelen;
280776dda93cSYan, Zheng 	int err = 0;
280876dda93cSYan, Zheng 
2809325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2810325c50e3SJeff Mahoney 		return -ENOTDIR;
2811325c50e3SJeff Mahoney 
281276dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
281376dda93cSYan, Zheng 	if (IS_ERR(vol_args))
281476dda93cSYan, Zheng 		return PTR_ERR(vol_args);
281576dda93cSYan, Zheng 
281676dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
281776dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
281876dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
281976dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
282076dda93cSYan, Zheng 		err = -EINVAL;
282176dda93cSYan, Zheng 		goto out;
282276dda93cSYan, Zheng 	}
282376dda93cSYan, Zheng 
2824a561be71SAl Viro 	err = mnt_want_write_file(file);
282576dda93cSYan, Zheng 	if (err)
282676dda93cSYan, Zheng 		goto out;
282776dda93cSYan, Zheng 
2828521e0546SDavid Sterba 
282900235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
283000235411SAl Viro 	if (err == -EINTR)
283100235411SAl Viro 		goto out_drop_write;
283276dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
283376dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
283476dda93cSYan, Zheng 		err = PTR_ERR(dentry);
283576dda93cSYan, Zheng 		goto out_unlock_dir;
283676dda93cSYan, Zheng 	}
283776dda93cSYan, Zheng 
28382b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
283976dda93cSYan, Zheng 		err = -ENOENT;
284076dda93cSYan, Zheng 		goto out_dput;
284176dda93cSYan, Zheng 	}
284276dda93cSYan, Zheng 
28432b0143b5SDavid Howells 	inode = d_inode(dentry);
28444260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
28454260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
28464260f7c7SSage Weil 		/*
28474260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
28484260f7c7SSage Weil 		 * option, when the user has write+exec access to the
28494260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
28504260f7c7SSage Weil 		 * allowed.
28514260f7c7SSage Weil 		 *
28524260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
28534260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
28544260f7c7SSage Weil 		 * otherwise be able to delete.
28554260f7c7SSage Weil 		 *
28564260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
28574260f7c7SSage Weil 		 * rmdir(2).
28584260f7c7SSage Weil 		 */
28594260f7c7SSage Weil 		err = -EPERM;
28600b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
28614260f7c7SSage Weil 			goto out_dput;
28624260f7c7SSage Weil 
28634260f7c7SSage Weil 		/*
28644260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
28654260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
28664260f7c7SSage Weil 		 * must be called on the dentry referencing the root
28674260f7c7SSage Weil 		 * of the subvol, not a random directory contained
28684260f7c7SSage Weil 		 * within it.
28694260f7c7SSage Weil 		 */
28704260f7c7SSage Weil 		err = -EINVAL;
28714260f7c7SSage Weil 		if (root == dest)
28724260f7c7SSage Weil 			goto out_dput;
28734260f7c7SSage Weil 
28744260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
28754260f7c7SSage Weil 		if (err)
28764260f7c7SSage Weil 			goto out_dput;
28775c39da5bSMiao Xie 	}
28784260f7c7SSage Weil 
28795c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
28804260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
28814260f7c7SSage Weil 	if (err)
28824260f7c7SSage Weil 		goto out_dput;
28834260f7c7SSage Weil 
28844a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
288576dda93cSYan, Zheng 		err = -EINVAL;
288676dda93cSYan, Zheng 		goto out_dput;
288776dda93cSYan, Zheng 	}
288876dda93cSYan, Zheng 
28895955102cSAl Viro 	inode_lock(inode);
2890f60a2364SMisono Tomohiro 	err = btrfs_delete_subvolume(dir, dentry);
28915955102cSAl Viro 	inode_unlock(inode);
2892f60a2364SMisono Tomohiro 	if (!err)
289376dda93cSYan, Zheng 		d_delete(dentry);
2894fa6ac876SLiu Bo 
289576dda93cSYan, Zheng out_dput:
289676dda93cSYan, Zheng 	dput(dentry);
289776dda93cSYan, Zheng out_unlock_dir:
28985955102cSAl Viro 	inode_unlock(dir);
289900235411SAl Viro out_drop_write:
29002a79f17eSAl Viro 	mnt_drop_write_file(file);
290176dda93cSYan, Zheng out:
290276dda93cSYan, Zheng 	kfree(vol_args);
290376dda93cSYan, Zheng 	return err;
290476dda93cSYan, Zheng }
290576dda93cSYan, Zheng 
29061e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2907f46b5a66SChristoph Hellwig {
2908496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2909f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
29101e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2911c146afadSYan Zheng 	int ret;
2912c146afadSYan Zheng 
291325122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
291425122d15SIlya Dryomov 	if (ret)
291525122d15SIlya Dryomov 		return ret;
2916b83cc969SLi Zefan 
291725122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
291825122d15SIlya Dryomov 		ret = -EROFS;
291925122d15SIlya Dryomov 		goto out;
29205ac00addSStefan Behrens 	}
2921f46b5a66SChristoph Hellwig 
2922f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2923f46b5a66SChristoph Hellwig 	case S_IFDIR:
2924e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2925e441d54dSChris Mason 			ret = -EPERM;
2926e441d54dSChris Mason 			goto out;
2927e441d54dSChris Mason 		}
2928de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
2929f46b5a66SChristoph Hellwig 		break;
2930f46b5a66SChristoph Hellwig 	case S_IFREG:
2931e441d54dSChris Mason 		if (!(file->f_mode & FMODE_WRITE)) {
2932e441d54dSChris Mason 			ret = -EINVAL;
2933e441d54dSChris Mason 			goto out;
2934e441d54dSChris Mason 		}
29351e701a32SChris Mason 
29361e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
29371e701a32SChris Mason 		if (!range) {
29381e701a32SChris Mason 			ret = -ENOMEM;
29391e701a32SChris Mason 			goto out;
29401e701a32SChris Mason 		}
29411e701a32SChris Mason 
29421e701a32SChris Mason 		if (argp) {
29431e701a32SChris Mason 			if (copy_from_user(range, argp,
29441e701a32SChris Mason 					   sizeof(*range))) {
29451e701a32SChris Mason 				ret = -EFAULT;
29461e701a32SChris Mason 				kfree(range);
2947683be16eSDan Carpenter 				goto out;
29481e701a32SChris Mason 			}
29491e701a32SChris Mason 			/* compression requires us to start the IO */
29501e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
29511e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
29521e701a32SChris Mason 				range->extent_thresh = (u32)-1;
29531e701a32SChris Mason 			}
29541e701a32SChris Mason 		} else {
29551e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
29561e701a32SChris Mason 			range->len = (u64)-1;
29571e701a32SChris Mason 		}
2958496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
29597c829b72SAnand Jain 					range, BTRFS_OLDEST_GENERATION, 0);
29604cb5300bSChris Mason 		if (ret > 0)
29614cb5300bSChris Mason 			ret = 0;
29621e701a32SChris Mason 		kfree(range);
2963f46b5a66SChristoph Hellwig 		break;
29648929ecfaSYan, Zheng 	default:
29658929ecfaSYan, Zheng 		ret = -EINVAL;
2966f46b5a66SChristoph Hellwig 	}
2967e441d54dSChris Mason out:
296825122d15SIlya Dryomov 	mnt_drop_write_file(file);
2969e441d54dSChris Mason 	return ret;
2970f46b5a66SChristoph Hellwig }
2971f46b5a66SChristoph Hellwig 
29722ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2973f46b5a66SChristoph Hellwig {
2974f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
2975f46b5a66SChristoph Hellwig 	int ret;
2976f46b5a66SChristoph Hellwig 
2977e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
2978e441d54dSChris Mason 		return -EPERM;
2979e441d54dSChris Mason 
2980171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2981e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2982c9e9f97bSIlya Dryomov 
2983dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
2984c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
2985c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
2986c9e9f97bSIlya Dryomov 		goto out;
2987c9e9f97bSIlya Dryomov 	}
2988f46b5a66SChristoph Hellwig 
29895516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
29902ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
2991f46b5a66SChristoph Hellwig 
299243d20761SAnand Jain 	if (!ret)
29930b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
299443d20761SAnand Jain 
2995f46b5a66SChristoph Hellwig 	kfree(vol_args);
2996c9e9f97bSIlya Dryomov out:
2997171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2998f46b5a66SChristoph Hellwig 	return ret;
2999f46b5a66SChristoph Hellwig }
3000f46b5a66SChristoph Hellwig 
30016b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3002f46b5a66SChristoph Hellwig {
30030b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
30040b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
30056b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
3006f46b5a66SChristoph Hellwig 	int ret;
3007f46b5a66SChristoph Hellwig 
3008e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
3009e441d54dSChris Mason 		return -EPERM;
3010e441d54dSChris Mason 
3011da24927bSMiao Xie 	ret = mnt_want_write_file(file);
3012da24927bSMiao Xie 	if (ret)
3013da24927bSMiao Xie 		return ret;
3014c146afadSYan Zheng 
3015dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
3016c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
3017c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
3018c47ca32dSDan Carpenter 		goto err_drop;
3019c9e9f97bSIlya Dryomov 	}
3020f46b5a66SChristoph Hellwig 
30216b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
3022fd4e994bSOmar Sandoval 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
3023fd4e994bSOmar Sandoval 		ret = -EOPNOTSUPP;
3024fd4e994bSOmar Sandoval 		goto out;
3025fd4e994bSOmar Sandoval 	}
3026f46b5a66SChristoph Hellwig 
3027171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3028183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3029183860f6SAnand Jain 		goto out;
3030183860f6SAnand Jain 	}
3031183860f6SAnand Jain 
3032735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
30332ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
30346b526ed7SAnand Jain 	} else {
30356b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
30362ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
30376b526ed7SAnand Jain 	}
3038171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3039183860f6SAnand Jain 
30406b526ed7SAnand Jain 	if (!ret) {
3041735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
30420b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
30436b526ed7SAnand Jain 					vol_args->devid);
30446b526ed7SAnand Jain 		else
30450b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
30466b526ed7SAnand Jain 					vol_args->name);
30476b526ed7SAnand Jain 	}
3048183860f6SAnand Jain out:
3049183860f6SAnand Jain 	kfree(vol_args);
3050c47ca32dSDan Carpenter err_drop:
30514ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
3052f46b5a66SChristoph Hellwig 	return ret;
3053f46b5a66SChristoph Hellwig }
3054f46b5a66SChristoph Hellwig 
3055f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3056f46b5a66SChristoph Hellwig {
30570b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
30580b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3059f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
3060f46b5a66SChristoph Hellwig 	int ret;
3061f46b5a66SChristoph Hellwig 
3062f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
3063f46b5a66SChristoph Hellwig 		return -EPERM;
3064f46b5a66SChristoph Hellwig 
3065f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
3066f46b5a66SChristoph Hellwig 	if (ret)
3067f46b5a66SChristoph Hellwig 		return ret;
3068f46b5a66SChristoph Hellwig 
3069171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3070f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
307158d7bbf8SDavid Sterba 		goto out_drop_write;
307258d7bbf8SDavid Sterba 	}
307358d7bbf8SDavid Sterba 
307458d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
307558d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
307658d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
3077f46b5a66SChristoph Hellwig 		goto out;
3078f46b5a66SChristoph Hellwig 	}
3079f46b5a66SChristoph Hellwig 
308058d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
30812ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3082f46b5a66SChristoph Hellwig 
3083f46b5a66SChristoph Hellwig 	if (!ret)
30840b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3085f46b5a66SChristoph Hellwig 	kfree(vol_args);
308658d7bbf8SDavid Sterba out:
3087171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
308858d7bbf8SDavid Sterba out_drop_write:
3089f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
309058d7bbf8SDavid Sterba 
3091f46b5a66SChristoph Hellwig 	return ret;
3092f46b5a66SChristoph Hellwig }
3093f46b5a66SChristoph Hellwig 
30942ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
30952ff7e61eSJeff Mahoney 				void __user *arg)
3096475f6387SJan Schmidt {
3097027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
3098475f6387SJan Schmidt 	struct btrfs_device *device;
30990b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3100027ed2f0SLi Zefan 	int ret = 0;
3101475f6387SJan Schmidt 
3102027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
3103027ed2f0SLi Zefan 	if (!fi_args)
3104027ed2f0SLi Zefan 		return -ENOMEM;
3105027ed2f0SLi Zefan 
3106d03262c7SDavid Sterba 	rcu_read_lock();
3107027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
3108475f6387SJan Schmidt 
3109d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3110027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
3111027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
3112475f6387SJan Schmidt 	}
3113d03262c7SDavid Sterba 	rcu_read_unlock();
3114475f6387SJan Schmidt 
3115d03262c7SDavid Sterba 	memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
3116bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
3117bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
3118bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
311980a773fbSDavid Sterba 
3120027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3121027ed2f0SLi Zefan 		ret = -EFAULT;
3122475f6387SJan Schmidt 
3123027ed2f0SLi Zefan 	kfree(fi_args);
3124027ed2f0SLi Zefan 	return ret;
3125475f6387SJan Schmidt }
3126475f6387SJan Schmidt 
31272ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
31282ff7e61eSJeff Mahoney 				 void __user *arg)
3129475f6387SJan Schmidt {
3130475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
3131475f6387SJan Schmidt 	struct btrfs_device *dev;
3132475f6387SJan Schmidt 	int ret = 0;
3133475f6387SJan Schmidt 	char *s_uuid = NULL;
3134475f6387SJan Schmidt 
3135475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
3136475f6387SJan Schmidt 	if (IS_ERR(di_args))
3137475f6387SJan Schmidt 		return PTR_ERR(di_args);
3138475f6387SJan Schmidt 
3139dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
3140475f6387SJan Schmidt 		s_uuid = di_args->uuid;
3141475f6387SJan Schmidt 
3142c5593ca3SDavid Sterba 	rcu_read_lock();
31430b246afaSJeff Mahoney 	dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
3144475f6387SJan Schmidt 
3145475f6387SJan Schmidt 	if (!dev) {
3146475f6387SJan Schmidt 		ret = -ENODEV;
3147475f6387SJan Schmidt 		goto out;
3148475f6387SJan Schmidt 	}
3149475f6387SJan Schmidt 
3150475f6387SJan Schmidt 	di_args->devid = dev->devid;
31517cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
31527cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3153475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3154a27202fbSJim Meyering 	if (dev->name) {
3155606686eeSJosef Bacik 		struct rcu_string *name;
3156606686eeSJosef Bacik 
3157606686eeSJosef Bacik 		name = rcu_dereference(dev->name);
31586670d4c2SXiongfeng Wang 		strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
3159a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
3160a27202fbSJim Meyering 	} else {
316199ba55adSStefan Behrens 		di_args->path[0] = '\0';
3162a27202fbSJim Meyering 	}
3163475f6387SJan Schmidt 
3164475f6387SJan Schmidt out:
3165c5593ca3SDavid Sterba 	rcu_read_unlock();
3166475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3167475f6387SJan Schmidt 		ret = -EFAULT;
3168475f6387SJan Schmidt 
3169475f6387SJan Schmidt 	kfree(di_args);
3170475f6387SJan Schmidt 	return ret;
3171475f6387SJan Schmidt }
3172475f6387SJan Schmidt 
3173f4414602SMark Fasheh static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
3174416161dbSMark Fasheh {
3175416161dbSMark Fasheh 	struct page *page;
3176416161dbSMark Fasheh 
3177416161dbSMark Fasheh 	page = grab_cache_page(inode->i_mapping, index);
3178416161dbSMark Fasheh 	if (!page)
317931314002SFilipe Manana 		return ERR_PTR(-ENOMEM);
3180416161dbSMark Fasheh 
3181416161dbSMark Fasheh 	if (!PageUptodate(page)) {
318231314002SFilipe Manana 		int ret;
318331314002SFilipe Manana 
318431314002SFilipe Manana 		ret = btrfs_readpage(NULL, page);
318531314002SFilipe Manana 		if (ret)
318631314002SFilipe Manana 			return ERR_PTR(ret);
3187416161dbSMark Fasheh 		lock_page(page);
3188416161dbSMark Fasheh 		if (!PageUptodate(page)) {
3189416161dbSMark Fasheh 			unlock_page(page);
319009cbfeafSKirill A. Shutemov 			put_page(page);
319131314002SFilipe Manana 			return ERR_PTR(-EIO);
3192416161dbSMark Fasheh 		}
319331314002SFilipe Manana 		if (page->mapping != inode->i_mapping) {
3194416161dbSMark Fasheh 			unlock_page(page);
319509cbfeafSKirill A. Shutemov 			put_page(page);
319631314002SFilipe Manana 			return ERR_PTR(-EAGAIN);
3197416161dbSMark Fasheh 		}
3198416161dbSMark Fasheh 	}
3199416161dbSMark Fasheh 
3200416161dbSMark Fasheh 	return page;
3201416161dbSMark Fasheh }
3202416161dbSMark Fasheh 
3203f4414602SMark Fasheh static int gather_extent_pages(struct inode *inode, struct page **pages,
3204f4414602SMark Fasheh 			       int num_pages, u64 off)
3205f4414602SMark Fasheh {
3206f4414602SMark Fasheh 	int i;
320709cbfeafSKirill A. Shutemov 	pgoff_t index = off >> PAGE_SHIFT;
3208f4414602SMark Fasheh 
3209f4414602SMark Fasheh 	for (i = 0; i < num_pages; i++) {
321031314002SFilipe Manana again:
3211f4414602SMark Fasheh 		pages[i] = extent_same_get_page(inode, index + i);
321231314002SFilipe Manana 		if (IS_ERR(pages[i])) {
321331314002SFilipe Manana 			int err = PTR_ERR(pages[i]);
321431314002SFilipe Manana 
321531314002SFilipe Manana 			if (err == -EAGAIN)
321631314002SFilipe Manana 				goto again;
321731314002SFilipe Manana 			pages[i] = NULL;
321831314002SFilipe Manana 			return err;
321931314002SFilipe Manana 		}
3220f4414602SMark Fasheh 	}
3221f4414602SMark Fasheh 	return 0;
3222f4414602SMark Fasheh }
3223f4414602SMark Fasheh 
3224e0bd70c6SFilipe Manana static int lock_extent_range(struct inode *inode, u64 off, u64 len,
3225e0bd70c6SFilipe Manana 			     bool retry_range_locking)
322677fe20dcSMark Fasheh {
3227e0bd70c6SFilipe Manana 	/*
3228e0bd70c6SFilipe Manana 	 * Do any pending delalloc/csum calculations on inode, one way or
3229e0bd70c6SFilipe Manana 	 * another, and lock file content.
3230e0bd70c6SFilipe Manana 	 * The locking order is:
3231e0bd70c6SFilipe Manana 	 *
3232e0bd70c6SFilipe Manana 	 *   1) pages
3233e0bd70c6SFilipe Manana 	 *   2) range in the inode's io tree
3234e0bd70c6SFilipe Manana 	 */
323577fe20dcSMark Fasheh 	while (1) {
323677fe20dcSMark Fasheh 		struct btrfs_ordered_extent *ordered;
323777fe20dcSMark Fasheh 		lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
323877fe20dcSMark Fasheh 		ordered = btrfs_lookup_first_ordered_extent(inode,
323977fe20dcSMark Fasheh 							    off + len - 1);
3240ff5df9b8SFilipe Manana 		if ((!ordered ||
3241ff5df9b8SFilipe Manana 		     ordered->file_offset + ordered->len <= off ||
3242ff5df9b8SFilipe Manana 		     ordered->file_offset >= off + len) &&
324377fe20dcSMark Fasheh 		    !test_range_bit(&BTRFS_I(inode)->io_tree, off,
3244ff5df9b8SFilipe Manana 				    off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
3245ff5df9b8SFilipe Manana 			if (ordered)
3246ff5df9b8SFilipe Manana 				btrfs_put_ordered_extent(ordered);
324777fe20dcSMark Fasheh 			break;
3248ff5df9b8SFilipe Manana 		}
324977fe20dcSMark Fasheh 		unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
325077fe20dcSMark Fasheh 		if (ordered)
325177fe20dcSMark Fasheh 			btrfs_put_ordered_extent(ordered);
3252e0bd70c6SFilipe Manana 		if (!retry_range_locking)
3253e0bd70c6SFilipe Manana 			return -EAGAIN;
325477fe20dcSMark Fasheh 		btrfs_wait_ordered_range(inode, off, len);
325577fe20dcSMark Fasheh 	}
3256e0bd70c6SFilipe Manana 	return 0;
325777fe20dcSMark Fasheh }
325877fe20dcSMark Fasheh 
3259f4414602SMark Fasheh static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
3260416161dbSMark Fasheh {
32615955102cSAl Viro 	inode_unlock(inode1);
32625955102cSAl Viro 	inode_unlock(inode2);
3263416161dbSMark Fasheh }
3264416161dbSMark Fasheh 
3265f4414602SMark Fasheh static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
3266f4414602SMark Fasheh {
3267f4414602SMark Fasheh 	if (inode1 < inode2)
3268f4414602SMark Fasheh 		swap(inode1, inode2);
3269f4414602SMark Fasheh 
32705955102cSAl Viro 	inode_lock_nested(inode1, I_MUTEX_PARENT);
32715955102cSAl Viro 	inode_lock_nested(inode2, I_MUTEX_CHILD);
3272f4414602SMark Fasheh }
3273f4414602SMark Fasheh 
3274f4414602SMark Fasheh static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
3275f4414602SMark Fasheh 				      struct inode *inode2, u64 loff2, u64 len)
3276f4414602SMark Fasheh {
3277f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3278f4414602SMark Fasheh 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3279f4414602SMark Fasheh }
3280f4414602SMark Fasheh 
3281e0bd70c6SFilipe Manana static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
3282e0bd70c6SFilipe Manana 				    struct inode *inode2, u64 loff2, u64 len,
3283e0bd70c6SFilipe Manana 				    bool retry_range_locking)
3284416161dbSMark Fasheh {
3285e0bd70c6SFilipe Manana 	int ret;
3286e0bd70c6SFilipe Manana 
3287416161dbSMark Fasheh 	if (inode1 < inode2) {
3288416161dbSMark Fasheh 		swap(inode1, inode2);
3289416161dbSMark Fasheh 		swap(loff1, loff2);
3290416161dbSMark Fasheh 	}
3291e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
3292e0bd70c6SFilipe Manana 	if (ret)
3293e0bd70c6SFilipe Manana 		return ret;
3294e0bd70c6SFilipe Manana 	ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
3295e0bd70c6SFilipe Manana 	if (ret)
3296e0bd70c6SFilipe Manana 		unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
3297e0bd70c6SFilipe Manana 			      loff1 + len - 1);
3298e0bd70c6SFilipe Manana 	return ret;
3299416161dbSMark Fasheh }
3300f4414602SMark Fasheh 
3301f4414602SMark Fasheh struct cmp_pages {
3302f4414602SMark Fasheh 	int		num_pages;
3303f4414602SMark Fasheh 	struct page	**src_pages;
3304f4414602SMark Fasheh 	struct page	**dst_pages;
3305f4414602SMark Fasheh };
3306f4414602SMark Fasheh 
3307f4414602SMark Fasheh static void btrfs_cmp_data_free(struct cmp_pages *cmp)
3308f4414602SMark Fasheh {
3309f4414602SMark Fasheh 	int i;
3310f4414602SMark Fasheh 	struct page *pg;
3311f4414602SMark Fasheh 
3312f4414602SMark Fasheh 	for (i = 0; i < cmp->num_pages; i++) {
3313f4414602SMark Fasheh 		pg = cmp->src_pages[i];
3314e0bd70c6SFilipe Manana 		if (pg) {
3315e0bd70c6SFilipe Manana 			unlock_page(pg);
331609cbfeafSKirill A. Shutemov 			put_page(pg);
331797b19170SNaohiro Aota 			cmp->src_pages[i] = NULL;
3318e0bd70c6SFilipe Manana 		}
3319f4414602SMark Fasheh 		pg = cmp->dst_pages[i];
3320e0bd70c6SFilipe Manana 		if (pg) {
3321e0bd70c6SFilipe Manana 			unlock_page(pg);
332209cbfeafSKirill A. Shutemov 			put_page(pg);
332397b19170SNaohiro Aota 			cmp->dst_pages[i] = NULL;
3324f4414602SMark Fasheh 		}
3325e0bd70c6SFilipe Manana 	}
3326f4414602SMark Fasheh }
3327f4414602SMark Fasheh 
3328f4414602SMark Fasheh static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
3329f4414602SMark Fasheh 				  struct inode *dst, u64 dst_loff,
3330f4414602SMark Fasheh 				  u64 len, struct cmp_pages *cmp)
3331f4414602SMark Fasheh {
3332f4414602SMark Fasheh 	int ret;
333309cbfeafSKirill A. Shutemov 	int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
3334f4414602SMark Fasheh 
3335f4414602SMark Fasheh 	cmp->num_pages = num_pages;
3336f4414602SMark Fasheh 
333767b07bd4STimofey Titovets 	ret = gather_extent_pages(src, cmp->src_pages, num_pages, loff);
3338f4414602SMark Fasheh 	if (ret)
3339f4414602SMark Fasheh 		goto out;
3340f4414602SMark Fasheh 
334167b07bd4STimofey Titovets 	ret = gather_extent_pages(dst, cmp->dst_pages, num_pages, dst_loff);
3342f4414602SMark Fasheh 
3343f4414602SMark Fasheh out:
3344f4414602SMark Fasheh 	if (ret)
3345f4414602SMark Fasheh 		btrfs_cmp_data_free(cmp);
334678ad4ce0SNaohiro Aota 	return ret;
3347416161dbSMark Fasheh }
3348416161dbSMark Fasheh 
33491a287cfeSDavid Sterba static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
3350416161dbSMark Fasheh {
3351416161dbSMark Fasheh 	int ret = 0;
3352f4414602SMark Fasheh 	int i;
3353416161dbSMark Fasheh 	struct page *src_page, *dst_page;
335409cbfeafSKirill A. Shutemov 	unsigned int cmp_len = PAGE_SIZE;
3355416161dbSMark Fasheh 	void *addr, *dst_addr;
3356416161dbSMark Fasheh 
3357f4414602SMark Fasheh 	i = 0;
3358416161dbSMark Fasheh 	while (len) {
335909cbfeafSKirill A. Shutemov 		if (len < PAGE_SIZE)
3360416161dbSMark Fasheh 			cmp_len = len;
3361416161dbSMark Fasheh 
3362f4414602SMark Fasheh 		BUG_ON(i >= cmp->num_pages);
3363f4414602SMark Fasheh 
3364f4414602SMark Fasheh 		src_page = cmp->src_pages[i];
3365f4414602SMark Fasheh 		dst_page = cmp->dst_pages[i];
3366e0bd70c6SFilipe Manana 		ASSERT(PageLocked(src_page));
3367e0bd70c6SFilipe Manana 		ASSERT(PageLocked(dst_page));
3368f4414602SMark Fasheh 
3369416161dbSMark Fasheh 		addr = kmap_atomic(src_page);
3370416161dbSMark Fasheh 		dst_addr = kmap_atomic(dst_page);
3371416161dbSMark Fasheh 
3372416161dbSMark Fasheh 		flush_dcache_page(src_page);
3373416161dbSMark Fasheh 		flush_dcache_page(dst_page);
3374416161dbSMark Fasheh 
3375416161dbSMark Fasheh 		if (memcmp(addr, dst_addr, cmp_len))
33762b3909f8SDarrick J. Wong 			ret = -EBADE;
3377416161dbSMark Fasheh 
3378416161dbSMark Fasheh 		kunmap_atomic(addr);
3379416161dbSMark Fasheh 		kunmap_atomic(dst_addr);
3380416161dbSMark Fasheh 
3381416161dbSMark Fasheh 		if (ret)
3382416161dbSMark Fasheh 			break;
3383416161dbSMark Fasheh 
3384416161dbSMark Fasheh 		len -= cmp_len;
3385f4414602SMark Fasheh 		i++;
3386416161dbSMark Fasheh 	}
3387416161dbSMark Fasheh 
3388416161dbSMark Fasheh 	return ret;
3389416161dbSMark Fasheh }
3390416161dbSMark Fasheh 
3391e1d227a4SMark Fasheh static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3392e1d227a4SMark Fasheh 				     u64 olen)
3393416161dbSMark Fasheh {
3394e1d227a4SMark Fasheh 	u64 len = *plen;
3395416161dbSMark Fasheh 	u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3396416161dbSMark Fasheh 
3397e1d227a4SMark Fasheh 	if (off + olen > inode->i_size || off + olen < off)
3398416161dbSMark Fasheh 		return -EINVAL;
3399e1d227a4SMark Fasheh 
3400e1d227a4SMark Fasheh 	/* if we extend to eof, continue to block boundary */
3401e1d227a4SMark Fasheh 	if (off + len == inode->i_size)
3402e1d227a4SMark Fasheh 		*plen = len = ALIGN(inode->i_size, bs) - off;
3403e1d227a4SMark Fasheh 
3404416161dbSMark Fasheh 	/* Check that we are block aligned - btrfs_clone() requires this */
3405416161dbSMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3406416161dbSMark Fasheh 		return -EINVAL;
3407416161dbSMark Fasheh 
3408416161dbSMark Fasheh 	return 0;
3409416161dbSMark Fasheh }
3410416161dbSMark Fasheh 
34113973909dSTimofey Titovets static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 olen,
341267b07bd4STimofey Titovets 				   struct inode *dst, u64 dst_loff,
341367b07bd4STimofey Titovets 				   struct cmp_pages *cmp)
3414416161dbSMark Fasheh {
3415416161dbSMark Fasheh 	int ret;
3416e1d227a4SMark Fasheh 	u64 len = olen;
3417fc4badd9SOmar Sandoval 	bool same_inode = (src == dst);
34180efa9f48SMark Fasheh 	u64 same_lock_start = 0;
34190efa9f48SMark Fasheh 	u64 same_lock_len = 0;
3420416161dbSMark Fasheh 
34210efa9f48SMark Fasheh 	ret = extent_same_check_offsets(src, loff, &len, olen);
34220efa9f48SMark Fasheh 	if (ret)
34233973909dSTimofey Titovets 		return ret;
3424fc4badd9SOmar Sandoval 
3425fc4badd9SOmar Sandoval 	ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3426f4dfe687SFilipe Manana 	if (ret)
34273973909dSTimofey Titovets 		return ret;
34280efa9f48SMark Fasheh 
3429fc4badd9SOmar Sandoval 	if (same_inode) {
34300efa9f48SMark Fasheh 		/*
34310efa9f48SMark Fasheh 		 * Single inode case wants the same checks, except we
34320efa9f48SMark Fasheh 		 * don't want our length pushed out past i_size as
34330efa9f48SMark Fasheh 		 * comparing that data range makes no sense.
34340efa9f48SMark Fasheh 		 *
34350efa9f48SMark Fasheh 		 * extent_same_check_offsets() will do this for an
34360efa9f48SMark Fasheh 		 * unaligned length at i_size, so catch it here and
34370efa9f48SMark Fasheh 		 * reject the request.
34380efa9f48SMark Fasheh 		 *
34390efa9f48SMark Fasheh 		 * This effectively means we require aligned extents
34400efa9f48SMark Fasheh 		 * for the single-inode case, whereas the other cases
34410efa9f48SMark Fasheh 		 * allow an unaligned length so long as it ends at
34420efa9f48SMark Fasheh 		 * i_size.
34430efa9f48SMark Fasheh 		 */
34443973909dSTimofey Titovets 		if (len != olen)
34453973909dSTimofey Titovets 			return -EINVAL;
34460efa9f48SMark Fasheh 
34470efa9f48SMark Fasheh 		/* Check for overlapping ranges */
34483973909dSTimofey Titovets 		if (dst_loff + len > loff && dst_loff < loff + len)
34493973909dSTimofey Titovets 			return -EINVAL;
34500efa9f48SMark Fasheh 
34510efa9f48SMark Fasheh 		same_lock_start = min_t(u64, loff, dst_loff);
34520efa9f48SMark Fasheh 		same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
34530efa9f48SMark Fasheh 	}
3454416161dbSMark Fasheh 
3455e0bd70c6SFilipe Manana again:
345667b07bd4STimofey Titovets 	ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, cmp);
3457f4414602SMark Fasheh 	if (ret)
34583973909dSTimofey Titovets 		return ret;
3459f4414602SMark Fasheh 
34600efa9f48SMark Fasheh 	if (same_inode)
3461e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, same_lock_start, same_lock_len,
3462e0bd70c6SFilipe Manana 					false);
34630efa9f48SMark Fasheh 	else
3464e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3465e0bd70c6SFilipe Manana 					       false);
3466e0bd70c6SFilipe Manana 	/*
3467e0bd70c6SFilipe Manana 	 * If one of the inodes has dirty pages in the respective range or
3468e0bd70c6SFilipe Manana 	 * ordered extents, we need to flush dellaloc and wait for all ordered
3469e0bd70c6SFilipe Manana 	 * extents in the range. We must unlock the pages and the ranges in the
3470e0bd70c6SFilipe Manana 	 * io trees to avoid deadlocks when flushing delalloc (requires locking
3471e0bd70c6SFilipe Manana 	 * pages) and when waiting for ordered extents to complete (they require
3472e0bd70c6SFilipe Manana 	 * range locking).
3473e0bd70c6SFilipe Manana 	 */
3474e0bd70c6SFilipe Manana 	if (ret == -EAGAIN) {
3475e0bd70c6SFilipe Manana 		/*
3476e0bd70c6SFilipe Manana 		 * Ranges in the io trees already unlocked. Now unlock all
3477e0bd70c6SFilipe Manana 		 * pages before waiting for all IO to complete.
3478e0bd70c6SFilipe Manana 		 */
347967b07bd4STimofey Titovets 		btrfs_cmp_data_free(cmp);
3480e0bd70c6SFilipe Manana 		if (same_inode) {
3481e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, same_lock_start,
3482e0bd70c6SFilipe Manana 						 same_lock_len);
3483e0bd70c6SFilipe Manana 		} else {
3484e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(src, loff, len);
3485e0bd70c6SFilipe Manana 			btrfs_wait_ordered_range(dst, dst_loff, len);
3486e0bd70c6SFilipe Manana 		}
3487e0bd70c6SFilipe Manana 		goto again;
3488e0bd70c6SFilipe Manana 	}
3489e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
3490e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
3491e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
349267b07bd4STimofey Titovets 		btrfs_cmp_data_free(cmp);
3493e0bd70c6SFilipe Manana 		return ret;
3494e0bd70c6SFilipe Manana 	}
3495f4414602SMark Fasheh 
3496207910ddSMark Fasheh 	/* pass original length for comparison so we stay within i_size */
349767b07bd4STimofey Titovets 	ret = btrfs_cmp_data(olen, cmp);
3498416161dbSMark Fasheh 	if (ret == 0)
34991c919a5eSMark Fasheh 		ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3500416161dbSMark Fasheh 
35010efa9f48SMark Fasheh 	if (same_inode)
35020efa9f48SMark Fasheh 		unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
35030efa9f48SMark Fasheh 			      same_lock_start + same_lock_len - 1);
35040efa9f48SMark Fasheh 	else
3505f4414602SMark Fasheh 		btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3506f4414602SMark Fasheh 
350767b07bd4STimofey Titovets 	btrfs_cmp_data_free(cmp);
35083973909dSTimofey Titovets 
35093973909dSTimofey Titovets 	return ret;
35103973909dSTimofey Titovets }
35113973909dSTimofey Titovets 
3512b6728768STimofey Titovets #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3513b6728768STimofey Titovets 
35143973909dSTimofey Titovets static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
35153973909dSTimofey Titovets 			     struct inode *dst, u64 dst_loff)
35163973909dSTimofey Titovets {
35173973909dSTimofey Titovets 	int ret;
351867b07bd4STimofey Titovets 	struct cmp_pages cmp;
351967b07bd4STimofey Titovets 	int num_pages = PAGE_ALIGN(BTRFS_MAX_DEDUPE_LEN) >> PAGE_SHIFT;
35203973909dSTimofey Titovets 	bool same_inode = (src == dst);
3521b6728768STimofey Titovets 	u64 i, tail_len, chunk_count;
35223973909dSTimofey Titovets 
35233973909dSTimofey Titovets 	if (olen == 0)
35243973909dSTimofey Titovets 		return 0;
35253973909dSTimofey Titovets 
35263973909dSTimofey Titovets 	if (same_inode)
35273973909dSTimofey Titovets 		inode_lock(src);
35283973909dSTimofey Titovets 	else
35293973909dSTimofey Titovets 		btrfs_double_inode_lock(src, dst);
35303973909dSTimofey Titovets 
35313973909dSTimofey Titovets 	/* don't make the dst file partly checksummed */
35323973909dSTimofey Titovets 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
35333973909dSTimofey Titovets 	    (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
35343973909dSTimofey Titovets 		ret = -EINVAL;
35353973909dSTimofey Titovets 		goto out_unlock;
35363973909dSTimofey Titovets 	}
35373973909dSTimofey Titovets 
3538b6728768STimofey Titovets 	tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3539b6728768STimofey Titovets 	chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
354067b07bd4STimofey Titovets 	if (chunk_count == 0)
354167b07bd4STimofey Titovets 		num_pages = PAGE_ALIGN(tail_len) >> PAGE_SHIFT;
354267b07bd4STimofey Titovets 
354367b07bd4STimofey Titovets 	/*
354467b07bd4STimofey Titovets 	 * If deduping ranges in the same inode, locking rules make it
354567b07bd4STimofey Titovets 	 * mandatory to always lock pages in ascending order to avoid deadlocks
354667b07bd4STimofey Titovets 	 * with concurrent tasks (such as starting writeback/delalloc).
354767b07bd4STimofey Titovets 	 */
354867b07bd4STimofey Titovets 	if (same_inode && dst_loff < loff)
354967b07bd4STimofey Titovets 		swap(loff, dst_loff);
355067b07bd4STimofey Titovets 
355167b07bd4STimofey Titovets 	/*
355267b07bd4STimofey Titovets 	 * We must gather up all the pages before we initiate our extent
355367b07bd4STimofey Titovets 	 * locking. We use an array for the page pointers. Size of the array is
355467b07bd4STimofey Titovets 	 * bounded by len, which is in turn bounded by BTRFS_MAX_DEDUPE_LEN.
355567b07bd4STimofey Titovets 	 */
3556bf5091c8SDavid Sterba 	cmp.src_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3557bf5091c8SDavid Sterba 				       GFP_KERNEL | __GFP_ZERO);
3558bf5091c8SDavid Sterba 	cmp.dst_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3559bf5091c8SDavid Sterba 				       GFP_KERNEL | __GFP_ZERO);
356067b07bd4STimofey Titovets 	if (!cmp.src_pages || !cmp.dst_pages) {
3561bf5091c8SDavid Sterba 		ret = -ENOMEM;
3562bf5091c8SDavid Sterba 		goto out_free;
356367b07bd4STimofey Titovets 	}
3564b6728768STimofey Titovets 
3565b6728768STimofey Titovets 	for (i = 0; i < chunk_count; i++) {
3566b6728768STimofey Titovets 		ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
356767b07bd4STimofey Titovets 					      dst, dst_loff, &cmp);
3568b6728768STimofey Titovets 		if (ret)
356922883ddcSLu Fengqi 			goto out_free;
3570b6728768STimofey Titovets 
3571b6728768STimofey Titovets 		loff += BTRFS_MAX_DEDUPE_LEN;
3572b6728768STimofey Titovets 		dst_loff += BTRFS_MAX_DEDUPE_LEN;
3573b6728768STimofey Titovets 	}
3574b6728768STimofey Titovets 
3575b6728768STimofey Titovets 	if (tail_len > 0)
357667b07bd4STimofey Titovets 		ret = btrfs_extent_same_range(src, loff, tail_len, dst,
357767b07bd4STimofey Titovets 					      dst_loff, &cmp);
35783973909dSTimofey Titovets 
357922883ddcSLu Fengqi out_free:
358022883ddcSLu Fengqi 	kvfree(cmp.src_pages);
358122883ddcSLu Fengqi 	kvfree(cmp.dst_pages);
358222883ddcSLu Fengqi 
3583416161dbSMark Fasheh out_unlock:
35840efa9f48SMark Fasheh 	if (same_inode)
35855955102cSAl Viro 		inode_unlock(src);
35860efa9f48SMark Fasheh 	else
3587f4414602SMark Fasheh 		btrfs_double_inode_unlock(src, dst);
3588416161dbSMark Fasheh 
3589416161dbSMark Fasheh 	return ret;
3590416161dbSMark Fasheh }
3591416161dbSMark Fasheh 
35922b3909f8SDarrick J. Wong ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
35932b3909f8SDarrick J. Wong 				struct file *dst_file, u64 dst_loff)
3594416161dbSMark Fasheh {
35952b3909f8SDarrick J. Wong 	struct inode *src = file_inode(src_file);
35962b3909f8SDarrick J. Wong 	struct inode *dst = file_inode(dst_file);
3597416161dbSMark Fasheh 	u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
35982b3909f8SDarrick J. Wong 	ssize_t res;
3599416161dbSMark Fasheh 
360009cbfeafSKirill A. Shutemov 	if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3601416161dbSMark Fasheh 		/*
3602416161dbSMark Fasheh 		 * Btrfs does not support blocksize < page_size. As a
3603416161dbSMark Fasheh 		 * result, btrfs_cmp_data() won't correctly handle
3604416161dbSMark Fasheh 		 * this situation without an update.
3605416161dbSMark Fasheh 		 */
36062b3909f8SDarrick J. Wong 		return -EINVAL;
3607416161dbSMark Fasheh 	}
3608416161dbSMark Fasheh 
36092b3909f8SDarrick J. Wong 	res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
36102b3909f8SDarrick J. Wong 	if (res)
36112b3909f8SDarrick J. Wong 		return res;
36122b3909f8SDarrick J. Wong 	return olen;
3613416161dbSMark Fasheh }
3614416161dbSMark Fasheh 
3615f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3616f82a9901SFilipe Manana 				     struct inode *inode,
3617f82a9901SFilipe Manana 				     u64 endoff,
3618f82a9901SFilipe Manana 				     const u64 destoff,
36191c919a5eSMark Fasheh 				     const u64 olen,
36201c919a5eSMark Fasheh 				     int no_time_update)
3621f82a9901SFilipe Manana {
3622f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3623f82a9901SFilipe Manana 	int ret;
3624f82a9901SFilipe Manana 
3625f82a9901SFilipe Manana 	inode_inc_iversion(inode);
36261c919a5eSMark Fasheh 	if (!no_time_update)
3627c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3628f82a9901SFilipe Manana 	/*
3629f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3630f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3631f82a9901SFilipe Manana 	 */
3632f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3633f82a9901SFilipe Manana 		endoff = destoff + olen;
3634f82a9901SFilipe Manana 	if (endoff > inode->i_size)
36356ef06d27SNikolay Borisov 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3636f82a9901SFilipe Manana 
3637f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3638f82a9901SFilipe Manana 	if (ret) {
363966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
36403a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3641f82a9901SFilipe Manana 		goto out;
3642f82a9901SFilipe Manana 	}
36433a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
3644f82a9901SFilipe Manana out:
3645f82a9901SFilipe Manana 	return ret;
3646f82a9901SFilipe Manana }
3647f82a9901SFilipe Manana 
3648a2f392e4SNikolay Borisov static void clone_update_extent_map(struct btrfs_inode *inode,
36497ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
36507ffbb598SFilipe Manana 				    const struct btrfs_path *path,
36517ffbb598SFilipe Manana 				    const u64 hole_offset,
36527ffbb598SFilipe Manana 				    const u64 hole_len)
36537ffbb598SFilipe Manana {
3654a2f392e4SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
36557ffbb598SFilipe Manana 	struct extent_map *em;
36567ffbb598SFilipe Manana 	int ret;
36577ffbb598SFilipe Manana 
36587ffbb598SFilipe Manana 	em = alloc_extent_map();
36597ffbb598SFilipe Manana 	if (!em) {
3660a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
36617ffbb598SFilipe Manana 		return;
36627ffbb598SFilipe Manana 	}
36637ffbb598SFilipe Manana 
366414f59796SFilipe Manana 	if (path) {
366514f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
366614f59796SFilipe Manana 
366714f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
366814f59796SFilipe Manana 				    struct btrfs_file_extent_item);
3669a2f392e4SNikolay Borisov 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
36707ffbb598SFilipe Manana 		em->generation = -1;
36717ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
36727ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
36737ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3674a2f392e4SNikolay Borisov 					&inode->runtime_flags);
36757ffbb598SFilipe Manana 	} else {
36767ffbb598SFilipe Manana 		em->start = hole_offset;
36777ffbb598SFilipe Manana 		em->len = hole_len;
36787ffbb598SFilipe Manana 		em->ram_bytes = em->len;
36797ffbb598SFilipe Manana 		em->orig_start = hole_offset;
36807ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
36817ffbb598SFilipe Manana 		em->block_len = 0;
36827ffbb598SFilipe Manana 		em->orig_block_len = 0;
36837ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
36847ffbb598SFilipe Manana 		em->generation = trans->transid;
36857ffbb598SFilipe Manana 	}
36867ffbb598SFilipe Manana 
36877ffbb598SFilipe Manana 	while (1) {
36887ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
36897ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
36907ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
36917ffbb598SFilipe Manana 		if (ret != -EEXIST) {
36927ffbb598SFilipe Manana 			free_extent_map(em);
36937ffbb598SFilipe Manana 			break;
36947ffbb598SFilipe Manana 		}
3695a2f392e4SNikolay Borisov 		btrfs_drop_extent_cache(inode, em->start,
36967ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
36977ffbb598SFilipe Manana 	}
36987ffbb598SFilipe Manana 
3699ee39b432SDavid Sterba 	if (ret)
3700a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
37017ffbb598SFilipe Manana }
37027ffbb598SFilipe Manana 
37038039d87dSFilipe Manana /*
37048039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
37058039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
37068039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
37078039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
37088039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
37098039d87dSFilipe Manana  *
37108039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
37118039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
37128039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
37138039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
37148039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
37158039d87dSFilipe Manana  * i_mutex, which we are holding here).
37168039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
37178039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
37188039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
37198039d87dSFilipe Manana  *
37208039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
37218039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
37228039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
37238039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
37248039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
37258039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
37268039d87dSFilipe Manana  * the former.
37278039d87dSFilipe Manana  */
37284a0ab9d7SDavid Sterba static int clone_copy_inline_extent(struct inode *dst,
37298039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
37308039d87dSFilipe Manana 				    struct btrfs_path *path,
37318039d87dSFilipe Manana 				    struct btrfs_key *new_key,
37328039d87dSFilipe Manana 				    const u64 drop_start,
37338039d87dSFilipe Manana 				    const u64 datal,
37348039d87dSFilipe Manana 				    const u64 skip,
37358039d87dSFilipe Manana 				    const u64 size,
37368039d87dSFilipe Manana 				    char *inline_data)
37378039d87dSFilipe Manana {
37380b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
37398039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
37408039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
37410b246afaSJeff Mahoney 				      fs_info->sectorsize);
37428039d87dSFilipe Manana 	int ret;
37438039d87dSFilipe Manana 	struct btrfs_key key;
37448039d87dSFilipe Manana 
37458039d87dSFilipe Manana 	if (new_key->offset > 0)
37468039d87dSFilipe Manana 		return -EOPNOTSUPP;
37478039d87dSFilipe Manana 
37484a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(dst));
37498039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
37508039d87dSFilipe Manana 	key.offset = 0;
37518039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
37528039d87dSFilipe Manana 	if (ret < 0) {
37538039d87dSFilipe Manana 		return ret;
37548039d87dSFilipe Manana 	} else if (ret > 0) {
37558039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
37568039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
37578039d87dSFilipe Manana 			if (ret < 0)
37588039d87dSFilipe Manana 				return ret;
37598039d87dSFilipe Manana 			else if (ret > 0)
37608039d87dSFilipe Manana 				goto copy_inline_extent;
37618039d87dSFilipe Manana 		}
37628039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
37634a0cc7caSNikolay Borisov 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
37648039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
37658039d87dSFilipe Manana 			ASSERT(key.offset > 0);
37668039d87dSFilipe Manana 			return -EOPNOTSUPP;
37678039d87dSFilipe Manana 		}
37688039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
37698039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
37708039d87dSFilipe Manana 		u64 ext_len;
37718039d87dSFilipe Manana 
37728039d87dSFilipe Manana 		/*
37738039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
37748039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
37758039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
37768039d87dSFilipe Manana 		 */
37778039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
37788039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
37798039d87dSFilipe Manana 		/*
37808039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
37818039d87dSFilipe Manana 		 * following it.
37828039d87dSFilipe Manana 		 */
37838039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
37848039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
37858039d87dSFilipe Manana 			goto copy_inline_extent;
37868039d87dSFilipe Manana 
37878039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
37888039d87dSFilipe Manana 		if (ext_len > aligned_end)
37898039d87dSFilipe Manana 			return -EOPNOTSUPP;
37908039d87dSFilipe Manana 
37918039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
37928039d87dSFilipe Manana 		if (ret < 0) {
37938039d87dSFilipe Manana 			return ret;
37948039d87dSFilipe Manana 		} else if (ret == 0) {
37958039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
37968039d87dSFilipe Manana 					      path->slots[0]);
37974a0cc7caSNikolay Borisov 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
37988039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
37998039d87dSFilipe Manana 				return -EOPNOTSUPP;
38008039d87dSFilipe Manana 		}
38018039d87dSFilipe Manana 	}
38028039d87dSFilipe Manana 
38038039d87dSFilipe Manana copy_inline_extent:
38048039d87dSFilipe Manana 	/*
38058039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
38068039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
38078039d87dSFilipe Manana 	 */
38088039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
38098039d87dSFilipe Manana 		/*
38108039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
38118039d87dSFilipe Manana 		 * This would require copying the data from the source inline
38128039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
38138039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
38148039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
38158039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
38168039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
38178039d87dSFilipe Manana 		 * inline extent).
38188039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
38198039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
38208039d87dSFilipe Manana 		 */
38218039d87dSFilipe Manana 		return -EOPNOTSUPP;
38228039d87dSFilipe Manana 	}
38238039d87dSFilipe Manana 
38248039d87dSFilipe Manana 	btrfs_release_path(path);
38258039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
38268039d87dSFilipe Manana 	if (ret)
38278039d87dSFilipe Manana 		return ret;
38288039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
38298039d87dSFilipe Manana 	if (ret)
38308039d87dSFilipe Manana 		return ret;
38318039d87dSFilipe Manana 
38328039d87dSFilipe Manana 	if (skip) {
38338039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
38348039d87dSFilipe Manana 
38358039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
38368039d87dSFilipe Manana 	}
38378039d87dSFilipe Manana 
38388039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
38398039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
38408039d87dSFilipe Manana 						  path->slots[0]),
38418039d87dSFilipe Manana 			    size);
38428039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
38438039d87dSFilipe Manana 
38448039d87dSFilipe Manana 	return 0;
38458039d87dSFilipe Manana }
38468039d87dSFilipe Manana 
384732b7c687SMark Fasheh /**
384832b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
384932b7c687SMark Fasheh  *
385032b7c687SMark Fasheh  * @src: Inode to clone from
385132b7c687SMark Fasheh  * @inode: Inode to clone to
385232b7c687SMark Fasheh  * @off: Offset within source to start clone from
385332b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
38541c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
385532b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
38561c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
385732b7c687SMark Fasheh  */
385832b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3859f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
38601c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3861f46b5a66SChristoph Hellwig {
38620b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3863f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
386432b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3865f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
386632b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
386732b7c687SMark Fasheh 	char *buf = NULL;
3868ae01a0abSYan Zheng 	struct btrfs_key key;
3869f46b5a66SChristoph Hellwig 	u32 nritems;
3870f46b5a66SChristoph Hellwig 	int slot;
3871ae01a0abSYan Zheng 	int ret;
3872f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3873f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3874ae01a0abSYan Zheng 
3875ae01a0abSYan Zheng 	ret = -ENOMEM;
3876752ade68SMichal Hocko 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3877ae01a0abSYan Zheng 	if (!buf)
387832b7c687SMark Fasheh 		return ret;
3879ae01a0abSYan Zheng 
3880ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3881ae01a0abSYan Zheng 	if (!path) {
388215351955SDavid Sterba 		kvfree(buf);
388332b7c687SMark Fasheh 		return ret;
3884ae01a0abSYan Zheng 	}
388532b7c687SMark Fasheh 
3886e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3887c5c9cd4dSSage Weil 	/* clone data */
38884a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(src));
3889ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
38902c463823SFilipe Manana 	key.offset = off;
3891f46b5a66SChristoph Hellwig 
3892f46b5a66SChristoph Hellwig 	while (1) {
3893de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3894df858e76SFilipe Manana 
3895f46b5a66SChristoph Hellwig 		/*
3896f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3897f46b5a66SChristoph Hellwig 		 * tree.
3898f46b5a66SChristoph Hellwig 		 */
3899e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3900362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3901362a20c5SDavid Sterba 				0, 0);
3902f46b5a66SChristoph Hellwig 		if (ret < 0)
3903f46b5a66SChristoph Hellwig 			goto out;
39042c463823SFilipe Manana 		/*
39052c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
39062c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
39072c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
39082c463823SFilipe Manana 		 */
39092c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
39102c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
39112c463823SFilipe Manana 					      path->slots[0] - 1);
39122c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
39132c463823SFilipe Manana 				path->slots[0]--;
39142c463823SFilipe Manana 		}
3915f46b5a66SChristoph Hellwig 
3916ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3917e4355f34SFilipe David Borba Manana process_slot:
3918ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3919362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3920f46b5a66SChristoph Hellwig 			if (ret < 0)
3921f46b5a66SChristoph Hellwig 				goto out;
3922f46b5a66SChristoph Hellwig 			if (ret > 0)
3923f46b5a66SChristoph Hellwig 				break;
3924ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3925f46b5a66SChristoph Hellwig 		}
3926f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3927f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3928f46b5a66SChristoph Hellwig 
3929ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3930962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
39314a0cc7caSNikolay Borisov 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3932f46b5a66SChristoph Hellwig 			break;
3933f46b5a66SChristoph Hellwig 
3934962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3935c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3936c5c9cd4dSSage Weil 			int type;
393731840ae1SZheng Yan 			u32 size;
393831840ae1SZheng Yan 			struct btrfs_key new_key;
3939c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3940c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3941c5c9cd4dSSage Weil 			u8 comp;
3942f82a9901SFilipe Manana 			u64 drop_start;
394331840ae1SZheng Yan 
3944c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3945c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3946c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3947c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3948c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3949c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3950d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3951d397712bSChris Mason 								      extent);
3952d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3953d397712bSChris Mason 								 extent);
3954c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3955d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3956d397712bSChris Mason 								    extent);
3957c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3958c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3959c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3960c5c9cd4dSSage Weil 								    extent);
3961c5c9cd4dSSage Weil 			}
396231840ae1SZheng Yan 
39632c463823SFilipe Manana 			/*
39642c463823SFilipe Manana 			 * The first search might have left us at an extent
39652c463823SFilipe Manana 			 * item that ends before our target range's start, can
39662c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
39672c463823SFilipe Manana 			 */
39682c463823SFilipe Manana 			if (key.offset + datal <= off) {
3969e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3970e4355f34SFilipe David Borba Manana 				goto process_slot;
39712c463823SFilipe Manana 			} else if (key.offset >= off + len) {
39722c463823SFilipe Manana 				break;
3973e4355f34SFilipe David Borba Manana 			}
3974df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3975e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3976e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3977e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3978e4355f34SFilipe David Borba Manana 					   size);
3979e4355f34SFilipe David Borba Manana 
3980e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3981e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3982c5c9cd4dSSage Weil 
398331840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
39844a0cc7caSNikolay Borisov 			new_key.objectid = btrfs_ino(BTRFS_I(inode));
39854d728ec7SLi Zefan 			if (off <= key.offset)
3986c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
39874d728ec7SLi Zefan 			else
39884d728ec7SLi Zefan 				new_key.offset = destoff;
3989c5c9cd4dSSage Weil 
3990b6f3409bSSage Weil 			/*
3991f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3992f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3993f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3994f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3995f82a9901SFilipe Manana 			 * partially overlaps it).
3996f82a9901SFilipe Manana 			 */
3997f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3998f82a9901SFilipe Manana 				drop_start = last_dest_end;
3999f82a9901SFilipe Manana 			else
4000f82a9901SFilipe Manana 				drop_start = new_key.offset;
4001f82a9901SFilipe Manana 
4002f82a9901SFilipe Manana 			/*
4003b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
4004b6f3409bSSage Weil 			 * 1 - add new extent
4005b6f3409bSSage Weil 			 * 1 - inode update
4006b6f3409bSSage Weil 			 */
4007b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
4008a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
4009a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
4010a22285a6SYan, Zheng 				goto out;
4011a22285a6SYan, Zheng 			}
4012a22285a6SYan, Zheng 
4013c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
4014c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
4015d72c0842SLi Zefan 				/*
4016d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
4017d72c0842SLi Zefan 				 * | ------------- extent ------------- |
4018d72c0842SLi Zefan 				 */
4019d72c0842SLi Zefan 
402093915584SAntonio Ospite 				/* subtract range b */
4021d72c0842SLi Zefan 				if (key.offset + datal > off + len)
4022d72c0842SLi Zefan 					datal = off + len - key.offset;
4023d72c0842SLi Zefan 
402493915584SAntonio Ospite 				/* subtract range a */
4025a22285a6SYan, Zheng 				if (off > key.offset) {
4026a22285a6SYan, Zheng 					datao += off - key.offset;
4027a22285a6SYan, Zheng 					datal -= off - key.offset;
4028a22285a6SYan, Zheng 				}
4029a22285a6SYan, Zheng 
40305dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
4031f82a9901SFilipe Manana 							 drop_start,
4032a22285a6SYan, Zheng 							 new_key.offset + datal,
40332671485dSJosef Bacik 							 1);
403479787eaaSJeff Mahoney 				if (ret) {
40353f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
403600fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
403766642832SJeff Mahoney 									ret);
40383a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
403979787eaaSJeff Mahoney 					goto out;
404079787eaaSJeff Mahoney 				}
4041a22285a6SYan, Zheng 
404231840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
404331840ae1SZheng Yan 							      &new_key, size);
404479787eaaSJeff Mahoney 				if (ret) {
404566642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
40463a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
404779787eaaSJeff Mahoney 					goto out;
404879787eaaSJeff Mahoney 				}
404931840ae1SZheng Yan 
405031840ae1SZheng Yan 				leaf = path->nodes[0];
405131840ae1SZheng Yan 				slot = path->slots[0];
405231840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
405331840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
405431840ae1SZheng Yan 					    size);
4055ae01a0abSYan Zheng 
4056f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
4057f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
4058c5c9cd4dSSage Weil 
4059c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
4060c5c9cd4dSSage Weil 				if (!disko)
4061c5c9cd4dSSage Weil 					datao = 0;
4062c5c9cd4dSSage Weil 
4063c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
4064c5c9cd4dSSage Weil 							     datao);
4065c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
4066c5c9cd4dSSage Weil 								datal);
4067fcebe456SJosef Bacik 
4068c5c9cd4dSSage Weil 				if (disko) {
4069c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
40702ff7e61eSJeff Mahoney 					ret = btrfs_inc_extent_ref(trans,
407184f7d8e6SJosef Bacik 							root,
40725d4f98a2SYan Zheng 							disko, diskl, 0,
4073f46b5a66SChristoph Hellwig 							root->root_key.objectid,
40744a0cc7caSNikolay Borisov 							btrfs_ino(BTRFS_I(inode)),
4075b06c4bf5SFilipe Manana 							new_key.offset - datao);
407679787eaaSJeff Mahoney 					if (ret) {
407779787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
407879787eaaSJeff Mahoney 									ret);
40793a45bb20SJeff Mahoney 						btrfs_end_transaction(trans);
408079787eaaSJeff Mahoney 						goto out;
408179787eaaSJeff Mahoney 
408279787eaaSJeff Mahoney 					}
4083f46b5a66SChristoph Hellwig 				}
4084c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
4085c5c9cd4dSSage Weil 				u64 skip = 0;
4086c5c9cd4dSSage Weil 				u64 trim = 0;
4087ed958762SFilipe Manana 
4088c5c9cd4dSSage Weil 				if (off > key.offset) {
4089c5c9cd4dSSage Weil 					skip = off - key.offset;
4090c5c9cd4dSSage Weil 					new_key.offset += skip;
409131840ae1SZheng Yan 				}
4092d397712bSChris Mason 
4093c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
4094c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
4095d397712bSChris Mason 
4096c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
4097c5c9cd4dSSage Weil 					ret = -EINVAL;
40983a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
4099c5c9cd4dSSage Weil 					goto out;
410031840ae1SZheng Yan 				}
4101c5c9cd4dSSage Weil 				size -= skip + trim;
4102c5c9cd4dSSage Weil 				datal -= skip + trim;
4103a22285a6SYan, Zheng 
41044a0ab9d7SDavid Sterba 				ret = clone_copy_inline_extent(inode,
41058039d87dSFilipe Manana 							       trans, path,
41068039d87dSFilipe Manana 							       &new_key,
4107f82a9901SFilipe Manana 							       drop_start,
41088039d87dSFilipe Manana 							       datal,
41098039d87dSFilipe Manana 							       skip, size, buf);
411079787eaaSJeff Mahoney 				if (ret) {
41113f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
41123a29bc09SChris Mason 						btrfs_abort_transaction(trans,
411379787eaaSJeff Mahoney 									ret);
41143a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
411579787eaaSJeff Mahoney 					goto out;
411679787eaaSJeff Mahoney 				}
4117c5c9cd4dSSage Weil 				leaf = path->nodes[0];
4118c5c9cd4dSSage Weil 				slot = path->slots[0];
4119c5c9cd4dSSage Weil 			}
4120c5c9cd4dSSage Weil 
41217ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
41227ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
4123a2f392e4SNikolay Borisov 				clone_update_extent_map(BTRFS_I(inode), trans,
412414f59796SFilipe Manana 						NULL, drop_start,
41257ffbb598SFilipe Manana 						new_key.offset - drop_start);
41267ffbb598SFilipe Manana 
4127a2f392e4SNikolay Borisov 			clone_update_extent_map(BTRFS_I(inode), trans,
4128a2f392e4SNikolay Borisov 					path, 0, 0);
41297ffbb598SFilipe Manana 
4130c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
4131b3b4aa74SDavid Sterba 			btrfs_release_path(path);
4132c5c9cd4dSSage Weil 
413362e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
41340b246afaSJeff Mahoney 					      fs_info->sectorsize);
4135f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
4136f82a9901SFilipe Manana 							last_dest_end,
41371c919a5eSMark Fasheh 							destoff, olen,
41381c919a5eSMark Fasheh 							no_time_update);
4139f82a9901SFilipe Manana 			if (ret)
414079787eaaSJeff Mahoney 				goto out;
41412c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
41422c463823SFilipe Manana 				break;
4143a22285a6SYan, Zheng 		}
4144b3b4aa74SDavid Sterba 		btrfs_release_path(path);
4145df858e76SFilipe Manana 		key.offset = next_key_min_offset;
414669ae5e44SWang Xiaoguang 
414769ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
414869ae5e44SWang Xiaoguang 			ret = -EINTR;
414969ae5e44SWang Xiaoguang 			goto out;
415069ae5e44SWang Xiaoguang 		}
4151ae01a0abSYan Zheng 	}
4152f46b5a66SChristoph Hellwig 	ret = 0;
415332b7c687SMark Fasheh 
4154f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
4155f82a9901SFilipe Manana 		/*
4156f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
4157f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
4158f82a9901SFilipe Manana 		 */
4159b3b4aa74SDavid Sterba 		btrfs_release_path(path);
4160f82a9901SFilipe Manana 
4161f82a9901SFilipe Manana 		/*
4162f82a9901SFilipe Manana 		 * 1 - remove extent(s)
4163f82a9901SFilipe Manana 		 * 1 - inode update
4164f82a9901SFilipe Manana 		 */
4165f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
4166f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
4167f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
4168f82a9901SFilipe Manana 			goto out;
4169f82a9901SFilipe Manana 		}
4170f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
4171f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
4172f82a9901SFilipe Manana 		if (ret) {
4173f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
417466642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
41753a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
4176f82a9901SFilipe Manana 			goto out;
4177f82a9901SFilipe Manana 		}
4178a2f392e4SNikolay Borisov 		clone_update_extent_map(BTRFS_I(inode), trans, NULL,
4179a2f392e4SNikolay Borisov 				last_dest_end,
418014f59796SFilipe Manana 				destoff + len - last_dest_end);
4181f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
41821c919a5eSMark Fasheh 						destoff, olen, no_time_update);
4183f82a9901SFilipe Manana 	}
4184f82a9901SFilipe Manana 
4185f46b5a66SChristoph Hellwig out:
418632b7c687SMark Fasheh 	btrfs_free_path(path);
418715351955SDavid Sterba 	kvfree(buf);
418832b7c687SMark Fasheh 	return ret;
418932b7c687SMark Fasheh }
419032b7c687SMark Fasheh 
41913db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
419232b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
419332b7c687SMark Fasheh {
419454563d41SAl Viro 	struct inode *inode = file_inode(file);
41953db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
41960b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
419732b7c687SMark Fasheh 	struct btrfs_root *root = BTRFS_I(inode)->root;
419832b7c687SMark Fasheh 	int ret;
419932b7c687SMark Fasheh 	u64 len = olen;
42000b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
42013db11b2eSZach Brown 	int same_inode = src == inode;
420232b7c687SMark Fasheh 
420332b7c687SMark Fasheh 	/*
420432b7c687SMark Fasheh 	 * TODO:
420532b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
420632b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
420732b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
420832b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
420900fdf13aSLiu Bo 	 *
421000fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
421100fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
421232b7c687SMark Fasheh 	 */
421332b7c687SMark Fasheh 
421432b7c687SMark Fasheh 	if (btrfs_root_readonly(root))
421532b7c687SMark Fasheh 		return -EROFS;
421632b7c687SMark Fasheh 
42173db11b2eSZach Brown 	if (file_src->f_path.mnt != file->f_path.mnt ||
42183db11b2eSZach Brown 	    src->i_sb != inode->i_sb)
42193db11b2eSZach Brown 		return -EXDEV;
422032b7c687SMark Fasheh 
422132b7c687SMark Fasheh 	if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
42223db11b2eSZach Brown 		return -EISDIR;
422332b7c687SMark Fasheh 
422432b7c687SMark Fasheh 	if (!same_inode) {
4225293a8489SMark Fasheh 		btrfs_double_inode_lock(src, inode);
422632b7c687SMark Fasheh 	} else {
42275955102cSAl Viro 		inode_lock(src);
422832b7c687SMark Fasheh 	}
422932b7c687SMark Fasheh 
4230b5c40d59SOmar Sandoval 	/* don't make the dst file partly checksummed */
4231b5c40d59SOmar Sandoval 	if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
4232b5c40d59SOmar Sandoval 	    (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
4233b5c40d59SOmar Sandoval 		ret = -EINVAL;
4234b5c40d59SOmar Sandoval 		goto out_unlock;
4235b5c40d59SOmar Sandoval 	}
4236b5c40d59SOmar Sandoval 
423732b7c687SMark Fasheh 	/* determine range to clone */
423832b7c687SMark Fasheh 	ret = -EINVAL;
423932b7c687SMark Fasheh 	if (off + len > src->i_size || off + len < off)
424032b7c687SMark Fasheh 		goto out_unlock;
424132b7c687SMark Fasheh 	if (len == 0)
424232b7c687SMark Fasheh 		olen = len = src->i_size - off;
424332b7c687SMark Fasheh 	/* if we extend to eof, continue to block boundary */
424432b7c687SMark Fasheh 	if (off + len == src->i_size)
424532b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
424632b7c687SMark Fasheh 
4247ccccf3d6SFilipe Manana 	if (len == 0) {
4248ccccf3d6SFilipe Manana 		ret = 0;
4249ccccf3d6SFilipe Manana 		goto out_unlock;
4250ccccf3d6SFilipe Manana 	}
4251ccccf3d6SFilipe Manana 
425232b7c687SMark Fasheh 	/* verify the end result is block aligned */
425332b7c687SMark Fasheh 	if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
425432b7c687SMark Fasheh 	    !IS_ALIGNED(destoff, bs))
425532b7c687SMark Fasheh 		goto out_unlock;
425632b7c687SMark Fasheh 
425732b7c687SMark Fasheh 	/* verify if ranges are overlapped within the same file */
425832b7c687SMark Fasheh 	if (same_inode) {
425932b7c687SMark Fasheh 		if (destoff + len > off && destoff < off + len)
426032b7c687SMark Fasheh 			goto out_unlock;
426132b7c687SMark Fasheh 	}
426232b7c687SMark Fasheh 
426332b7c687SMark Fasheh 	if (destoff > inode->i_size) {
426432b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
426532b7c687SMark Fasheh 		if (ret)
426632b7c687SMark Fasheh 			goto out_unlock;
426732b7c687SMark Fasheh 	}
426832b7c687SMark Fasheh 
4269c125b8bfSFilipe Manana 	/*
4270c125b8bfSFilipe Manana 	 * Lock the target range too. Right after we replace the file extent
4271c125b8bfSFilipe Manana 	 * items in the fs tree (which now point to the cloned data), we might
4272c125b8bfSFilipe Manana 	 * have a worker replace them with extent items relative to a write
4273c125b8bfSFilipe Manana 	 * operation that was issued before this clone operation (i.e. confront
4274c125b8bfSFilipe Manana 	 * with inode.c:btrfs_finish_ordered_io).
4275c125b8bfSFilipe Manana 	 */
4276c125b8bfSFilipe Manana 	if (same_inode) {
4277c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
4278c125b8bfSFilipe Manana 		u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
427932b7c687SMark Fasheh 
4280e0bd70c6SFilipe Manana 		ret = lock_extent_range(src, lock_start, lock_len, true);
4281c125b8bfSFilipe Manana 	} else {
4282e0bd70c6SFilipe Manana 		ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
4283e0bd70c6SFilipe Manana 					       true);
4284e0bd70c6SFilipe Manana 	}
4285e0bd70c6SFilipe Manana 	ASSERT(ret == 0);
4286e0bd70c6SFilipe Manana 	if (WARN_ON(ret)) {
4287e0bd70c6SFilipe Manana 		/* ranges in the io trees already unlocked */
4288e0bd70c6SFilipe Manana 		goto out_unlock;
4289c125b8bfSFilipe Manana 	}
429032b7c687SMark Fasheh 
42911c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
429232b7c687SMark Fasheh 
4293c125b8bfSFilipe Manana 	if (same_inode) {
4294c125b8bfSFilipe Manana 		u64 lock_start = min_t(u64, off, destoff);
4295c125b8bfSFilipe Manana 		u64 lock_end = max_t(u64, off, destoff) + len - 1;
4296c125b8bfSFilipe Manana 
4297c125b8bfSFilipe Manana 		unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
4298c125b8bfSFilipe Manana 	} else {
4299293a8489SMark Fasheh 		btrfs_double_extent_unlock(src, off, inode, destoff, len);
4300c125b8bfSFilipe Manana 	}
4301c125b8bfSFilipe Manana 	/*
4302c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
4303c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
4304c125b8bfSFilipe Manana 	 */
430565bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
430609cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
430709cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
4308f46b5a66SChristoph Hellwig out_unlock:
4309293a8489SMark Fasheh 	if (!same_inode)
4310293a8489SMark Fasheh 		btrfs_double_inode_unlock(src, inode);
4311293a8489SMark Fasheh 	else
43125955102cSAl Viro 		inode_unlock(src);
43133db11b2eSZach Brown 	return ret;
43143db11b2eSZach Brown }
43153db11b2eSZach Brown 
431604b38d60SChristoph Hellwig int btrfs_clone_file_range(struct file *src_file, loff_t off,
431704b38d60SChristoph Hellwig 		struct file *dst_file, loff_t destoff, u64 len)
43183db11b2eSZach Brown {
431904b38d60SChristoph Hellwig 	return btrfs_clone_files(dst_file, src_file, off, len, destoff);
4320c5c9cd4dSSage Weil }
4321c5c9cd4dSSage Weil 
43226ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
43236ef5ed0dSJosef Bacik {
4324496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
43250b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
43266ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
43276ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
43286ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
43296ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
43306ef5ed0dSJosef Bacik 	struct btrfs_path *path;
43316ef5ed0dSJosef Bacik 	struct btrfs_key location;
43326ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
43336ef5ed0dSJosef Bacik 	u64 objectid = 0;
43346ef5ed0dSJosef Bacik 	u64 dir_id;
43353c04ce01SMiao Xie 	int ret;
43366ef5ed0dSJosef Bacik 
43376ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
43386ef5ed0dSJosef Bacik 		return -EPERM;
43396ef5ed0dSJosef Bacik 
43403c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
43413c04ce01SMiao Xie 	if (ret)
43423c04ce01SMiao Xie 		return ret;
43433c04ce01SMiao Xie 
43443c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
43453c04ce01SMiao Xie 		ret = -EFAULT;
43463c04ce01SMiao Xie 		goto out;
43473c04ce01SMiao Xie 	}
43486ef5ed0dSJosef Bacik 
43496ef5ed0dSJosef Bacik 	if (!objectid)
43501cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
43516ef5ed0dSJosef Bacik 
43526ef5ed0dSJosef Bacik 	location.objectid = objectid;
43536ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
43546ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
43556ef5ed0dSJosef Bacik 
43560b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
43573c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
43583c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
43593c04ce01SMiao Xie 		goto out;
43603c04ce01SMiao Xie 	}
43616d6d2829Ssatoru takeuchi 	if (!is_fstree(new_root->objectid)) {
43626d6d2829Ssatoru takeuchi 		ret = -ENOENT;
43636d6d2829Ssatoru takeuchi 		goto out;
43646d6d2829Ssatoru takeuchi 	}
43656ef5ed0dSJosef Bacik 
43666ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
43673c04ce01SMiao Xie 	if (!path) {
43683c04ce01SMiao Xie 		ret = -ENOMEM;
43693c04ce01SMiao Xie 		goto out;
43703c04ce01SMiao Xie 	}
43716ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
43726ef5ed0dSJosef Bacik 
43736ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
437498d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
43756ef5ed0dSJosef Bacik 		btrfs_free_path(path);
43763c04ce01SMiao Xie 		ret = PTR_ERR(trans);
43773c04ce01SMiao Xie 		goto out;
43786ef5ed0dSJosef Bacik 	}
43796ef5ed0dSJosef Bacik 
43800b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
43810b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
43826ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
4383cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
43846ef5ed0dSJosef Bacik 		btrfs_free_path(path);
43853a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
43860b246afaSJeff Mahoney 		btrfs_err(fs_info,
43875d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
43883c04ce01SMiao Xie 		ret = -ENOENT;
43893c04ce01SMiao Xie 		goto out;
43906ef5ed0dSJosef Bacik 	}
43916ef5ed0dSJosef Bacik 
43926ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
43936ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
43946ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
43956ef5ed0dSJosef Bacik 	btrfs_free_path(path);
43966ef5ed0dSJosef Bacik 
43970b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
43983a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
43993c04ce01SMiao Xie out:
44003c04ce01SMiao Xie 	mnt_drop_write_file(file);
44013c04ce01SMiao Xie 	return ret;
44026ef5ed0dSJosef Bacik }
44036ef5ed0dSJosef Bacik 
4404c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
4405bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
4406bf5fc093SJosef Bacik {
4407bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4408bf5fc093SJosef Bacik 
4409bf5fc093SJosef Bacik 	space->total_bytes = 0;
4410bf5fc093SJosef Bacik 	space->used_bytes = 0;
4411bf5fc093SJosef Bacik 	space->flags = 0;
4412bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4413bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4414bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4415bf5fc093SJosef Bacik 		space->used_bytes +=
4416bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4417bf5fc093SJosef Bacik 	}
4418bf5fc093SJosef Bacik }
4419bf5fc093SJosef Bacik 
44202ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
44212ff7e61eSJeff Mahoney 				   void __user *arg)
44221406e432SJosef Bacik {
44231406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
44241406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
44251406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
44267fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
442713f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
44281406e432SJosef Bacik 	struct btrfs_space_info *info;
4429315d8e98SColin Ian King 	static const u64 types[] = {
4430315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
4431bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
4432bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
4433315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4434315d8e98SColin Ian King 	};
4435bf5fc093SJosef Bacik 	int num_types = 4;
44367fde62bfSChris Mason 	int alloc_size;
44371406e432SJosef Bacik 	int ret = 0;
443851788b1bSDan Rosenberg 	u64 slot_count = 0;
4439bf5fc093SJosef Bacik 	int i, c;
44401406e432SJosef Bacik 
44411406e432SJosef Bacik 	if (copy_from_user(&space_args,
44421406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
44431406e432SJosef Bacik 			   sizeof(space_args)))
44441406e432SJosef Bacik 		return -EFAULT;
44451406e432SJosef Bacik 
4446bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4447bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4448bf5fc093SJosef Bacik 
4449bf5fc093SJosef Bacik 		info = NULL;
44507fde62bfSChris Mason 		rcu_read_lock();
44510b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4452bf5fc093SJosef Bacik 					list) {
4453bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4454bf5fc093SJosef Bacik 				info = tmp;
4455bf5fc093SJosef Bacik 				break;
4456bf5fc093SJosef Bacik 			}
4457bf5fc093SJosef Bacik 		}
44587fde62bfSChris Mason 		rcu_read_unlock();
44591406e432SJosef Bacik 
4460bf5fc093SJosef Bacik 		if (!info)
4461bf5fc093SJosef Bacik 			continue;
4462bf5fc093SJosef Bacik 
4463bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4464bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4465bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4466bf5fc093SJosef Bacik 				slot_count++;
4467bf5fc093SJosef Bacik 		}
4468bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4469bf5fc093SJosef Bacik 	}
4470bf5fc093SJosef Bacik 
447136523e95SDavid Sterba 	/*
447236523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
447336523e95SDavid Sterba 	 */
447436523e95SDavid Sterba 	slot_count++;
447536523e95SDavid Sterba 
44767fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
44777fde62bfSChris Mason 	if (space_args.space_slots == 0) {
44787fde62bfSChris Mason 		space_args.total_spaces = slot_count;
44797fde62bfSChris Mason 		goto out;
44807fde62bfSChris Mason 	}
4481bf5fc093SJosef Bacik 
448251788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4483bf5fc093SJosef Bacik 
44847fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4485bf5fc093SJosef Bacik 
44867fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
44877fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
44887fde62bfSChris Mason 	 */
448909cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
44907fde62bfSChris Mason 		return -ENOMEM;
44917fde62bfSChris Mason 
44927fde62bfSChris Mason 	space_args.total_spaces = 0;
44938d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
44947fde62bfSChris Mason 	if (!dest)
44957fde62bfSChris Mason 		return -ENOMEM;
44967fde62bfSChris Mason 	dest_orig = dest;
44977fde62bfSChris Mason 
44987fde62bfSChris Mason 	/* now we have a buffer to copy into */
4499bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4500bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4501bf5fc093SJosef Bacik 
450251788b1bSDan Rosenberg 		if (!slot_count)
450351788b1bSDan Rosenberg 			break;
450451788b1bSDan Rosenberg 
4505bf5fc093SJosef Bacik 		info = NULL;
45061406e432SJosef Bacik 		rcu_read_lock();
45070b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4508bf5fc093SJosef Bacik 					list) {
4509bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4510bf5fc093SJosef Bacik 				info = tmp;
45117fde62bfSChris Mason 				break;
4512bf5fc093SJosef Bacik 			}
4513bf5fc093SJosef Bacik 		}
4514bf5fc093SJosef Bacik 		rcu_read_unlock();
45157fde62bfSChris Mason 
4516bf5fc093SJosef Bacik 		if (!info)
4517bf5fc093SJosef Bacik 			continue;
4518bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4519bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4520bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
4521c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
4522c065f5b1SSu Yue 						     &space);
45237fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
45241406e432SJosef Bacik 				dest++;
45251406e432SJosef Bacik 				space_args.total_spaces++;
452651788b1bSDan Rosenberg 				slot_count--;
45271406e432SJosef Bacik 			}
452851788b1bSDan Rosenberg 			if (!slot_count)
452951788b1bSDan Rosenberg 				break;
4530bf5fc093SJosef Bacik 		}
4531bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4532bf5fc093SJosef Bacik 	}
45331406e432SJosef Bacik 
453436523e95SDavid Sterba 	/*
453536523e95SDavid Sterba 	 * Add global block reserve
453636523e95SDavid Sterba 	 */
453736523e95SDavid Sterba 	if (slot_count) {
45380b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
453936523e95SDavid Sterba 
454036523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
454136523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
454236523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
454336523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
454436523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
454536523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
454636523e95SDavid Sterba 		space_args.total_spaces++;
454736523e95SDavid Sterba 	}
454836523e95SDavid Sterba 
45492eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
45507fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
45517fde62bfSChris Mason 
45527fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
45537fde62bfSChris Mason 		ret = -EFAULT;
45547fde62bfSChris Mason 
45557fde62bfSChris Mason 	kfree(dest_orig);
45567fde62bfSChris Mason out:
45577fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
45581406e432SJosef Bacik 		ret = -EFAULT;
45591406e432SJosef Bacik 
45601406e432SJosef Bacik 	return ret;
45611406e432SJosef Bacik }
45621406e432SJosef Bacik 
45639a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
45649a8c28beSMiao Xie 					    void __user *argp)
456546204592SSage Weil {
456646204592SSage Weil 	struct btrfs_trans_handle *trans;
456746204592SSage Weil 	u64 transid;
4568db5b493aSTsutomu Itoh 	int ret;
456946204592SSage Weil 
4570d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4571ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4572ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
457398d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4574ff7c1d33SMiao Xie 
4575ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4576ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4577ff7c1d33SMiao Xie 		goto out;
4578ff7c1d33SMiao Xie 	}
457946204592SSage Weil 	transid = trans->transid;
45803a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction_async(trans, 0);
45818b2b2d3cSTsutomu Itoh 	if (ret) {
45823a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
4583db5b493aSTsutomu Itoh 		return ret;
45848b2b2d3cSTsutomu Itoh 	}
4585ff7c1d33SMiao Xie out:
458646204592SSage Weil 	if (argp)
458746204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
458846204592SSage Weil 			return -EFAULT;
458946204592SSage Weil 	return 0;
459046204592SSage Weil }
459146204592SSage Weil 
45922ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
45939a8c28beSMiao Xie 					   void __user *argp)
459446204592SSage Weil {
459546204592SSage Weil 	u64 transid;
459646204592SSage Weil 
459746204592SSage Weil 	if (argp) {
459846204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
459946204592SSage Weil 			return -EFAULT;
460046204592SSage Weil 	} else {
460146204592SSage Weil 		transid = 0;  /* current trans */
460246204592SSage Weil 	}
46032ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
460446204592SSage Weil }
460546204592SSage Weil 
4606b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4607475f6387SJan Schmidt {
46080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4609475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4610b8e95489SMiao Xie 	int ret;
4611475f6387SJan Schmidt 
4612475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4613475f6387SJan Schmidt 		return -EPERM;
4614475f6387SJan Schmidt 
4615475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4616475f6387SJan Schmidt 	if (IS_ERR(sa))
4617475f6387SJan Schmidt 		return PTR_ERR(sa);
4618475f6387SJan Schmidt 
4619b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4620b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4621b8e95489SMiao Xie 		if (ret)
4622b8e95489SMiao Xie 			goto out;
4623b8e95489SMiao Xie 	}
4624b8e95489SMiao Xie 
46250b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
462663a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
462763a212abSStefan Behrens 			      0);
4628475f6387SJan Schmidt 
4629475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4630475f6387SJan Schmidt 		ret = -EFAULT;
4631475f6387SJan Schmidt 
4632b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4633b8e95489SMiao Xie 		mnt_drop_write_file(file);
4634b8e95489SMiao Xie out:
4635475f6387SJan Schmidt 	kfree(sa);
4636475f6387SJan Schmidt 	return ret;
4637475f6387SJan Schmidt }
4638475f6387SJan Schmidt 
46392ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4640475f6387SJan Schmidt {
4641475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4642475f6387SJan Schmidt 		return -EPERM;
4643475f6387SJan Schmidt 
46442ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4645475f6387SJan Schmidt }
4646475f6387SJan Schmidt 
46472ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4648475f6387SJan Schmidt 				       void __user *arg)
4649475f6387SJan Schmidt {
4650475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4651475f6387SJan Schmidt 	int ret;
4652475f6387SJan Schmidt 
4653475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4654475f6387SJan Schmidt 		return -EPERM;
4655475f6387SJan Schmidt 
4656475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4657475f6387SJan Schmidt 	if (IS_ERR(sa))
4658475f6387SJan Schmidt 		return PTR_ERR(sa);
4659475f6387SJan Schmidt 
46602ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4661475f6387SJan Schmidt 
4662475f6387SJan Schmidt 	if (copy_to_user(arg, sa, sizeof(*sa)))
4663475f6387SJan Schmidt 		ret = -EFAULT;
4664475f6387SJan Schmidt 
4665475f6387SJan Schmidt 	kfree(sa);
4666475f6387SJan Schmidt 	return ret;
4667475f6387SJan Schmidt }
4668475f6387SJan Schmidt 
46692ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4670b27f7c0cSDavid Sterba 				      void __user *arg)
4671c11d2c23SStefan Behrens {
4672c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4673c11d2c23SStefan Behrens 	int ret;
4674c11d2c23SStefan Behrens 
4675c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4676c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4677c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4678c11d2c23SStefan Behrens 
4679b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4680b27f7c0cSDavid Sterba 		kfree(sa);
4681b27f7c0cSDavid Sterba 		return -EPERM;
4682b27f7c0cSDavid Sterba 	}
4683b27f7c0cSDavid Sterba 
46842ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4685c11d2c23SStefan Behrens 
4686c11d2c23SStefan Behrens 	if (copy_to_user(arg, sa, sizeof(*sa)))
4687c11d2c23SStefan Behrens 		ret = -EFAULT;
4688c11d2c23SStefan Behrens 
4689c11d2c23SStefan Behrens 	kfree(sa);
4690c11d2c23SStefan Behrens 	return ret;
4691c11d2c23SStefan Behrens }
4692c11d2c23SStefan Behrens 
46932ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
46942ff7e61eSJeff Mahoney 				    void __user *arg)
46953f6bcfbdSStefan Behrens {
46963f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
46973f6bcfbdSStefan Behrens 	int ret;
46983f6bcfbdSStefan Behrens 
46993f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
47003f6bcfbdSStefan Behrens 		return -EPERM;
47013f6bcfbdSStefan Behrens 
47023f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
47033f6bcfbdSStefan Behrens 	if (IS_ERR(p))
47043f6bcfbdSStefan Behrens 		return PTR_ERR(p);
47053f6bcfbdSStefan Behrens 
47063f6bcfbdSStefan Behrens 	switch (p->cmd) {
47073f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4708bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
4709adfa97cbSIlya Dryomov 			ret = -EROFS;
4710adfa97cbSIlya Dryomov 			goto out;
4711adfa97cbSIlya Dryomov 		}
4712171938e5SDavid Sterba 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4713e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
47143f6bcfbdSStefan Behrens 		} else {
47152ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4716171938e5SDavid Sterba 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
47173f6bcfbdSStefan Behrens 		}
47183f6bcfbdSStefan Behrens 		break;
47193f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
47200b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
47213f6bcfbdSStefan Behrens 		ret = 0;
47223f6bcfbdSStefan Behrens 		break;
47233f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
472417d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
472597282031SAnand Jain 		ret = 0;
47263f6bcfbdSStefan Behrens 		break;
47273f6bcfbdSStefan Behrens 	default:
47283f6bcfbdSStefan Behrens 		ret = -EINVAL;
47293f6bcfbdSStefan Behrens 		break;
47303f6bcfbdSStefan Behrens 	}
47313f6bcfbdSStefan Behrens 
47323f6bcfbdSStefan Behrens 	if (copy_to_user(arg, p, sizeof(*p)))
47333f6bcfbdSStefan Behrens 		ret = -EFAULT;
4734adfa97cbSIlya Dryomov out:
47353f6bcfbdSStefan Behrens 	kfree(p);
47363f6bcfbdSStefan Behrens 	return ret;
47373f6bcfbdSStefan Behrens }
47383f6bcfbdSStefan Behrens 
4739d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4740d7728c96SJan Schmidt {
4741d7728c96SJan Schmidt 	int ret = 0;
4742d7728c96SJan Schmidt 	int i;
4743740c3d22SChris Mason 	u64 rel_ptr;
4744d7728c96SJan Schmidt 	int size;
4745806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4746d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4747d7728c96SJan Schmidt 	struct btrfs_path *path;
4748d7728c96SJan Schmidt 
474982b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4750d7728c96SJan Schmidt 		return -EPERM;
4751d7728c96SJan Schmidt 
4752d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4753d7728c96SJan Schmidt 	if (!path) {
4754d7728c96SJan Schmidt 		ret = -ENOMEM;
4755d7728c96SJan Schmidt 		goto out;
4756d7728c96SJan Schmidt 	}
4757d7728c96SJan Schmidt 
4758d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4759d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4760d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4761d7728c96SJan Schmidt 		ipa = NULL;
4762d7728c96SJan Schmidt 		goto out;
4763d7728c96SJan Schmidt 	}
4764d7728c96SJan Schmidt 
4765d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4766d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4767d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4768d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4769d7728c96SJan Schmidt 		ipath = NULL;
4770d7728c96SJan Schmidt 		goto out;
4771d7728c96SJan Schmidt 	}
4772d7728c96SJan Schmidt 
4773d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4774d7728c96SJan Schmidt 	if (ret < 0)
4775d7728c96SJan Schmidt 		goto out;
4776d7728c96SJan Schmidt 
4777d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4778745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4779745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4780740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4781d7728c96SJan Schmidt 	}
4782d7728c96SJan Schmidt 
4783718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4784718dc5faSOmar Sandoval 			   ipath->fspath, size);
4785d7728c96SJan Schmidt 	if (ret) {
4786d7728c96SJan Schmidt 		ret = -EFAULT;
4787d7728c96SJan Schmidt 		goto out;
4788d7728c96SJan Schmidt 	}
4789d7728c96SJan Schmidt 
4790d7728c96SJan Schmidt out:
4791d7728c96SJan Schmidt 	btrfs_free_path(path);
4792d7728c96SJan Schmidt 	free_ipath(ipath);
4793d7728c96SJan Schmidt 	kfree(ipa);
4794d7728c96SJan Schmidt 
4795d7728c96SJan Schmidt 	return ret;
4796d7728c96SJan Schmidt }
4797d7728c96SJan Schmidt 
4798d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4799d7728c96SJan Schmidt {
4800d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4801d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4802d7728c96SJan Schmidt 
4803d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4804d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4805d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4806d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4807d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4808d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4809d7728c96SJan Schmidt 	} else {
4810d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4811d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4812d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4813d7728c96SJan Schmidt 	}
4814d7728c96SJan Schmidt 
4815d7728c96SJan Schmidt 	return 0;
4816d7728c96SJan Schmidt }
4817d7728c96SJan Schmidt 
48182ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4819d24a67b2SZygo Blaxell 					void __user *arg, int version)
4820d7728c96SJan Schmidt {
4821d7728c96SJan Schmidt 	int ret = 0;
4822d7728c96SJan Schmidt 	int size;
4823d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4824d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4825d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4826d24a67b2SZygo Blaxell 	bool ignore_offset;
4827d7728c96SJan Schmidt 
4828d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4829d7728c96SJan Schmidt 		return -EPERM;
4830d7728c96SJan Schmidt 
4831d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
48327b9ea627SShailendra Verma 	if (IS_ERR(loi))
48337b9ea627SShailendra Verma 		return PTR_ERR(loi);
4834d7728c96SJan Schmidt 
4835d24a67b2SZygo Blaxell 	if (version == 1) {
4836d24a67b2SZygo Blaxell 		ignore_offset = false;
4837b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
4838d24a67b2SZygo Blaxell 	} else {
4839d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
4840d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4841d24a67b2SZygo Blaxell 			ret = -EINVAL;
4842d24a67b2SZygo Blaxell 			goto out_loi;
4843d24a67b2SZygo Blaxell 		}
4844d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
4845d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4846d24a67b2SZygo Blaxell 			ret = -EINVAL;
4847d24a67b2SZygo Blaxell 			goto out_loi;
4848d24a67b2SZygo Blaxell 		}
4849d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4850b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
4851d24a67b2SZygo Blaxell 	}
4852d24a67b2SZygo Blaxell 
4853d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4854d7728c96SJan Schmidt 	if (!path) {
4855d7728c96SJan Schmidt 		ret = -ENOMEM;
4856d7728c96SJan Schmidt 		goto out;
4857d7728c96SJan Schmidt 	}
4858d7728c96SJan Schmidt 
4859d7728c96SJan Schmidt 	inodes = init_data_container(size);
4860d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4861d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4862d7728c96SJan Schmidt 		inodes = NULL;
4863d7728c96SJan Schmidt 		goto out;
4864d7728c96SJan Schmidt 	}
4865d7728c96SJan Schmidt 
48662ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4867d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
4868df031f07SLiu Bo 	if (ret == -EINVAL)
4869d7728c96SJan Schmidt 		ret = -ENOENT;
4870d7728c96SJan Schmidt 	if (ret < 0)
4871d7728c96SJan Schmidt 		goto out;
4872d7728c96SJan Schmidt 
4873718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4874718dc5faSOmar Sandoval 			   size);
4875d7728c96SJan Schmidt 	if (ret)
4876d7728c96SJan Schmidt 		ret = -EFAULT;
4877d7728c96SJan Schmidt 
4878d7728c96SJan Schmidt out:
4879d7728c96SJan Schmidt 	btrfs_free_path(path);
4880f54de068SDavid Sterba 	kvfree(inodes);
4881d24a67b2SZygo Blaxell out_loi:
4882d7728c96SJan Schmidt 	kfree(loi);
4883d7728c96SJan Schmidt 
4884d7728c96SJan Schmidt 	return ret;
4885d7728c96SJan Schmidt }
4886d7728c96SJan Schmidt 
4887008ef096SDavid Sterba void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4888c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4889c9e9f97bSIlya Dryomov {
4890c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4891c9e9f97bSIlya Dryomov 
4892c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4893c9e9f97bSIlya Dryomov 
48943009a62fSDavid Sterba 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4895837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4896837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4897837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4898a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4899a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4900837d5b6eSIlya Dryomov 
4901c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4902c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4903c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
490419a39dceSIlya Dryomov 
490519a39dceSIlya Dryomov 	spin_lock(&fs_info->balance_lock);
490619a39dceSIlya Dryomov 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
490719a39dceSIlya Dryomov 	spin_unlock(&fs_info->balance_lock);
4908c9e9f97bSIlya Dryomov }
4909c9e9f97bSIlya Dryomov 
49109ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4911c9e9f97bSIlya Dryomov {
4912496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4913c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4914c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4915c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4916ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4917c9e9f97bSIlya Dryomov 	int ret;
4918c9e9f97bSIlya Dryomov 
4919c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4920c9e9f97bSIlya Dryomov 		return -EPERM;
4921c9e9f97bSIlya Dryomov 
4922e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
49239ba1f6e4SLiu Bo 	if (ret)
49249ba1f6e4SLiu Bo 		return ret;
49259ba1f6e4SLiu Bo 
4926ed0fb78fSIlya Dryomov again:
4927171938e5SDavid Sterba 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4928c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4929ed0fb78fSIlya Dryomov 		need_unlock = true;
4930ed0fb78fSIlya Dryomov 		goto locked;
4931ed0fb78fSIlya Dryomov 	}
4932ed0fb78fSIlya Dryomov 
4933ed0fb78fSIlya Dryomov 	/*
493401327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4935ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4936ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4937ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4938ed0fb78fSIlya Dryomov 	 */
4939ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4940ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4941ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
49423009a62fSDavid Sterba 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4943ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4944dccdb07bSDavid Sterba 			/*
4945dccdb07bSDavid Sterba 			 * Lock released to allow other waiters to continue,
4946dccdb07bSDavid Sterba 			 * we'll reexamine the status again.
4947dccdb07bSDavid Sterba 			 */
4948ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4949ed0fb78fSIlya Dryomov 
4950ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
49513009a62fSDavid Sterba 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4952ed0fb78fSIlya Dryomov 				/* this is (3) */
4953ed0fb78fSIlya Dryomov 				need_unlock = false;
4954ed0fb78fSIlya Dryomov 				goto locked;
4955ed0fb78fSIlya Dryomov 			}
4956ed0fb78fSIlya Dryomov 
4957ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4958ed0fb78fSIlya Dryomov 			goto again;
4959ed0fb78fSIlya Dryomov 		} else {
4960ed0fb78fSIlya Dryomov 			/* this is (2) */
4961ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4962ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4963ed0fb78fSIlya Dryomov 			goto out;
4964ed0fb78fSIlya Dryomov 		}
4965ed0fb78fSIlya Dryomov 	} else {
4966ed0fb78fSIlya Dryomov 		/* this is (1) */
4967ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4968e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4969ed0fb78fSIlya Dryomov 		goto out;
4970ed0fb78fSIlya Dryomov 	}
4971ed0fb78fSIlya Dryomov 
4972ed0fb78fSIlya Dryomov locked:
4973171938e5SDavid Sterba 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4974c9e9f97bSIlya Dryomov 
4975c9e9f97bSIlya Dryomov 	if (arg) {
4976c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4977c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4978c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4979ed0fb78fSIlya Dryomov 			goto out_unlock;
4980c9e9f97bSIlya Dryomov 		}
4981de322263SIlya Dryomov 
4982de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4983de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4984de322263SIlya Dryomov 				ret = -ENOTCONN;
4985de322263SIlya Dryomov 				goto out_bargs;
4986de322263SIlya Dryomov 			}
4987de322263SIlya Dryomov 
4988de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4989de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4990de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4991de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4992de322263SIlya Dryomov 
4993de322263SIlya Dryomov 			goto do_balance;
4994de322263SIlya Dryomov 		}
4995c9e9f97bSIlya Dryomov 	} else {
4996c9e9f97bSIlya Dryomov 		bargs = NULL;
4997c9e9f97bSIlya Dryomov 	}
4998c9e9f97bSIlya Dryomov 
4999ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
5000837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
5001837d5b6eSIlya Dryomov 		goto out_bargs;
5002837d5b6eSIlya Dryomov 	}
5003837d5b6eSIlya Dryomov 
50048d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
5005c9e9f97bSIlya Dryomov 	if (!bctl) {
5006c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
5007c9e9f97bSIlya Dryomov 		goto out_bargs;
5008c9e9f97bSIlya Dryomov 	}
5009c9e9f97bSIlya Dryomov 
5010c9e9f97bSIlya Dryomov 	if (arg) {
5011c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
5012c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
5013c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
5014c9e9f97bSIlya Dryomov 
5015c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
5016f43ffb60SIlya Dryomov 	} else {
5017f43ffb60SIlya Dryomov 		/* balance everything - no filters */
5018f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
5019c9e9f97bSIlya Dryomov 	}
5020c9e9f97bSIlya Dryomov 
50218eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
50228eb93459SDavid Sterba 		ret = -EINVAL;
50230f89abf5SChristian Engelmayer 		goto out_bctl;
50248eb93459SDavid Sterba 	}
50258eb93459SDavid Sterba 
5026de322263SIlya Dryomov do_balance:
5027c9e9f97bSIlya Dryomov 	/*
5028149196a2SDavid Sterba 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
5029149196a2SDavid Sterba 	 * btrfs_balance.  bctl is freed in reset_balance_state, or, if
5030149196a2SDavid Sterba 	 * restriper was paused all the way until unmount, in free_fs_info.
5031149196a2SDavid Sterba 	 * The flag should be cleared after reset_balance_state.
5032c9e9f97bSIlya Dryomov 	 */
5033ed0fb78fSIlya Dryomov 	need_unlock = false;
5034ed0fb78fSIlya Dryomov 
50356fcf6e2bSDavid Sterba 	ret = btrfs_balance(fs_info, bctl, bargs);
50360f89abf5SChristian Engelmayer 	bctl = NULL;
5037ed0fb78fSIlya Dryomov 
5038c9e9f97bSIlya Dryomov 	if (arg) {
5039c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
5040c9e9f97bSIlya Dryomov 			ret = -EFAULT;
5041c9e9f97bSIlya Dryomov 	}
5042c9e9f97bSIlya Dryomov 
50430f89abf5SChristian Engelmayer out_bctl:
50440f89abf5SChristian Engelmayer 	kfree(bctl);
5045c9e9f97bSIlya Dryomov out_bargs:
5046c9e9f97bSIlya Dryomov 	kfree(bargs);
5047ed0fb78fSIlya Dryomov out_unlock:
5048c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
5049ed0fb78fSIlya Dryomov 	if (need_unlock)
5050171938e5SDavid Sterba 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
5051ed0fb78fSIlya Dryomov out:
5052e54bfa31SLiu Bo 	mnt_drop_write_file(file);
5053c9e9f97bSIlya Dryomov 	return ret;
5054c9e9f97bSIlya Dryomov }
5055c9e9f97bSIlya Dryomov 
50562ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
5057837d5b6eSIlya Dryomov {
5058837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
5059837d5b6eSIlya Dryomov 		return -EPERM;
5060837d5b6eSIlya Dryomov 
5061837d5b6eSIlya Dryomov 	switch (cmd) {
5062837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
50630b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
5064a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
50650b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
5066837d5b6eSIlya Dryomov 	}
5067837d5b6eSIlya Dryomov 
5068837d5b6eSIlya Dryomov 	return -EINVAL;
5069837d5b6eSIlya Dryomov }
5070837d5b6eSIlya Dryomov 
50712ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
507219a39dceSIlya Dryomov 					 void __user *arg)
507319a39dceSIlya Dryomov {
507419a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
507519a39dceSIlya Dryomov 	int ret = 0;
507619a39dceSIlya Dryomov 
507719a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
507819a39dceSIlya Dryomov 		return -EPERM;
507919a39dceSIlya Dryomov 
508019a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
508119a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
508219a39dceSIlya Dryomov 		ret = -ENOTCONN;
508319a39dceSIlya Dryomov 		goto out;
508419a39dceSIlya Dryomov 	}
508519a39dceSIlya Dryomov 
50868d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
508719a39dceSIlya Dryomov 	if (!bargs) {
508819a39dceSIlya Dryomov 		ret = -ENOMEM;
508919a39dceSIlya Dryomov 		goto out;
509019a39dceSIlya Dryomov 	}
509119a39dceSIlya Dryomov 
5092008ef096SDavid Sterba 	btrfs_update_ioctl_balance_args(fs_info, bargs);
509319a39dceSIlya Dryomov 
509419a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
509519a39dceSIlya Dryomov 		ret = -EFAULT;
509619a39dceSIlya Dryomov 
509719a39dceSIlya Dryomov 	kfree(bargs);
509819a39dceSIlya Dryomov out:
509919a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
510019a39dceSIlya Dryomov 	return ret;
510119a39dceSIlya Dryomov }
510219a39dceSIlya Dryomov 
5103905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
51045d13a37bSArne Jansen {
51050b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51060b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51075d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
51085d13a37bSArne Jansen 	int ret;
51095d13a37bSArne Jansen 
51105d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
51115d13a37bSArne Jansen 		return -EPERM;
51125d13a37bSArne Jansen 
5113905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5114905b0ddaSMiao Xie 	if (ret)
5115905b0ddaSMiao Xie 		return ret;
51165d13a37bSArne Jansen 
51175d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5118905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5119905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5120905b0ddaSMiao Xie 		goto drop_write;
5121905b0ddaSMiao Xie 	}
51225d13a37bSArne Jansen 
51230b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
51245d13a37bSArne Jansen 
51255d13a37bSArne Jansen 	switch (sa->cmd) {
51265d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
5127340f1aa2SNikolay Borisov 		ret = btrfs_quota_enable(fs_info);
51285d13a37bSArne Jansen 		break;
51295d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
5130340f1aa2SNikolay Borisov 		ret = btrfs_quota_disable(fs_info);
51315d13a37bSArne Jansen 		break;
51325d13a37bSArne Jansen 	default:
51335d13a37bSArne Jansen 		ret = -EINVAL;
51345d13a37bSArne Jansen 		break;
51355d13a37bSArne Jansen 	}
51365d13a37bSArne Jansen 
51375d13a37bSArne Jansen 	kfree(sa);
51380b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5139905b0ddaSMiao Xie drop_write:
5140905b0ddaSMiao Xie 	mnt_drop_write_file(file);
51415d13a37bSArne Jansen 	return ret;
51425d13a37bSArne Jansen }
51435d13a37bSArne Jansen 
5144905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
51455d13a37bSArne Jansen {
51460b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51480b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
51495d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
51505d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
51515d13a37bSArne Jansen 	int ret;
51525d13a37bSArne Jansen 	int err;
51535d13a37bSArne Jansen 
51545d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
51555d13a37bSArne Jansen 		return -EPERM;
51565d13a37bSArne Jansen 
5157905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5158905b0ddaSMiao Xie 	if (ret)
5159905b0ddaSMiao Xie 		return ret;
51605d13a37bSArne Jansen 
51615d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5162905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5163905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5164905b0ddaSMiao Xie 		goto drop_write;
5165905b0ddaSMiao Xie 	}
51665d13a37bSArne Jansen 
51675d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
51685d13a37bSArne Jansen 	if (IS_ERR(trans)) {
51695d13a37bSArne Jansen 		ret = PTR_ERR(trans);
51705d13a37bSArne Jansen 		goto out;
51715d13a37bSArne Jansen 	}
51725d13a37bSArne Jansen 
51735d13a37bSArne Jansen 	if (sa->assign) {
51749f8a6ce6SLu Fengqi 		ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
51755d13a37bSArne Jansen 	} else {
517639616c27SLu Fengqi 		ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
51775d13a37bSArne Jansen 	}
51785d13a37bSArne Jansen 
5179e082f563SQu Wenruo 	/* update qgroup status and info */
51800b246afaSJeff Mahoney 	err = btrfs_run_qgroups(trans, fs_info);
5181e082f563SQu Wenruo 	if (err < 0)
51820b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
5183ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
51843a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
51855d13a37bSArne Jansen 	if (err && !ret)
51865d13a37bSArne Jansen 		ret = err;
51875d13a37bSArne Jansen 
51885d13a37bSArne Jansen out:
51895d13a37bSArne Jansen 	kfree(sa);
5190905b0ddaSMiao Xie drop_write:
5191905b0ddaSMiao Xie 	mnt_drop_write_file(file);
51925d13a37bSArne Jansen 	return ret;
51935d13a37bSArne Jansen }
51945d13a37bSArne Jansen 
5195905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
51965d13a37bSArne Jansen {
51970b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
51980b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
51995d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
52005d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
52015d13a37bSArne Jansen 	int ret;
52025d13a37bSArne Jansen 	int err;
52035d13a37bSArne Jansen 
52045d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
52055d13a37bSArne Jansen 		return -EPERM;
52065d13a37bSArne Jansen 
5207905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5208905b0ddaSMiao Xie 	if (ret)
5209905b0ddaSMiao Xie 		return ret;
52105d13a37bSArne Jansen 
52115d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5212905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5213905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5214905b0ddaSMiao Xie 		goto drop_write;
5215905b0ddaSMiao Xie 	}
52165d13a37bSArne Jansen 
5217d86e56cfSMiao Xie 	if (!sa->qgroupid) {
5218d86e56cfSMiao Xie 		ret = -EINVAL;
5219d86e56cfSMiao Xie 		goto out;
5220d86e56cfSMiao Xie 	}
5221d86e56cfSMiao Xie 
52225d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
52235d13a37bSArne Jansen 	if (IS_ERR(trans)) {
52245d13a37bSArne Jansen 		ret = PTR_ERR(trans);
52255d13a37bSArne Jansen 		goto out;
52265d13a37bSArne Jansen 	}
52275d13a37bSArne Jansen 
52285d13a37bSArne Jansen 	if (sa->create) {
522949a05ecdSLu Fengqi 		ret = btrfs_create_qgroup(trans, sa->qgroupid);
52305d13a37bSArne Jansen 	} else {
52313efbee1dSLu Fengqi 		ret = btrfs_remove_qgroup(trans, sa->qgroupid);
52325d13a37bSArne Jansen 	}
52335d13a37bSArne Jansen 
52343a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
52355d13a37bSArne Jansen 	if (err && !ret)
52365d13a37bSArne Jansen 		ret = err;
52375d13a37bSArne Jansen 
52385d13a37bSArne Jansen out:
52395d13a37bSArne Jansen 	kfree(sa);
5240905b0ddaSMiao Xie drop_write:
5241905b0ddaSMiao Xie 	mnt_drop_write_file(file);
52425d13a37bSArne Jansen 	return ret;
52435d13a37bSArne Jansen }
52445d13a37bSArne Jansen 
5245905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
52465d13a37bSArne Jansen {
52470b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52480b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52490b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
52505d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
52515d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
52525d13a37bSArne Jansen 	int ret;
52535d13a37bSArne Jansen 	int err;
52545d13a37bSArne Jansen 	u64 qgroupid;
52555d13a37bSArne Jansen 
52565d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
52575d13a37bSArne Jansen 		return -EPERM;
52585d13a37bSArne Jansen 
5259905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
5260905b0ddaSMiao Xie 	if (ret)
5261905b0ddaSMiao Xie 		return ret;
52625d13a37bSArne Jansen 
52635d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
5264905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
5265905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
5266905b0ddaSMiao Xie 		goto drop_write;
5267905b0ddaSMiao Xie 	}
52685d13a37bSArne Jansen 
52695d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
52705d13a37bSArne Jansen 	if (IS_ERR(trans)) {
52715d13a37bSArne Jansen 		ret = PTR_ERR(trans);
52725d13a37bSArne Jansen 		goto out;
52735d13a37bSArne Jansen 	}
52745d13a37bSArne Jansen 
52755d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
52765d13a37bSArne Jansen 	if (!qgroupid) {
52775d13a37bSArne Jansen 		/* take the current subvol as qgroup */
52785d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
52795d13a37bSArne Jansen 	}
52805d13a37bSArne Jansen 
52810b246afaSJeff Mahoney 	ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
52825d13a37bSArne Jansen 
52833a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
52845d13a37bSArne Jansen 	if (err && !ret)
52855d13a37bSArne Jansen 		ret = err;
52865d13a37bSArne Jansen 
52875d13a37bSArne Jansen out:
52885d13a37bSArne Jansen 	kfree(sa);
5289905b0ddaSMiao Xie drop_write:
5290905b0ddaSMiao Xie 	mnt_drop_write_file(file);
52915d13a37bSArne Jansen 	return ret;
52925d13a37bSArne Jansen }
52935d13a37bSArne Jansen 
52942f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
52952f232036SJan Schmidt {
52960b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52982f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
52992f232036SJan Schmidt 	int ret;
53002f232036SJan Schmidt 
53012f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
53022f232036SJan Schmidt 		return -EPERM;
53032f232036SJan Schmidt 
53042f232036SJan Schmidt 	ret = mnt_want_write_file(file);
53052f232036SJan Schmidt 	if (ret)
53062f232036SJan Schmidt 		return ret;
53072f232036SJan Schmidt 
53082f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
53092f232036SJan Schmidt 	if (IS_ERR(qsa)) {
53102f232036SJan Schmidt 		ret = PTR_ERR(qsa);
53112f232036SJan Schmidt 		goto drop_write;
53122f232036SJan Schmidt 	}
53132f232036SJan Schmidt 
53142f232036SJan Schmidt 	if (qsa->flags) {
53152f232036SJan Schmidt 		ret = -EINVAL;
53162f232036SJan Schmidt 		goto out;
53172f232036SJan Schmidt 	}
53182f232036SJan Schmidt 
53190b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
53202f232036SJan Schmidt 
53212f232036SJan Schmidt out:
53222f232036SJan Schmidt 	kfree(qsa);
53232f232036SJan Schmidt drop_write:
53242f232036SJan Schmidt 	mnt_drop_write_file(file);
53252f232036SJan Schmidt 	return ret;
53262f232036SJan Schmidt }
53272f232036SJan Schmidt 
53282f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
53292f232036SJan Schmidt {
53300b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53322f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
53332f232036SJan Schmidt 	int ret = 0;
53342f232036SJan Schmidt 
53352f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
53362f232036SJan Schmidt 		return -EPERM;
53372f232036SJan Schmidt 
53388d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
53392f232036SJan Schmidt 	if (!qsa)
53402f232036SJan Schmidt 		return -ENOMEM;
53412f232036SJan Schmidt 
53420b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
53432f232036SJan Schmidt 		qsa->flags = 1;
53440b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
53452f232036SJan Schmidt 	}
53462f232036SJan Schmidt 
53472f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
53482f232036SJan Schmidt 		ret = -EFAULT;
53492f232036SJan Schmidt 
53502f232036SJan Schmidt 	kfree(qsa);
53512f232036SJan Schmidt 	return ret;
53522f232036SJan Schmidt }
53532f232036SJan Schmidt 
535457254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
535557254b6eSJan Schmidt {
53560b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
535857254b6eSJan Schmidt 
535957254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
536057254b6eSJan Schmidt 		return -EPERM;
536157254b6eSJan Schmidt 
53620b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
536357254b6eSJan Schmidt }
536457254b6eSJan Schmidt 
5365abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
5366abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
53678ea05e3aSAlexander Block {
5368496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
53690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53708ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
53718ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
53728ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
537395582b00SDeepa Dinamani 	struct timespec64 ct = current_time(inode);
53748ea05e3aSAlexander Block 	int ret = 0;
5375dd5f9615SStefan Behrens 	int received_uuid_changed;
53768ea05e3aSAlexander Block 
5377bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
5378bd60ea0fSDavid Sterba 		return -EPERM;
5379bd60ea0fSDavid Sterba 
53808ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
53818ea05e3aSAlexander Block 	if (ret < 0)
53828ea05e3aSAlexander Block 		return ret;
53838ea05e3aSAlexander Block 
53840b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
53858ea05e3aSAlexander Block 
53864a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
53878ea05e3aSAlexander Block 		ret = -EINVAL;
53888ea05e3aSAlexander Block 		goto out;
53898ea05e3aSAlexander Block 	}
53908ea05e3aSAlexander Block 
53918ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
53928ea05e3aSAlexander Block 		ret = -EROFS;
53938ea05e3aSAlexander Block 		goto out;
53948ea05e3aSAlexander Block 	}
53958ea05e3aSAlexander Block 
5396dd5f9615SStefan Behrens 	/*
5397dd5f9615SStefan Behrens 	 * 1 - root item
5398dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5399dd5f9615SStefan Behrens 	 */
5400dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
54018ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
54028ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
54038ea05e3aSAlexander Block 		trans = NULL;
54048ea05e3aSAlexander Block 		goto out;
54058ea05e3aSAlexander Block 	}
54068ea05e3aSAlexander Block 
54078ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
54088ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
54098ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
54108ea05e3aSAlexander Block 
5411dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5412dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5413dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5414d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
5415d1957791SLu Fengqi 		ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
5416dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5417dd5f9615SStefan Behrens 					  root->root_key.objectid);
5418d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
5419d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
5420d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
5421d87ff758SNikolay Borisov 		        goto out;
5422d87ff758SNikolay Borisov 		}
5423d87ff758SNikolay Borisov 	}
54248ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
54258ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
54268ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
54273cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
54283cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
54293cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
54303cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
54318ea05e3aSAlexander Block 
54320b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
54338ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
54348ea05e3aSAlexander Block 	if (ret < 0) {
54353a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
54368ea05e3aSAlexander Block 		goto out;
5437dd5f9615SStefan Behrens 	}
5438dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5439cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, sa->uuid,
5440dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5441dd5f9615SStefan Behrens 					  root->root_key.objectid);
5442dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
544366642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
5444efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
5445dd5f9615SStefan Behrens 			goto out;
5446dd5f9615SStefan Behrens 		}
5447dd5f9615SStefan Behrens 	}
54483a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5449abccd00fSHugo Mills out:
54500b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5451abccd00fSHugo Mills 	mnt_drop_write_file(file);
5452abccd00fSHugo Mills 	return ret;
5453abccd00fSHugo Mills }
5454abccd00fSHugo Mills 
5455abccd00fSHugo Mills #ifdef CONFIG_64BIT
5456abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5457abccd00fSHugo Mills 						void __user *arg)
5458abccd00fSHugo Mills {
5459abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5460abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5461abccd00fSHugo Mills 	int ret = 0;
5462abccd00fSHugo Mills 
5463abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
54647b9ea627SShailendra Verma 	if (IS_ERR(args32))
54657b9ea627SShailendra Verma 		return PTR_ERR(args32);
5466abccd00fSHugo Mills 
54678d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
546884dbeb87SDan Carpenter 	if (!args64) {
546984dbeb87SDan Carpenter 		ret = -ENOMEM;
5470abccd00fSHugo Mills 		goto out;
5471abccd00fSHugo Mills 	}
5472abccd00fSHugo Mills 
5473abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5474abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5475abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5476abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5477abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5478abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5479abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5480abccd00fSHugo Mills 	args64->flags = args32->flags;
5481abccd00fSHugo Mills 
5482abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5483abccd00fSHugo Mills 	if (ret)
5484abccd00fSHugo Mills 		goto out;
5485abccd00fSHugo Mills 
5486abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5487abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5488abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5489abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5490abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5491abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5492abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5493abccd00fSHugo Mills 	args32->flags = args64->flags;
5494abccd00fSHugo Mills 
5495abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5496abccd00fSHugo Mills 	if (ret)
5497abccd00fSHugo Mills 		ret = -EFAULT;
5498abccd00fSHugo Mills 
5499abccd00fSHugo Mills out:
5500abccd00fSHugo Mills 	kfree(args32);
5501abccd00fSHugo Mills 	kfree(args64);
5502abccd00fSHugo Mills 	return ret;
5503abccd00fSHugo Mills }
5504abccd00fSHugo Mills #endif
5505abccd00fSHugo Mills 
5506abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5507abccd00fSHugo Mills 					    void __user *arg)
5508abccd00fSHugo Mills {
5509abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5510abccd00fSHugo Mills 	int ret = 0;
5511abccd00fSHugo Mills 
5512abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
55137b9ea627SShailendra Verma 	if (IS_ERR(sa))
55147b9ea627SShailendra Verma 		return PTR_ERR(sa);
5515abccd00fSHugo Mills 
5516abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5517abccd00fSHugo Mills 
5518abccd00fSHugo Mills 	if (ret)
5519abccd00fSHugo Mills 		goto out;
5520abccd00fSHugo Mills 
55218ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
55228ea05e3aSAlexander Block 	if (ret)
55238ea05e3aSAlexander Block 		ret = -EFAULT;
55248ea05e3aSAlexander Block 
55258ea05e3aSAlexander Block out:
55268ea05e3aSAlexander Block 	kfree(sa);
55278ea05e3aSAlexander Block 	return ret;
55288ea05e3aSAlexander Block }
55298ea05e3aSAlexander Block 
5530867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5531867ab667Sjeff.liu {
55320b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
55330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5534a1b83ac5SAnand Jain 	size_t len;
5535867ab667Sjeff.liu 	int ret;
5536a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5537a1b83ac5SAnand Jain 
55380b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
55390b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
55400b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
5541a1b83ac5SAnand Jain 
5542a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5543867ab667Sjeff.liu 
5544867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
55450b246afaSJeff Mahoney 		btrfs_warn(fs_info,
55460b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
55470b246afaSJeff Mahoney 			   --len);
5548867ab667Sjeff.liu 	}
5549867ab667Sjeff.liu 
5550867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5551867ab667Sjeff.liu 
5552867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5553867ab667Sjeff.liu }
5554867ab667Sjeff.liu 
5555a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5556a8bfd4abSjeff.liu {
55570b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
55580b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
55590b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
55600b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
5561a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5562a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5563a8bfd4abSjeff.liu 	int ret;
5564a8bfd4abSjeff.liu 
5565a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5566a8bfd4abSjeff.liu 		return -EPERM;
5567a8bfd4abSjeff.liu 
5568a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5569a8bfd4abSjeff.liu 		return -EFAULT;
5570a8bfd4abSjeff.liu 
5571a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
55720b246afaSJeff Mahoney 		btrfs_err(fs_info,
55735d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5574a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5575a8bfd4abSjeff.liu 		return -EINVAL;
5576a8bfd4abSjeff.liu 	}
5577a8bfd4abSjeff.liu 
5578a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5579a8bfd4abSjeff.liu 	if (ret)
5580a8bfd4abSjeff.liu 		return ret;
5581a8bfd4abSjeff.liu 
5582a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5583a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5584a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5585a8bfd4abSjeff.liu 		goto out_unlock;
5586a8bfd4abSjeff.liu 	}
5587a8bfd4abSjeff.liu 
55880b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5589a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
55900b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
55913a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5592a8bfd4abSjeff.liu 
5593a8bfd4abSjeff.liu out_unlock:
5594a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5595a8bfd4abSjeff.liu 	return ret;
5596a8bfd4abSjeff.liu }
5597a8bfd4abSjeff.liu 
55982eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
55992eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
56002eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
56012eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
56022eaa055fSJeff Mahoney 
5603d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
56042eaa055fSJeff Mahoney {
56054d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
56062eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
56072eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
56082eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
56092eaa055fSJeff Mahoney 	};
56102eaa055fSJeff Mahoney 
56112eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
56122eaa055fSJeff Mahoney 		return -EFAULT;
56132eaa055fSJeff Mahoney 
56142eaa055fSJeff Mahoney 	return 0;
56152eaa055fSJeff Mahoney }
56162eaa055fSJeff Mahoney 
56172eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
56182eaa055fSJeff Mahoney {
56190b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
56200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
56210b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
56222eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
56232eaa055fSJeff Mahoney 
56242eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
56252eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
56262eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
56272eaa055fSJeff Mahoney 
56282eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
56292eaa055fSJeff Mahoney 		return -EFAULT;
56302eaa055fSJeff Mahoney 
56312eaa055fSJeff Mahoney 	return 0;
56322eaa055fSJeff Mahoney }
56332eaa055fSJeff Mahoney 
56342ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
56353b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
56362eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
56372eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
56382eaa055fSJeff Mahoney {
56393b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
56403b02a68aSJeff Mahoney 	char *names;
56412eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
56422eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
56432eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
56442eaa055fSJeff Mahoney 
56452eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
56462eaa055fSJeff Mahoney 	if (unsupported) {
56473b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
56483b02a68aSJeff Mahoney 		if (names) {
56490b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56503b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
56513b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
56523b02a68aSJeff Mahoney 			kfree(names);
56533b02a68aSJeff Mahoney 		} else
56540b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56552eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
56562eaa055fSJeff Mahoney 				   type, unsupported);
56572eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
56582eaa055fSJeff Mahoney 	}
56592eaa055fSJeff Mahoney 
56602eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
56612eaa055fSJeff Mahoney 	if (disallowed) {
56623b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
56633b02a68aSJeff Mahoney 		if (names) {
56640b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56653b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
56663b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
56673b02a68aSJeff Mahoney 			kfree(names);
56683b02a68aSJeff Mahoney 		} else
56690b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56702eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
56712eaa055fSJeff Mahoney 				   type, disallowed);
56722eaa055fSJeff Mahoney 		return -EPERM;
56732eaa055fSJeff Mahoney 	}
56742eaa055fSJeff Mahoney 
56752eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
56762eaa055fSJeff Mahoney 	if (disallowed) {
56773b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
56783b02a68aSJeff Mahoney 		if (names) {
56790b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56803b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
56813b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
56823b02a68aSJeff Mahoney 			kfree(names);
56833b02a68aSJeff Mahoney 		} else
56840b246afaSJeff Mahoney 			btrfs_warn(fs_info,
56852eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
56862eaa055fSJeff Mahoney 				   type, disallowed);
56872eaa055fSJeff Mahoney 		return -EPERM;
56882eaa055fSJeff Mahoney 	}
56892eaa055fSJeff Mahoney 
56902eaa055fSJeff Mahoney 	return 0;
56912eaa055fSJeff Mahoney }
56922eaa055fSJeff Mahoney 
56932ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
56942ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
56952eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
56962eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
56972eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
56982eaa055fSJeff Mahoney 
56992eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
57002eaa055fSJeff Mahoney {
57010b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
57020b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
57030b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
57040b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
57052eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
57062eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
57072eaa055fSJeff Mahoney 	u64 newflags;
57082eaa055fSJeff Mahoney 	int ret;
57092eaa055fSJeff Mahoney 
57102eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
57112eaa055fSJeff Mahoney 		return -EPERM;
57122eaa055fSJeff Mahoney 
57132eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
57142eaa055fSJeff Mahoney 		return -EFAULT;
57152eaa055fSJeff Mahoney 
57162eaa055fSJeff Mahoney 	/* Nothing to do */
57172eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
57182eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
57192eaa055fSJeff Mahoney 		return 0;
57202eaa055fSJeff Mahoney 
57212ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
57222eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
57232eaa055fSJeff Mahoney 	if (ret)
57242eaa055fSJeff Mahoney 		return ret;
57252eaa055fSJeff Mahoney 
57262ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
57272eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
57282eaa055fSJeff Mahoney 	if (ret)
57292eaa055fSJeff Mahoney 		return ret;
57302eaa055fSJeff Mahoney 
57312ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
57322eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
57332eaa055fSJeff Mahoney 	if (ret)
57342eaa055fSJeff Mahoney 		return ret;
57352eaa055fSJeff Mahoney 
57367ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
57377ab19625SDavid Sterba 	if (ret)
57387ab19625SDavid Sterba 		return ret;
57397ab19625SDavid Sterba 
57408051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
57417ab19625SDavid Sterba 	if (IS_ERR(trans)) {
57427ab19625SDavid Sterba 		ret = PTR_ERR(trans);
57437ab19625SDavid Sterba 		goto out_drop_write;
57447ab19625SDavid Sterba 	}
57452eaa055fSJeff Mahoney 
57460b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
57472eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
57482eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
57492eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
57502eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
57512eaa055fSJeff Mahoney 
57522eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
57532eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
57542eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
57552eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
57562eaa055fSJeff Mahoney 
57572eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
57582eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
57592eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
57602eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
57610b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
57622eaa055fSJeff Mahoney 
57633a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
57647ab19625SDavid Sterba out_drop_write:
57657ab19625SDavid Sterba 	mnt_drop_write_file(file);
57667ab19625SDavid Sterba 
57677ab19625SDavid Sterba 	return ret;
57682eaa055fSJeff Mahoney }
57692eaa055fSJeff Mahoney 
57702351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
57712351f431SJosef Bacik {
57722351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
57732351f431SJosef Bacik 	int ret;
57742351f431SJosef Bacik 
57752351f431SJosef Bacik 	if (compat) {
57762351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
57772351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
57782351f431SJosef Bacik 
57792351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
57802351f431SJosef Bacik 		if (ret)
57812351f431SJosef Bacik 			return -EFAULT;
57822351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
57832351f431SJosef Bacik 		if (!arg)
57842351f431SJosef Bacik 			return -ENOMEM;
57852351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
57862351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
57872351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
57882351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
57892351f431SJosef Bacik 		arg->flags = args32.flags;
57902351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
57912351f431SJosef Bacik 		       sizeof(args32.reserved));
57922351f431SJosef Bacik #else
57932351f431SJosef Bacik 		return -ENOTTY;
57942351f431SJosef Bacik #endif
57952351f431SJosef Bacik 	} else {
57962351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
57972351f431SJosef Bacik 		if (IS_ERR(arg))
57982351f431SJosef Bacik 			return PTR_ERR(arg);
57992351f431SJosef Bacik 	}
58002351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
58012351f431SJosef Bacik 	kfree(arg);
58022351f431SJosef Bacik 	return ret;
58032351f431SJosef Bacik }
58042351f431SJosef Bacik 
5805f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5806f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5807f46b5a66SChristoph Hellwig {
58080b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
58090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
58100b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
58114bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5812f46b5a66SChristoph Hellwig 
5813f46b5a66SChristoph Hellwig 	switch (cmd) {
58146cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
58156cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
58166cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
58176cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
58186cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
58196cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5820f7039b1dSLi Dongyang 	case FITRIM:
5821f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5822f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5823fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5824fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5825fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
58263de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5827fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
58286f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
58296f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
583076dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
583176dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
58320caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
58330caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
58340caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
58350caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
58366ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
58376ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5838f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
58391e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
58401e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
58411e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5842f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5843198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5844f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
58452ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5846f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5847da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
58486b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
58496b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5850475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
58512ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5852475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
58532ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5854f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
58559ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5856ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5857ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5858cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5859cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5860ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5861ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5862d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5863d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5864d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5865d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5866d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
5867d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
58681406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
58692ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
58709b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
58719b199859SFilipe David Borba Manana 		int ret;
58729b199859SFilipe David Borba Manana 
587382b3e53bSNikolay Borisov 		ret = btrfs_start_delalloc_roots(fs_info, -1);
58749b199859SFilipe David Borba Manana 		if (ret)
58759b199859SFilipe David Borba Manana 			return ret;
58760b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
58772fad4e83SDavid Sterba 		/*
58782fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
587901327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
58802fad4e83SDavid Sterba 		 * processing uncleaned subvols.
58812fad4e83SDavid Sterba 		 */
58820b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
58839b199859SFilipe David Borba Manana 		return ret;
58849b199859SFilipe David Borba Manana 	}
588546204592SSage Weil 	case BTRFS_IOC_START_SYNC:
58869a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
588746204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
58882ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5889475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5890b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5891475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
58922ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5893475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
58942ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5895c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
58969ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5897837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
58982ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
589919a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
59002ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
59018ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
59028ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5903abccd00fSHugo Mills #ifdef CONFIG_64BIT
5904abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5905abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5906abccd00fSHugo Mills #endif
590731db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
59082351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
59092351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
59102351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
59112351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
59122351f431SJosef Bacik #endif
5913c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
59142ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
59155d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5916905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
59175d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5918905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
59195d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5920905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
59215d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5922905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
59232f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
59242f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
59252f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
59262f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
592757254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
592857254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
59293f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
59302ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5931867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5932867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5933a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5934a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
59352eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5936d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
59372eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
59382eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
59392eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
59402eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5941e4202ac9SDavid Sterba 	case FS_IOC_FSGETXATTR:
5942e4202ac9SDavid Sterba 		return btrfs_ioctl_fsgetxattr(file, argp);
5943025f2121SDavid Sterba 	case FS_IOC_FSSETXATTR:
5944025f2121SDavid Sterba 		return btrfs_ioctl_fssetxattr(file, argp);
5945b64ec075STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_INFO:
5946b64ec075STomohiro Misono 		return btrfs_ioctl_get_subvol_info(file, argp);
594742e4b520STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_ROOTREF:
594842e4b520STomohiro Misono 		return btrfs_ioctl_get_subvol_rootref(file, argp);
594923d0b79dSTomohiro Misono 	case BTRFS_IOC_INO_LOOKUP_USER:
595023d0b79dSTomohiro Misono 		return btrfs_ioctl_ino_lookup_user(file, argp);
5951f46b5a66SChristoph Hellwig 	}
5952f46b5a66SChristoph Hellwig 
5953f46b5a66SChristoph Hellwig 	return -ENOTTY;
5954f46b5a66SChristoph Hellwig }
59554c63c245SLuke Dashjr 
59564c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
59574c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
59584c63c245SLuke Dashjr {
59592a362249SJeff Mahoney 	/*
59602a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
59612a362249SJeff Mahoney 	 * handling is necessary.
59622a362249SJeff Mahoney 	 */
59634c63c245SLuke Dashjr 	switch (cmd) {
59644c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
59654c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
59664c63c245SLuke Dashjr 		break;
59674c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
59684c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
59694c63c245SLuke Dashjr 		break;
59704c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
59714c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
59724c63c245SLuke Dashjr 		break;
59734c63c245SLuke Dashjr 	}
59744c63c245SLuke Dashjr 
59754c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
59764c63c245SLuke Dashjr }
59774c63c245SLuke Dashjr #endif
5978