xref: /openbmc/linux/fs/btrfs/ioctl.c (revision d2b8fcfe)
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;
1927e97b8daSDavid Sterba 	umode_t mode;
193ff9fef55SAnand Jain 	const char *comp = NULL;
194d2b8fcfeSAnand Jain 	u32 binode_flags = binode->flags;
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 
2157e97b8daSDavid Sterba 	mode = inode->i_mode;
216f062abf0SLi Zefan 
2175c57b8b6SDavid Sterba 	fsflags = btrfs_mask_fsflags_for_type(inode, fsflags);
2185c57b8b6SDavid Sterba 	old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags);
2195c57b8b6SDavid Sterba 	if ((fsflags ^ old_fsflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
2206cbff00fSChristoph Hellwig 		if (!capable(CAP_LINUX_IMMUTABLE)) {
2216cbff00fSChristoph Hellwig 			ret = -EPERM;
2226cbff00fSChristoph Hellwig 			goto out_unlock;
2236cbff00fSChristoph Hellwig 		}
2246cbff00fSChristoph Hellwig 	}
2256cbff00fSChristoph Hellwig 
2265c57b8b6SDavid Sterba 	if (fsflags & FS_SYNC_FL)
227d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_SYNC;
2286cbff00fSChristoph Hellwig 	else
229d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_SYNC;
2305c57b8b6SDavid Sterba 	if (fsflags & FS_IMMUTABLE_FL)
231d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_IMMUTABLE;
2326cbff00fSChristoph Hellwig 	else
233d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_IMMUTABLE;
2345c57b8b6SDavid Sterba 	if (fsflags & FS_APPEND_FL)
235d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_APPEND;
2366cbff00fSChristoph Hellwig 	else
237d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_APPEND;
2385c57b8b6SDavid Sterba 	if (fsflags & FS_NODUMP_FL)
239d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NODUMP;
2406cbff00fSChristoph Hellwig 	else
241d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NODUMP;
2425c57b8b6SDavid Sterba 	if (fsflags & FS_NOATIME_FL)
243d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NOATIME;
2446cbff00fSChristoph Hellwig 	else
245d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NOATIME;
2465c57b8b6SDavid Sterba 	if (fsflags & FS_DIRSYNC_FL)
247d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_DIRSYNC;
2486cbff00fSChristoph Hellwig 	else
249d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_DIRSYNC;
2505c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOW_FL) {
2517e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2527e97b8daSDavid Sterba 			/*
2537e97b8daSDavid Sterba 			 * It's safe to turn csums off here, no extents exist.
2547e97b8daSDavid Sterba 			 * Otherwise we want the flag to reflect the real COW
2557e97b8daSDavid Sterba 			 * status of the file and will not set it.
2567e97b8daSDavid Sterba 			 */
2577e97b8daSDavid Sterba 			if (inode->i_size == 0)
258d2b8fcfeSAnand Jain 				binode_flags |= BTRFS_INODE_NODATACOW |
259d2b8fcfeSAnand Jain 						BTRFS_INODE_NODATASUM;
2607e97b8daSDavid Sterba 		} else {
261d2b8fcfeSAnand Jain 			binode_flags |= BTRFS_INODE_NODATACOW;
2627e97b8daSDavid Sterba 		}
2637e97b8daSDavid Sterba 	} else {
2647e97b8daSDavid Sterba 		/*
26501327610SNicholas D Steeves 		 * Revert back under same assumptions as above
2667e97b8daSDavid Sterba 		 */
2677e97b8daSDavid Sterba 		if (S_ISREG(mode)) {
2687e97b8daSDavid Sterba 			if (inode->i_size == 0)
269d2b8fcfeSAnand Jain 				binode_flags &= ~(BTRFS_INODE_NODATACOW |
270d2b8fcfeSAnand Jain 						  BTRFS_INODE_NODATASUM);
2717e97b8daSDavid Sterba 		} else {
272d2b8fcfeSAnand Jain 			binode_flags &= ~BTRFS_INODE_NODATACOW;
2737e97b8daSDavid Sterba 		}
2747e97b8daSDavid Sterba 	}
2756cbff00fSChristoph Hellwig 
27675e7cb7fSLiu Bo 	/*
27775e7cb7fSLiu Bo 	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
27875e7cb7fSLiu Bo 	 * flag may be changed automatically if compression code won't make
27975e7cb7fSLiu Bo 	 * things smaller.
28075e7cb7fSLiu Bo 	 */
2815c57b8b6SDavid Sterba 	if (fsflags & FS_NOCOMP_FL) {
282d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_COMPRESS;
283d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_NOCOMPRESS;
2845c57b8b6SDavid Sterba 	} else if (fsflags & FS_COMPR_FL) {
28563541927SFilipe David Borba Manana 
286eede2bf3SOmar Sandoval 		if (IS_SWAPFILE(inode)) {
287eede2bf3SOmar Sandoval 			ret = -ETXTBSY;
288eede2bf3SOmar Sandoval 			goto out_unlock;
289eede2bf3SOmar Sandoval 		}
290eede2bf3SOmar Sandoval 
291d2b8fcfeSAnand Jain 		binode_flags |= BTRFS_INODE_COMPRESS;
292d2b8fcfeSAnand Jain 		binode_flags &= ~BTRFS_INODE_NOCOMPRESS;
29363541927SFilipe David Borba Manana 
29493370509SDavid Sterba 		comp = btrfs_compress_type2str(fs_info->compress_type);
29593370509SDavid Sterba 		if (!comp || comp[0] == 0)
29693370509SDavid Sterba 			comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
297ebcb904dSLi Zefan 	} else {
298d2b8fcfeSAnand Jain 		binode_flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
29975e7cb7fSLiu Bo 	}
3006cbff00fSChristoph Hellwig 
301ff9fef55SAnand Jain 	/*
302ff9fef55SAnand Jain 	 * 1 for inode item
303ff9fef55SAnand Jain 	 * 2 for properties
304ff9fef55SAnand Jain 	 */
305ff9fef55SAnand Jain 	trans = btrfs_start_transaction(root, 3);
306f062abf0SLi Zefan 	if (IS_ERR(trans)) {
307f062abf0SLi Zefan 		ret = PTR_ERR(trans);
308d2b8fcfeSAnand Jain 		goto out_unlock;
309f062abf0SLi Zefan 	}
3106cbff00fSChristoph Hellwig 
311ff9fef55SAnand Jain 	if (comp) {
312ff9fef55SAnand Jain 		ret = btrfs_set_prop(trans, inode, "btrfs.compression", comp,
313ff9fef55SAnand Jain 				     strlen(comp), 0);
314ff9fef55SAnand Jain 		if (ret) {
315ff9fef55SAnand Jain 			btrfs_abort_transaction(trans, ret);
316ff9fef55SAnand Jain 			goto out_end_trans;
317ff9fef55SAnand Jain 		}
318ff9fef55SAnand Jain 		set_bit(BTRFS_INODE_COPY_EVERYTHING,
319ff9fef55SAnand Jain 			&BTRFS_I(inode)->runtime_flags);
320ff9fef55SAnand Jain 	} else {
321ff9fef55SAnand Jain 		ret = btrfs_set_prop(trans, inode, "btrfs.compression", NULL,
322ff9fef55SAnand Jain 				     0, 0);
323ff9fef55SAnand Jain 		if (ret && ret != -ENODATA) {
324ff9fef55SAnand Jain 			btrfs_abort_transaction(trans, ret);
325ff9fef55SAnand Jain 			goto out_end_trans;
326ff9fef55SAnand Jain 		}
327ff9fef55SAnand Jain 	}
328ff9fef55SAnand Jain 
329d2b8fcfeSAnand Jain 	binode->flags = binode_flags;
3307b6a221eSDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
3310c4d2d95SJosef Bacik 	inode_inc_iversion(inode);
332c2050a45SDeepa Dinamani 	inode->i_ctime = current_time(inode);
3336cbff00fSChristoph Hellwig 	ret = btrfs_update_inode(trans, root, inode);
3346cbff00fSChristoph Hellwig 
335ff9fef55SAnand Jain  out_end_trans:
3363a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
3376cbff00fSChristoph Hellwig  out_unlock:
3385955102cSAl Viro 	inode_unlock(inode);
339e7848683SJan Kara 	mnt_drop_write_file(file);
3402d4e6f6aSliubo 	return ret;
3416cbff00fSChristoph Hellwig }
3426cbff00fSChristoph Hellwig 
34319f93b3cSDavid Sterba /*
34419f93b3cSDavid Sterba  * Translate btrfs internal inode flags to xflags as expected by the
34519f93b3cSDavid Sterba  * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are
34619f93b3cSDavid Sterba  * silently dropped.
34719f93b3cSDavid Sterba  */
34819f93b3cSDavid Sterba static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags)
34919f93b3cSDavid Sterba {
35019f93b3cSDavid Sterba 	unsigned int xflags = 0;
35119f93b3cSDavid Sterba 
35219f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_APPEND)
35319f93b3cSDavid Sterba 		xflags |= FS_XFLAG_APPEND;
35419f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_IMMUTABLE)
35519f93b3cSDavid Sterba 		xflags |= FS_XFLAG_IMMUTABLE;
35619f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_NOATIME)
35719f93b3cSDavid Sterba 		xflags |= FS_XFLAG_NOATIME;
35819f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_NODUMP)
35919f93b3cSDavid Sterba 		xflags |= FS_XFLAG_NODUMP;
36019f93b3cSDavid Sterba 	if (flags & BTRFS_INODE_SYNC)
36119f93b3cSDavid Sterba 		xflags |= FS_XFLAG_SYNC;
36219f93b3cSDavid Sterba 
36319f93b3cSDavid Sterba 	return xflags;
36419f93b3cSDavid Sterba }
36519f93b3cSDavid Sterba 
36619f93b3cSDavid Sterba /* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */
36719f93b3cSDavid Sterba static int check_xflags(unsigned int flags)
36819f93b3cSDavid Sterba {
36919f93b3cSDavid Sterba 	if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME |
37019f93b3cSDavid Sterba 		      FS_XFLAG_NODUMP | FS_XFLAG_SYNC))
37119f93b3cSDavid Sterba 		return -EOPNOTSUPP;
37219f93b3cSDavid Sterba 	return 0;
37319f93b3cSDavid Sterba }
37419f93b3cSDavid Sterba 
375e4202ac9SDavid Sterba /*
376e4202ac9SDavid Sterba  * Set the xflags from the internal inode flags. The remaining items of fsxattr
377e4202ac9SDavid Sterba  * are zeroed.
378e4202ac9SDavid Sterba  */
379e4202ac9SDavid Sterba static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg)
380e4202ac9SDavid Sterba {
381e4202ac9SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(file_inode(file));
382e4202ac9SDavid Sterba 	struct fsxattr fa;
383e4202ac9SDavid Sterba 
384e4202ac9SDavid Sterba 	memset(&fa, 0, sizeof(fa));
385e4202ac9SDavid Sterba 	fa.fsx_xflags = btrfs_inode_flags_to_xflags(binode->flags);
386e4202ac9SDavid Sterba 
387e4202ac9SDavid Sterba 	if (copy_to_user(arg, &fa, sizeof(fa)))
388e4202ac9SDavid Sterba 		return -EFAULT;
389e4202ac9SDavid Sterba 
390e4202ac9SDavid Sterba 	return 0;
391e4202ac9SDavid Sterba }
392e4202ac9SDavid Sterba 
393025f2121SDavid Sterba static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg)
394025f2121SDavid Sterba {
395025f2121SDavid Sterba 	struct inode *inode = file_inode(file);
396025f2121SDavid Sterba 	struct btrfs_inode *binode = BTRFS_I(inode);
397025f2121SDavid Sterba 	struct btrfs_root *root = binode->root;
398025f2121SDavid Sterba 	struct btrfs_trans_handle *trans;
399025f2121SDavid Sterba 	struct fsxattr fa;
400025f2121SDavid Sterba 	unsigned old_flags;
401025f2121SDavid Sterba 	unsigned old_i_flags;
402025f2121SDavid Sterba 	int ret = 0;
403025f2121SDavid Sterba 
404025f2121SDavid Sterba 	if (!inode_owner_or_capable(inode))
405025f2121SDavid Sterba 		return -EPERM;
406025f2121SDavid Sterba 
407025f2121SDavid Sterba 	if (btrfs_root_readonly(root))
408025f2121SDavid Sterba 		return -EROFS;
409025f2121SDavid Sterba 
410025f2121SDavid Sterba 	memset(&fa, 0, sizeof(fa));
411025f2121SDavid Sterba 	if (copy_from_user(&fa, arg, sizeof(fa)))
412025f2121SDavid Sterba 		return -EFAULT;
413025f2121SDavid Sterba 
414025f2121SDavid Sterba 	ret = check_xflags(fa.fsx_xflags);
415025f2121SDavid Sterba 	if (ret)
416025f2121SDavid Sterba 		return ret;
417025f2121SDavid Sterba 
418025f2121SDavid Sterba 	if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0)
419025f2121SDavid Sterba 		return -EOPNOTSUPP;
420025f2121SDavid Sterba 
421025f2121SDavid Sterba 	ret = mnt_want_write_file(file);
422025f2121SDavid Sterba 	if (ret)
423025f2121SDavid Sterba 		return ret;
424025f2121SDavid Sterba 
425025f2121SDavid Sterba 	inode_lock(inode);
426025f2121SDavid Sterba 
427025f2121SDavid Sterba 	old_flags = binode->flags;
428025f2121SDavid Sterba 	old_i_flags = inode->i_flags;
429025f2121SDavid Sterba 
430025f2121SDavid Sterba 	/* We need the capabilities to change append-only or immutable inode */
431025f2121SDavid Sterba 	if (((old_flags & (BTRFS_INODE_APPEND | BTRFS_INODE_IMMUTABLE)) ||
432025f2121SDavid Sterba 	     (fa.fsx_xflags & (FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE))) &&
433025f2121SDavid Sterba 	    !capable(CAP_LINUX_IMMUTABLE)) {
434025f2121SDavid Sterba 		ret = -EPERM;
435025f2121SDavid Sterba 		goto out_unlock;
436025f2121SDavid Sterba 	}
437025f2121SDavid Sterba 
438025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_SYNC)
439025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_SYNC;
440025f2121SDavid Sterba 	else
441025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_SYNC;
442025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE)
443025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_IMMUTABLE;
444025f2121SDavid Sterba 	else
445025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_IMMUTABLE;
446025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_APPEND)
447025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_APPEND;
448025f2121SDavid Sterba 	else
449025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_APPEND;
450025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_NODUMP)
451025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_NODUMP;
452025f2121SDavid Sterba 	else
453025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NODUMP;
454025f2121SDavid Sterba 	if (fa.fsx_xflags & FS_XFLAG_NOATIME)
455025f2121SDavid Sterba 		binode->flags |= BTRFS_INODE_NOATIME;
456025f2121SDavid Sterba 	else
457025f2121SDavid Sterba 		binode->flags &= ~BTRFS_INODE_NOATIME;
458025f2121SDavid Sterba 
459025f2121SDavid Sterba 	/* 1 item for the inode */
460025f2121SDavid Sterba 	trans = btrfs_start_transaction(root, 1);
461025f2121SDavid Sterba 	if (IS_ERR(trans)) {
462025f2121SDavid Sterba 		ret = PTR_ERR(trans);
463025f2121SDavid Sterba 		goto out_unlock;
464025f2121SDavid Sterba 	}
465025f2121SDavid Sterba 
466025f2121SDavid Sterba 	btrfs_sync_inode_flags_to_i_flags(inode);
467025f2121SDavid Sterba 	inode_inc_iversion(inode);
468025f2121SDavid Sterba 	inode->i_ctime = current_time(inode);
469025f2121SDavid Sterba 	ret = btrfs_update_inode(trans, root, inode);
470025f2121SDavid Sterba 
471025f2121SDavid Sterba 	btrfs_end_transaction(trans);
472025f2121SDavid Sterba 
473025f2121SDavid Sterba out_unlock:
474025f2121SDavid Sterba 	if (ret) {
475025f2121SDavid Sterba 		binode->flags = old_flags;
476025f2121SDavid Sterba 		inode->i_flags = old_i_flags;
477025f2121SDavid Sterba 	}
478025f2121SDavid Sterba 
479025f2121SDavid Sterba 	inode_unlock(inode);
480025f2121SDavid Sterba 	mnt_drop_write_file(file);
481025f2121SDavid Sterba 
482025f2121SDavid Sterba 	return ret;
483025f2121SDavid Sterba }
484025f2121SDavid Sterba 
4856cbff00fSChristoph Hellwig static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
4866cbff00fSChristoph Hellwig {
487496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
4886cbff00fSChristoph Hellwig 
4896cbff00fSChristoph Hellwig 	return put_user(inode->i_generation, arg);
4906cbff00fSChristoph Hellwig }
491f46b5a66SChristoph Hellwig 
492f7039b1dSLi Dongyang static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
493f7039b1dSLi Dongyang {
4940b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
4950b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
496f7039b1dSLi Dongyang 	struct btrfs_device *device;
497f7039b1dSLi Dongyang 	struct request_queue *q;
498f7039b1dSLi Dongyang 	struct fstrim_range range;
499f7039b1dSLi Dongyang 	u64 minlen = ULLONG_MAX;
500f7039b1dSLi Dongyang 	u64 num_devices = 0;
501f7039b1dSLi Dongyang 	int ret;
502f7039b1dSLi Dongyang 
503f7039b1dSLi Dongyang 	if (!capable(CAP_SYS_ADMIN))
504f7039b1dSLi Dongyang 		return -EPERM;
505f7039b1dSLi Dongyang 
506f35f06c3SFilipe Manana 	/*
507f35f06c3SFilipe Manana 	 * If the fs is mounted with nologreplay, which requires it to be
508f35f06c3SFilipe Manana 	 * mounted in RO mode as well, we can not allow discard on free space
509f35f06c3SFilipe Manana 	 * inside block groups, because log trees refer to extents that are not
510f35f06c3SFilipe Manana 	 * pinned in a block group's free space cache (pinning the extents is
511f35f06c3SFilipe Manana 	 * precisely the first phase of replaying a log tree).
512f35f06c3SFilipe Manana 	 */
513f35f06c3SFilipe Manana 	if (btrfs_test_opt(fs_info, NOLOGREPLAY))
514f35f06c3SFilipe Manana 		return -EROFS;
515f35f06c3SFilipe Manana 
5161f78160cSXiao Guangrong 	rcu_read_lock();
5171f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
5181f78160cSXiao Guangrong 				dev_list) {
519f7039b1dSLi Dongyang 		if (!device->bdev)
520f7039b1dSLi Dongyang 			continue;
521f7039b1dSLi Dongyang 		q = bdev_get_queue(device->bdev);
522f7039b1dSLi Dongyang 		if (blk_queue_discard(q)) {
523f7039b1dSLi Dongyang 			num_devices++;
52450d0446eSSeraphime Kirkovski 			minlen = min_t(u64, q->limits.discard_granularity,
525f7039b1dSLi Dongyang 				     minlen);
526f7039b1dSLi Dongyang 		}
527f7039b1dSLi Dongyang 	}
5281f78160cSXiao Guangrong 	rcu_read_unlock();
529f4c697e6SLukas Czerner 
530f7039b1dSLi Dongyang 	if (!num_devices)
531f7039b1dSLi Dongyang 		return -EOPNOTSUPP;
532f7039b1dSLi Dongyang 	if (copy_from_user(&range, arg, sizeof(range)))
533f7039b1dSLi Dongyang 		return -EFAULT;
5346ba9fc8eSQu Wenruo 
5356ba9fc8eSQu Wenruo 	/*
5366ba9fc8eSQu Wenruo 	 * NOTE: Don't truncate the range using super->total_bytes.  Bytenr of
5376ba9fc8eSQu Wenruo 	 * block group is in the logical address space, which can be any
5386ba9fc8eSQu Wenruo 	 * sectorsize aligned bytenr in  the range [0, U64_MAX].
5396ba9fc8eSQu Wenruo 	 */
5406ba9fc8eSQu Wenruo 	if (range.len < fs_info->sb->s_blocksize)
541f4c697e6SLukas Czerner 		return -EINVAL;
542f7039b1dSLi Dongyang 
543f7039b1dSLi Dongyang 	range.minlen = max(range.minlen, minlen);
5442ff7e61eSJeff Mahoney 	ret = btrfs_trim_fs(fs_info, &range);
545f7039b1dSLi Dongyang 	if (ret < 0)
546f7039b1dSLi Dongyang 		return ret;
547f7039b1dSLi Dongyang 
548f7039b1dSLi Dongyang 	if (copy_to_user(arg, &range, sizeof(range)))
549f7039b1dSLi Dongyang 		return -EFAULT;
550f7039b1dSLi Dongyang 
551f7039b1dSLi Dongyang 	return 0;
552f7039b1dSLi Dongyang }
553f7039b1dSLi Dongyang 
554dd5f9615SStefan Behrens int btrfs_is_empty_uuid(u8 *uuid)
555dd5f9615SStefan Behrens {
55646e0f66aSChris Mason 	int i;
55746e0f66aSChris Mason 
55846e0f66aSChris Mason 	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
55946e0f66aSChris Mason 		if (uuid[i])
56046e0f66aSChris Mason 			return 0;
56146e0f66aSChris Mason 	}
56246e0f66aSChris Mason 	return 1;
563dd5f9615SStefan Behrens }
564dd5f9615SStefan Behrens 
565d5c12070SMiao Xie static noinline int create_subvol(struct inode *dir,
566cb8e7090SChristoph Hellwig 				  struct dentry *dentry,
56752f75f4fSDavid Sterba 				  const char *name, int namelen,
5686f72c7e2SArne Jansen 				  u64 *async_transid,
5698696c533SMiao Xie 				  struct btrfs_qgroup_inherit *inherit)
570f46b5a66SChristoph Hellwig {
5710b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
572f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
573f46b5a66SChristoph Hellwig 	struct btrfs_key key;
57449a3c4d9SDavid Sterba 	struct btrfs_root_item *root_item;
575f46b5a66SChristoph Hellwig 	struct btrfs_inode_item *inode_item;
576f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
577d5c12070SMiao Xie 	struct btrfs_root *root = BTRFS_I(dir)->root;
57876dda93cSYan, Zheng 	struct btrfs_root *new_root;
579d5c12070SMiao Xie 	struct btrfs_block_rsv block_rsv;
58095582b00SDeepa Dinamani 	struct timespec64 cur_time = current_time(dir);
5815662344bSTsutomu Itoh 	struct inode *inode;
582f46b5a66SChristoph Hellwig 	int ret;
583f46b5a66SChristoph Hellwig 	int err;
584f46b5a66SChristoph Hellwig 	u64 objectid;
585f46b5a66SChristoph Hellwig 	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
5863de4586cSChris Mason 	u64 index = 0;
5878ea05e3aSAlexander Block 	uuid_le new_uuid;
588f46b5a66SChristoph Hellwig 
58949a3c4d9SDavid Sterba 	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
59049a3c4d9SDavid Sterba 	if (!root_item)
59149a3c4d9SDavid Sterba 		return -ENOMEM;
59249a3c4d9SDavid Sterba 
5930b246afaSJeff Mahoney 	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
5942fbe8c8aSAl Viro 	if (ret)
59549a3c4d9SDavid Sterba 		goto fail_free;
5966a912213SJosef Bacik 
597e09fe2d2SQu Wenruo 	/*
598e09fe2d2SQu Wenruo 	 * Don't create subvolume whose level is not zero. Or qgroup will be
59901327610SNicholas D Steeves 	 * screwed up since it assumes subvolume qgroup's level to be 0.
600e09fe2d2SQu Wenruo 	 */
60149a3c4d9SDavid Sterba 	if (btrfs_qgroup_level(objectid)) {
60249a3c4d9SDavid Sterba 		ret = -ENOSPC;
60349a3c4d9SDavid Sterba 		goto fail_free;
60449a3c4d9SDavid Sterba 	}
605e09fe2d2SQu Wenruo 
606d5c12070SMiao Xie 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
6079ed74f2dSJosef Bacik 	/*
608d5c12070SMiao Xie 	 * The same as the snapshot creation, please see the comment
609d5c12070SMiao Xie 	 * of create_snapshot().
6109ed74f2dSJosef Bacik 	 */
611c4c129dbSGu JinXiang 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
612d5c12070SMiao Xie 	if (ret)
61349a3c4d9SDavid Sterba 		goto fail_free;
614f46b5a66SChristoph Hellwig 
615d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
616d5c12070SMiao Xie 	if (IS_ERR(trans)) {
617d5c12070SMiao Xie 		ret = PTR_ERR(trans);
6187775c818SDavid Sterba 		btrfs_subvolume_release_metadata(fs_info, &block_rsv);
61949a3c4d9SDavid Sterba 		goto fail_free;
620d5c12070SMiao Xie 	}
621d5c12070SMiao Xie 	trans->block_rsv = &block_rsv;
622d5c12070SMiao Xie 	trans->bytes_reserved = block_rsv.size;
623f46b5a66SChristoph Hellwig 
624a9377422SLu Fengqi 	ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
6256f72c7e2SArne Jansen 	if (ret)
6266f72c7e2SArne Jansen 		goto fail;
6276f72c7e2SArne Jansen 
6284d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
6298e8a1e31SJosef Bacik 	if (IS_ERR(leaf)) {
6308e8a1e31SJosef Bacik 		ret = PTR_ERR(leaf);
6318e8a1e31SJosef Bacik 		goto fail;
6328e8a1e31SJosef Bacik 	}
633f46b5a66SChristoph Hellwig 
634f46b5a66SChristoph Hellwig 	btrfs_mark_buffer_dirty(leaf);
635f46b5a66SChristoph Hellwig 
63649a3c4d9SDavid Sterba 	inode_item = &root_item->inode;
6373cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
6383cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
6393cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
640da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
6410b246afaSJeff Mahoney 				     fs_info->nodesize);
6423cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
643f46b5a66SChristoph Hellwig 
64449a3c4d9SDavid Sterba 	btrfs_set_root_flags(root_item, 0);
64549a3c4d9SDavid Sterba 	btrfs_set_root_limit(root_item, 0);
6463cae210fSQu Wenruo 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
64708fe4db1SLi Zefan 
64849a3c4d9SDavid Sterba 	btrfs_set_root_bytenr(root_item, leaf->start);
64949a3c4d9SDavid Sterba 	btrfs_set_root_generation(root_item, trans->transid);
65049a3c4d9SDavid Sterba 	btrfs_set_root_level(root_item, 0);
65149a3c4d9SDavid Sterba 	btrfs_set_root_refs(root_item, 1);
65249a3c4d9SDavid Sterba 	btrfs_set_root_used(root_item, leaf->len);
65349a3c4d9SDavid Sterba 	btrfs_set_root_last_snapshot(root_item, 0);
654f46b5a66SChristoph Hellwig 
65549a3c4d9SDavid Sterba 	btrfs_set_root_generation_v2(root_item,
65649a3c4d9SDavid Sterba 			btrfs_root_generation(root_item));
6578ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
65849a3c4d9SDavid Sterba 	memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
65949a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
66049a3c4d9SDavid Sterba 	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
66149a3c4d9SDavid Sterba 	root_item->ctime = root_item->otime;
66249a3c4d9SDavid Sterba 	btrfs_set_root_ctransid(root_item, trans->transid);
66349a3c4d9SDavid Sterba 	btrfs_set_root_otransid(root_item, trans->transid);
664f46b5a66SChristoph Hellwig 
665925baeddSChris Mason 	btrfs_tree_unlock(leaf);
666f46b5a66SChristoph Hellwig 	free_extent_buffer(leaf);
667f46b5a66SChristoph Hellwig 	leaf = NULL;
668f46b5a66SChristoph Hellwig 
66949a3c4d9SDavid Sterba 	btrfs_set_root_dirid(root_item, new_dirid);
670f46b5a66SChristoph Hellwig 
671f46b5a66SChristoph Hellwig 	key.objectid = objectid;
6725d4f98a2SYan Zheng 	key.offset = 0;
673962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
6740b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
67549a3c4d9SDavid Sterba 				root_item);
676f46b5a66SChristoph Hellwig 	if (ret)
677f46b5a66SChristoph Hellwig 		goto fail;
678f46b5a66SChristoph Hellwig 
67976dda93cSYan, Zheng 	key.offset = (u64)-1;
6800b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &key);
68179787eaaSJeff Mahoney 	if (IS_ERR(new_root)) {
68279787eaaSJeff Mahoney 		ret = PTR_ERR(new_root);
68366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
68479787eaaSJeff Mahoney 		goto fail;
68579787eaaSJeff Mahoney 	}
68676dda93cSYan, Zheng 
68776dda93cSYan, Zheng 	btrfs_record_root_in_trans(trans, new_root);
68876dda93cSYan, Zheng 
68963541927SFilipe David Borba Manana 	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
690ce598979SMark Fasheh 	if (ret) {
691ce598979SMark Fasheh 		/* We potentially lose an unused inode item here */
69266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
693ce598979SMark Fasheh 		goto fail;
694ce598979SMark Fasheh 	}
695ce598979SMark Fasheh 
696f32e48e9SChandan Rajendra 	mutex_lock(&new_root->objectid_mutex);
697f32e48e9SChandan Rajendra 	new_root->highest_objectid = new_dirid;
698f32e48e9SChandan Rajendra 	mutex_unlock(&new_root->objectid_mutex);
699f32e48e9SChandan Rajendra 
700f46b5a66SChristoph Hellwig 	/*
701f46b5a66SChristoph Hellwig 	 * insert the directory item
702f46b5a66SChristoph Hellwig 	 */
703877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
70479787eaaSJeff Mahoney 	if (ret) {
70566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
70679787eaaSJeff Mahoney 		goto fail;
70779787eaaSJeff Mahoney 	}
7083de4586cSChris Mason 
709684572dfSLu Fengqi 	ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
7103de4586cSChris Mason 				    BTRFS_FT_DIR, index);
71179787eaaSJeff Mahoney 	if (ret) {
71266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
713f46b5a66SChristoph Hellwig 		goto fail;
71479787eaaSJeff Mahoney 	}
7150660b5afSChris Mason 
7166ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
71752c26179SYan Zheng 	ret = btrfs_update_inode(trans, root, dir);
71852c26179SYan Zheng 	BUG_ON(ret);
71952c26179SYan Zheng 
7206025c19fSLu Fengqi 	ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
7214a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
7220660b5afSChris Mason 	BUG_ON(ret);
7230660b5afSChris Mason 
724cdb345a8SLu Fengqi 	ret = btrfs_uuid_tree_add(trans, root_item->uuid,
7256bccf3abSJeff Mahoney 				  BTRFS_UUID_KEY_SUBVOL, objectid);
726dd5f9615SStefan Behrens 	if (ret)
72766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
728dd5f9615SStefan Behrens 
729f46b5a66SChristoph Hellwig fail:
73049a3c4d9SDavid Sterba 	kfree(root_item);
731d5c12070SMiao Xie 	trans->block_rsv = NULL;
732d5c12070SMiao Xie 	trans->bytes_reserved = 0;
7337775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
734de6e8200SLiu Bo 
73572fd032eSSage Weil 	if (async_transid) {
73672fd032eSSage Weil 		*async_transid = trans->transid;
7373a45bb20SJeff Mahoney 		err = btrfs_commit_transaction_async(trans, 1);
73800d71c9cSMiao Xie 		if (err)
7393a45bb20SJeff Mahoney 			err = btrfs_commit_transaction(trans);
74072fd032eSSage Weil 	} else {
7413a45bb20SJeff Mahoney 		err = btrfs_commit_transaction(trans);
74272fd032eSSage Weil 	}
743f46b5a66SChristoph Hellwig 	if (err && !ret)
744f46b5a66SChristoph Hellwig 		ret = err;
7451a65e24bSChris Mason 
7465662344bSTsutomu Itoh 	if (!ret) {
7475662344bSTsutomu Itoh 		inode = btrfs_lookup_dentry(dir, dentry);
748de6e8200SLiu Bo 		if (IS_ERR(inode))
749de6e8200SLiu Bo 			return PTR_ERR(inode);
7505662344bSTsutomu Itoh 		d_instantiate(dentry, inode);
7515662344bSTsutomu Itoh 	}
752f46b5a66SChristoph Hellwig 	return ret;
75349a3c4d9SDavid Sterba 
75449a3c4d9SDavid Sterba fail_free:
75549a3c4d9SDavid Sterba 	kfree(root_item);
75649a3c4d9SDavid Sterba 	return ret;
757f46b5a66SChristoph Hellwig }
758f46b5a66SChristoph Hellwig 
759e9662f70SMiao Xie static int create_snapshot(struct btrfs_root *root, struct inode *dir,
76061d7e4cbSDavid Sterba 			   struct dentry *dentry,
761e9662f70SMiao Xie 			   u64 *async_transid, bool readonly,
762e9662f70SMiao Xie 			   struct btrfs_qgroup_inherit *inherit)
763f46b5a66SChristoph Hellwig {
7640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
7652e4bfab9SYan, Zheng 	struct inode *inode;
766f46b5a66SChristoph Hellwig 	struct btrfs_pending_snapshot *pending_snapshot;
767f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
7682e4bfab9SYan, Zheng 	int ret;
7698ecebf4dSRobbie Ko 	bool snapshot_force_cow = false;
770f46b5a66SChristoph Hellwig 
77127cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
772f46b5a66SChristoph Hellwig 		return -EINVAL;
773f46b5a66SChristoph Hellwig 
774eede2bf3SOmar Sandoval 	if (atomic_read(&root->nr_swapfiles)) {
775eede2bf3SOmar Sandoval 		btrfs_warn(fs_info,
776eede2bf3SOmar Sandoval 			   "cannot snapshot subvolume with active swapfile");
777eede2bf3SOmar Sandoval 		return -ETXTBSY;
778eede2bf3SOmar Sandoval 	}
779eede2bf3SOmar Sandoval 
78023269bf5SDavid Sterba 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
781a1ee7362SDavid Sterba 	if (!pending_snapshot)
782a1ee7362SDavid Sterba 		return -ENOMEM;
783a1ee7362SDavid Sterba 
784b0c0ea63SDavid Sterba 	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
78523269bf5SDavid Sterba 			GFP_KERNEL);
7868546b570SDavid Sterba 	pending_snapshot->path = btrfs_alloc_path();
7878546b570SDavid Sterba 	if (!pending_snapshot->root_item || !pending_snapshot->path) {
788b0c0ea63SDavid Sterba 		ret = -ENOMEM;
789b0c0ea63SDavid Sterba 		goto free_pending;
790b0c0ea63SDavid Sterba 	}
791b0c0ea63SDavid Sterba 
7928ecebf4dSRobbie Ko 	/*
7938ecebf4dSRobbie Ko 	 * Force new buffered writes to reserve space even when NOCOW is
7948ecebf4dSRobbie Ko 	 * possible. This is to avoid later writeback (running dealloc) to
7958ecebf4dSRobbie Ko 	 * fallback to COW mode and unexpectedly fail with ENOSPC.
7968ecebf4dSRobbie Ko 	 */
797ea14b57fSDavid Sterba 	atomic_inc(&root->will_be_snapshotted);
7984e857c58SPeter Zijlstra 	smp_mb__after_atomic();
79945bac0f3SLiu Bo 	/* wait for no snapshot writes */
80045bac0f3SLiu Bo 	wait_event(root->subv_writers->wait,
80145bac0f3SLiu Bo 		   percpu_counter_sum(&root->subv_writers->counter) == 0);
8028257b2dcSMiao Xie 
8033cd24c69SEthan Lien 	ret = btrfs_start_delalloc_snapshot(root);
8046a03843dSMiao Xie 	if (ret)
805a1ee7362SDavid Sterba 		goto dec_and_free;
8066a03843dSMiao Xie 
8078ecebf4dSRobbie Ko 	/*
8088ecebf4dSRobbie Ko 	 * All previous writes have started writeback in NOCOW mode, so now
8098ecebf4dSRobbie Ko 	 * we force future writes to fallback to COW mode during snapshot
8108ecebf4dSRobbie Ko 	 * creation.
8118ecebf4dSRobbie Ko 	 */
8128ecebf4dSRobbie Ko 	atomic_inc(&root->snapshot_force_cow);
8138ecebf4dSRobbie Ko 	snapshot_force_cow = true;
8148ecebf4dSRobbie Ko 
8156374e57aSChris Mason 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
8166a03843dSMiao Xie 
81766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
81866d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_TEMP);
819d5c12070SMiao Xie 	/*
820d5c12070SMiao Xie 	 * 1 - parent dir inode
821d5c12070SMiao Xie 	 * 2 - dir entries
822d5c12070SMiao Xie 	 * 1 - root item
823d5c12070SMiao Xie 	 * 2 - root ref/backref
824d5c12070SMiao Xie 	 * 1 - root of snapshot
825dd5f9615SStefan Behrens 	 * 1 - UUID item
826d5c12070SMiao Xie 	 */
827d5c12070SMiao Xie 	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
828dd5f9615SStefan Behrens 					&pending_snapshot->block_rsv, 8,
829ee3441b4SJeff Mahoney 					false);
830d5c12070SMiao Xie 	if (ret)
831a1ee7362SDavid Sterba 		goto dec_and_free;
832d5c12070SMiao Xie 
833a22285a6SYan, Zheng 	pending_snapshot->dentry = dentry;
834a22285a6SYan, Zheng 	pending_snapshot->root = root;
835b83cc969SLi Zefan 	pending_snapshot->readonly = readonly;
836e9662f70SMiao Xie 	pending_snapshot->dir = dir;
8378696c533SMiao Xie 	pending_snapshot->inherit = inherit;
838a22285a6SYan, Zheng 
839d5c12070SMiao Xie 	trans = btrfs_start_transaction(root, 0);
840a22285a6SYan, Zheng 	if (IS_ERR(trans)) {
841a22285a6SYan, Zheng 		ret = PTR_ERR(trans);
842a22285a6SYan, Zheng 		goto fail;
843a22285a6SYan, Zheng 	}
844a22285a6SYan, Zheng 
8450b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
846a22285a6SYan, Zheng 	list_add(&pending_snapshot->list,
847a22285a6SYan, Zheng 		 &trans->transaction->pending_snapshots);
8480b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
84972fd032eSSage Weil 	if (async_transid) {
85072fd032eSSage Weil 		*async_transid = trans->transid;
8513a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction_async(trans, 1);
85200d71c9cSMiao Xie 		if (ret)
8533a45bb20SJeff Mahoney 			ret = btrfs_commit_transaction(trans);
85472fd032eSSage Weil 	} else {
8553a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
85672fd032eSSage Weil 	}
857aec8030aSMiao Xie 	if (ret)
858c37b2b62SJosef Bacik 		goto fail;
859a22285a6SYan, Zheng 
860a22285a6SYan, Zheng 	ret = pending_snapshot->error;
861f46b5a66SChristoph Hellwig 	if (ret)
8622e4bfab9SYan, Zheng 		goto fail;
863f46b5a66SChristoph Hellwig 
864d3797308SChris Mason 	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
865d3797308SChris Mason 	if (ret)
866d3797308SChris Mason 		goto fail;
867d3797308SChris Mason 
8682b0143b5SDavid Howells 	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
8692e4bfab9SYan, Zheng 	if (IS_ERR(inode)) {
8702e4bfab9SYan, Zheng 		ret = PTR_ERR(inode);
8712e4bfab9SYan, Zheng 		goto fail;
8722e4bfab9SYan, Zheng 	}
8735662344bSTsutomu Itoh 
8742e4bfab9SYan, Zheng 	d_instantiate(dentry, inode);
8752e4bfab9SYan, Zheng 	ret = 0;
8762e4bfab9SYan, Zheng fail:
8777775c818SDavid Sterba 	btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
878a1ee7362SDavid Sterba dec_and_free:
8798ecebf4dSRobbie Ko 	if (snapshot_force_cow)
8808ecebf4dSRobbie Ko 		atomic_dec(&root->snapshot_force_cow);
881ea14b57fSDavid Sterba 	if (atomic_dec_and_test(&root->will_be_snapshotted))
8824625956aSPeter Zijlstra 		wake_up_var(&root->will_be_snapshotted);
883b0c0ea63SDavid Sterba free_pending:
884b0c0ea63SDavid Sterba 	kfree(pending_snapshot->root_item);
8858546b570SDavid Sterba 	btrfs_free_path(pending_snapshot->path);
886a1ee7362SDavid Sterba 	kfree(pending_snapshot);
887a1ee7362SDavid Sterba 
888f46b5a66SChristoph Hellwig 	return ret;
889f46b5a66SChristoph Hellwig }
890f46b5a66SChristoph Hellwig 
8914260f7c7SSage Weil /*  copy of may_delete in fs/namei.c()
8924260f7c7SSage Weil  *	Check whether we can remove a link victim from directory dir, check
8934260f7c7SSage Weil  *  whether the type of victim is right.
8944260f7c7SSage Weil  *  1. We can't do it if dir is read-only (done in permission())
8954260f7c7SSage Weil  *  2. We should have write and exec permissions on dir
8964260f7c7SSage Weil  *  3. We can't remove anything from append-only dir
8974260f7c7SSage Weil  *  4. We can't do anything with immutable dir (done in permission())
8984260f7c7SSage Weil  *  5. If the sticky bit on dir is set we should either
8994260f7c7SSage Weil  *	a. be owner of dir, or
9004260f7c7SSage Weil  *	b. be owner of victim, or
9014260f7c7SSage Weil  *	c. have CAP_FOWNER capability
90201327610SNicholas D Steeves  *  6. If the victim is append-only or immutable we can't do anything with
9034260f7c7SSage Weil  *     links pointing to it.
9044260f7c7SSage Weil  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
9054260f7c7SSage Weil  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
9064260f7c7SSage Weil  *  9. We can't remove a root or mountpoint.
9074260f7c7SSage Weil  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
9084260f7c7SSage Weil  *     nfs_async_unlink().
9094260f7c7SSage Weil  */
9104260f7c7SSage Weil 
9114260f7c7SSage Weil static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
9124260f7c7SSage Weil {
9134260f7c7SSage Weil 	int error;
9144260f7c7SSage Weil 
9152b0143b5SDavid Howells 	if (d_really_is_negative(victim))
9164260f7c7SSage Weil 		return -ENOENT;
9174260f7c7SSage Weil 
9182b0143b5SDavid Howells 	BUG_ON(d_inode(victim->d_parent) != dir);
9194fa6b5ecSJeff Layton 	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
9204260f7c7SSage Weil 
9214260f7c7SSage Weil 	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
9224260f7c7SSage Weil 	if (error)
9234260f7c7SSage Weil 		return error;
9244260f7c7SSage Weil 	if (IS_APPEND(dir))
9254260f7c7SSage Weil 		return -EPERM;
9262b0143b5SDavid Howells 	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
9272b0143b5SDavid Howells 	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
9284260f7c7SSage Weil 		return -EPERM;
9294260f7c7SSage Weil 	if (isdir) {
930e36cb0b8SDavid Howells 		if (!d_is_dir(victim))
9314260f7c7SSage Weil 			return -ENOTDIR;
9324260f7c7SSage Weil 		if (IS_ROOT(victim))
9334260f7c7SSage Weil 			return -EBUSY;
934e36cb0b8SDavid Howells 	} else if (d_is_dir(victim))
9354260f7c7SSage Weil 		return -EISDIR;
9364260f7c7SSage Weil 	if (IS_DEADDIR(dir))
9374260f7c7SSage Weil 		return -ENOENT;
9384260f7c7SSage Weil 	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
9394260f7c7SSage Weil 		return -EBUSY;
9404260f7c7SSage Weil 	return 0;
9414260f7c7SSage Weil }
9424260f7c7SSage Weil 
943cb8e7090SChristoph Hellwig /* copy of may_create in fs/namei.c() */
944cb8e7090SChristoph Hellwig static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
945cb8e7090SChristoph Hellwig {
9462b0143b5SDavid Howells 	if (d_really_is_positive(child))
947cb8e7090SChristoph Hellwig 		return -EEXIST;
948cb8e7090SChristoph Hellwig 	if (IS_DEADDIR(dir))
949cb8e7090SChristoph Hellwig 		return -ENOENT;
950cb8e7090SChristoph Hellwig 	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
951cb8e7090SChristoph Hellwig }
952cb8e7090SChristoph Hellwig 
953cb8e7090SChristoph Hellwig /*
954cb8e7090SChristoph Hellwig  * Create a new subvolume below @parent.  This is largely modeled after
955cb8e7090SChristoph Hellwig  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
956cb8e7090SChristoph Hellwig  * inside this filesystem so it's quite a bit simpler.
957cb8e7090SChristoph Hellwig  */
95892872094SAl Viro static noinline int btrfs_mksubvol(const struct path *parent,
95952f75f4fSDavid Sterba 				   const char *name, int namelen,
96072fd032eSSage Weil 				   struct btrfs_root *snap_src,
9616f72c7e2SArne Jansen 				   u64 *async_transid, bool readonly,
9628696c533SMiao Xie 				   struct btrfs_qgroup_inherit *inherit)
963cb8e7090SChristoph Hellwig {
9642b0143b5SDavid Howells 	struct inode *dir = d_inode(parent->dentry);
9650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
966cb8e7090SChristoph Hellwig 	struct dentry *dentry;
967cb8e7090SChristoph Hellwig 	int error;
968cb8e7090SChristoph Hellwig 
96900235411SAl Viro 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
97000235411SAl Viro 	if (error == -EINTR)
97100235411SAl Viro 		return error;
972cb8e7090SChristoph Hellwig 
973cb8e7090SChristoph Hellwig 	dentry = lookup_one_len(name, parent->dentry, namelen);
974cb8e7090SChristoph Hellwig 	error = PTR_ERR(dentry);
975cb8e7090SChristoph Hellwig 	if (IS_ERR(dentry))
976cb8e7090SChristoph Hellwig 		goto out_unlock;
977cb8e7090SChristoph Hellwig 
97876dda93cSYan, Zheng 	error = btrfs_may_create(dir, dentry);
979cb8e7090SChristoph Hellwig 	if (error)
980a874a63eSLiu Bo 		goto out_dput;
981cb8e7090SChristoph Hellwig 
9829c52057cSChris Mason 	/*
9839c52057cSChris Mason 	 * even if this name doesn't exist, we may get hash collisions.
9849c52057cSChris Mason 	 * check for them now when we can safely fail
9859c52057cSChris Mason 	 */
9869c52057cSChris Mason 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
9879c52057cSChris Mason 					       dir->i_ino, name,
9889c52057cSChris Mason 					       namelen);
9899c52057cSChris Mason 	if (error)
9909c52057cSChris Mason 		goto out_dput;
9919c52057cSChris Mason 
9920b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
99376dda93cSYan, Zheng 
99476dda93cSYan, Zheng 	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
99576dda93cSYan, Zheng 		goto out_up_read;
99676dda93cSYan, Zheng 
9973de4586cSChris Mason 	if (snap_src) {
99861d7e4cbSDavid Sterba 		error = create_snapshot(snap_src, dir, dentry,
9996f72c7e2SArne Jansen 					async_transid, readonly, inherit);
10003de4586cSChris Mason 	} else {
1001d5c12070SMiao Xie 		error = create_subvol(dir, dentry, name, namelen,
1002d5c12070SMiao Xie 				      async_transid, inherit);
10033de4586cSChris Mason 	}
100476dda93cSYan, Zheng 	if (!error)
100576dda93cSYan, Zheng 		fsnotify_mkdir(dir, dentry);
100676dda93cSYan, Zheng out_up_read:
10070b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
1008cb8e7090SChristoph Hellwig out_dput:
1009cb8e7090SChristoph Hellwig 	dput(dentry);
1010cb8e7090SChristoph Hellwig out_unlock:
10115955102cSAl Viro 	inode_unlock(dir);
1012cb8e7090SChristoph Hellwig 	return error;
1013cb8e7090SChristoph Hellwig }
1014cb8e7090SChristoph Hellwig 
10154cb5300bSChris Mason /*
10164cb5300bSChris Mason  * When we're defragging a range, we don't want to kick it off again
10174cb5300bSChris Mason  * if it is really just waiting for delalloc to send it down.
10184cb5300bSChris Mason  * If we find a nice big extent or delalloc range for the bytes in the
10194cb5300bSChris Mason  * file you want to defrag, we return 0 to let you know to skip this
10204cb5300bSChris Mason  * part of the file
10214cb5300bSChris Mason  */
1022aab110abSDavid Sterba static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
10234cb5300bSChris Mason {
10244cb5300bSChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10254cb5300bSChris Mason 	struct extent_map *em = NULL;
10264cb5300bSChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10274cb5300bSChris Mason 	u64 end;
10284cb5300bSChris Mason 
10294cb5300bSChris Mason 	read_lock(&em_tree->lock);
103009cbfeafSKirill A. Shutemov 	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
10314cb5300bSChris Mason 	read_unlock(&em_tree->lock);
10324cb5300bSChris Mason 
10334cb5300bSChris Mason 	if (em) {
10344cb5300bSChris Mason 		end = extent_map_end(em);
10354cb5300bSChris Mason 		free_extent_map(em);
10364cb5300bSChris Mason 		if (end - offset > thresh)
10374cb5300bSChris Mason 			return 0;
10384cb5300bSChris Mason 	}
10394cb5300bSChris Mason 	/* if we already have a nice delalloc here, just stop */
10404cb5300bSChris Mason 	thresh /= 2;
10414cb5300bSChris Mason 	end = count_range_bits(io_tree, &offset, offset + thresh,
10424cb5300bSChris Mason 			       thresh, EXTENT_DELALLOC, 1);
10434cb5300bSChris Mason 	if (end >= thresh)
10444cb5300bSChris Mason 		return 0;
10454cb5300bSChris Mason 	return 1;
10464cb5300bSChris Mason }
10474cb5300bSChris Mason 
10484cb5300bSChris Mason /*
10494cb5300bSChris Mason  * helper function to walk through a file and find extents
10504cb5300bSChris Mason  * newer than a specific transid, and smaller than thresh.
10514cb5300bSChris Mason  *
10524cb5300bSChris Mason  * This is used by the defragging code to find new and small
10534cb5300bSChris Mason  * extents
10544cb5300bSChris Mason  */
10554cb5300bSChris Mason static int find_new_extents(struct btrfs_root *root,
10564cb5300bSChris Mason 			    struct inode *inode, u64 newer_than,
1057aab110abSDavid Sterba 			    u64 *off, u32 thresh)
10584cb5300bSChris Mason {
10594cb5300bSChris Mason 	struct btrfs_path *path;
10604cb5300bSChris Mason 	struct btrfs_key min_key;
10614cb5300bSChris Mason 	struct extent_buffer *leaf;
10624cb5300bSChris Mason 	struct btrfs_file_extent_item *extent;
10634cb5300bSChris Mason 	int type;
10644cb5300bSChris Mason 	int ret;
10654a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
10664cb5300bSChris Mason 
10674cb5300bSChris Mason 	path = btrfs_alloc_path();
10684cb5300bSChris Mason 	if (!path)
10694cb5300bSChris Mason 		return -ENOMEM;
10704cb5300bSChris Mason 
1071a4689d2bSDavid Sterba 	min_key.objectid = ino;
10724cb5300bSChris Mason 	min_key.type = BTRFS_EXTENT_DATA_KEY;
10734cb5300bSChris Mason 	min_key.offset = *off;
10744cb5300bSChris Mason 
10754cb5300bSChris Mason 	while (1) {
10766174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &min_key, path, newer_than);
10774cb5300bSChris Mason 		if (ret != 0)
10784cb5300bSChris Mason 			goto none;
1079f094c9bdSFilipe Manana process_slot:
1080a4689d2bSDavid Sterba 		if (min_key.objectid != ino)
10814cb5300bSChris Mason 			goto none;
10824cb5300bSChris Mason 		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
10834cb5300bSChris Mason 			goto none;
10844cb5300bSChris Mason 
10854cb5300bSChris Mason 		leaf = path->nodes[0];
10864cb5300bSChris Mason 		extent = btrfs_item_ptr(leaf, path->slots[0],
10874cb5300bSChris Mason 					struct btrfs_file_extent_item);
10884cb5300bSChris Mason 
10894cb5300bSChris Mason 		type = btrfs_file_extent_type(leaf, extent);
10904cb5300bSChris Mason 		if (type == BTRFS_FILE_EXTENT_REG &&
10914cb5300bSChris Mason 		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
10924cb5300bSChris Mason 		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
10934cb5300bSChris Mason 			*off = min_key.offset;
10944cb5300bSChris Mason 			btrfs_free_path(path);
10954cb5300bSChris Mason 			return 0;
10964cb5300bSChris Mason 		}
10974cb5300bSChris Mason 
1098f094c9bdSFilipe Manana 		path->slots[0]++;
1099f094c9bdSFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(leaf)) {
1100f094c9bdSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1101f094c9bdSFilipe Manana 			goto process_slot;
1102f094c9bdSFilipe Manana 		}
1103f094c9bdSFilipe Manana 
11044cb5300bSChris Mason 		if (min_key.offset == (u64)-1)
11054cb5300bSChris Mason 			goto none;
11064cb5300bSChris Mason 
11074cb5300bSChris Mason 		min_key.offset++;
11084cb5300bSChris Mason 		btrfs_release_path(path);
11094cb5300bSChris Mason 	}
11104cb5300bSChris Mason none:
11114cb5300bSChris Mason 	btrfs_free_path(path);
11124cb5300bSChris Mason 	return -ENOENT;
11134cb5300bSChris Mason }
11144cb5300bSChris Mason 
11156c282eb4SLi Zefan static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
111617ce6ef8SLiu Bo {
111717ce6ef8SLiu Bo 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1118940100a4SChris Mason 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
11196c282eb4SLi Zefan 	struct extent_map *em;
112009cbfeafSKirill A. Shutemov 	u64 len = PAGE_SIZE;
1121940100a4SChris Mason 
1122940100a4SChris Mason 	/*
1123940100a4SChris Mason 	 * hopefully we have this extent in the tree already, try without
1124940100a4SChris Mason 	 * the full extent lock
1125940100a4SChris Mason 	 */
1126940100a4SChris Mason 	read_lock(&em_tree->lock);
1127940100a4SChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
1128940100a4SChris Mason 	read_unlock(&em_tree->lock);
1129940100a4SChris Mason 
1130940100a4SChris Mason 	if (!em) {
1131308d9800SFilipe Manana 		struct extent_state *cached = NULL;
1132308d9800SFilipe Manana 		u64 end = start + len - 1;
1133308d9800SFilipe Manana 
1134940100a4SChris Mason 		/* get the big lock and read metadata off disk */
1135ff13db41SDavid Sterba 		lock_extent_bits(io_tree, start, end, &cached);
1136fc4f21b1SNikolay Borisov 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1137e43bbe5eSDavid Sterba 		unlock_extent_cached(io_tree, start, end, &cached);
1138940100a4SChris Mason 
11396cf8bfbfSDan Carpenter 		if (IS_ERR(em))
11406c282eb4SLi Zefan 			return NULL;
1141940100a4SChris Mason 	}
1142940100a4SChris Mason 
11436c282eb4SLi Zefan 	return em;
11446c282eb4SLi Zefan }
11456c282eb4SLi Zefan 
11466c282eb4SLi Zefan static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
11476c282eb4SLi Zefan {
11486c282eb4SLi Zefan 	struct extent_map *next;
11496c282eb4SLi Zefan 	bool ret = true;
11506c282eb4SLi Zefan 
11516c282eb4SLi Zefan 	/* this is the last extent */
11526c282eb4SLi Zefan 	if (em->start + em->len >= i_size_read(inode))
11536c282eb4SLi Zefan 		return false;
11546c282eb4SLi Zefan 
11556c282eb4SLi Zefan 	next = defrag_lookup_extent(inode, em->start + em->len);
1156e9512d72SChris Mason 	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1157e9512d72SChris Mason 		ret = false;
1158e9512d72SChris Mason 	else if ((em->block_start + em->block_len == next->block_start) &&
1159ee22184bSByongho Lee 		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
11606c282eb4SLi Zefan 		ret = false;
11616c282eb4SLi Zefan 
11626c282eb4SLi Zefan 	free_extent_map(next);
11636c282eb4SLi Zefan 	return ret;
11646c282eb4SLi Zefan }
11656c282eb4SLi Zefan 
1166aab110abSDavid Sterba static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1167a43a2111SAndrew Mahone 			       u64 *last_len, u64 *skip, u64 *defrag_end,
1168a43a2111SAndrew Mahone 			       int compress)
11696c282eb4SLi Zefan {
11706c282eb4SLi Zefan 	struct extent_map *em;
11716c282eb4SLi Zefan 	int ret = 1;
11726c282eb4SLi Zefan 	bool next_mergeable = true;
11734a3560c4SLiu Bo 	bool prev_mergeable = true;
11746c282eb4SLi Zefan 
11756c282eb4SLi Zefan 	/*
11766c282eb4SLi Zefan 	 * make sure that once we start defragging an extent, we keep on
11776c282eb4SLi Zefan 	 * defragging it
11786c282eb4SLi Zefan 	 */
11796c282eb4SLi Zefan 	if (start < *defrag_end)
11806c282eb4SLi Zefan 		return 1;
11816c282eb4SLi Zefan 
11826c282eb4SLi Zefan 	*skip = 0;
11836c282eb4SLi Zefan 
11846c282eb4SLi Zefan 	em = defrag_lookup_extent(inode, start);
11856c282eb4SLi Zefan 	if (!em)
11866c282eb4SLi Zefan 		return 0;
11876c282eb4SLi Zefan 
1188940100a4SChris Mason 	/* this will cover holes, and inline extents */
118917ce6ef8SLiu Bo 	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1190940100a4SChris Mason 		ret = 0;
119117ce6ef8SLiu Bo 		goto out;
119217ce6ef8SLiu Bo 	}
119317ce6ef8SLiu Bo 
11944a3560c4SLiu Bo 	if (!*defrag_end)
11954a3560c4SLiu Bo 		prev_mergeable = false;
11964a3560c4SLiu Bo 
11976c282eb4SLi Zefan 	next_mergeable = defrag_check_next_extent(inode, em);
1198940100a4SChris Mason 	/*
11996c282eb4SLi Zefan 	 * we hit a real extent, if it is big or the next extent is not a
12006c282eb4SLi Zefan 	 * real extent, don't bother defragging it
1201940100a4SChris Mason 	 */
1202a43a2111SAndrew Mahone 	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
12034a3560c4SLiu Bo 	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1204940100a4SChris Mason 		ret = 0;
120517ce6ef8SLiu Bo out:
1206940100a4SChris Mason 	/*
1207940100a4SChris Mason 	 * last_len ends up being a counter of how many bytes we've defragged.
1208940100a4SChris Mason 	 * every time we choose not to defrag an extent, we reset *last_len
1209940100a4SChris Mason 	 * so that the next tiny extent will force a defrag.
1210940100a4SChris Mason 	 *
1211940100a4SChris Mason 	 * The end result of this is that tiny extents before a single big
1212940100a4SChris Mason 	 * extent will force at least part of that big extent to be defragged.
1213940100a4SChris Mason 	 */
1214940100a4SChris Mason 	if (ret) {
1215940100a4SChris Mason 		*defrag_end = extent_map_end(em);
1216940100a4SChris Mason 	} else {
1217940100a4SChris Mason 		*last_len = 0;
1218940100a4SChris Mason 		*skip = extent_map_end(em);
1219940100a4SChris Mason 		*defrag_end = 0;
1220940100a4SChris Mason 	}
1221940100a4SChris Mason 
1222940100a4SChris Mason 	free_extent_map(em);
1223940100a4SChris Mason 	return ret;
1224940100a4SChris Mason }
1225940100a4SChris Mason 
12264cb5300bSChris Mason /*
12274cb5300bSChris Mason  * it doesn't do much good to defrag one or two pages
12284cb5300bSChris Mason  * at a time.  This pulls in a nice chunk of pages
12294cb5300bSChris Mason  * to COW and defrag.
12304cb5300bSChris Mason  *
12314cb5300bSChris Mason  * It also makes sure the delalloc code has enough
12324cb5300bSChris Mason  * dirty data to avoid making new small extents as part
12334cb5300bSChris Mason  * of the defrag
12344cb5300bSChris Mason  *
12354cb5300bSChris Mason  * It's a good idea to start RA on this range
12364cb5300bSChris Mason  * before calling this.
12374cb5300bSChris Mason  */
12384cb5300bSChris Mason static int cluster_pages_for_defrag(struct inode *inode,
12394cb5300bSChris Mason 				    struct page **pages,
12404cb5300bSChris Mason 				    unsigned long start_index,
1241c41570c9SJustin Maggard 				    unsigned long num_pages)
1242f46b5a66SChristoph Hellwig {
12434cb5300bSChris Mason 	unsigned long file_end;
12444cb5300bSChris Mason 	u64 isize = i_size_read(inode);
1245f46b5a66SChristoph Hellwig 	u64 page_start;
1246f46b5a66SChristoph Hellwig 	u64 page_end;
12471f12bd06SLiu Bo 	u64 page_cnt;
12484cb5300bSChris Mason 	int ret;
12494cb5300bSChris Mason 	int i;
12504cb5300bSChris Mason 	int i_done;
12514cb5300bSChris Mason 	struct btrfs_ordered_extent *ordered;
12524cb5300bSChris Mason 	struct extent_state *cached_state = NULL;
1253600a45e1SMiao Xie 	struct extent_io_tree *tree;
1254364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
12553b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
12564cb5300bSChris Mason 
125709cbfeafSKirill A. Shutemov 	file_end = (isize - 1) >> PAGE_SHIFT;
12581f12bd06SLiu Bo 	if (!isize || start_index > file_end)
12591f12bd06SLiu Bo 		return 0;
12601f12bd06SLiu Bo 
12611f12bd06SLiu Bo 	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
12624cb5300bSChris Mason 
1263364ecf36SQu Wenruo 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
126409cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
126509cbfeafSKirill A. Shutemov 			page_cnt << PAGE_SHIFT);
12664cb5300bSChris Mason 	if (ret)
12674cb5300bSChris Mason 		return ret;
12684cb5300bSChris Mason 	i_done = 0;
1269600a45e1SMiao Xie 	tree = &BTRFS_I(inode)->io_tree;
12704cb5300bSChris Mason 
12714cb5300bSChris Mason 	/* step one, lock all the pages */
12721f12bd06SLiu Bo 	for (i = 0; i < page_cnt; i++) {
12734cb5300bSChris Mason 		struct page *page;
1274600a45e1SMiao Xie again:
1275a94733d0SJosef Bacik 		page = find_or_create_page(inode->i_mapping,
12763b16a4e3SJosef Bacik 					   start_index + i, mask);
12774cb5300bSChris Mason 		if (!page)
12784cb5300bSChris Mason 			break;
12794cb5300bSChris Mason 
1280600a45e1SMiao Xie 		page_start = page_offset(page);
128109cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
1282600a45e1SMiao Xie 		while (1) {
1283308d9800SFilipe Manana 			lock_extent_bits(tree, page_start, page_end,
1284ff13db41SDavid Sterba 					 &cached_state);
1285600a45e1SMiao Xie 			ordered = btrfs_lookup_ordered_extent(inode,
1286600a45e1SMiao Xie 							      page_start);
1287308d9800SFilipe Manana 			unlock_extent_cached(tree, page_start, page_end,
1288e43bbe5eSDavid Sterba 					     &cached_state);
1289600a45e1SMiao Xie 			if (!ordered)
1290600a45e1SMiao Xie 				break;
1291600a45e1SMiao Xie 
1292600a45e1SMiao Xie 			unlock_page(page);
1293600a45e1SMiao Xie 			btrfs_start_ordered_extent(inode, ordered, 1);
1294600a45e1SMiao Xie 			btrfs_put_ordered_extent(ordered);
1295600a45e1SMiao Xie 			lock_page(page);
12961f12bd06SLiu Bo 			/*
12971f12bd06SLiu Bo 			 * we unlocked the page above, so we need check if
12981f12bd06SLiu Bo 			 * it was released or not.
12991f12bd06SLiu Bo 			 */
13001f12bd06SLiu Bo 			if (page->mapping != inode->i_mapping) {
13011f12bd06SLiu Bo 				unlock_page(page);
130209cbfeafSKirill A. Shutemov 				put_page(page);
13031f12bd06SLiu Bo 				goto again;
13041f12bd06SLiu Bo 			}
1305600a45e1SMiao Xie 		}
1306600a45e1SMiao Xie 
13074cb5300bSChris Mason 		if (!PageUptodate(page)) {
13084cb5300bSChris Mason 			btrfs_readpage(NULL, page);
13094cb5300bSChris Mason 			lock_page(page);
13104cb5300bSChris Mason 			if (!PageUptodate(page)) {
13114cb5300bSChris Mason 				unlock_page(page);
131209cbfeafSKirill A. Shutemov 				put_page(page);
13134cb5300bSChris Mason 				ret = -EIO;
13144cb5300bSChris Mason 				break;
13154cb5300bSChris Mason 			}
13164cb5300bSChris Mason 		}
1317600a45e1SMiao Xie 
1318600a45e1SMiao Xie 		if (page->mapping != inode->i_mapping) {
1319600a45e1SMiao Xie 			unlock_page(page);
132009cbfeafSKirill A. Shutemov 			put_page(page);
1321600a45e1SMiao Xie 			goto again;
1322600a45e1SMiao Xie 		}
1323600a45e1SMiao Xie 
13244cb5300bSChris Mason 		pages[i] = page;
13254cb5300bSChris Mason 		i_done++;
13264cb5300bSChris Mason 	}
13274cb5300bSChris Mason 	if (!i_done || ret)
13284cb5300bSChris Mason 		goto out;
13294cb5300bSChris Mason 
13301751e8a6SLinus Torvalds 	if (!(inode->i_sb->s_flags & SB_ACTIVE))
13314cb5300bSChris Mason 		goto out;
13324cb5300bSChris Mason 
13334cb5300bSChris Mason 	/*
13344cb5300bSChris Mason 	 * so now we have a nice long stream of locked
13354cb5300bSChris Mason 	 * and up to date pages, lets wait on them
13364cb5300bSChris Mason 	 */
13374cb5300bSChris Mason 	for (i = 0; i < i_done; i++)
13384cb5300bSChris Mason 		wait_on_page_writeback(pages[i]);
13394cb5300bSChris Mason 
13404cb5300bSChris Mason 	page_start = page_offset(pages[0]);
134109cbfeafSKirill A. Shutemov 	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
13424cb5300bSChris Mason 
13434cb5300bSChris Mason 	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1344ff13db41SDavid Sterba 			 page_start, page_end - 1, &cached_state);
13454cb5300bSChris Mason 	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
13464cb5300bSChris Mason 			  page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
13479e8a4a8bSLiu Bo 			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1348ae0f1625SDavid Sterba 			  &cached_state);
13494cb5300bSChris Mason 
13501f12bd06SLiu Bo 	if (i_done != page_cnt) {
13519e0baf60SJosef Bacik 		spin_lock(&BTRFS_I(inode)->lock);
135228c4a3e2SSu Yue 		btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
13539e0baf60SJosef Bacik 		spin_unlock(&BTRFS_I(inode)->lock);
1354bc42bda2SQu Wenruo 		btrfs_delalloc_release_space(inode, data_reserved,
135509cbfeafSKirill A. Shutemov 				start_index << PAGE_SHIFT,
135643b18595SQu Wenruo 				(page_cnt - i_done) << PAGE_SHIFT, true);
13574cb5300bSChris Mason 	}
13584cb5300bSChris Mason 
13594cb5300bSChris Mason 
13609e8a4a8bSLiu Bo 	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1361018ed4f7SDavid Sterba 			  &cached_state);
13624cb5300bSChris Mason 
13634cb5300bSChris Mason 	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1364e43bbe5eSDavid Sterba 			     page_start, page_end - 1, &cached_state);
13654cb5300bSChris Mason 
13664cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
13674cb5300bSChris Mason 		clear_page_dirty_for_io(pages[i]);
13684cb5300bSChris Mason 		ClearPageChecked(pages[i]);
13694cb5300bSChris Mason 		set_page_extent_mapped(pages[i]);
13704cb5300bSChris Mason 		set_page_dirty(pages[i]);
13714cb5300bSChris Mason 		unlock_page(pages[i]);
137209cbfeafSKirill A. Shutemov 		put_page(pages[i]);
13734cb5300bSChris Mason 	}
137443b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
137543b18595SQu Wenruo 				       false);
1376364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
13774cb5300bSChris Mason 	return i_done;
13784cb5300bSChris Mason out:
13794cb5300bSChris Mason 	for (i = 0; i < i_done; i++) {
13804cb5300bSChris Mason 		unlock_page(pages[i]);
138109cbfeafSKirill A. Shutemov 		put_page(pages[i]);
13824cb5300bSChris Mason 	}
1383bc42bda2SQu Wenruo 	btrfs_delalloc_release_space(inode, data_reserved,
138409cbfeafSKirill A. Shutemov 			start_index << PAGE_SHIFT,
138543b18595SQu Wenruo 			page_cnt << PAGE_SHIFT, true);
138643b18595SQu Wenruo 	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
138743b18595SQu Wenruo 				       true);
1388364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
13894cb5300bSChris Mason 	return ret;
13904cb5300bSChris Mason 
13914cb5300bSChris Mason }
13924cb5300bSChris Mason 
13934cb5300bSChris Mason int btrfs_defrag_file(struct inode *inode, struct file *file,
13944cb5300bSChris Mason 		      struct btrfs_ioctl_defrag_range_args *range,
13954cb5300bSChris Mason 		      u64 newer_than, unsigned long max_to_defrag)
13964cb5300bSChris Mason {
13970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
13984cb5300bSChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
13994cb5300bSChris Mason 	struct file_ra_state *ra = NULL;
14004cb5300bSChris Mason 	unsigned long last_index;
1401151a31b2SLi Zefan 	u64 isize = i_size_read(inode);
1402940100a4SChris Mason 	u64 last_len = 0;
1403940100a4SChris Mason 	u64 skip = 0;
1404940100a4SChris Mason 	u64 defrag_end = 0;
14054cb5300bSChris Mason 	u64 newer_off = range->start;
1406f46b5a66SChristoph Hellwig 	unsigned long i;
1407008873eaSLi Zefan 	unsigned long ra_index = 0;
1408f46b5a66SChristoph Hellwig 	int ret;
14094cb5300bSChris Mason 	int defrag_count = 0;
14101a419d85SLi Zefan 	int compress_type = BTRFS_COMPRESS_ZLIB;
1411aab110abSDavid Sterba 	u32 extent_thresh = range->extent_thresh;
141209cbfeafSKirill A. Shutemov 	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1413c41570c9SJustin Maggard 	unsigned long cluster = max_cluster;
1414ee22184bSByongho Lee 	u64 new_align = ~((u64)SZ_128K - 1);
14154cb5300bSChris Mason 	struct page **pages = NULL;
14161e2ef46dSDavid Sterba 	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
14174cb5300bSChris Mason 
14180abd5b17SLiu Bo 	if (isize == 0)
14190abd5b17SLiu Bo 		return 0;
14200abd5b17SLiu Bo 
14210abd5b17SLiu Bo 	if (range->start >= isize)
14220abd5b17SLiu Bo 		return -EINVAL;
14231a419d85SLi Zefan 
14241e2ef46dSDavid Sterba 	if (do_compress) {
14251a419d85SLi Zefan 		if (range->compress_type > BTRFS_COMPRESS_TYPES)
14261a419d85SLi Zefan 			return -EINVAL;
14271a419d85SLi Zefan 		if (range->compress_type)
14281a419d85SLi Zefan 			compress_type = range->compress_type;
14291a419d85SLi Zefan 	}
1430f46b5a66SChristoph Hellwig 
14310abd5b17SLiu Bo 	if (extent_thresh == 0)
1432ee22184bSByongho Lee 		extent_thresh = SZ_256K;
1433f46b5a66SChristoph Hellwig 
14344cb5300bSChris Mason 	/*
14350a52d108SDavid Sterba 	 * If we were not given a file, allocate a readahead context. As
14360a52d108SDavid Sterba 	 * readahead is just an optimization, defrag will work without it so
14370a52d108SDavid Sterba 	 * we don't error out.
14384cb5300bSChris Mason 	 */
14394cb5300bSChris Mason 	if (!file) {
144063e727ecSDavid Sterba 		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
14410a52d108SDavid Sterba 		if (ra)
14424cb5300bSChris Mason 			file_ra_state_init(ra, inode->i_mapping);
14434cb5300bSChris Mason 	} else {
14444cb5300bSChris Mason 		ra = &file->f_ra;
14454cb5300bSChris Mason 	}
14464cb5300bSChris Mason 
144763e727ecSDavid Sterba 	pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
14484cb5300bSChris Mason 	if (!pages) {
14494cb5300bSChris Mason 		ret = -ENOMEM;
14504cb5300bSChris Mason 		goto out_ra;
14514cb5300bSChris Mason 	}
14524cb5300bSChris Mason 
14534cb5300bSChris Mason 	/* find the last page to defrag */
14541e701a32SChris Mason 	if (range->start + range->len > range->start) {
1455151a31b2SLi Zefan 		last_index = min_t(u64, isize - 1,
145609cbfeafSKirill A. Shutemov 			 range->start + range->len - 1) >> PAGE_SHIFT;
14571e701a32SChris Mason 	} else {
145809cbfeafSKirill A. Shutemov 		last_index = (isize - 1) >> PAGE_SHIFT;
14591e701a32SChris Mason 	}
14601e701a32SChris Mason 
14614cb5300bSChris Mason 	if (newer_than) {
14624cb5300bSChris Mason 		ret = find_new_extents(root, inode, newer_than,
1463ee22184bSByongho Lee 				       &newer_off, SZ_64K);
14644cb5300bSChris Mason 		if (!ret) {
14654cb5300bSChris Mason 			range->start = newer_off;
14664cb5300bSChris Mason 			/*
14674cb5300bSChris Mason 			 * we always align our defrag to help keep
14684cb5300bSChris Mason 			 * the extents in the file evenly spaced
14694cb5300bSChris Mason 			 */
147009cbfeafSKirill A. Shutemov 			i = (newer_off & new_align) >> PAGE_SHIFT;
14714cb5300bSChris Mason 		} else
14724cb5300bSChris Mason 			goto out_ra;
14734cb5300bSChris Mason 	} else {
147409cbfeafSKirill A. Shutemov 		i = range->start >> PAGE_SHIFT;
14754cb5300bSChris Mason 	}
14764cb5300bSChris Mason 	if (!max_to_defrag)
1477070034bdSchandan 		max_to_defrag = last_index - i + 1;
14784cb5300bSChris Mason 
14792a0f7f57SLi Zefan 	/*
14802a0f7f57SLi Zefan 	 * make writeback starts from i, so the defrag range can be
14812a0f7f57SLi Zefan 	 * written sequentially.
14822a0f7f57SLi Zefan 	 */
14832a0f7f57SLi Zefan 	if (i < inode->i_mapping->writeback_index)
14842a0f7f57SLi Zefan 		inode->i_mapping->writeback_index = i;
14852a0f7f57SLi Zefan 
1486f7f43cc8SChris Mason 	while (i <= last_index && defrag_count < max_to_defrag &&
148709cbfeafSKirill A. Shutemov 	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
14884cb5300bSChris Mason 		/*
14894cb5300bSChris Mason 		 * make sure we stop running if someone unmounts
14904cb5300bSChris Mason 		 * the FS
14914cb5300bSChris Mason 		 */
14921751e8a6SLinus Torvalds 		if (!(inode->i_sb->s_flags & SB_ACTIVE))
14934cb5300bSChris Mason 			break;
14944cb5300bSChris Mason 
14950b246afaSJeff Mahoney 		if (btrfs_defrag_cancelled(fs_info)) {
14960b246afaSJeff Mahoney 			btrfs_debug(fs_info, "defrag_file cancelled");
1497210549ebSDavid Sterba 			ret = -EAGAIN;
1498210549ebSDavid Sterba 			break;
1499210549ebSDavid Sterba 		}
1500210549ebSDavid Sterba 
150109cbfeafSKirill A. Shutemov 		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
15026c282eb4SLi Zefan 					 extent_thresh, &last_len, &skip,
15031e2ef46dSDavid Sterba 					 &defrag_end, do_compress)){
1504940100a4SChris Mason 			unsigned long next;
1505940100a4SChris Mason 			/*
1506940100a4SChris Mason 			 * the should_defrag function tells us how much to skip
1507940100a4SChris Mason 			 * bump our counter by the suggested amount
1508940100a4SChris Mason 			 */
150909cbfeafSKirill A. Shutemov 			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1510940100a4SChris Mason 			i = max(i + 1, next);
1511940100a4SChris Mason 			continue;
1512940100a4SChris Mason 		}
1513008873eaSLi Zefan 
1514008873eaSLi Zefan 		if (!newer_than) {
151509cbfeafSKirill A. Shutemov 			cluster = (PAGE_ALIGN(defrag_end) >>
151609cbfeafSKirill A. Shutemov 				   PAGE_SHIFT) - i;
1517008873eaSLi Zefan 			cluster = min(cluster, max_cluster);
1518008873eaSLi Zefan 		} else {
1519008873eaSLi Zefan 			cluster = max_cluster;
1520008873eaSLi Zefan 		}
1521008873eaSLi Zefan 
1522008873eaSLi Zefan 		if (i + cluster > ra_index) {
1523008873eaSLi Zefan 			ra_index = max(i, ra_index);
15240a52d108SDavid Sterba 			if (ra)
1525d3c0bab5SDavid Sterba 				page_cache_sync_readahead(inode->i_mapping, ra,
1526d3c0bab5SDavid Sterba 						file, ra_index, cluster);
1527e4826a5bSchandan 			ra_index += cluster;
1528008873eaSLi Zefan 		}
15294cb5300bSChris Mason 
15305955102cSAl Viro 		inode_lock(inode);
1531eede2bf3SOmar Sandoval 		if (IS_SWAPFILE(inode)) {
1532eede2bf3SOmar Sandoval 			ret = -ETXTBSY;
1533eede2bf3SOmar Sandoval 		} else {
15341e2ef46dSDavid Sterba 			if (do_compress)
1535eec63c65SDavid Sterba 				BTRFS_I(inode)->defrag_compress = compress_type;
1536008873eaSLi Zefan 			ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1537eede2bf3SOmar Sandoval 		}
1538ecb8bea8SLiu Bo 		if (ret < 0) {
15395955102cSAl Viro 			inode_unlock(inode);
15404cb5300bSChris Mason 			goto out_ra;
1541ecb8bea8SLiu Bo 		}
15424cb5300bSChris Mason 
15434cb5300bSChris Mason 		defrag_count += ret;
1544d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(inode->i_mapping);
15455955102cSAl Viro 		inode_unlock(inode);
15464cb5300bSChris Mason 
15474cb5300bSChris Mason 		if (newer_than) {
15484cb5300bSChris Mason 			if (newer_off == (u64)-1)
15494cb5300bSChris Mason 				break;
15504cb5300bSChris Mason 
1551e1f041e1SLiu Bo 			if (ret > 0)
1552e1f041e1SLiu Bo 				i += ret;
1553e1f041e1SLiu Bo 
15544cb5300bSChris Mason 			newer_off = max(newer_off + 1,
155509cbfeafSKirill A. Shutemov 					(u64)i << PAGE_SHIFT);
15564cb5300bSChris Mason 
1557ee22184bSByongho Lee 			ret = find_new_extents(root, inode, newer_than,
1558ee22184bSByongho Lee 					       &newer_off, SZ_64K);
15594cb5300bSChris Mason 			if (!ret) {
15604cb5300bSChris Mason 				range->start = newer_off;
156109cbfeafSKirill A. Shutemov 				i = (newer_off & new_align) >> PAGE_SHIFT;
15624cb5300bSChris Mason 			} else {
15634cb5300bSChris Mason 				break;
1564940100a4SChris Mason 			}
15654cb5300bSChris Mason 		} else {
1566008873eaSLi Zefan 			if (ret > 0) {
1567cbcc8326SLi Zefan 				i += ret;
156809cbfeafSKirill A. Shutemov 				last_len += ret << PAGE_SHIFT;
1569008873eaSLi Zefan 			} else {
1570940100a4SChris Mason 				i++;
1571008873eaSLi Zefan 				last_len = 0;
1572008873eaSLi Zefan 			}
1573f46b5a66SChristoph Hellwig 		}
15744cb5300bSChris Mason 	}
1575f46b5a66SChristoph Hellwig 
1576dec8ef90SFilipe Manana 	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
15771e701a32SChris Mason 		filemap_flush(inode->i_mapping);
1578dec8ef90SFilipe Manana 		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1579dec8ef90SFilipe Manana 			     &BTRFS_I(inode)->runtime_flags))
1580dec8ef90SFilipe Manana 			filemap_flush(inode->i_mapping);
1581dec8ef90SFilipe Manana 	}
15821e701a32SChris Mason 
15831a419d85SLi Zefan 	if (range->compress_type == BTRFS_COMPRESS_LZO) {
15840b246afaSJeff Mahoney 		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
15855c1aab1dSNick Terrell 	} else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
15865c1aab1dSNick Terrell 		btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
15871a419d85SLi Zefan 	}
15881a419d85SLi Zefan 
158960ccf82fSDiego Calleja 	ret = defrag_count;
1590940100a4SChris Mason 
15914cb5300bSChris Mason out_ra:
15921e2ef46dSDavid Sterba 	if (do_compress) {
15935955102cSAl Viro 		inode_lock(inode);
1594eec63c65SDavid Sterba 		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
15955955102cSAl Viro 		inode_unlock(inode);
1596633085c7SFilipe David Borba Manana 	}
15974cb5300bSChris Mason 	if (!file)
15984cb5300bSChris Mason 		kfree(ra);
15994cb5300bSChris Mason 	kfree(pages);
1600940100a4SChris Mason 	return ret;
1601f46b5a66SChristoph Hellwig }
1602f46b5a66SChristoph Hellwig 
1603198605a8SMiao Xie static noinline int btrfs_ioctl_resize(struct file *file,
160476dda93cSYan, Zheng 					void __user *arg)
1605f46b5a66SChristoph Hellwig {
16060b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
16070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1608f46b5a66SChristoph Hellwig 	u64 new_size;
1609f46b5a66SChristoph Hellwig 	u64 old_size;
1610f46b5a66SChristoph Hellwig 	u64 devid = 1;
16110b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
1612f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
1613f46b5a66SChristoph Hellwig 	struct btrfs_trans_handle *trans;
1614f46b5a66SChristoph Hellwig 	struct btrfs_device *device = NULL;
1615f46b5a66SChristoph Hellwig 	char *sizestr;
16169a40f122SGui Hecheng 	char *retptr;
1617f46b5a66SChristoph Hellwig 	char *devstr = NULL;
1618f46b5a66SChristoph Hellwig 	int ret = 0;
1619f46b5a66SChristoph Hellwig 	int mod = 0;
1620f46b5a66SChristoph Hellwig 
1621e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
1622e441d54dSChris Mason 		return -EPERM;
1623e441d54dSChris Mason 
1624198605a8SMiao Xie 	ret = mnt_want_write_file(file);
1625198605a8SMiao Xie 	if (ret)
1626198605a8SMiao Xie 		return ret;
1627198605a8SMiao Xie 
1628171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
162997547676SMiao Xie 		mnt_drop_write_file(file);
1630e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1631c9e9f97bSIlya Dryomov 	}
1632c9e9f97bSIlya Dryomov 
1633dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1634c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
1635c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
1636c9e9f97bSIlya Dryomov 		goto out;
1637c9e9f97bSIlya Dryomov 	}
16385516e595SMark Fasheh 
16395516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1640f46b5a66SChristoph Hellwig 
1641f46b5a66SChristoph Hellwig 	sizestr = vol_args->name;
1642f46b5a66SChristoph Hellwig 	devstr = strchr(sizestr, ':');
1643f46b5a66SChristoph Hellwig 	if (devstr) {
1644f46b5a66SChristoph Hellwig 		sizestr = devstr + 1;
1645f46b5a66SChristoph Hellwig 		*devstr = '\0';
1646f46b5a66SChristoph Hellwig 		devstr = vol_args->name;
164758dfae63SZhangZhen 		ret = kstrtoull(devstr, 10, &devid);
164858dfae63SZhangZhen 		if (ret)
164958dfae63SZhangZhen 			goto out_free;
1650dfd79829SMiao Xie 		if (!devid) {
1651dfd79829SMiao Xie 			ret = -EINVAL;
1652dfd79829SMiao Xie 			goto out_free;
1653dfd79829SMiao Xie 		}
16540b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizing devid %llu", devid);
1655f46b5a66SChristoph Hellwig 	}
1656dba60f3fSMiao Xie 
165709ba3bc9SAnand Jain 	device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
1658f46b5a66SChristoph Hellwig 	if (!device) {
16590b246afaSJeff Mahoney 		btrfs_info(fs_info, "resizer unable to find device %llu",
1660c1c9ff7cSGeert Uytterhoeven 			   devid);
1661dfd79829SMiao Xie 		ret = -ENODEV;
1662c9e9f97bSIlya Dryomov 		goto out_free;
1663f46b5a66SChristoph Hellwig 	}
1664dba60f3fSMiao Xie 
1665ebbede42SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
16660b246afaSJeff Mahoney 		btrfs_info(fs_info,
1667efe120a0SFrank Holton 			   "resizer unable to apply on readonly device %llu",
1668c1c9ff7cSGeert Uytterhoeven 		       devid);
1669dfd79829SMiao Xie 		ret = -EPERM;
16704e42ae1bSLiu Bo 		goto out_free;
16714e42ae1bSLiu Bo 	}
16724e42ae1bSLiu Bo 
1673f46b5a66SChristoph Hellwig 	if (!strcmp(sizestr, "max"))
1674f46b5a66SChristoph Hellwig 		new_size = device->bdev->bd_inode->i_size;
1675f46b5a66SChristoph Hellwig 	else {
1676f46b5a66SChristoph Hellwig 		if (sizestr[0] == '-') {
1677f46b5a66SChristoph Hellwig 			mod = -1;
1678f46b5a66SChristoph Hellwig 			sizestr++;
1679f46b5a66SChristoph Hellwig 		} else if (sizestr[0] == '+') {
1680f46b5a66SChristoph Hellwig 			mod = 1;
1681f46b5a66SChristoph Hellwig 			sizestr++;
1682f46b5a66SChristoph Hellwig 		}
16839a40f122SGui Hecheng 		new_size = memparse(sizestr, &retptr);
16849a40f122SGui Hecheng 		if (*retptr != '\0' || new_size == 0) {
1685f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1686c9e9f97bSIlya Dryomov 			goto out_free;
1687f46b5a66SChristoph Hellwig 		}
1688f46b5a66SChristoph Hellwig 	}
1689f46b5a66SChristoph Hellwig 
1690401e29c1SAnand Jain 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1691dfd79829SMiao Xie 		ret = -EPERM;
169263a212abSStefan Behrens 		goto out_free;
169363a212abSStefan Behrens 	}
169463a212abSStefan Behrens 
16957cc8e58dSMiao Xie 	old_size = btrfs_device_get_total_bytes(device);
1696f46b5a66SChristoph Hellwig 
1697f46b5a66SChristoph Hellwig 	if (mod < 0) {
1698f46b5a66SChristoph Hellwig 		if (new_size > old_size) {
1699f46b5a66SChristoph Hellwig 			ret = -EINVAL;
1700c9e9f97bSIlya Dryomov 			goto out_free;
1701f46b5a66SChristoph Hellwig 		}
1702f46b5a66SChristoph Hellwig 		new_size = old_size - new_size;
1703f46b5a66SChristoph Hellwig 	} else if (mod > 0) {
1704eb8052e0SWenliang Fan 		if (new_size > ULLONG_MAX - old_size) {
1705902c68a4SGui Hecheng 			ret = -ERANGE;
1706eb8052e0SWenliang Fan 			goto out_free;
1707eb8052e0SWenliang Fan 		}
1708f46b5a66SChristoph Hellwig 		new_size = old_size + new_size;
1709f46b5a66SChristoph Hellwig 	}
1710f46b5a66SChristoph Hellwig 
1711ee22184bSByongho Lee 	if (new_size < SZ_256M) {
1712f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1713c9e9f97bSIlya Dryomov 		goto out_free;
1714f46b5a66SChristoph Hellwig 	}
1715f46b5a66SChristoph Hellwig 	if (new_size > device->bdev->bd_inode->i_size) {
1716f46b5a66SChristoph Hellwig 		ret = -EFBIG;
1717c9e9f97bSIlya Dryomov 		goto out_free;
1718f46b5a66SChristoph Hellwig 	}
1719f46b5a66SChristoph Hellwig 
172047f08b96SNikolay Borisov 	new_size = round_down(new_size, fs_info->sectorsize);
1721f46b5a66SChristoph Hellwig 
17220b246afaSJeff Mahoney 	btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1723c1c9ff7cSGeert Uytterhoeven 			  rcu_str_deref(device->name), new_size);
1724f46b5a66SChristoph Hellwig 
1725f46b5a66SChristoph Hellwig 	if (new_size > old_size) {
1726a22285a6SYan, Zheng 		trans = btrfs_start_transaction(root, 0);
172798d5dc13STsutomu Itoh 		if (IS_ERR(trans)) {
172898d5dc13STsutomu Itoh 			ret = PTR_ERR(trans);
1729c9e9f97bSIlya Dryomov 			goto out_free;
173098d5dc13STsutomu Itoh 		}
1731f46b5a66SChristoph Hellwig 		ret = btrfs_grow_device(trans, device, new_size);
17323a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
1733ece7d20eSMike Fleetwood 	} else if (new_size < old_size) {
1734f46b5a66SChristoph Hellwig 		ret = btrfs_shrink_device(device, new_size);
17350253f40eSjeff.liu 	} /* equal, nothing need to do */
1736f46b5a66SChristoph Hellwig 
1737c9e9f97bSIlya Dryomov out_free:
1738f46b5a66SChristoph Hellwig 	kfree(vol_args);
1739c9e9f97bSIlya Dryomov out:
1740171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
174118f39c41SIlya Dryomov 	mnt_drop_write_file(file);
1742f46b5a66SChristoph Hellwig 	return ret;
1743f46b5a66SChristoph Hellwig }
1744f46b5a66SChristoph Hellwig 
174572fd032eSSage Weil static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
174652f75f4fSDavid Sterba 				const char *name, unsigned long fd, int subvol,
17476f72c7e2SArne Jansen 				u64 *transid, bool readonly,
17488696c533SMiao Xie 				struct btrfs_qgroup_inherit *inherit)
1749f46b5a66SChristoph Hellwig {
1750f46b5a66SChristoph Hellwig 	int namelen;
17513de4586cSChris Mason 	int ret = 0;
1752f46b5a66SChristoph Hellwig 
1753325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1754325c50e3SJeff Mahoney 		return -ENOTDIR;
1755325c50e3SJeff Mahoney 
1756a874a63eSLiu Bo 	ret = mnt_want_write_file(file);
1757a874a63eSLiu Bo 	if (ret)
1758a874a63eSLiu Bo 		goto out;
1759a874a63eSLiu Bo 
176072fd032eSSage Weil 	namelen = strlen(name);
176172fd032eSSage Weil 	if (strchr(name, '/')) {
1762f46b5a66SChristoph Hellwig 		ret = -EINVAL;
1763a874a63eSLiu Bo 		goto out_drop_write;
1764f46b5a66SChristoph Hellwig 	}
1765f46b5a66SChristoph Hellwig 
176616780cabSChris Mason 	if (name[0] == '.' &&
176716780cabSChris Mason 	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
176816780cabSChris Mason 		ret = -EEXIST;
1769a874a63eSLiu Bo 		goto out_drop_write;
177016780cabSChris Mason 	}
177116780cabSChris Mason 
17723de4586cSChris Mason 	if (subvol) {
177372fd032eSSage Weil 		ret = btrfs_mksubvol(&file->f_path, name, namelen,
17746f72c7e2SArne Jansen 				     NULL, transid, readonly, inherit);
1775cb8e7090SChristoph Hellwig 	} else {
17762903ff01SAl Viro 		struct fd src = fdget(fd);
17773de4586cSChris Mason 		struct inode *src_inode;
17782903ff01SAl Viro 		if (!src.file) {
17793de4586cSChris Mason 			ret = -EINVAL;
1780a874a63eSLiu Bo 			goto out_drop_write;
17813de4586cSChris Mason 		}
17823de4586cSChris Mason 
1783496ad9aaSAl Viro 		src_inode = file_inode(src.file);
1784496ad9aaSAl Viro 		if (src_inode->i_sb != file_inode(file)->i_sb) {
1785c79b4713SJosef Bacik 			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1786efe120a0SFrank Holton 				   "Snapshot src from another FS");
178723ad5b17SKusanagi Kouichi 			ret = -EXDEV;
1788d0242061SDavid Sterba 		} else if (!inode_owner_or_capable(src_inode)) {
1789d0242061SDavid Sterba 			/*
1790d0242061SDavid Sterba 			 * Subvolume creation is not restricted, but snapshots
1791d0242061SDavid Sterba 			 * are limited to own subvolumes only
1792d0242061SDavid Sterba 			 */
1793d0242061SDavid Sterba 			ret = -EPERM;
1794ecd18815SAl Viro 		} else {
179572fd032eSSage Weil 			ret = btrfs_mksubvol(&file->f_path, name, namelen,
179672fd032eSSage Weil 					     BTRFS_I(src_inode)->root,
17976f72c7e2SArne Jansen 					     transid, readonly, inherit);
1798ecd18815SAl Viro 		}
17992903ff01SAl Viro 		fdput(src);
1800cb8e7090SChristoph Hellwig 	}
1801a874a63eSLiu Bo out_drop_write:
1802a874a63eSLiu Bo 	mnt_drop_write_file(file);
1803f46b5a66SChristoph Hellwig out:
180472fd032eSSage Weil 	return ret;
180572fd032eSSage Weil }
180672fd032eSSage Weil 
180772fd032eSSage Weil static noinline int btrfs_ioctl_snap_create(struct file *file,
1808fa0d2b9bSLi Zefan 					    void __user *arg, int subvol)
180972fd032eSSage Weil {
1810fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args *vol_args;
181172fd032eSSage Weil 	int ret;
181272fd032eSSage Weil 
1813325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1814325c50e3SJeff Mahoney 		return -ENOTDIR;
1815325c50e3SJeff Mahoney 
1816fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1817fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1818fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1819fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1820fa0d2b9bSLi Zefan 
1821fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1822b83cc969SLi Zefan 					      vol_args->fd, subvol,
18236f72c7e2SArne Jansen 					      NULL, false, NULL);
1824fa0d2b9bSLi Zefan 
1825fa0d2b9bSLi Zefan 	kfree(vol_args);
1826fa0d2b9bSLi Zefan 	return ret;
1827fa0d2b9bSLi Zefan }
1828fa0d2b9bSLi Zefan 
1829fa0d2b9bSLi Zefan static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1830fa0d2b9bSLi Zefan 					       void __user *arg, int subvol)
1831fa0d2b9bSLi Zefan {
1832fa0d2b9bSLi Zefan 	struct btrfs_ioctl_vol_args_v2 *vol_args;
1833fa0d2b9bSLi Zefan 	int ret;
1834fdfb1e4fSLi Zefan 	u64 transid = 0;
1835fdfb1e4fSLi Zefan 	u64 *ptr = NULL;
1836b83cc969SLi Zefan 	bool readonly = false;
18376f72c7e2SArne Jansen 	struct btrfs_qgroup_inherit *inherit = NULL;
183872fd032eSSage Weil 
1839325c50e3SJeff Mahoney 	if (!S_ISDIR(file_inode(file)->i_mode))
1840325c50e3SJeff Mahoney 		return -ENOTDIR;
1841325c50e3SJeff Mahoney 
1842fa0d2b9bSLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
1843fa0d2b9bSLi Zefan 	if (IS_ERR(vol_args))
1844fa0d2b9bSLi Zefan 		return PTR_ERR(vol_args);
1845fa0d2b9bSLi Zefan 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1846fdfb1e4fSLi Zefan 
1847b83cc969SLi Zefan 	if (vol_args->flags &
18486f72c7e2SArne Jansen 	    ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
18496f72c7e2SArne Jansen 	      BTRFS_SUBVOL_QGROUP_INHERIT)) {
1850b83cc969SLi Zefan 		ret = -EOPNOTSUPP;
1851c47ca32dSDan Carpenter 		goto free_args;
1852fdfb1e4fSLi Zefan 	}
1853fdfb1e4fSLi Zefan 
1854fa0d2b9bSLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1855fdfb1e4fSLi Zefan 		ptr = &transid;
1856b83cc969SLi Zefan 	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1857b83cc969SLi Zefan 		readonly = true;
18586f72c7e2SArne Jansen 	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
185909cbfeafSKirill A. Shutemov 		if (vol_args->size > PAGE_SIZE) {
18606f72c7e2SArne Jansen 			ret = -EINVAL;
1861c47ca32dSDan Carpenter 			goto free_args;
18626f72c7e2SArne Jansen 		}
18636f72c7e2SArne Jansen 		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
18646f72c7e2SArne Jansen 		if (IS_ERR(inherit)) {
18656f72c7e2SArne Jansen 			ret = PTR_ERR(inherit);
1866c47ca32dSDan Carpenter 			goto free_args;
18676f72c7e2SArne Jansen 		}
18686f72c7e2SArne Jansen 	}
186975eaa0e2SSage Weil 
1870fa0d2b9bSLi Zefan 	ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
18716f72c7e2SArne Jansen 					      vol_args->fd, subvol, ptr,
18728696c533SMiao Xie 					      readonly, inherit);
1873c47ca32dSDan Carpenter 	if (ret)
1874c47ca32dSDan Carpenter 		goto free_inherit;
187575eaa0e2SSage Weil 
1876c47ca32dSDan Carpenter 	if (ptr && copy_to_user(arg +
1877fdfb1e4fSLi Zefan 				offsetof(struct btrfs_ioctl_vol_args_v2,
1878c47ca32dSDan Carpenter 					transid),
1879c47ca32dSDan Carpenter 				ptr, sizeof(*ptr)))
188075eaa0e2SSage Weil 		ret = -EFAULT;
1881c47ca32dSDan Carpenter 
1882c47ca32dSDan Carpenter free_inherit:
18836f72c7e2SArne Jansen 	kfree(inherit);
1884c47ca32dSDan Carpenter free_args:
1885c47ca32dSDan Carpenter 	kfree(vol_args);
1886f46b5a66SChristoph Hellwig 	return ret;
1887f46b5a66SChristoph Hellwig }
1888f46b5a66SChristoph Hellwig 
18890caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
18900caa102dSLi Zefan 						void __user *arg)
18910caa102dSLi Zefan {
1892496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18940caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
18950caa102dSLi Zefan 	int ret = 0;
18960caa102dSLi Zefan 	u64 flags = 0;
18970caa102dSLi Zefan 
18984a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
18990caa102dSLi Zefan 		return -EINVAL;
19000caa102dSLi Zefan 
19010b246afaSJeff Mahoney 	down_read(&fs_info->subvol_sem);
19020caa102dSLi Zefan 	if (btrfs_root_readonly(root))
19030caa102dSLi Zefan 		flags |= BTRFS_SUBVOL_RDONLY;
19040b246afaSJeff Mahoney 	up_read(&fs_info->subvol_sem);
19050caa102dSLi Zefan 
19060caa102dSLi Zefan 	if (copy_to_user(arg, &flags, sizeof(flags)))
19070caa102dSLi Zefan 		ret = -EFAULT;
19080caa102dSLi Zefan 
19090caa102dSLi Zefan 	return ret;
19100caa102dSLi Zefan }
19110caa102dSLi Zefan 
19120caa102dSLi Zefan static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
19130caa102dSLi Zefan 					      void __user *arg)
19140caa102dSLi Zefan {
1915496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
19160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
19170caa102dSLi Zefan 	struct btrfs_root *root = BTRFS_I(inode)->root;
19180caa102dSLi Zefan 	struct btrfs_trans_handle *trans;
19190caa102dSLi Zefan 	u64 root_flags;
19200caa102dSLi Zefan 	u64 flags;
19210caa102dSLi Zefan 	int ret = 0;
19220caa102dSLi Zefan 
1923bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
1924bd60ea0fSDavid Sterba 		return -EPERM;
1925bd60ea0fSDavid Sterba 
1926b9ca0664SLiu Bo 	ret = mnt_want_write_file(file);
1927b9ca0664SLiu Bo 	if (ret)
1928b9ca0664SLiu Bo 		goto out;
19290caa102dSLi Zefan 
19304a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1931b9ca0664SLiu Bo 		ret = -EINVAL;
1932b9ca0664SLiu Bo 		goto out_drop_write;
1933b9ca0664SLiu Bo 	}
19340caa102dSLi Zefan 
1935b9ca0664SLiu Bo 	if (copy_from_user(&flags, arg, sizeof(flags))) {
1936b9ca0664SLiu Bo 		ret = -EFAULT;
1937b9ca0664SLiu Bo 		goto out_drop_write;
1938b9ca0664SLiu Bo 	}
19390caa102dSLi Zefan 
1940b9ca0664SLiu Bo 	if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1941b9ca0664SLiu Bo 		ret = -EINVAL;
1942b9ca0664SLiu Bo 		goto out_drop_write;
1943b9ca0664SLiu Bo 	}
19440caa102dSLi Zefan 
1945b9ca0664SLiu Bo 	if (flags & ~BTRFS_SUBVOL_RDONLY) {
1946b9ca0664SLiu Bo 		ret = -EOPNOTSUPP;
1947b9ca0664SLiu Bo 		goto out_drop_write;
1948b9ca0664SLiu Bo 	}
19490caa102dSLi Zefan 
19500b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
19510caa102dSLi Zefan 
19520caa102dSLi Zefan 	/* nothing to do */
19530caa102dSLi Zefan 	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1954b9ca0664SLiu Bo 		goto out_drop_sem;
19550caa102dSLi Zefan 
19560caa102dSLi Zefan 	root_flags = btrfs_root_flags(&root->root_item);
19572c686537SDavid Sterba 	if (flags & BTRFS_SUBVOL_RDONLY) {
19580caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item,
19590caa102dSLi Zefan 				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
19602c686537SDavid Sterba 	} else {
19612c686537SDavid Sterba 		/*
19622c686537SDavid Sterba 		 * Block RO -> RW transition if this subvolume is involved in
19632c686537SDavid Sterba 		 * send
19642c686537SDavid Sterba 		 */
19652c686537SDavid Sterba 		spin_lock(&root->root_item_lock);
19662c686537SDavid Sterba 		if (root->send_in_progress == 0) {
19670caa102dSLi Zefan 			btrfs_set_root_flags(&root->root_item,
19680caa102dSLi Zefan 				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
19692c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19702c686537SDavid Sterba 		} else {
19712c686537SDavid Sterba 			spin_unlock(&root->root_item_lock);
19720b246afaSJeff Mahoney 			btrfs_warn(fs_info,
19732c686537SDavid Sterba 				   "Attempt to set subvolume %llu read-write during send",
19742c686537SDavid Sterba 				   root->root_key.objectid);
19752c686537SDavid Sterba 			ret = -EPERM;
19762c686537SDavid Sterba 			goto out_drop_sem;
19772c686537SDavid Sterba 		}
19782c686537SDavid Sterba 	}
19790caa102dSLi Zefan 
19800caa102dSLi Zefan 	trans = btrfs_start_transaction(root, 1);
19810caa102dSLi Zefan 	if (IS_ERR(trans)) {
19820caa102dSLi Zefan 		ret = PTR_ERR(trans);
19830caa102dSLi Zefan 		goto out_reset;
19840caa102dSLi Zefan 	}
19850caa102dSLi Zefan 
19860b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
19870caa102dSLi Zefan 				&root->root_key, &root->root_item);
19889417ebc8SNikolay Borisov 	if (ret < 0) {
19899417ebc8SNikolay Borisov 		btrfs_end_transaction(trans);
19909417ebc8SNikolay Borisov 		goto out_reset;
19919417ebc8SNikolay Borisov 	}
19920caa102dSLi Zefan 
19939417ebc8SNikolay Borisov 	ret = btrfs_commit_transaction(trans);
19949417ebc8SNikolay Borisov 
19950caa102dSLi Zefan out_reset:
19960caa102dSLi Zefan 	if (ret)
19970caa102dSLi Zefan 		btrfs_set_root_flags(&root->root_item, root_flags);
1998b9ca0664SLiu Bo out_drop_sem:
19990b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
2000b9ca0664SLiu Bo out_drop_write:
2001b9ca0664SLiu Bo 	mnt_drop_write_file(file);
2002b9ca0664SLiu Bo out:
20030caa102dSLi Zefan 	return ret;
20040caa102dSLi Zefan }
20050caa102dSLi Zefan 
2006ac8e9819SChris Mason static noinline int key_in_sk(struct btrfs_key *key,
2007ac8e9819SChris Mason 			      struct btrfs_ioctl_search_key *sk)
2008ac8e9819SChris Mason {
2009abc6e134SChris Mason 	struct btrfs_key test;
2010abc6e134SChris Mason 	int ret;
2011abc6e134SChris Mason 
2012abc6e134SChris Mason 	test.objectid = sk->min_objectid;
2013abc6e134SChris Mason 	test.type = sk->min_type;
2014abc6e134SChris Mason 	test.offset = sk->min_offset;
2015abc6e134SChris Mason 
2016abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
2017abc6e134SChris Mason 	if (ret < 0)
2018ac8e9819SChris Mason 		return 0;
2019abc6e134SChris Mason 
2020abc6e134SChris Mason 	test.objectid = sk->max_objectid;
2021abc6e134SChris Mason 	test.type = sk->max_type;
2022abc6e134SChris Mason 	test.offset = sk->max_offset;
2023abc6e134SChris Mason 
2024abc6e134SChris Mason 	ret = btrfs_comp_cpu_keys(key, &test);
2025abc6e134SChris Mason 	if (ret > 0)
2026ac8e9819SChris Mason 		return 0;
2027ac8e9819SChris Mason 	return 1;
2028ac8e9819SChris Mason }
2029ac8e9819SChris Mason 
2030df397565SJeff Mahoney static noinline int copy_to_sk(struct btrfs_path *path,
2031ac8e9819SChris Mason 			       struct btrfs_key *key,
2032ac8e9819SChris Mason 			       struct btrfs_ioctl_search_key *sk,
20339b6e817dSGerhard Heift 			       size_t *buf_size,
2034ba346b35SGerhard Heift 			       char __user *ubuf,
2035ac8e9819SChris Mason 			       unsigned long *sk_offset,
2036ac8e9819SChris Mason 			       int *num_found)
2037ac8e9819SChris Mason {
2038ac8e9819SChris Mason 	u64 found_transid;
2039ac8e9819SChris Mason 	struct extent_buffer *leaf;
2040ac8e9819SChris Mason 	struct btrfs_ioctl_search_header sh;
2041dd81d459SNaohiro Aota 	struct btrfs_key test;
2042ac8e9819SChris Mason 	unsigned long item_off;
2043ac8e9819SChris Mason 	unsigned long item_len;
2044ac8e9819SChris Mason 	int nritems;
2045ac8e9819SChris Mason 	int i;
2046ac8e9819SChris Mason 	int slot;
2047ac8e9819SChris Mason 	int ret = 0;
2048ac8e9819SChris Mason 
2049ac8e9819SChris Mason 	leaf = path->nodes[0];
2050ac8e9819SChris Mason 	slot = path->slots[0];
2051ac8e9819SChris Mason 	nritems = btrfs_header_nritems(leaf);
2052ac8e9819SChris Mason 
2053ac8e9819SChris Mason 	if (btrfs_header_generation(leaf) > sk->max_transid) {
2054ac8e9819SChris Mason 		i = nritems;
2055ac8e9819SChris Mason 		goto advance_key;
2056ac8e9819SChris Mason 	}
2057ac8e9819SChris Mason 	found_transid = btrfs_header_generation(leaf);
2058ac8e9819SChris Mason 
2059ac8e9819SChris Mason 	for (i = slot; i < nritems; i++) {
2060ac8e9819SChris Mason 		item_off = btrfs_item_ptr_offset(leaf, i);
2061ac8e9819SChris Mason 		item_len = btrfs_item_size_nr(leaf, i);
2062ac8e9819SChris Mason 
206303b71c6cSGabriel de Perthuis 		btrfs_item_key_to_cpu(leaf, key, i);
206403b71c6cSGabriel de Perthuis 		if (!key_in_sk(key, sk))
206503b71c6cSGabriel de Perthuis 			continue;
206603b71c6cSGabriel de Perthuis 
20679b6e817dSGerhard Heift 		if (sizeof(sh) + item_len > *buf_size) {
20688f5f6178SGerhard Heift 			if (*num_found) {
2069ac8e9819SChris Mason 				ret = 1;
20708f5f6178SGerhard Heift 				goto out;
20718f5f6178SGerhard Heift 			}
20728f5f6178SGerhard Heift 
20738f5f6178SGerhard Heift 			/*
20748f5f6178SGerhard Heift 			 * return one empty item back for v1, which does not
20758f5f6178SGerhard Heift 			 * handle -EOVERFLOW
20768f5f6178SGerhard Heift 			 */
20778f5f6178SGerhard Heift 
20789b6e817dSGerhard Heift 			*buf_size = sizeof(sh) + item_len;
2079ac8e9819SChris Mason 			item_len = 0;
20808f5f6178SGerhard Heift 			ret = -EOVERFLOW;
20818f5f6178SGerhard Heift 		}
2082ac8e9819SChris Mason 
20839b6e817dSGerhard Heift 		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2084ac8e9819SChris Mason 			ret = 1;
208525c9bc2eSGerhard Heift 			goto out;
2086ac8e9819SChris Mason 		}
2087ac8e9819SChris Mason 
2088ac8e9819SChris Mason 		sh.objectid = key->objectid;
2089ac8e9819SChris Mason 		sh.offset = key->offset;
2090ac8e9819SChris Mason 		sh.type = key->type;
2091ac8e9819SChris Mason 		sh.len = item_len;
2092ac8e9819SChris Mason 		sh.transid = found_transid;
2093ac8e9819SChris Mason 
2094ac8e9819SChris Mason 		/* copy search result header */
2095ba346b35SGerhard Heift 		if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2096ba346b35SGerhard Heift 			ret = -EFAULT;
2097ba346b35SGerhard Heift 			goto out;
2098ba346b35SGerhard Heift 		}
2099ba346b35SGerhard Heift 
2100ac8e9819SChris Mason 		*sk_offset += sizeof(sh);
2101ac8e9819SChris Mason 
2102ac8e9819SChris Mason 		if (item_len) {
2103ba346b35SGerhard Heift 			char __user *up = ubuf + *sk_offset;
2104ac8e9819SChris Mason 			/* copy the item */
2105ba346b35SGerhard Heift 			if (read_extent_buffer_to_user(leaf, up,
2106ba346b35SGerhard Heift 						       item_off, item_len)) {
2107ba346b35SGerhard Heift 				ret = -EFAULT;
2108ba346b35SGerhard Heift 				goto out;
2109ba346b35SGerhard Heift 			}
2110ba346b35SGerhard Heift 
2111ac8e9819SChris Mason 			*sk_offset += item_len;
2112ac8e9819SChris Mason 		}
2113e2156867SHugo Mills 		(*num_found)++;
2114ac8e9819SChris Mason 
21158f5f6178SGerhard Heift 		if (ret) /* -EOVERFLOW from above */
21168f5f6178SGerhard Heift 			goto out;
21178f5f6178SGerhard Heift 
211825c9bc2eSGerhard Heift 		if (*num_found >= sk->nr_items) {
211925c9bc2eSGerhard Heift 			ret = 1;
212025c9bc2eSGerhard Heift 			goto out;
212125c9bc2eSGerhard Heift 		}
2122ac8e9819SChris Mason 	}
2123ac8e9819SChris Mason advance_key:
2124ac8e9819SChris Mason 	ret = 0;
2125dd81d459SNaohiro Aota 	test.objectid = sk->max_objectid;
2126dd81d459SNaohiro Aota 	test.type = sk->max_type;
2127dd81d459SNaohiro Aota 	test.offset = sk->max_offset;
2128dd81d459SNaohiro Aota 	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2129dd81d459SNaohiro Aota 		ret = 1;
2130dd81d459SNaohiro Aota 	else if (key->offset < (u64)-1)
2131abc6e134SChris Mason 		key->offset++;
2132dd81d459SNaohiro Aota 	else if (key->type < (u8)-1) {
2133abc6e134SChris Mason 		key->offset = 0;
2134abc6e134SChris Mason 		key->type++;
2135dd81d459SNaohiro Aota 	} else if (key->objectid < (u64)-1) {
2136abc6e134SChris Mason 		key->offset = 0;
2137abc6e134SChris Mason 		key->type = 0;
2138abc6e134SChris Mason 		key->objectid++;
2139abc6e134SChris Mason 	} else
2140abc6e134SChris Mason 		ret = 1;
214125c9bc2eSGerhard Heift out:
2142ba346b35SGerhard Heift 	/*
2143ba346b35SGerhard Heift 	 *  0: all items from this leaf copied, continue with next
2144ba346b35SGerhard Heift 	 *  1: * more items can be copied, but unused buffer is too small
2145ba346b35SGerhard Heift 	 *     * all items were found
2146ba346b35SGerhard Heift 	 *     Either way, it will stops the loop which iterates to the next
2147ba346b35SGerhard Heift 	 *     leaf
2148ba346b35SGerhard Heift 	 *  -EOVERFLOW: item was to large for buffer
2149ba346b35SGerhard Heift 	 *  -EFAULT: could not copy extent buffer back to userspace
2150ba346b35SGerhard Heift 	 */
2151ac8e9819SChris Mason 	return ret;
2152ac8e9819SChris Mason }
2153ac8e9819SChris Mason 
2154ac8e9819SChris Mason static noinline int search_ioctl(struct inode *inode,
215512544442SGerhard Heift 				 struct btrfs_ioctl_search_key *sk,
21569b6e817dSGerhard Heift 				 size_t *buf_size,
2157ba346b35SGerhard Heift 				 char __user *ubuf)
2158ac8e9819SChris Mason {
21590b246afaSJeff Mahoney 	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2160ac8e9819SChris Mason 	struct btrfs_root *root;
2161ac8e9819SChris Mason 	struct btrfs_key key;
2162ac8e9819SChris Mason 	struct btrfs_path *path;
2163ac8e9819SChris Mason 	int ret;
2164ac8e9819SChris Mason 	int num_found = 0;
2165ac8e9819SChris Mason 	unsigned long sk_offset = 0;
2166ac8e9819SChris Mason 
21679b6e817dSGerhard Heift 	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
21689b6e817dSGerhard Heift 		*buf_size = sizeof(struct btrfs_ioctl_search_header);
216912544442SGerhard Heift 		return -EOVERFLOW;
21709b6e817dSGerhard Heift 	}
217112544442SGerhard Heift 
2172ac8e9819SChris Mason 	path = btrfs_alloc_path();
2173ac8e9819SChris Mason 	if (!path)
2174ac8e9819SChris Mason 		return -ENOMEM;
2175ac8e9819SChris Mason 
2176ac8e9819SChris Mason 	if (sk->tree_id == 0) {
2177ac8e9819SChris Mason 		/* search the root of the inode that was passed */
2178ac8e9819SChris Mason 		root = BTRFS_I(inode)->root;
2179ac8e9819SChris Mason 	} else {
2180ac8e9819SChris Mason 		key.objectid = sk->tree_id;
2181ac8e9819SChris Mason 		key.type = BTRFS_ROOT_ITEM_KEY;
2182ac8e9819SChris Mason 		key.offset = (u64)-1;
2183ac8e9819SChris Mason 		root = btrfs_read_fs_root_no_name(info, &key);
2184ac8e9819SChris Mason 		if (IS_ERR(root)) {
2185ac8e9819SChris Mason 			btrfs_free_path(path);
2186ad1e3d56SMisono Tomohiro 			return PTR_ERR(root);
2187ac8e9819SChris Mason 		}
2188ac8e9819SChris Mason 	}
2189ac8e9819SChris Mason 
2190ac8e9819SChris Mason 	key.objectid = sk->min_objectid;
2191ac8e9819SChris Mason 	key.type = sk->min_type;
2192ac8e9819SChris Mason 	key.offset = sk->min_offset;
2193ac8e9819SChris Mason 
2194ac8e9819SChris Mason 	while (1) {
21956174d3cbSFilipe David Borba Manana 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2196ac8e9819SChris Mason 		if (ret != 0) {
2197ac8e9819SChris Mason 			if (ret > 0)
2198ac8e9819SChris Mason 				ret = 0;
2199ac8e9819SChris Mason 			goto err;
2200ac8e9819SChris Mason 		}
2201df397565SJeff Mahoney 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2202ac8e9819SChris Mason 				 &sk_offset, &num_found);
2203b3b4aa74SDavid Sterba 		btrfs_release_path(path);
220425c9bc2eSGerhard Heift 		if (ret)
2205ac8e9819SChris Mason 			break;
2206ac8e9819SChris Mason 
2207ac8e9819SChris Mason 	}
22088f5f6178SGerhard Heift 	if (ret > 0)
2209ac8e9819SChris Mason 		ret = 0;
2210ac8e9819SChris Mason err:
2211ac8e9819SChris Mason 	sk->nr_items = num_found;
2212ac8e9819SChris Mason 	btrfs_free_path(path);
2213ac8e9819SChris Mason 	return ret;
2214ac8e9819SChris Mason }
2215ac8e9819SChris Mason 
2216ac8e9819SChris Mason static noinline int btrfs_ioctl_tree_search(struct file *file,
2217ac8e9819SChris Mason 					   void __user *argp)
2218ac8e9819SChris Mason {
2219ba346b35SGerhard Heift 	struct btrfs_ioctl_search_args __user *uargs;
2220ba346b35SGerhard Heift 	struct btrfs_ioctl_search_key sk;
2221ac8e9819SChris Mason 	struct inode *inode;
2222ac8e9819SChris Mason 	int ret;
22239b6e817dSGerhard Heift 	size_t buf_size;
2224ac8e9819SChris Mason 
2225ac8e9819SChris Mason 	if (!capable(CAP_SYS_ADMIN))
2226ac8e9819SChris Mason 		return -EPERM;
2227ac8e9819SChris Mason 
2228ba346b35SGerhard Heift 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2229ac8e9819SChris Mason 
2230ba346b35SGerhard Heift 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2231ba346b35SGerhard Heift 		return -EFAULT;
2232ba346b35SGerhard Heift 
2233ba346b35SGerhard Heift 	buf_size = sizeof(uargs->buf);
2234ac8e9819SChris Mason 
2235496ad9aaSAl Viro 	inode = file_inode(file);
2236ba346b35SGerhard Heift 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
22378f5f6178SGerhard Heift 
22388f5f6178SGerhard Heift 	/*
22398f5f6178SGerhard Heift 	 * In the origin implementation an overflow is handled by returning a
22408f5f6178SGerhard Heift 	 * search header with a len of zero, so reset ret.
22418f5f6178SGerhard Heift 	 */
22428f5f6178SGerhard Heift 	if (ret == -EOVERFLOW)
22438f5f6178SGerhard Heift 		ret = 0;
22448f5f6178SGerhard Heift 
2245ba346b35SGerhard Heift 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2246ac8e9819SChris Mason 		ret = -EFAULT;
2247ac8e9819SChris Mason 	return ret;
2248ac8e9819SChris Mason }
2249ac8e9819SChris Mason 
2250cc68a8a5SGerhard Heift static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2251cc68a8a5SGerhard Heift 					       void __user *argp)
2252cc68a8a5SGerhard Heift {
2253cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2254cc68a8a5SGerhard Heift 	struct btrfs_ioctl_search_args_v2 args;
2255cc68a8a5SGerhard Heift 	struct inode *inode;
2256cc68a8a5SGerhard Heift 	int ret;
2257cc68a8a5SGerhard Heift 	size_t buf_size;
2258ee22184bSByongho Lee 	const size_t buf_limit = SZ_16M;
2259cc68a8a5SGerhard Heift 
2260cc68a8a5SGerhard Heift 	if (!capable(CAP_SYS_ADMIN))
2261cc68a8a5SGerhard Heift 		return -EPERM;
2262cc68a8a5SGerhard Heift 
2263cc68a8a5SGerhard Heift 	/* copy search header and buffer size */
2264cc68a8a5SGerhard Heift 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2265cc68a8a5SGerhard Heift 	if (copy_from_user(&args, uarg, sizeof(args)))
2266cc68a8a5SGerhard Heift 		return -EFAULT;
2267cc68a8a5SGerhard Heift 
2268cc68a8a5SGerhard Heift 	buf_size = args.buf_size;
2269cc68a8a5SGerhard Heift 
2270cc68a8a5SGerhard Heift 	/* limit result size to 16MB */
2271cc68a8a5SGerhard Heift 	if (buf_size > buf_limit)
2272cc68a8a5SGerhard Heift 		buf_size = buf_limit;
2273cc68a8a5SGerhard Heift 
2274cc68a8a5SGerhard Heift 	inode = file_inode(file);
2275cc68a8a5SGerhard Heift 	ret = search_ioctl(inode, &args.key, &buf_size,
2276718dc5faSOmar Sandoval 			   (char __user *)(&uarg->buf[0]));
2277cc68a8a5SGerhard Heift 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2278cc68a8a5SGerhard Heift 		ret = -EFAULT;
2279cc68a8a5SGerhard Heift 	else if (ret == -EOVERFLOW &&
2280cc68a8a5SGerhard Heift 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2281cc68a8a5SGerhard Heift 		ret = -EFAULT;
2282cc68a8a5SGerhard Heift 
228376dda93cSYan, Zheng 	return ret;
228476dda93cSYan, Zheng }
228576dda93cSYan, Zheng 
228698d377a0STARUISI Hiroaki /*
2287ac8e9819SChris Mason  * Search INODE_REFs to identify path name of 'dirid' directory
2288ac8e9819SChris Mason  * in a 'tree_id' tree. and sets path name to 'name'.
228998d377a0STARUISI Hiroaki  */
229098d377a0STARUISI Hiroaki static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
229198d377a0STARUISI Hiroaki 				u64 tree_id, u64 dirid, char *name)
229298d377a0STARUISI Hiroaki {
229398d377a0STARUISI Hiroaki 	struct btrfs_root *root;
229498d377a0STARUISI Hiroaki 	struct btrfs_key key;
2295ac8e9819SChris Mason 	char *ptr;
229698d377a0STARUISI Hiroaki 	int ret = -1;
229798d377a0STARUISI Hiroaki 	int slot;
229898d377a0STARUISI Hiroaki 	int len;
229998d377a0STARUISI Hiroaki 	int total_len = 0;
230098d377a0STARUISI Hiroaki 	struct btrfs_inode_ref *iref;
230198d377a0STARUISI Hiroaki 	struct extent_buffer *l;
230298d377a0STARUISI Hiroaki 	struct btrfs_path *path;
230398d377a0STARUISI Hiroaki 
230498d377a0STARUISI Hiroaki 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
230598d377a0STARUISI Hiroaki 		name[0]='\0';
230698d377a0STARUISI Hiroaki 		return 0;
230798d377a0STARUISI Hiroaki 	}
230898d377a0STARUISI Hiroaki 
230998d377a0STARUISI Hiroaki 	path = btrfs_alloc_path();
231098d377a0STARUISI Hiroaki 	if (!path)
231198d377a0STARUISI Hiroaki 		return -ENOMEM;
231298d377a0STARUISI Hiroaki 
2313c8bcbfbdSNikolay Borisov 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
231498d377a0STARUISI Hiroaki 
231598d377a0STARUISI Hiroaki 	key.objectid = tree_id;
231698d377a0STARUISI Hiroaki 	key.type = BTRFS_ROOT_ITEM_KEY;
231798d377a0STARUISI Hiroaki 	key.offset = (u64)-1;
231898d377a0STARUISI Hiroaki 	root = btrfs_read_fs_root_no_name(info, &key);
231998d377a0STARUISI Hiroaki 	if (IS_ERR(root)) {
2320ad1e3d56SMisono Tomohiro 		ret = PTR_ERR(root);
23218ad6fcabSChris Mason 		goto out;
232298d377a0STARUISI Hiroaki 	}
232398d377a0STARUISI Hiroaki 
232498d377a0STARUISI Hiroaki 	key.objectid = dirid;
232598d377a0STARUISI Hiroaki 	key.type = BTRFS_INODE_REF_KEY;
23268ad6fcabSChris Mason 	key.offset = (u64)-1;
232798d377a0STARUISI Hiroaki 
232898d377a0STARUISI Hiroaki 	while (1) {
232998d377a0STARUISI Hiroaki 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
233098d377a0STARUISI Hiroaki 		if (ret < 0)
233198d377a0STARUISI Hiroaki 			goto out;
233218674c6cSFilipe David Borba Manana 		else if (ret > 0) {
233318674c6cSFilipe David Borba Manana 			ret = btrfs_previous_item(root, path, dirid,
233418674c6cSFilipe David Borba Manana 						  BTRFS_INODE_REF_KEY);
233518674c6cSFilipe David Borba Manana 			if (ret < 0)
233618674c6cSFilipe David Borba Manana 				goto out;
233718674c6cSFilipe David Borba Manana 			else if (ret > 0) {
2338ac8e9819SChris Mason 				ret = -ENOENT;
233998d377a0STARUISI Hiroaki 				goto out;
2340ac8e9819SChris Mason 			}
234118674c6cSFilipe David Borba Manana 		}
234218674c6cSFilipe David Borba Manana 
234318674c6cSFilipe David Borba Manana 		l = path->nodes[0];
234418674c6cSFilipe David Borba Manana 		slot = path->slots[0];
234518674c6cSFilipe David Borba Manana 		btrfs_item_key_to_cpu(l, &key, slot);
234698d377a0STARUISI Hiroaki 
234798d377a0STARUISI Hiroaki 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
234898d377a0STARUISI Hiroaki 		len = btrfs_inode_ref_name_len(l, iref);
234998d377a0STARUISI Hiroaki 		ptr -= len + 1;
235098d377a0STARUISI Hiroaki 		total_len += len + 1;
2351a696cf35SFilipe David Borba Manana 		if (ptr < name) {
2352a696cf35SFilipe David Borba Manana 			ret = -ENAMETOOLONG;
235398d377a0STARUISI Hiroaki 			goto out;
2354a696cf35SFilipe David Borba Manana 		}
235598d377a0STARUISI Hiroaki 
235698d377a0STARUISI Hiroaki 		*(ptr + len) = '/';
235798d377a0STARUISI Hiroaki 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
235898d377a0STARUISI Hiroaki 
235998d377a0STARUISI Hiroaki 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
236098d377a0STARUISI Hiroaki 			break;
236198d377a0STARUISI Hiroaki 
2362b3b4aa74SDavid Sterba 		btrfs_release_path(path);
236398d377a0STARUISI Hiroaki 		key.objectid = key.offset;
23648ad6fcabSChris Mason 		key.offset = (u64)-1;
236598d377a0STARUISI Hiroaki 		dirid = key.objectid;
236698d377a0STARUISI Hiroaki 	}
236777906a50SLi Zefan 	memmove(name, ptr, total_len);
236898d377a0STARUISI Hiroaki 	name[total_len] = '\0';
236998d377a0STARUISI Hiroaki 	ret = 0;
237098d377a0STARUISI Hiroaki out:
237198d377a0STARUISI Hiroaki 	btrfs_free_path(path);
2372ac8e9819SChris Mason 	return ret;
2373ac8e9819SChris Mason }
2374ac8e9819SChris Mason 
237523d0b79dSTomohiro Misono static int btrfs_search_path_in_tree_user(struct inode *inode,
237623d0b79dSTomohiro Misono 				struct btrfs_ioctl_ino_lookup_user_args *args)
237723d0b79dSTomohiro Misono {
237823d0b79dSTomohiro Misono 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
237923d0b79dSTomohiro Misono 	struct super_block *sb = inode->i_sb;
238023d0b79dSTomohiro Misono 	struct btrfs_key upper_limit = BTRFS_I(inode)->location;
238123d0b79dSTomohiro Misono 	u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
238223d0b79dSTomohiro Misono 	u64 dirid = args->dirid;
238323d0b79dSTomohiro Misono 	unsigned long item_off;
238423d0b79dSTomohiro Misono 	unsigned long item_len;
238523d0b79dSTomohiro Misono 	struct btrfs_inode_ref *iref;
238623d0b79dSTomohiro Misono 	struct btrfs_root_ref *rref;
238723d0b79dSTomohiro Misono 	struct btrfs_root *root;
238823d0b79dSTomohiro Misono 	struct btrfs_path *path;
238923d0b79dSTomohiro Misono 	struct btrfs_key key, key2;
239023d0b79dSTomohiro Misono 	struct extent_buffer *leaf;
239123d0b79dSTomohiro Misono 	struct inode *temp_inode;
239223d0b79dSTomohiro Misono 	char *ptr;
239323d0b79dSTomohiro Misono 	int slot;
239423d0b79dSTomohiro Misono 	int len;
239523d0b79dSTomohiro Misono 	int total_len = 0;
239623d0b79dSTomohiro Misono 	int ret;
239723d0b79dSTomohiro Misono 
239823d0b79dSTomohiro Misono 	path = btrfs_alloc_path();
239923d0b79dSTomohiro Misono 	if (!path)
240023d0b79dSTomohiro Misono 		return -ENOMEM;
240123d0b79dSTomohiro Misono 
240223d0b79dSTomohiro Misono 	/*
240323d0b79dSTomohiro Misono 	 * If the bottom subvolume does not exist directly under upper_limit,
240423d0b79dSTomohiro Misono 	 * construct the path in from the bottom up.
240523d0b79dSTomohiro Misono 	 */
240623d0b79dSTomohiro Misono 	if (dirid != upper_limit.objectid) {
240723d0b79dSTomohiro Misono 		ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
240823d0b79dSTomohiro Misono 
240923d0b79dSTomohiro Misono 		key.objectid = treeid;
241023d0b79dSTomohiro Misono 		key.type = BTRFS_ROOT_ITEM_KEY;
241123d0b79dSTomohiro Misono 		key.offset = (u64)-1;
241223d0b79dSTomohiro Misono 		root = btrfs_read_fs_root_no_name(fs_info, &key);
241323d0b79dSTomohiro Misono 		if (IS_ERR(root)) {
241423d0b79dSTomohiro Misono 			ret = PTR_ERR(root);
241523d0b79dSTomohiro Misono 			goto out;
241623d0b79dSTomohiro Misono 		}
241723d0b79dSTomohiro Misono 
241823d0b79dSTomohiro Misono 		key.objectid = dirid;
241923d0b79dSTomohiro Misono 		key.type = BTRFS_INODE_REF_KEY;
242023d0b79dSTomohiro Misono 		key.offset = (u64)-1;
242123d0b79dSTomohiro Misono 		while (1) {
242223d0b79dSTomohiro Misono 			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
242323d0b79dSTomohiro Misono 			if (ret < 0) {
242423d0b79dSTomohiro Misono 				goto out;
242523d0b79dSTomohiro Misono 			} else if (ret > 0) {
242623d0b79dSTomohiro Misono 				ret = btrfs_previous_item(root, path, dirid,
242723d0b79dSTomohiro Misono 							  BTRFS_INODE_REF_KEY);
242823d0b79dSTomohiro Misono 				if (ret < 0) {
242923d0b79dSTomohiro Misono 					goto out;
243023d0b79dSTomohiro Misono 				} else if (ret > 0) {
243123d0b79dSTomohiro Misono 					ret = -ENOENT;
243223d0b79dSTomohiro Misono 					goto out;
243323d0b79dSTomohiro Misono 				}
243423d0b79dSTomohiro Misono 			}
243523d0b79dSTomohiro Misono 
243623d0b79dSTomohiro Misono 			leaf = path->nodes[0];
243723d0b79dSTomohiro Misono 			slot = path->slots[0];
243823d0b79dSTomohiro Misono 			btrfs_item_key_to_cpu(leaf, &key, slot);
243923d0b79dSTomohiro Misono 
244023d0b79dSTomohiro Misono 			iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
244123d0b79dSTomohiro Misono 			len = btrfs_inode_ref_name_len(leaf, iref);
244223d0b79dSTomohiro Misono 			ptr -= len + 1;
244323d0b79dSTomohiro Misono 			total_len += len + 1;
244423d0b79dSTomohiro Misono 			if (ptr < args->path) {
244523d0b79dSTomohiro Misono 				ret = -ENAMETOOLONG;
244623d0b79dSTomohiro Misono 				goto out;
244723d0b79dSTomohiro Misono 			}
244823d0b79dSTomohiro Misono 
244923d0b79dSTomohiro Misono 			*(ptr + len) = '/';
245023d0b79dSTomohiro Misono 			read_extent_buffer(leaf, ptr,
245123d0b79dSTomohiro Misono 					(unsigned long)(iref + 1), len);
245223d0b79dSTomohiro Misono 
245323d0b79dSTomohiro Misono 			/* Check the read+exec permission of this directory */
245423d0b79dSTomohiro Misono 			ret = btrfs_previous_item(root, path, dirid,
245523d0b79dSTomohiro Misono 						  BTRFS_INODE_ITEM_KEY);
245623d0b79dSTomohiro Misono 			if (ret < 0) {
245723d0b79dSTomohiro Misono 				goto out;
245823d0b79dSTomohiro Misono 			} else if (ret > 0) {
245923d0b79dSTomohiro Misono 				ret = -ENOENT;
246023d0b79dSTomohiro Misono 				goto out;
246123d0b79dSTomohiro Misono 			}
246223d0b79dSTomohiro Misono 
246323d0b79dSTomohiro Misono 			leaf = path->nodes[0];
246423d0b79dSTomohiro Misono 			slot = path->slots[0];
246523d0b79dSTomohiro Misono 			btrfs_item_key_to_cpu(leaf, &key2, slot);
246623d0b79dSTomohiro Misono 			if (key2.objectid != dirid) {
246723d0b79dSTomohiro Misono 				ret = -ENOENT;
246823d0b79dSTomohiro Misono 				goto out;
246923d0b79dSTomohiro Misono 			}
247023d0b79dSTomohiro Misono 
247123d0b79dSTomohiro Misono 			temp_inode = btrfs_iget(sb, &key2, root, NULL);
24723ca57bd6SMisono Tomohiro 			if (IS_ERR(temp_inode)) {
24733ca57bd6SMisono Tomohiro 				ret = PTR_ERR(temp_inode);
24743ca57bd6SMisono Tomohiro 				goto out;
24753ca57bd6SMisono Tomohiro 			}
247623d0b79dSTomohiro Misono 			ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC);
247723d0b79dSTomohiro Misono 			iput(temp_inode);
247823d0b79dSTomohiro Misono 			if (ret) {
247923d0b79dSTomohiro Misono 				ret = -EACCES;
248023d0b79dSTomohiro Misono 				goto out;
248123d0b79dSTomohiro Misono 			}
248223d0b79dSTomohiro Misono 
248323d0b79dSTomohiro Misono 			if (key.offset == upper_limit.objectid)
248423d0b79dSTomohiro Misono 				break;
248523d0b79dSTomohiro Misono 			if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
248623d0b79dSTomohiro Misono 				ret = -EACCES;
248723d0b79dSTomohiro Misono 				goto out;
248823d0b79dSTomohiro Misono 			}
248923d0b79dSTomohiro Misono 
249023d0b79dSTomohiro Misono 			btrfs_release_path(path);
249123d0b79dSTomohiro Misono 			key.objectid = key.offset;
249223d0b79dSTomohiro Misono 			key.offset = (u64)-1;
249323d0b79dSTomohiro Misono 			dirid = key.objectid;
249423d0b79dSTomohiro Misono 		}
249523d0b79dSTomohiro Misono 
249623d0b79dSTomohiro Misono 		memmove(args->path, ptr, total_len);
249723d0b79dSTomohiro Misono 		args->path[total_len] = '\0';
249823d0b79dSTomohiro Misono 		btrfs_release_path(path);
249923d0b79dSTomohiro Misono 	}
250023d0b79dSTomohiro Misono 
250123d0b79dSTomohiro Misono 	/* Get the bottom subvolume's name from ROOT_REF */
250223d0b79dSTomohiro Misono 	root = fs_info->tree_root;
250323d0b79dSTomohiro Misono 	key.objectid = treeid;
250423d0b79dSTomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
250523d0b79dSTomohiro Misono 	key.offset = args->treeid;
250623d0b79dSTomohiro Misono 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
250723d0b79dSTomohiro Misono 	if (ret < 0) {
250823d0b79dSTomohiro Misono 		goto out;
250923d0b79dSTomohiro Misono 	} else if (ret > 0) {
251023d0b79dSTomohiro Misono 		ret = -ENOENT;
251123d0b79dSTomohiro Misono 		goto out;
251223d0b79dSTomohiro Misono 	}
251323d0b79dSTomohiro Misono 
251423d0b79dSTomohiro Misono 	leaf = path->nodes[0];
251523d0b79dSTomohiro Misono 	slot = path->slots[0];
251623d0b79dSTomohiro Misono 	btrfs_item_key_to_cpu(leaf, &key, slot);
251723d0b79dSTomohiro Misono 
251823d0b79dSTomohiro Misono 	item_off = btrfs_item_ptr_offset(leaf, slot);
251923d0b79dSTomohiro Misono 	item_len = btrfs_item_size_nr(leaf, slot);
252023d0b79dSTomohiro Misono 	/* Check if dirid in ROOT_REF corresponds to passed dirid */
252123d0b79dSTomohiro Misono 	rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
252223d0b79dSTomohiro Misono 	if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
252323d0b79dSTomohiro Misono 		ret = -EINVAL;
252423d0b79dSTomohiro Misono 		goto out;
252523d0b79dSTomohiro Misono 	}
252623d0b79dSTomohiro Misono 
252723d0b79dSTomohiro Misono 	/* Copy subvolume's name */
252823d0b79dSTomohiro Misono 	item_off += sizeof(struct btrfs_root_ref);
252923d0b79dSTomohiro Misono 	item_len -= sizeof(struct btrfs_root_ref);
253023d0b79dSTomohiro Misono 	read_extent_buffer(leaf, args->name, item_off, item_len);
253123d0b79dSTomohiro Misono 	args->name[item_len] = 0;
253223d0b79dSTomohiro Misono 
253323d0b79dSTomohiro Misono out:
253423d0b79dSTomohiro Misono 	btrfs_free_path(path);
253523d0b79dSTomohiro Misono 	return ret;
253623d0b79dSTomohiro Misono }
253723d0b79dSTomohiro Misono 
2538ac8e9819SChris Mason static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2539ac8e9819SChris Mason 					   void __user *argp)
2540ac8e9819SChris Mason {
2541ac8e9819SChris Mason 	struct btrfs_ioctl_ino_lookup_args *args;
2542ac8e9819SChris Mason 	struct inode *inode;
254301b810b8SDavid Sterba 	int ret = 0;
2544ac8e9819SChris Mason 
25452354d08fSJulia Lawall 	args = memdup_user(argp, sizeof(*args));
25462354d08fSJulia Lawall 	if (IS_ERR(args))
25472354d08fSJulia Lawall 		return PTR_ERR(args);
2548c2b96929SDan Carpenter 
2549496ad9aaSAl Viro 	inode = file_inode(file);
2550ac8e9819SChris Mason 
255101b810b8SDavid Sterba 	/*
255201b810b8SDavid Sterba 	 * Unprivileged query to obtain the containing subvolume root id. The
255301b810b8SDavid Sterba 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
255401b810b8SDavid Sterba 	 */
25551b53ac4dSChris Mason 	if (args->treeid == 0)
25561b53ac4dSChris Mason 		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
25571b53ac4dSChris Mason 
255801b810b8SDavid Sterba 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
255901b810b8SDavid Sterba 		args->name[0] = 0;
256001b810b8SDavid Sterba 		goto out;
256101b810b8SDavid Sterba 	}
256201b810b8SDavid Sterba 
256301b810b8SDavid Sterba 	if (!capable(CAP_SYS_ADMIN)) {
256401b810b8SDavid Sterba 		ret = -EPERM;
256501b810b8SDavid Sterba 		goto out;
256601b810b8SDavid Sterba 	}
256701b810b8SDavid Sterba 
2568ac8e9819SChris Mason 	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2569ac8e9819SChris Mason 					args->treeid, args->objectid,
2570ac8e9819SChris Mason 					args->name);
2571ac8e9819SChris Mason 
257201b810b8SDavid Sterba out:
2573ac8e9819SChris Mason 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2574ac8e9819SChris Mason 		ret = -EFAULT;
2575ac8e9819SChris Mason 
2576ac8e9819SChris Mason 	kfree(args);
257798d377a0STARUISI Hiroaki 	return ret;
257898d377a0STARUISI Hiroaki }
257998d377a0STARUISI Hiroaki 
258023d0b79dSTomohiro Misono /*
258123d0b79dSTomohiro Misono  * Version of ino_lookup ioctl (unprivileged)
258223d0b79dSTomohiro Misono  *
258323d0b79dSTomohiro Misono  * The main differences from ino_lookup ioctl are:
258423d0b79dSTomohiro Misono  *
258523d0b79dSTomohiro Misono  *   1. Read + Exec permission will be checked using inode_permission() during
258623d0b79dSTomohiro Misono  *      path construction. -EACCES will be returned in case of failure.
258723d0b79dSTomohiro Misono  *   2. Path construction will be stopped at the inode number which corresponds
258823d0b79dSTomohiro Misono  *      to the fd with which this ioctl is called. If constructed path does not
258923d0b79dSTomohiro Misono  *      exist under fd's inode, -EACCES will be returned.
259023d0b79dSTomohiro Misono  *   3. The name of bottom subvolume is also searched and filled.
259123d0b79dSTomohiro Misono  */
259223d0b79dSTomohiro Misono static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
259323d0b79dSTomohiro Misono {
259423d0b79dSTomohiro Misono 	struct btrfs_ioctl_ino_lookup_user_args *args;
259523d0b79dSTomohiro Misono 	struct inode *inode;
259623d0b79dSTomohiro Misono 	int ret;
259723d0b79dSTomohiro Misono 
259823d0b79dSTomohiro Misono 	args = memdup_user(argp, sizeof(*args));
259923d0b79dSTomohiro Misono 	if (IS_ERR(args))
260023d0b79dSTomohiro Misono 		return PTR_ERR(args);
260123d0b79dSTomohiro Misono 
260223d0b79dSTomohiro Misono 	inode = file_inode(file);
260323d0b79dSTomohiro Misono 
260423d0b79dSTomohiro Misono 	if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
260523d0b79dSTomohiro Misono 	    BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
260623d0b79dSTomohiro Misono 		/*
260723d0b79dSTomohiro Misono 		 * The subvolume does not exist under fd with which this is
260823d0b79dSTomohiro Misono 		 * called
260923d0b79dSTomohiro Misono 		 */
261023d0b79dSTomohiro Misono 		kfree(args);
261123d0b79dSTomohiro Misono 		return -EACCES;
261223d0b79dSTomohiro Misono 	}
261323d0b79dSTomohiro Misono 
261423d0b79dSTomohiro Misono 	ret = btrfs_search_path_in_tree_user(inode, args);
261523d0b79dSTomohiro Misono 
261623d0b79dSTomohiro Misono 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
261723d0b79dSTomohiro Misono 		ret = -EFAULT;
261823d0b79dSTomohiro Misono 
261923d0b79dSTomohiro Misono 	kfree(args);
262023d0b79dSTomohiro Misono 	return ret;
262123d0b79dSTomohiro Misono }
262223d0b79dSTomohiro Misono 
2623b64ec075STomohiro Misono /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2624b64ec075STomohiro Misono static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2625b64ec075STomohiro Misono {
2626b64ec075STomohiro Misono 	struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2627b64ec075STomohiro Misono 	struct btrfs_fs_info *fs_info;
2628b64ec075STomohiro Misono 	struct btrfs_root *root;
2629b64ec075STomohiro Misono 	struct btrfs_path *path;
2630b64ec075STomohiro Misono 	struct btrfs_key key;
2631b64ec075STomohiro Misono 	struct btrfs_root_item *root_item;
2632b64ec075STomohiro Misono 	struct btrfs_root_ref *rref;
2633b64ec075STomohiro Misono 	struct extent_buffer *leaf;
2634b64ec075STomohiro Misono 	unsigned long item_off;
2635b64ec075STomohiro Misono 	unsigned long item_len;
2636b64ec075STomohiro Misono 	struct inode *inode;
2637b64ec075STomohiro Misono 	int slot;
2638b64ec075STomohiro Misono 	int ret = 0;
2639b64ec075STomohiro Misono 
2640b64ec075STomohiro Misono 	path = btrfs_alloc_path();
2641b64ec075STomohiro Misono 	if (!path)
2642b64ec075STomohiro Misono 		return -ENOMEM;
2643b64ec075STomohiro Misono 
2644b64ec075STomohiro Misono 	subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2645b64ec075STomohiro Misono 	if (!subvol_info) {
2646b64ec075STomohiro Misono 		btrfs_free_path(path);
2647b64ec075STomohiro Misono 		return -ENOMEM;
2648b64ec075STomohiro Misono 	}
2649b64ec075STomohiro Misono 
2650b64ec075STomohiro Misono 	inode = file_inode(file);
2651b64ec075STomohiro Misono 	fs_info = BTRFS_I(inode)->root->fs_info;
2652b64ec075STomohiro Misono 
2653b64ec075STomohiro Misono 	/* Get root_item of inode's subvolume */
2654b64ec075STomohiro Misono 	key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2655b64ec075STomohiro Misono 	key.type = BTRFS_ROOT_ITEM_KEY;
2656b64ec075STomohiro Misono 	key.offset = (u64)-1;
2657b64ec075STomohiro Misono 	root = btrfs_read_fs_root_no_name(fs_info, &key);
2658b64ec075STomohiro Misono 	if (IS_ERR(root)) {
2659b64ec075STomohiro Misono 		ret = PTR_ERR(root);
2660b64ec075STomohiro Misono 		goto out;
2661b64ec075STomohiro Misono 	}
2662b64ec075STomohiro Misono 	root_item = &root->root_item;
2663b64ec075STomohiro Misono 
2664b64ec075STomohiro Misono 	subvol_info->treeid = key.objectid;
2665b64ec075STomohiro Misono 
2666b64ec075STomohiro Misono 	subvol_info->generation = btrfs_root_generation(root_item);
2667b64ec075STomohiro Misono 	subvol_info->flags = btrfs_root_flags(root_item);
2668b64ec075STomohiro Misono 
2669b64ec075STomohiro Misono 	memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2670b64ec075STomohiro Misono 	memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2671b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2672b64ec075STomohiro Misono 	memcpy(subvol_info->received_uuid, root_item->received_uuid,
2673b64ec075STomohiro Misono 						    BTRFS_UUID_SIZE);
2674b64ec075STomohiro Misono 
2675b64ec075STomohiro Misono 	subvol_info->ctransid = btrfs_root_ctransid(root_item);
2676b64ec075STomohiro Misono 	subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2677b64ec075STomohiro Misono 	subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2678b64ec075STomohiro Misono 
2679b64ec075STomohiro Misono 	subvol_info->otransid = btrfs_root_otransid(root_item);
2680b64ec075STomohiro Misono 	subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2681b64ec075STomohiro Misono 	subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2682b64ec075STomohiro Misono 
2683b64ec075STomohiro Misono 	subvol_info->stransid = btrfs_root_stransid(root_item);
2684b64ec075STomohiro Misono 	subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2685b64ec075STomohiro Misono 	subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2686b64ec075STomohiro Misono 
2687b64ec075STomohiro Misono 	subvol_info->rtransid = btrfs_root_rtransid(root_item);
2688b64ec075STomohiro Misono 	subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2689b64ec075STomohiro Misono 	subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2690b64ec075STomohiro Misono 
2691b64ec075STomohiro Misono 	if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2692b64ec075STomohiro Misono 		/* Search root tree for ROOT_BACKREF of this subvolume */
2693b64ec075STomohiro Misono 		root = fs_info->tree_root;
2694b64ec075STomohiro Misono 
2695b64ec075STomohiro Misono 		key.type = BTRFS_ROOT_BACKREF_KEY;
2696b64ec075STomohiro Misono 		key.offset = 0;
2697b64ec075STomohiro Misono 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2698b64ec075STomohiro Misono 		if (ret < 0) {
2699b64ec075STomohiro Misono 			goto out;
2700b64ec075STomohiro Misono 		} else if (path->slots[0] >=
2701b64ec075STomohiro Misono 			   btrfs_header_nritems(path->nodes[0])) {
2702b64ec075STomohiro Misono 			ret = btrfs_next_leaf(root, path);
2703b64ec075STomohiro Misono 			if (ret < 0) {
2704b64ec075STomohiro Misono 				goto out;
2705b64ec075STomohiro Misono 			} else if (ret > 0) {
2706b64ec075STomohiro Misono 				ret = -EUCLEAN;
2707b64ec075STomohiro Misono 				goto out;
2708b64ec075STomohiro Misono 			}
2709b64ec075STomohiro Misono 		}
2710b64ec075STomohiro Misono 
2711b64ec075STomohiro Misono 		leaf = path->nodes[0];
2712b64ec075STomohiro Misono 		slot = path->slots[0];
2713b64ec075STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
2714b64ec075STomohiro Misono 		if (key.objectid == subvol_info->treeid &&
2715b64ec075STomohiro Misono 		    key.type == BTRFS_ROOT_BACKREF_KEY) {
2716b64ec075STomohiro Misono 			subvol_info->parent_id = key.offset;
2717b64ec075STomohiro Misono 
2718b64ec075STomohiro Misono 			rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2719b64ec075STomohiro Misono 			subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2720b64ec075STomohiro Misono 
2721b64ec075STomohiro Misono 			item_off = btrfs_item_ptr_offset(leaf, slot)
2722b64ec075STomohiro Misono 					+ sizeof(struct btrfs_root_ref);
2723b64ec075STomohiro Misono 			item_len = btrfs_item_size_nr(leaf, slot)
2724b64ec075STomohiro Misono 					- sizeof(struct btrfs_root_ref);
2725b64ec075STomohiro Misono 			read_extent_buffer(leaf, subvol_info->name,
2726b64ec075STomohiro Misono 					   item_off, item_len);
2727b64ec075STomohiro Misono 		} else {
2728b64ec075STomohiro Misono 			ret = -ENOENT;
2729b64ec075STomohiro Misono 			goto out;
2730b64ec075STomohiro Misono 		}
2731b64ec075STomohiro Misono 	}
2732b64ec075STomohiro Misono 
2733b64ec075STomohiro Misono 	if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2734b64ec075STomohiro Misono 		ret = -EFAULT;
2735b64ec075STomohiro Misono 
2736b64ec075STomohiro Misono out:
2737b64ec075STomohiro Misono 	btrfs_free_path(path);
2738b64ec075STomohiro Misono 	kzfree(subvol_info);
2739b64ec075STomohiro Misono 	return ret;
2740b64ec075STomohiro Misono }
2741b64ec075STomohiro Misono 
274242e4b520STomohiro Misono /*
274342e4b520STomohiro Misono  * Return ROOT_REF information of the subvolume containing this inode
274442e4b520STomohiro Misono  * except the subvolume name.
274542e4b520STomohiro Misono  */
274642e4b520STomohiro Misono static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
274742e4b520STomohiro Misono {
274842e4b520STomohiro Misono 	struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
274942e4b520STomohiro Misono 	struct btrfs_root_ref *rref;
275042e4b520STomohiro Misono 	struct btrfs_root *root;
275142e4b520STomohiro Misono 	struct btrfs_path *path;
275242e4b520STomohiro Misono 	struct btrfs_key key;
275342e4b520STomohiro Misono 	struct extent_buffer *leaf;
275442e4b520STomohiro Misono 	struct inode *inode;
275542e4b520STomohiro Misono 	u64 objectid;
275642e4b520STomohiro Misono 	int slot;
275742e4b520STomohiro Misono 	int ret;
275842e4b520STomohiro Misono 	u8 found;
275942e4b520STomohiro Misono 
276042e4b520STomohiro Misono 	path = btrfs_alloc_path();
276142e4b520STomohiro Misono 	if (!path)
276242e4b520STomohiro Misono 		return -ENOMEM;
276342e4b520STomohiro Misono 
276442e4b520STomohiro Misono 	rootrefs = memdup_user(argp, sizeof(*rootrefs));
276542e4b520STomohiro Misono 	if (IS_ERR(rootrefs)) {
276642e4b520STomohiro Misono 		btrfs_free_path(path);
276742e4b520STomohiro Misono 		return PTR_ERR(rootrefs);
276842e4b520STomohiro Misono 	}
276942e4b520STomohiro Misono 
277042e4b520STomohiro Misono 	inode = file_inode(file);
277142e4b520STomohiro Misono 	root = BTRFS_I(inode)->root->fs_info->tree_root;
277242e4b520STomohiro Misono 	objectid = BTRFS_I(inode)->root->root_key.objectid;
277342e4b520STomohiro Misono 
277442e4b520STomohiro Misono 	key.objectid = objectid;
277542e4b520STomohiro Misono 	key.type = BTRFS_ROOT_REF_KEY;
277642e4b520STomohiro Misono 	key.offset = rootrefs->min_treeid;
277742e4b520STomohiro Misono 	found = 0;
277842e4b520STomohiro Misono 
277942e4b520STomohiro Misono 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
278042e4b520STomohiro Misono 	if (ret < 0) {
278142e4b520STomohiro Misono 		goto out;
278242e4b520STomohiro Misono 	} else if (path->slots[0] >=
278342e4b520STomohiro Misono 		   btrfs_header_nritems(path->nodes[0])) {
278442e4b520STomohiro Misono 		ret = btrfs_next_leaf(root, path);
278542e4b520STomohiro Misono 		if (ret < 0) {
278642e4b520STomohiro Misono 			goto out;
278742e4b520STomohiro Misono 		} else if (ret > 0) {
278842e4b520STomohiro Misono 			ret = -EUCLEAN;
278942e4b520STomohiro Misono 			goto out;
279042e4b520STomohiro Misono 		}
279142e4b520STomohiro Misono 	}
279242e4b520STomohiro Misono 	while (1) {
279342e4b520STomohiro Misono 		leaf = path->nodes[0];
279442e4b520STomohiro Misono 		slot = path->slots[0];
279542e4b520STomohiro Misono 
279642e4b520STomohiro Misono 		btrfs_item_key_to_cpu(leaf, &key, slot);
279742e4b520STomohiro Misono 		if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
279842e4b520STomohiro Misono 			ret = 0;
279942e4b520STomohiro Misono 			goto out;
280042e4b520STomohiro Misono 		}
280142e4b520STomohiro Misono 
280242e4b520STomohiro Misono 		if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
280342e4b520STomohiro Misono 			ret = -EOVERFLOW;
280442e4b520STomohiro Misono 			goto out;
280542e4b520STomohiro Misono 		}
280642e4b520STomohiro Misono 
280742e4b520STomohiro Misono 		rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
280842e4b520STomohiro Misono 		rootrefs->rootref[found].treeid = key.offset;
280942e4b520STomohiro Misono 		rootrefs->rootref[found].dirid =
281042e4b520STomohiro Misono 				  btrfs_root_ref_dirid(leaf, rref);
281142e4b520STomohiro Misono 		found++;
281242e4b520STomohiro Misono 
281342e4b520STomohiro Misono 		ret = btrfs_next_item(root, path);
281442e4b520STomohiro Misono 		if (ret < 0) {
281542e4b520STomohiro Misono 			goto out;
281642e4b520STomohiro Misono 		} else if (ret > 0) {
281742e4b520STomohiro Misono 			ret = -EUCLEAN;
281842e4b520STomohiro Misono 			goto out;
281942e4b520STomohiro Misono 		}
282042e4b520STomohiro Misono 	}
282142e4b520STomohiro Misono 
282242e4b520STomohiro Misono out:
282342e4b520STomohiro Misono 	if (!ret || ret == -EOVERFLOW) {
282442e4b520STomohiro Misono 		rootrefs->num_items = found;
282542e4b520STomohiro Misono 		/* update min_treeid for next search */
282642e4b520STomohiro Misono 		if (found)
282742e4b520STomohiro Misono 			rootrefs->min_treeid =
282842e4b520STomohiro Misono 				rootrefs->rootref[found - 1].treeid + 1;
282942e4b520STomohiro Misono 		if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
283042e4b520STomohiro Misono 			ret = -EFAULT;
283142e4b520STomohiro Misono 	}
283242e4b520STomohiro Misono 
283342e4b520STomohiro Misono 	kfree(rootrefs);
283442e4b520STomohiro Misono 	btrfs_free_path(path);
283542e4b520STomohiro Misono 
283642e4b520STomohiro Misono 	return ret;
283742e4b520STomohiro Misono }
283842e4b520STomohiro Misono 
283976dda93cSYan, Zheng static noinline int btrfs_ioctl_snap_destroy(struct file *file,
284076dda93cSYan, Zheng 					     void __user *arg)
284176dda93cSYan, Zheng {
284254563d41SAl Viro 	struct dentry *parent = file->f_path.dentry;
28430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
284476dda93cSYan, Zheng 	struct dentry *dentry;
28452b0143b5SDavid Howells 	struct inode *dir = d_inode(parent);
284676dda93cSYan, Zheng 	struct inode *inode;
284776dda93cSYan, Zheng 	struct btrfs_root *root = BTRFS_I(dir)->root;
284876dda93cSYan, Zheng 	struct btrfs_root *dest = NULL;
284976dda93cSYan, Zheng 	struct btrfs_ioctl_vol_args *vol_args;
285076dda93cSYan, Zheng 	int namelen;
285176dda93cSYan, Zheng 	int err = 0;
285276dda93cSYan, Zheng 
2853325c50e3SJeff Mahoney 	if (!S_ISDIR(dir->i_mode))
2854325c50e3SJeff Mahoney 		return -ENOTDIR;
2855325c50e3SJeff Mahoney 
285676dda93cSYan, Zheng 	vol_args = memdup_user(arg, sizeof(*vol_args));
285776dda93cSYan, Zheng 	if (IS_ERR(vol_args))
285876dda93cSYan, Zheng 		return PTR_ERR(vol_args);
285976dda93cSYan, Zheng 
286076dda93cSYan, Zheng 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
286176dda93cSYan, Zheng 	namelen = strlen(vol_args->name);
286276dda93cSYan, Zheng 	if (strchr(vol_args->name, '/') ||
286376dda93cSYan, Zheng 	    strncmp(vol_args->name, "..", namelen) == 0) {
286476dda93cSYan, Zheng 		err = -EINVAL;
286576dda93cSYan, Zheng 		goto out;
286676dda93cSYan, Zheng 	}
286776dda93cSYan, Zheng 
2868a561be71SAl Viro 	err = mnt_want_write_file(file);
286976dda93cSYan, Zheng 	if (err)
287076dda93cSYan, Zheng 		goto out;
287176dda93cSYan, Zheng 
2872521e0546SDavid Sterba 
287300235411SAl Viro 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
287400235411SAl Viro 	if (err == -EINTR)
287500235411SAl Viro 		goto out_drop_write;
287676dda93cSYan, Zheng 	dentry = lookup_one_len(vol_args->name, parent, namelen);
287776dda93cSYan, Zheng 	if (IS_ERR(dentry)) {
287876dda93cSYan, Zheng 		err = PTR_ERR(dentry);
287976dda93cSYan, Zheng 		goto out_unlock_dir;
288076dda93cSYan, Zheng 	}
288176dda93cSYan, Zheng 
28822b0143b5SDavid Howells 	if (d_really_is_negative(dentry)) {
288376dda93cSYan, Zheng 		err = -ENOENT;
288476dda93cSYan, Zheng 		goto out_dput;
288576dda93cSYan, Zheng 	}
288676dda93cSYan, Zheng 
28872b0143b5SDavid Howells 	inode = d_inode(dentry);
28884260f7c7SSage Weil 	dest = BTRFS_I(inode)->root;
28894260f7c7SSage Weil 	if (!capable(CAP_SYS_ADMIN)) {
28904260f7c7SSage Weil 		/*
28914260f7c7SSage Weil 		 * Regular user.  Only allow this with a special mount
28924260f7c7SSage Weil 		 * option, when the user has write+exec access to the
28934260f7c7SSage Weil 		 * subvol root, and when rmdir(2) would have been
28944260f7c7SSage Weil 		 * allowed.
28954260f7c7SSage Weil 		 *
28964260f7c7SSage Weil 		 * Note that this is _not_ check that the subvol is
28974260f7c7SSage Weil 		 * empty or doesn't contain data that we wouldn't
28984260f7c7SSage Weil 		 * otherwise be able to delete.
28994260f7c7SSage Weil 		 *
29004260f7c7SSage Weil 		 * Users who want to delete empty subvols should try
29014260f7c7SSage Weil 		 * rmdir(2).
29024260f7c7SSage Weil 		 */
29034260f7c7SSage Weil 		err = -EPERM;
29040b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
29054260f7c7SSage Weil 			goto out_dput;
29064260f7c7SSage Weil 
29074260f7c7SSage Weil 		/*
29084260f7c7SSage Weil 		 * Do not allow deletion if the parent dir is the same
29094260f7c7SSage Weil 		 * as the dir to be deleted.  That means the ioctl
29104260f7c7SSage Weil 		 * must be called on the dentry referencing the root
29114260f7c7SSage Weil 		 * of the subvol, not a random directory contained
29124260f7c7SSage Weil 		 * within it.
29134260f7c7SSage Weil 		 */
29144260f7c7SSage Weil 		err = -EINVAL;
29154260f7c7SSage Weil 		if (root == dest)
29164260f7c7SSage Weil 			goto out_dput;
29174260f7c7SSage Weil 
29184260f7c7SSage Weil 		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
29194260f7c7SSage Weil 		if (err)
29204260f7c7SSage Weil 			goto out_dput;
29215c39da5bSMiao Xie 	}
29224260f7c7SSage Weil 
29235c39da5bSMiao Xie 	/* check if subvolume may be deleted by a user */
29244260f7c7SSage Weil 	err = btrfs_may_delete(dir, dentry, 1);
29254260f7c7SSage Weil 	if (err)
29264260f7c7SSage Weil 		goto out_dput;
29274260f7c7SSage Weil 
29284a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
292976dda93cSYan, Zheng 		err = -EINVAL;
293076dda93cSYan, Zheng 		goto out_dput;
293176dda93cSYan, Zheng 	}
293276dda93cSYan, Zheng 
29335955102cSAl Viro 	inode_lock(inode);
2934f60a2364SMisono Tomohiro 	err = btrfs_delete_subvolume(dir, dentry);
29355955102cSAl Viro 	inode_unlock(inode);
2936f60a2364SMisono Tomohiro 	if (!err)
293776dda93cSYan, Zheng 		d_delete(dentry);
2938fa6ac876SLiu Bo 
293976dda93cSYan, Zheng out_dput:
294076dda93cSYan, Zheng 	dput(dentry);
294176dda93cSYan, Zheng out_unlock_dir:
29425955102cSAl Viro 	inode_unlock(dir);
294300235411SAl Viro out_drop_write:
29442a79f17eSAl Viro 	mnt_drop_write_file(file);
294576dda93cSYan, Zheng out:
294676dda93cSYan, Zheng 	kfree(vol_args);
294776dda93cSYan, Zheng 	return err;
294876dda93cSYan, Zheng }
294976dda93cSYan, Zheng 
29501e701a32SChris Mason static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2951f46b5a66SChristoph Hellwig {
2952496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2953f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
29541e701a32SChris Mason 	struct btrfs_ioctl_defrag_range_args *range;
2955c146afadSYan Zheng 	int ret;
2956c146afadSYan Zheng 
295725122d15SIlya Dryomov 	ret = mnt_want_write_file(file);
295825122d15SIlya Dryomov 	if (ret)
295925122d15SIlya Dryomov 		return ret;
2960b83cc969SLi Zefan 
296125122d15SIlya Dryomov 	if (btrfs_root_readonly(root)) {
296225122d15SIlya Dryomov 		ret = -EROFS;
296325122d15SIlya Dryomov 		goto out;
29645ac00addSStefan Behrens 	}
2965f46b5a66SChristoph Hellwig 
2966f46b5a66SChristoph Hellwig 	switch (inode->i_mode & S_IFMT) {
2967f46b5a66SChristoph Hellwig 	case S_IFDIR:
2968e441d54dSChris Mason 		if (!capable(CAP_SYS_ADMIN)) {
2969e441d54dSChris Mason 			ret = -EPERM;
2970e441d54dSChris Mason 			goto out;
2971e441d54dSChris Mason 		}
2972de78b51aSEric Sandeen 		ret = btrfs_defrag_root(root);
2973f46b5a66SChristoph Hellwig 		break;
2974f46b5a66SChristoph Hellwig 	case S_IFREG:
2975616d374eSAdam Borowski 		/*
2976616d374eSAdam Borowski 		 * Note that this does not check the file descriptor for write
2977616d374eSAdam Borowski 		 * access. This prevents defragmenting executables that are
2978616d374eSAdam Borowski 		 * running and allows defrag on files open in read-only mode.
2979616d374eSAdam Borowski 		 */
2980616d374eSAdam Borowski 		if (!capable(CAP_SYS_ADMIN) &&
2981616d374eSAdam Borowski 		    inode_permission(inode, MAY_WRITE)) {
2982616d374eSAdam Borowski 			ret = -EPERM;
2983e441d54dSChris Mason 			goto out;
2984e441d54dSChris Mason 		}
29851e701a32SChris Mason 
29861e701a32SChris Mason 		range = kzalloc(sizeof(*range), GFP_KERNEL);
29871e701a32SChris Mason 		if (!range) {
29881e701a32SChris Mason 			ret = -ENOMEM;
29891e701a32SChris Mason 			goto out;
29901e701a32SChris Mason 		}
29911e701a32SChris Mason 
29921e701a32SChris Mason 		if (argp) {
29931e701a32SChris Mason 			if (copy_from_user(range, argp,
29941e701a32SChris Mason 					   sizeof(*range))) {
29951e701a32SChris Mason 				ret = -EFAULT;
29961e701a32SChris Mason 				kfree(range);
2997683be16eSDan Carpenter 				goto out;
29981e701a32SChris Mason 			}
29991e701a32SChris Mason 			/* compression requires us to start the IO */
30001e701a32SChris Mason 			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
30011e701a32SChris Mason 				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
30021e701a32SChris Mason 				range->extent_thresh = (u32)-1;
30031e701a32SChris Mason 			}
30041e701a32SChris Mason 		} else {
30051e701a32SChris Mason 			/* the rest are all set to zero by kzalloc */
30061e701a32SChris Mason 			range->len = (u64)-1;
30071e701a32SChris Mason 		}
3008496ad9aaSAl Viro 		ret = btrfs_defrag_file(file_inode(file), file,
30097c829b72SAnand Jain 					range, BTRFS_OLDEST_GENERATION, 0);
30104cb5300bSChris Mason 		if (ret > 0)
30114cb5300bSChris Mason 			ret = 0;
30121e701a32SChris Mason 		kfree(range);
3013f46b5a66SChristoph Hellwig 		break;
30148929ecfaSYan, Zheng 	default:
30158929ecfaSYan, Zheng 		ret = -EINVAL;
3016f46b5a66SChristoph Hellwig 	}
3017e441d54dSChris Mason out:
301825122d15SIlya Dryomov 	mnt_drop_write_file(file);
3019e441d54dSChris Mason 	return ret;
3020f46b5a66SChristoph Hellwig }
3021f46b5a66SChristoph Hellwig 
30222ff7e61eSJeff Mahoney static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3023f46b5a66SChristoph Hellwig {
3024f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
3025f46b5a66SChristoph Hellwig 	int ret;
3026f46b5a66SChristoph Hellwig 
3027e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
3028e441d54dSChris Mason 		return -EPERM;
3029e441d54dSChris Mason 
3030171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
3031e57138b3SAnand Jain 		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3032c9e9f97bSIlya Dryomov 
3033dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
3034c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
3035c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
3036c9e9f97bSIlya Dryomov 		goto out;
3037c9e9f97bSIlya Dryomov 	}
3038f46b5a66SChristoph Hellwig 
30395516e595SMark Fasheh 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
30402ff7e61eSJeff Mahoney 	ret = btrfs_init_new_device(fs_info, vol_args->name);
3041f46b5a66SChristoph Hellwig 
304243d20761SAnand Jain 	if (!ret)
30430b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk added %s", vol_args->name);
304443d20761SAnand Jain 
3045f46b5a66SChristoph Hellwig 	kfree(vol_args);
3046c9e9f97bSIlya Dryomov out:
3047171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3048f46b5a66SChristoph Hellwig 	return ret;
3049f46b5a66SChristoph Hellwig }
3050f46b5a66SChristoph Hellwig 
30516b526ed7SAnand Jain static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3052f46b5a66SChristoph Hellwig {
30530b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
30540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
30556b526ed7SAnand Jain 	struct btrfs_ioctl_vol_args_v2 *vol_args;
3056f46b5a66SChristoph Hellwig 	int ret;
3057f46b5a66SChristoph Hellwig 
3058e441d54dSChris Mason 	if (!capable(CAP_SYS_ADMIN))
3059e441d54dSChris Mason 		return -EPERM;
3060e441d54dSChris Mason 
3061da24927bSMiao Xie 	ret = mnt_want_write_file(file);
3062da24927bSMiao Xie 	if (ret)
3063da24927bSMiao Xie 		return ret;
3064c146afadSYan Zheng 
3065dae7b665SLi Zefan 	vol_args = memdup_user(arg, sizeof(*vol_args));
3066c9e9f97bSIlya Dryomov 	if (IS_ERR(vol_args)) {
3067c9e9f97bSIlya Dryomov 		ret = PTR_ERR(vol_args);
3068c47ca32dSDan Carpenter 		goto err_drop;
3069c9e9f97bSIlya Dryomov 	}
3070f46b5a66SChristoph Hellwig 
30716b526ed7SAnand Jain 	/* Check for compatibility reject unknown flags */
3072fd4e994bSOmar Sandoval 	if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
3073fd4e994bSOmar Sandoval 		ret = -EOPNOTSUPP;
3074fd4e994bSOmar Sandoval 		goto out;
3075fd4e994bSOmar Sandoval 	}
3076f46b5a66SChristoph Hellwig 
3077171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3078183860f6SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3079183860f6SAnand Jain 		goto out;
3080183860f6SAnand Jain 	}
3081183860f6SAnand Jain 
3082735654eaSDavid Sterba 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
30832ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
30846b526ed7SAnand Jain 	} else {
30856b526ed7SAnand Jain 		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
30862ff7e61eSJeff Mahoney 		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
30876b526ed7SAnand Jain 	}
3088171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3089183860f6SAnand Jain 
30906b526ed7SAnand Jain 	if (!ret) {
3091735654eaSDavid Sterba 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
30920b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: id %llu",
30936b526ed7SAnand Jain 					vol_args->devid);
30946b526ed7SAnand Jain 		else
30950b246afaSJeff Mahoney 			btrfs_info(fs_info, "device deleted: %s",
30966b526ed7SAnand Jain 					vol_args->name);
30976b526ed7SAnand Jain 	}
3098183860f6SAnand Jain out:
3099183860f6SAnand Jain 	kfree(vol_args);
3100c47ca32dSDan Carpenter err_drop:
31014ac20c70SIlya Dryomov 	mnt_drop_write_file(file);
3102f46b5a66SChristoph Hellwig 	return ret;
3103f46b5a66SChristoph Hellwig }
3104f46b5a66SChristoph Hellwig 
3105f46b5a66SChristoph Hellwig static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3106f46b5a66SChristoph Hellwig {
31070b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
31080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3109f46b5a66SChristoph Hellwig 	struct btrfs_ioctl_vol_args *vol_args;
3110f46b5a66SChristoph Hellwig 	int ret;
3111f46b5a66SChristoph Hellwig 
3112f46b5a66SChristoph Hellwig 	if (!capable(CAP_SYS_ADMIN))
3113f46b5a66SChristoph Hellwig 		return -EPERM;
3114f46b5a66SChristoph Hellwig 
3115f46b5a66SChristoph Hellwig 	ret = mnt_want_write_file(file);
3116f46b5a66SChristoph Hellwig 	if (ret)
3117f46b5a66SChristoph Hellwig 		return ret;
3118f46b5a66SChristoph Hellwig 
3119171938e5SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3120f46b5a66SChristoph Hellwig 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
312158d7bbf8SDavid Sterba 		goto out_drop_write;
312258d7bbf8SDavid Sterba 	}
312358d7bbf8SDavid Sterba 
312458d7bbf8SDavid Sterba 	vol_args = memdup_user(arg, sizeof(*vol_args));
312558d7bbf8SDavid Sterba 	if (IS_ERR(vol_args)) {
312658d7bbf8SDavid Sterba 		ret = PTR_ERR(vol_args);
3127f46b5a66SChristoph Hellwig 		goto out;
3128f46b5a66SChristoph Hellwig 	}
3129f46b5a66SChristoph Hellwig 
313058d7bbf8SDavid Sterba 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
31312ff7e61eSJeff Mahoney 	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3132f46b5a66SChristoph Hellwig 
3133f46b5a66SChristoph Hellwig 	if (!ret)
31340b246afaSJeff Mahoney 		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3135f46b5a66SChristoph Hellwig 	kfree(vol_args);
313658d7bbf8SDavid Sterba out:
3137171938e5SDavid Sterba 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
313858d7bbf8SDavid Sterba out_drop_write:
3139f46b5a66SChristoph Hellwig 	mnt_drop_write_file(file);
314058d7bbf8SDavid Sterba 
3141f46b5a66SChristoph Hellwig 	return ret;
3142f46b5a66SChristoph Hellwig }
3143f46b5a66SChristoph Hellwig 
31442ff7e61eSJeff Mahoney static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
31452ff7e61eSJeff Mahoney 				void __user *arg)
3146475f6387SJan Schmidt {
3147027ed2f0SLi Zefan 	struct btrfs_ioctl_fs_info_args *fi_args;
3148475f6387SJan Schmidt 	struct btrfs_device *device;
31490b246afaSJeff Mahoney 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3150027ed2f0SLi Zefan 	int ret = 0;
3151475f6387SJan Schmidt 
3152027ed2f0SLi Zefan 	fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
3153027ed2f0SLi Zefan 	if (!fi_args)
3154027ed2f0SLi Zefan 		return -ENOMEM;
3155027ed2f0SLi Zefan 
3156d03262c7SDavid Sterba 	rcu_read_lock();
3157027ed2f0SLi Zefan 	fi_args->num_devices = fs_devices->num_devices;
3158475f6387SJan Schmidt 
3159d03262c7SDavid Sterba 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3160027ed2f0SLi Zefan 		if (device->devid > fi_args->max_id)
3161027ed2f0SLi Zefan 			fi_args->max_id = device->devid;
3162475f6387SJan Schmidt 	}
3163d03262c7SDavid Sterba 	rcu_read_unlock();
3164475f6387SJan Schmidt 
3165de37aa51SNikolay Borisov 	memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3166bea7eafdSOmar Sandoval 	fi_args->nodesize = fs_info->nodesize;
3167bea7eafdSOmar Sandoval 	fi_args->sectorsize = fs_info->sectorsize;
3168bea7eafdSOmar Sandoval 	fi_args->clone_alignment = fs_info->sectorsize;
316980a773fbSDavid Sterba 
3170027ed2f0SLi Zefan 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3171027ed2f0SLi Zefan 		ret = -EFAULT;
3172475f6387SJan Schmidt 
3173027ed2f0SLi Zefan 	kfree(fi_args);
3174027ed2f0SLi Zefan 	return ret;
3175475f6387SJan Schmidt }
3176475f6387SJan Schmidt 
31772ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
31782ff7e61eSJeff Mahoney 				 void __user *arg)
3179475f6387SJan Schmidt {
3180475f6387SJan Schmidt 	struct btrfs_ioctl_dev_info_args *di_args;
3181475f6387SJan Schmidt 	struct btrfs_device *dev;
3182475f6387SJan Schmidt 	int ret = 0;
3183475f6387SJan Schmidt 	char *s_uuid = NULL;
3184475f6387SJan Schmidt 
3185475f6387SJan Schmidt 	di_args = memdup_user(arg, sizeof(*di_args));
3186475f6387SJan Schmidt 	if (IS_ERR(di_args))
3187475f6387SJan Schmidt 		return PTR_ERR(di_args);
3188475f6387SJan Schmidt 
3189dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(di_args->uuid))
3190475f6387SJan Schmidt 		s_uuid = di_args->uuid;
3191475f6387SJan Schmidt 
3192c5593ca3SDavid Sterba 	rcu_read_lock();
3193e4319cd9SAnand Jain 	dev = btrfs_find_device(fs_info->fs_devices, di_args->devid, s_uuid,
319409ba3bc9SAnand Jain 				NULL, true);
3195475f6387SJan Schmidt 
3196475f6387SJan Schmidt 	if (!dev) {
3197475f6387SJan Schmidt 		ret = -ENODEV;
3198475f6387SJan Schmidt 		goto out;
3199475f6387SJan Schmidt 	}
3200475f6387SJan Schmidt 
3201475f6387SJan Schmidt 	di_args->devid = dev->devid;
32027cc8e58dSMiao Xie 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
32037cc8e58dSMiao Xie 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3204475f6387SJan Schmidt 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3205a27202fbSJim Meyering 	if (dev->name) {
3206672d5990SMisono Tomohiro 		strncpy(di_args->path, rcu_str_deref(dev->name),
3207672d5990SMisono Tomohiro 				sizeof(di_args->path) - 1);
3208a27202fbSJim Meyering 		di_args->path[sizeof(di_args->path) - 1] = 0;
3209a27202fbSJim Meyering 	} else {
321099ba55adSStefan Behrens 		di_args->path[0] = '\0';
3211a27202fbSJim Meyering 	}
3212475f6387SJan Schmidt 
3213475f6387SJan Schmidt out:
3214c5593ca3SDavid Sterba 	rcu_read_unlock();
3215475f6387SJan Schmidt 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3216475f6387SJan Schmidt 		ret = -EFAULT;
3217475f6387SJan Schmidt 
3218475f6387SJan Schmidt 	kfree(di_args);
3219475f6387SJan Schmidt 	return ret;
3220475f6387SJan Schmidt }
3221475f6387SJan Schmidt 
3222d8b55242SFilipe Manana static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
3223d8b55242SFilipe Manana 				       struct inode *inode2, u64 loff2, u64 len)
3224d8b55242SFilipe Manana {
3225d8b55242SFilipe Manana 	unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3226d8b55242SFilipe Manana 	unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3227d8b55242SFilipe Manana }
3228d8b55242SFilipe Manana 
3229d8b55242SFilipe Manana static void btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
3230d8b55242SFilipe Manana 				     struct inode *inode2, u64 loff2, u64 len)
3231d8b55242SFilipe Manana {
3232d8b55242SFilipe Manana 	if (inode1 < inode2) {
3233d8b55242SFilipe Manana 		swap(inode1, inode2);
3234d8b55242SFilipe Manana 		swap(loff1, loff2);
3235d8b55242SFilipe Manana 	} else if (inode1 == inode2 && loff2 < loff1) {
3236d8b55242SFilipe Manana 		swap(loff1, loff2);
3237d8b55242SFilipe Manana 	}
3238d8b55242SFilipe Manana 	lock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3239d8b55242SFilipe Manana 	lock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3240d8b55242SFilipe Manana }
3241d8b55242SFilipe Manana 
324257a50e25SFilipe Manana static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 len,
324334a28e3dSFilipe Manana 				   struct inode *dst, u64 dst_loff)
3244416161dbSMark Fasheh {
3245416161dbSMark Fasheh 	int ret;
32460efa9f48SMark Fasheh 
3247de02b9f6SFilipe Manana 	/*
3248d8b55242SFilipe Manana 	 * Lock destination range to serialize with concurrent readpages() and
3249d8b55242SFilipe Manana 	 * source range to serialize with relocation.
3250de02b9f6SFilipe Manana 	 */
3251d8b55242SFilipe Manana 	btrfs_double_extent_lock(src, loff, dst, dst_loff, len);
325257a50e25SFilipe Manana 	ret = btrfs_clone(src, dst, loff, len, len, dst_loff, 1);
3253d8b55242SFilipe Manana 	btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
32543973909dSTimofey Titovets 
32553973909dSTimofey Titovets 	return ret;
32563973909dSTimofey Titovets }
32573973909dSTimofey Titovets 
3258b6728768STimofey Titovets #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3259b6728768STimofey Titovets 
32603973909dSTimofey Titovets static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
32613973909dSTimofey Titovets 			     struct inode *dst, u64 dst_loff)
32623973909dSTimofey Titovets {
32633973909dSTimofey Titovets 	int ret;
3264b6728768STimofey Titovets 	u64 i, tail_len, chunk_count;
326562d54f3aSFilipe Manana 	struct btrfs_root *root_dst = BTRFS_I(dst)->root;
326662d54f3aSFilipe Manana 
326762d54f3aSFilipe Manana 	spin_lock(&root_dst->root_item_lock);
326862d54f3aSFilipe Manana 	if (root_dst->send_in_progress) {
326962d54f3aSFilipe Manana 		btrfs_warn_rl(root_dst->fs_info,
327062d54f3aSFilipe Manana "cannot deduplicate to root %llu while send operations are using it (%d in progress)",
327162d54f3aSFilipe Manana 			      root_dst->root_key.objectid,
327262d54f3aSFilipe Manana 			      root_dst->send_in_progress);
327362d54f3aSFilipe Manana 		spin_unlock(&root_dst->root_item_lock);
327462d54f3aSFilipe Manana 		return -EAGAIN;
327562d54f3aSFilipe Manana 	}
327662d54f3aSFilipe Manana 	root_dst->dedupe_in_progress++;
327762d54f3aSFilipe Manana 	spin_unlock(&root_dst->root_item_lock);
32783973909dSTimofey Titovets 
3279b6728768STimofey Titovets 	tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3280b6728768STimofey Titovets 	chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
328167b07bd4STimofey Titovets 
3282b6728768STimofey Titovets 	for (i = 0; i < chunk_count; i++) {
3283b6728768STimofey Titovets 		ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
328434a28e3dSFilipe Manana 					      dst, dst_loff);
3285b6728768STimofey Titovets 		if (ret)
328662d54f3aSFilipe Manana 			goto out;
3287b6728768STimofey Titovets 
3288b6728768STimofey Titovets 		loff += BTRFS_MAX_DEDUPE_LEN;
3289b6728768STimofey Titovets 		dst_loff += BTRFS_MAX_DEDUPE_LEN;
3290b6728768STimofey Titovets 	}
3291b6728768STimofey Titovets 
3292b6728768STimofey Titovets 	if (tail_len > 0)
329367b07bd4STimofey Titovets 		ret = btrfs_extent_same_range(src, loff, tail_len, dst,
329434a28e3dSFilipe Manana 					      dst_loff);
329562d54f3aSFilipe Manana out:
329662d54f3aSFilipe Manana 	spin_lock(&root_dst->root_item_lock);
329762d54f3aSFilipe Manana 	root_dst->dedupe_in_progress--;
329862d54f3aSFilipe Manana 	spin_unlock(&root_dst->root_item_lock);
3299416161dbSMark Fasheh 
3300416161dbSMark Fasheh 	return ret;
3301416161dbSMark Fasheh }
3302416161dbSMark Fasheh 
3303f82a9901SFilipe Manana static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3304f82a9901SFilipe Manana 				     struct inode *inode,
3305f82a9901SFilipe Manana 				     u64 endoff,
3306f82a9901SFilipe Manana 				     const u64 destoff,
33071c919a5eSMark Fasheh 				     const u64 olen,
33081c919a5eSMark Fasheh 				     int no_time_update)
3309f82a9901SFilipe Manana {
3310f82a9901SFilipe Manana 	struct btrfs_root *root = BTRFS_I(inode)->root;
3311f82a9901SFilipe Manana 	int ret;
3312f82a9901SFilipe Manana 
3313f82a9901SFilipe Manana 	inode_inc_iversion(inode);
33141c919a5eSMark Fasheh 	if (!no_time_update)
3315c2050a45SDeepa Dinamani 		inode->i_mtime = inode->i_ctime = current_time(inode);
3316f82a9901SFilipe Manana 	/*
3317f82a9901SFilipe Manana 	 * We round up to the block size at eof when determining which
3318f82a9901SFilipe Manana 	 * extents to clone above, but shouldn't round up the file size.
3319f82a9901SFilipe Manana 	 */
3320f82a9901SFilipe Manana 	if (endoff > destoff + olen)
3321f82a9901SFilipe Manana 		endoff = destoff + olen;
3322f82a9901SFilipe Manana 	if (endoff > inode->i_size)
33236ef06d27SNikolay Borisov 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3324f82a9901SFilipe Manana 
3325f82a9901SFilipe Manana 	ret = btrfs_update_inode(trans, root, inode);
3326f82a9901SFilipe Manana 	if (ret) {
332766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33283a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
3329f82a9901SFilipe Manana 		goto out;
3330f82a9901SFilipe Manana 	}
33313a45bb20SJeff Mahoney 	ret = btrfs_end_transaction(trans);
3332f82a9901SFilipe Manana out:
3333f82a9901SFilipe Manana 	return ret;
3334f82a9901SFilipe Manana }
3335f82a9901SFilipe Manana 
3336a2f392e4SNikolay Borisov static void clone_update_extent_map(struct btrfs_inode *inode,
33377ffbb598SFilipe Manana 				    const struct btrfs_trans_handle *trans,
33387ffbb598SFilipe Manana 				    const struct btrfs_path *path,
33397ffbb598SFilipe Manana 				    const u64 hole_offset,
33407ffbb598SFilipe Manana 				    const u64 hole_len)
33417ffbb598SFilipe Manana {
3342a2f392e4SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
33437ffbb598SFilipe Manana 	struct extent_map *em;
33447ffbb598SFilipe Manana 	int ret;
33457ffbb598SFilipe Manana 
33467ffbb598SFilipe Manana 	em = alloc_extent_map();
33477ffbb598SFilipe Manana 	if (!em) {
3348a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
33497ffbb598SFilipe Manana 		return;
33507ffbb598SFilipe Manana 	}
33517ffbb598SFilipe Manana 
335214f59796SFilipe Manana 	if (path) {
335314f59796SFilipe Manana 		struct btrfs_file_extent_item *fi;
335414f59796SFilipe Manana 
335514f59796SFilipe Manana 		fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
335614f59796SFilipe Manana 				    struct btrfs_file_extent_item);
3357a2f392e4SNikolay Borisov 		btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
33587ffbb598SFilipe Manana 		em->generation = -1;
33597ffbb598SFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], fi) ==
33607ffbb598SFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
33617ffbb598SFilipe Manana 			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3362a2f392e4SNikolay Borisov 					&inode->runtime_flags);
33637ffbb598SFilipe Manana 	} else {
33647ffbb598SFilipe Manana 		em->start = hole_offset;
33657ffbb598SFilipe Manana 		em->len = hole_len;
33667ffbb598SFilipe Manana 		em->ram_bytes = em->len;
33677ffbb598SFilipe Manana 		em->orig_start = hole_offset;
33687ffbb598SFilipe Manana 		em->block_start = EXTENT_MAP_HOLE;
33697ffbb598SFilipe Manana 		em->block_len = 0;
33707ffbb598SFilipe Manana 		em->orig_block_len = 0;
33717ffbb598SFilipe Manana 		em->compress_type = BTRFS_COMPRESS_NONE;
33727ffbb598SFilipe Manana 		em->generation = trans->transid;
33737ffbb598SFilipe Manana 	}
33747ffbb598SFilipe Manana 
33757ffbb598SFilipe Manana 	while (1) {
33767ffbb598SFilipe Manana 		write_lock(&em_tree->lock);
33777ffbb598SFilipe Manana 		ret = add_extent_mapping(em_tree, em, 1);
33787ffbb598SFilipe Manana 		write_unlock(&em_tree->lock);
33797ffbb598SFilipe Manana 		if (ret != -EEXIST) {
33807ffbb598SFilipe Manana 			free_extent_map(em);
33817ffbb598SFilipe Manana 			break;
33827ffbb598SFilipe Manana 		}
3383a2f392e4SNikolay Borisov 		btrfs_drop_extent_cache(inode, em->start,
33847ffbb598SFilipe Manana 					em->start + em->len - 1, 0);
33857ffbb598SFilipe Manana 	}
33867ffbb598SFilipe Manana 
3387ee39b432SDavid Sterba 	if (ret)
3388a2f392e4SNikolay Borisov 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
33897ffbb598SFilipe Manana }
33907ffbb598SFilipe Manana 
33918039d87dSFilipe Manana /*
33928039d87dSFilipe Manana  * Make sure we do not end up inserting an inline extent into a file that has
33938039d87dSFilipe Manana  * already other (non-inline) extents. If a file has an inline extent it can
33948039d87dSFilipe Manana  * not have any other extents and the (single) inline extent must start at the
33958039d87dSFilipe Manana  * file offset 0. Failing to respect these rules will lead to file corruption,
33968039d87dSFilipe Manana  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
33978039d87dSFilipe Manana  *
33988039d87dSFilipe Manana  * We can have extents that have been already written to disk or we can have
33998039d87dSFilipe Manana  * dirty ranges still in delalloc, in which case the extent maps and items are
34008039d87dSFilipe Manana  * created only when we run delalloc, and the delalloc ranges might fall outside
34018039d87dSFilipe Manana  * the range we are currently locking in the inode's io tree. So we check the
34028039d87dSFilipe Manana  * inode's i_size because of that (i_size updates are done while holding the
34038039d87dSFilipe Manana  * i_mutex, which we are holding here).
34048039d87dSFilipe Manana  * We also check to see if the inode has a size not greater than "datal" but has
34058039d87dSFilipe Manana  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
34068039d87dSFilipe Manana  * protected against such concurrent fallocate calls by the i_mutex).
34078039d87dSFilipe Manana  *
34088039d87dSFilipe Manana  * If the file has no extents but a size greater than datal, do not allow the
34098039d87dSFilipe Manana  * copy because we would need turn the inline extent into a non-inline one (even
34108039d87dSFilipe Manana  * with NO_HOLES enabled). If we find our destination inode only has one inline
34118039d87dSFilipe Manana  * extent, just overwrite it with the source inline extent if its size is less
34128039d87dSFilipe Manana  * than the source extent's size, or we could copy the source inline extent's
34138039d87dSFilipe Manana  * data into the destination inode's inline extent if the later is greater then
34148039d87dSFilipe Manana  * the former.
34158039d87dSFilipe Manana  */
34164a0ab9d7SDavid Sterba static int clone_copy_inline_extent(struct inode *dst,
34178039d87dSFilipe Manana 				    struct btrfs_trans_handle *trans,
34188039d87dSFilipe Manana 				    struct btrfs_path *path,
34198039d87dSFilipe Manana 				    struct btrfs_key *new_key,
34208039d87dSFilipe Manana 				    const u64 drop_start,
34218039d87dSFilipe Manana 				    const u64 datal,
34228039d87dSFilipe Manana 				    const u64 skip,
34238039d87dSFilipe Manana 				    const u64 size,
34248039d87dSFilipe Manana 				    char *inline_data)
34258039d87dSFilipe Manana {
34260b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
34278039d87dSFilipe Manana 	struct btrfs_root *root = BTRFS_I(dst)->root;
34288039d87dSFilipe Manana 	const u64 aligned_end = ALIGN(new_key->offset + datal,
34290b246afaSJeff Mahoney 				      fs_info->sectorsize);
34308039d87dSFilipe Manana 	int ret;
34318039d87dSFilipe Manana 	struct btrfs_key key;
34328039d87dSFilipe Manana 
34338039d87dSFilipe Manana 	if (new_key->offset > 0)
34348039d87dSFilipe Manana 		return -EOPNOTSUPP;
34358039d87dSFilipe Manana 
34364a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(dst));
34378039d87dSFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
34388039d87dSFilipe Manana 	key.offset = 0;
34398039d87dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
34408039d87dSFilipe Manana 	if (ret < 0) {
34418039d87dSFilipe Manana 		return ret;
34428039d87dSFilipe Manana 	} else if (ret > 0) {
34438039d87dSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
34448039d87dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
34458039d87dSFilipe Manana 			if (ret < 0)
34468039d87dSFilipe Manana 				return ret;
34478039d87dSFilipe Manana 			else if (ret > 0)
34488039d87dSFilipe Manana 				goto copy_inline_extent;
34498039d87dSFilipe Manana 		}
34508039d87dSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
34514a0cc7caSNikolay Borisov 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
34528039d87dSFilipe Manana 		    key.type == BTRFS_EXTENT_DATA_KEY) {
34538039d87dSFilipe Manana 			ASSERT(key.offset > 0);
34548039d87dSFilipe Manana 			return -EOPNOTSUPP;
34558039d87dSFilipe Manana 		}
34568039d87dSFilipe Manana 	} else if (i_size_read(dst) <= datal) {
34578039d87dSFilipe Manana 		struct btrfs_file_extent_item *ei;
34588039d87dSFilipe Manana 		u64 ext_len;
34598039d87dSFilipe Manana 
34608039d87dSFilipe Manana 		/*
34618039d87dSFilipe Manana 		 * If the file size is <= datal, make sure there are no other
34628039d87dSFilipe Manana 		 * extents following (can happen do to an fallocate call with
34638039d87dSFilipe Manana 		 * the flag FALLOC_FL_KEEP_SIZE).
34648039d87dSFilipe Manana 		 */
34658039d87dSFilipe Manana 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
34668039d87dSFilipe Manana 				    struct btrfs_file_extent_item);
34678039d87dSFilipe Manana 		/*
34688039d87dSFilipe Manana 		 * If it's an inline extent, it can not have other extents
34698039d87dSFilipe Manana 		 * following it.
34708039d87dSFilipe Manana 		 */
34718039d87dSFilipe Manana 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
34728039d87dSFilipe Manana 		    BTRFS_FILE_EXTENT_INLINE)
34738039d87dSFilipe Manana 			goto copy_inline_extent;
34748039d87dSFilipe Manana 
34758039d87dSFilipe Manana 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
34768039d87dSFilipe Manana 		if (ext_len > aligned_end)
34778039d87dSFilipe Manana 			return -EOPNOTSUPP;
34788039d87dSFilipe Manana 
34798039d87dSFilipe Manana 		ret = btrfs_next_item(root, path);
34808039d87dSFilipe Manana 		if (ret < 0) {
34818039d87dSFilipe Manana 			return ret;
34828039d87dSFilipe Manana 		} else if (ret == 0) {
34838039d87dSFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
34848039d87dSFilipe Manana 					      path->slots[0]);
34854a0cc7caSNikolay Borisov 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
34868039d87dSFilipe Manana 			    key.type == BTRFS_EXTENT_DATA_KEY)
34878039d87dSFilipe Manana 				return -EOPNOTSUPP;
34888039d87dSFilipe Manana 		}
34898039d87dSFilipe Manana 	}
34908039d87dSFilipe Manana 
34918039d87dSFilipe Manana copy_inline_extent:
34928039d87dSFilipe Manana 	/*
34938039d87dSFilipe Manana 	 * We have no extent items, or we have an extent at offset 0 which may
34948039d87dSFilipe Manana 	 * or may not be inlined. All these cases are dealt the same way.
34958039d87dSFilipe Manana 	 */
34968039d87dSFilipe Manana 	if (i_size_read(dst) > datal) {
34978039d87dSFilipe Manana 		/*
34988039d87dSFilipe Manana 		 * If the destination inode has an inline extent...
34998039d87dSFilipe Manana 		 * This would require copying the data from the source inline
35008039d87dSFilipe Manana 		 * extent into the beginning of the destination's inline extent.
35018039d87dSFilipe Manana 		 * But this is really complex, both extents can be compressed
35028039d87dSFilipe Manana 		 * or just one of them, which would require decompressing and
35038039d87dSFilipe Manana 		 * re-compressing data (which could increase the new compressed
35048039d87dSFilipe Manana 		 * size, not allowing the compressed data to fit anymore in an
35058039d87dSFilipe Manana 		 * inline extent).
35068039d87dSFilipe Manana 		 * So just don't support this case for now (it should be rare,
35078039d87dSFilipe Manana 		 * we are not really saving space when cloning inline extents).
35088039d87dSFilipe Manana 		 */
35098039d87dSFilipe Manana 		return -EOPNOTSUPP;
35108039d87dSFilipe Manana 	}
35118039d87dSFilipe Manana 
35128039d87dSFilipe Manana 	btrfs_release_path(path);
35138039d87dSFilipe Manana 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
35148039d87dSFilipe Manana 	if (ret)
35158039d87dSFilipe Manana 		return ret;
35168039d87dSFilipe Manana 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
35178039d87dSFilipe Manana 	if (ret)
35188039d87dSFilipe Manana 		return ret;
35198039d87dSFilipe Manana 
35208039d87dSFilipe Manana 	if (skip) {
35218039d87dSFilipe Manana 		const u32 start = btrfs_file_extent_calc_inline_size(0);
35228039d87dSFilipe Manana 
35238039d87dSFilipe Manana 		memmove(inline_data + start, inline_data + start + skip, datal);
35248039d87dSFilipe Manana 	}
35258039d87dSFilipe Manana 
35268039d87dSFilipe Manana 	write_extent_buffer(path->nodes[0], inline_data,
35278039d87dSFilipe Manana 			    btrfs_item_ptr_offset(path->nodes[0],
35288039d87dSFilipe Manana 						  path->slots[0]),
35298039d87dSFilipe Manana 			    size);
35308039d87dSFilipe Manana 	inode_add_bytes(dst, datal);
35318039d87dSFilipe Manana 
35328039d87dSFilipe Manana 	return 0;
35338039d87dSFilipe Manana }
35348039d87dSFilipe Manana 
353532b7c687SMark Fasheh /**
353632b7c687SMark Fasheh  * btrfs_clone() - clone a range from inode file to another
353732b7c687SMark Fasheh  *
353832b7c687SMark Fasheh  * @src: Inode to clone from
353932b7c687SMark Fasheh  * @inode: Inode to clone to
354032b7c687SMark Fasheh  * @off: Offset within source to start clone from
354132b7c687SMark Fasheh  * @olen: Original length, passed by user, of range to clone
35421c919a5eSMark Fasheh  * @olen_aligned: Block-aligned value of olen
354332b7c687SMark Fasheh  * @destoff: Offset within @inode to start clone
35441c919a5eSMark Fasheh  * @no_time_update: Whether to update mtime/ctime on the target inode
354532b7c687SMark Fasheh  */
354632b7c687SMark Fasheh static int btrfs_clone(struct inode *src, struct inode *inode,
3547f82a9901SFilipe Manana 		       const u64 off, const u64 olen, const u64 olen_aligned,
35481c919a5eSMark Fasheh 		       const u64 destoff, int no_time_update)
3549f46b5a66SChristoph Hellwig {
35500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3551f46b5a66SChristoph Hellwig 	struct btrfs_root *root = BTRFS_I(inode)->root;
355232b7c687SMark Fasheh 	struct btrfs_path *path = NULL;
3553f46b5a66SChristoph Hellwig 	struct extent_buffer *leaf;
355432b7c687SMark Fasheh 	struct btrfs_trans_handle *trans;
355532b7c687SMark Fasheh 	char *buf = NULL;
3556ae01a0abSYan Zheng 	struct btrfs_key key;
3557f46b5a66SChristoph Hellwig 	u32 nritems;
3558f46b5a66SChristoph Hellwig 	int slot;
3559ae01a0abSYan Zheng 	int ret;
3560f82a9901SFilipe Manana 	const u64 len = olen_aligned;
3561f82a9901SFilipe Manana 	u64 last_dest_end = destoff;
3562ae01a0abSYan Zheng 
3563ae01a0abSYan Zheng 	ret = -ENOMEM;
3564752ade68SMichal Hocko 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3565ae01a0abSYan Zheng 	if (!buf)
356632b7c687SMark Fasheh 		return ret;
3567ae01a0abSYan Zheng 
3568ae01a0abSYan Zheng 	path = btrfs_alloc_path();
3569ae01a0abSYan Zheng 	if (!path) {
357015351955SDavid Sterba 		kvfree(buf);
357132b7c687SMark Fasheh 		return ret;
3572ae01a0abSYan Zheng 	}
357332b7c687SMark Fasheh 
3574e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
3575c5c9cd4dSSage Weil 	/* clone data */
35764a0cc7caSNikolay Borisov 	key.objectid = btrfs_ino(BTRFS_I(src));
3577ae01a0abSYan Zheng 	key.type = BTRFS_EXTENT_DATA_KEY;
35782c463823SFilipe Manana 	key.offset = off;
3579f46b5a66SChristoph Hellwig 
3580f46b5a66SChristoph Hellwig 	while (1) {
3581de249e66SChris Mason 		u64 next_key_min_offset = key.offset + 1;
3582df858e76SFilipe Manana 
3583f46b5a66SChristoph Hellwig 		/*
3584f46b5a66SChristoph Hellwig 		 * note the key will change type as we walk through the
3585f46b5a66SChristoph Hellwig 		 * tree.
3586f46b5a66SChristoph Hellwig 		 */
3587e4355f34SFilipe David Borba Manana 		path->leave_spinning = 1;
3588362a20c5SDavid Sterba 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3589362a20c5SDavid Sterba 				0, 0);
3590f46b5a66SChristoph Hellwig 		if (ret < 0)
3591f46b5a66SChristoph Hellwig 			goto out;
35922c463823SFilipe Manana 		/*
35932c463823SFilipe Manana 		 * First search, if no extent item that starts at offset off was
35942c463823SFilipe Manana 		 * found but the previous item is an extent item, it's possible
35952c463823SFilipe Manana 		 * it might overlap our target range, therefore process it.
35962c463823SFilipe Manana 		 */
35972c463823SFilipe Manana 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
35982c463823SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], &key,
35992c463823SFilipe Manana 					      path->slots[0] - 1);
36002c463823SFilipe Manana 			if (key.type == BTRFS_EXTENT_DATA_KEY)
36012c463823SFilipe Manana 				path->slots[0]--;
36022c463823SFilipe Manana 		}
3603f46b5a66SChristoph Hellwig 
3604ae01a0abSYan Zheng 		nritems = btrfs_header_nritems(path->nodes[0]);
3605e4355f34SFilipe David Borba Manana process_slot:
3606ae01a0abSYan Zheng 		if (path->slots[0] >= nritems) {
3607362a20c5SDavid Sterba 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3608f46b5a66SChristoph Hellwig 			if (ret < 0)
3609f46b5a66SChristoph Hellwig 				goto out;
3610f46b5a66SChristoph Hellwig 			if (ret > 0)
3611f46b5a66SChristoph Hellwig 				break;
3612ae01a0abSYan Zheng 			nritems = btrfs_header_nritems(path->nodes[0]);
3613f46b5a66SChristoph Hellwig 		}
3614f46b5a66SChristoph Hellwig 		leaf = path->nodes[0];
3615f46b5a66SChristoph Hellwig 		slot = path->slots[0];
3616f46b5a66SChristoph Hellwig 
3617ae01a0abSYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, slot);
3618962a298fSDavid Sterba 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
36194a0cc7caSNikolay Borisov 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3620f46b5a66SChristoph Hellwig 			break;
3621f46b5a66SChristoph Hellwig 
3622962a298fSDavid Sterba 		if (key.type == BTRFS_EXTENT_DATA_KEY) {
3623c5c9cd4dSSage Weil 			struct btrfs_file_extent_item *extent;
3624c5c9cd4dSSage Weil 			int type;
362531840ae1SZheng Yan 			u32 size;
362631840ae1SZheng Yan 			struct btrfs_key new_key;
3627c5c9cd4dSSage Weil 			u64 disko = 0, diskl = 0;
3628c5c9cd4dSSage Weil 			u64 datao = 0, datal = 0;
3629c5c9cd4dSSage Weil 			u8 comp;
3630f82a9901SFilipe Manana 			u64 drop_start;
363131840ae1SZheng Yan 
3632c5c9cd4dSSage Weil 			extent = btrfs_item_ptr(leaf, slot,
3633c5c9cd4dSSage Weil 						struct btrfs_file_extent_item);
3634c5c9cd4dSSage Weil 			comp = btrfs_file_extent_compression(leaf, extent);
3635c5c9cd4dSSage Weil 			type = btrfs_file_extent_type(leaf, extent);
3636c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3637c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3638d397712bSChris Mason 				disko = btrfs_file_extent_disk_bytenr(leaf,
3639d397712bSChris Mason 								      extent);
3640d397712bSChris Mason 				diskl = btrfs_file_extent_disk_num_bytes(leaf,
3641d397712bSChris Mason 								 extent);
3642c5c9cd4dSSage Weil 				datao = btrfs_file_extent_offset(leaf, extent);
3643d397712bSChris Mason 				datal = btrfs_file_extent_num_bytes(leaf,
3644d397712bSChris Mason 								    extent);
3645c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3646c5c9cd4dSSage Weil 				/* take upper bound, may be compressed */
3647c5c9cd4dSSage Weil 				datal = btrfs_file_extent_ram_bytes(leaf,
3648c5c9cd4dSSage Weil 								    extent);
3649c5c9cd4dSSage Weil 			}
365031840ae1SZheng Yan 
36512c463823SFilipe Manana 			/*
36522c463823SFilipe Manana 			 * The first search might have left us at an extent
36532c463823SFilipe Manana 			 * item that ends before our target range's start, can
36542c463823SFilipe Manana 			 * happen if we have holes and NO_HOLES feature enabled.
36552c463823SFilipe Manana 			 */
36562c463823SFilipe Manana 			if (key.offset + datal <= off) {
3657e4355f34SFilipe David Borba Manana 				path->slots[0]++;
3658e4355f34SFilipe David Borba Manana 				goto process_slot;
36592c463823SFilipe Manana 			} else if (key.offset >= off + len) {
36602c463823SFilipe Manana 				break;
3661e4355f34SFilipe David Borba Manana 			}
3662df858e76SFilipe Manana 			next_key_min_offset = key.offset + datal;
3663e4355f34SFilipe David Borba Manana 			size = btrfs_item_size_nr(leaf, slot);
3664e4355f34SFilipe David Borba Manana 			read_extent_buffer(leaf, buf,
3665e4355f34SFilipe David Borba Manana 					   btrfs_item_ptr_offset(leaf, slot),
3666e4355f34SFilipe David Borba Manana 					   size);
3667e4355f34SFilipe David Borba Manana 
3668e4355f34SFilipe David Borba Manana 			btrfs_release_path(path);
3669e4355f34SFilipe David Borba Manana 			path->leave_spinning = 0;
3670c5c9cd4dSSage Weil 
367131840ae1SZheng Yan 			memcpy(&new_key, &key, sizeof(new_key));
36724a0cc7caSNikolay Borisov 			new_key.objectid = btrfs_ino(BTRFS_I(inode));
36734d728ec7SLi Zefan 			if (off <= key.offset)
3674c5c9cd4dSSage Weil 				new_key.offset = key.offset + destoff - off;
36754d728ec7SLi Zefan 			else
36764d728ec7SLi Zefan 				new_key.offset = destoff;
3677c5c9cd4dSSage Weil 
3678b6f3409bSSage Weil 			/*
3679f82a9901SFilipe Manana 			 * Deal with a hole that doesn't have an extent item
3680f82a9901SFilipe Manana 			 * that represents it (NO_HOLES feature enabled).
3681f82a9901SFilipe Manana 			 * This hole is either in the middle of the cloning
3682f82a9901SFilipe Manana 			 * range or at the beginning (fully overlaps it or
3683f82a9901SFilipe Manana 			 * partially overlaps it).
3684f82a9901SFilipe Manana 			 */
3685f82a9901SFilipe Manana 			if (new_key.offset != last_dest_end)
3686f82a9901SFilipe Manana 				drop_start = last_dest_end;
3687f82a9901SFilipe Manana 			else
3688f82a9901SFilipe Manana 				drop_start = new_key.offset;
3689f82a9901SFilipe Manana 
3690f82a9901SFilipe Manana 			/*
3691b6f3409bSSage Weil 			 * 1 - adjusting old extent (we may have to split it)
3692b6f3409bSSage Weil 			 * 1 - add new extent
3693b6f3409bSSage Weil 			 * 1 - inode update
3694b6f3409bSSage Weil 			 */
3695b6f3409bSSage Weil 			trans = btrfs_start_transaction(root, 3);
3696a22285a6SYan, Zheng 			if (IS_ERR(trans)) {
3697a22285a6SYan, Zheng 				ret = PTR_ERR(trans);
3698a22285a6SYan, Zheng 				goto out;
3699a22285a6SYan, Zheng 			}
3700a22285a6SYan, Zheng 
3701c8a894d7SChris Mason 			if (type == BTRFS_FILE_EXTENT_REG ||
3702c8a894d7SChris Mason 			    type == BTRFS_FILE_EXTENT_PREALLOC) {
3703d72c0842SLi Zefan 				/*
3704d72c0842SLi Zefan 				 *    a  | --- range to clone ---|  b
3705d72c0842SLi Zefan 				 * | ------------- extent ------------- |
3706d72c0842SLi Zefan 				 */
3707d72c0842SLi Zefan 
370893915584SAntonio Ospite 				/* subtract range b */
3709d72c0842SLi Zefan 				if (key.offset + datal > off + len)
3710d72c0842SLi Zefan 					datal = off + len - key.offset;
3711d72c0842SLi Zefan 
371293915584SAntonio Ospite 				/* subtract range a */
3713a22285a6SYan, Zheng 				if (off > key.offset) {
3714a22285a6SYan, Zheng 					datao += off - key.offset;
3715a22285a6SYan, Zheng 					datal -= off - key.offset;
3716a22285a6SYan, Zheng 				}
3717a22285a6SYan, Zheng 
37185dc562c5SJosef Bacik 				ret = btrfs_drop_extents(trans, root, inode,
3719f82a9901SFilipe Manana 							 drop_start,
3720a22285a6SYan, Zheng 							 new_key.offset + datal,
37212671485dSJosef Bacik 							 1);
372279787eaaSJeff Mahoney 				if (ret) {
37233f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
372400fdf13aSLiu Bo 						btrfs_abort_transaction(trans,
372566642832SJeff Mahoney 									ret);
37263a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
372779787eaaSJeff Mahoney 					goto out;
372879787eaaSJeff Mahoney 				}
3729a22285a6SYan, Zheng 
373031840ae1SZheng Yan 				ret = btrfs_insert_empty_item(trans, root, path,
373131840ae1SZheng Yan 							      &new_key, size);
373279787eaaSJeff Mahoney 				if (ret) {
373366642832SJeff Mahoney 					btrfs_abort_transaction(trans, ret);
37343a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
373579787eaaSJeff Mahoney 					goto out;
373679787eaaSJeff Mahoney 				}
373731840ae1SZheng Yan 
373831840ae1SZheng Yan 				leaf = path->nodes[0];
373931840ae1SZheng Yan 				slot = path->slots[0];
374031840ae1SZheng Yan 				write_extent_buffer(leaf, buf,
374131840ae1SZheng Yan 					    btrfs_item_ptr_offset(leaf, slot),
374231840ae1SZheng Yan 					    size);
3743ae01a0abSYan Zheng 
3744f46b5a66SChristoph Hellwig 				extent = btrfs_item_ptr(leaf, slot,
3745f46b5a66SChristoph Hellwig 						struct btrfs_file_extent_item);
3746c5c9cd4dSSage Weil 
3747c5c9cd4dSSage Weil 				/* disko == 0 means it's a hole */
3748c5c9cd4dSSage Weil 				if (!disko)
3749c5c9cd4dSSage Weil 					datao = 0;
3750c5c9cd4dSSage Weil 
3751c5c9cd4dSSage Weil 				btrfs_set_file_extent_offset(leaf, extent,
3752c5c9cd4dSSage Weil 							     datao);
3753c5c9cd4dSSage Weil 				btrfs_set_file_extent_num_bytes(leaf, extent,
3754c5c9cd4dSSage Weil 								datal);
3755fcebe456SJosef Bacik 
3756c5c9cd4dSSage Weil 				if (disko) {
375782fa113fSQu Wenruo 					struct btrfs_ref ref = { 0 };
3758c5c9cd4dSSage Weil 					inode_add_bytes(inode, datal);
375982fa113fSQu Wenruo 					btrfs_init_generic_ref(&ref,
376082fa113fSQu Wenruo 						BTRFS_ADD_DELAYED_REF, disko,
376182fa113fSQu Wenruo 						diskl, 0);
376282fa113fSQu Wenruo 					btrfs_init_data_ref(&ref,
3763f46b5a66SChristoph Hellwig 						root->root_key.objectid,
37644a0cc7caSNikolay Borisov 						btrfs_ino(BTRFS_I(inode)),
3765b06c4bf5SFilipe Manana 						new_key.offset - datao);
376682fa113fSQu Wenruo 					ret = btrfs_inc_extent_ref(trans, &ref);
376779787eaaSJeff Mahoney 					if (ret) {
376879787eaaSJeff Mahoney 						btrfs_abort_transaction(trans,
376979787eaaSJeff Mahoney 									ret);
37703a45bb20SJeff Mahoney 						btrfs_end_transaction(trans);
377179787eaaSJeff Mahoney 						goto out;
377279787eaaSJeff Mahoney 
377379787eaaSJeff Mahoney 					}
3774f46b5a66SChristoph Hellwig 				}
3775c5c9cd4dSSage Weil 			} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3776c5c9cd4dSSage Weil 				u64 skip = 0;
3777c5c9cd4dSSage Weil 				u64 trim = 0;
3778ed958762SFilipe Manana 
3779c5c9cd4dSSage Weil 				if (off > key.offset) {
3780c5c9cd4dSSage Weil 					skip = off - key.offset;
3781c5c9cd4dSSage Weil 					new_key.offset += skip;
378231840ae1SZheng Yan 				}
3783d397712bSChris Mason 
3784c5c9cd4dSSage Weil 				if (key.offset + datal > off + len)
3785c5c9cd4dSSage Weil 					trim = key.offset + datal - (off + len);
3786d397712bSChris Mason 
3787c5c9cd4dSSage Weil 				if (comp && (skip || trim)) {
3788c5c9cd4dSSage Weil 					ret = -EINVAL;
37893a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
3790c5c9cd4dSSage Weil 					goto out;
379131840ae1SZheng Yan 				}
3792c5c9cd4dSSage Weil 				size -= skip + trim;
3793c5c9cd4dSSage Weil 				datal -= skip + trim;
3794a22285a6SYan, Zheng 
37954a0ab9d7SDavid Sterba 				ret = clone_copy_inline_extent(inode,
37968039d87dSFilipe Manana 							       trans, path,
37978039d87dSFilipe Manana 							       &new_key,
3798f82a9901SFilipe Manana 							       drop_start,
37998039d87dSFilipe Manana 							       datal,
38008039d87dSFilipe Manana 							       skip, size, buf);
380179787eaaSJeff Mahoney 				if (ret) {
38023f9e3df8SDavid Sterba 					if (ret != -EOPNOTSUPP)
38033a29bc09SChris Mason 						btrfs_abort_transaction(trans,
380479787eaaSJeff Mahoney 									ret);
38053a45bb20SJeff Mahoney 					btrfs_end_transaction(trans);
380679787eaaSJeff Mahoney 					goto out;
380779787eaaSJeff Mahoney 				}
3808c5c9cd4dSSage Weil 				leaf = path->nodes[0];
3809c5c9cd4dSSage Weil 				slot = path->slots[0];
3810c5c9cd4dSSage Weil 			}
3811c5c9cd4dSSage Weil 
38127ffbb598SFilipe Manana 			/* If we have an implicit hole (NO_HOLES feature). */
38137ffbb598SFilipe Manana 			if (drop_start < new_key.offset)
3814a2f392e4SNikolay Borisov 				clone_update_extent_map(BTRFS_I(inode), trans,
381514f59796SFilipe Manana 						NULL, drop_start,
38167ffbb598SFilipe Manana 						new_key.offset - drop_start);
38177ffbb598SFilipe Manana 
3818a2f392e4SNikolay Borisov 			clone_update_extent_map(BTRFS_I(inode), trans,
3819a2f392e4SNikolay Borisov 					path, 0, 0);
38207ffbb598SFilipe Manana 
3821c5c9cd4dSSage Weil 			btrfs_mark_buffer_dirty(leaf);
3822b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3823c5c9cd4dSSage Weil 
382462e2390eSFilipe Manana 			last_dest_end = ALIGN(new_key.offset + datal,
38250b246afaSJeff Mahoney 					      fs_info->sectorsize);
3826f82a9901SFilipe Manana 			ret = clone_finish_inode_update(trans, inode,
3827f82a9901SFilipe Manana 							last_dest_end,
38281c919a5eSMark Fasheh 							destoff, olen,
38291c919a5eSMark Fasheh 							no_time_update);
3830f82a9901SFilipe Manana 			if (ret)
383179787eaaSJeff Mahoney 				goto out;
38322c463823SFilipe Manana 			if (new_key.offset + datal >= destoff + len)
38332c463823SFilipe Manana 				break;
3834a22285a6SYan, Zheng 		}
3835b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3836df858e76SFilipe Manana 		key.offset = next_key_min_offset;
383769ae5e44SWang Xiaoguang 
383869ae5e44SWang Xiaoguang 		if (fatal_signal_pending(current)) {
383969ae5e44SWang Xiaoguang 			ret = -EINTR;
384069ae5e44SWang Xiaoguang 			goto out;
384169ae5e44SWang Xiaoguang 		}
3842ae01a0abSYan Zheng 	}
3843f46b5a66SChristoph Hellwig 	ret = 0;
384432b7c687SMark Fasheh 
3845f82a9901SFilipe Manana 	if (last_dest_end < destoff + len) {
3846f82a9901SFilipe Manana 		/*
3847f82a9901SFilipe Manana 		 * We have an implicit hole (NO_HOLES feature is enabled) that
3848f82a9901SFilipe Manana 		 * fully or partially overlaps our cloning range at its end.
3849f82a9901SFilipe Manana 		 */
3850b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3851f82a9901SFilipe Manana 
3852f82a9901SFilipe Manana 		/*
3853f82a9901SFilipe Manana 		 * 1 - remove extent(s)
3854f82a9901SFilipe Manana 		 * 1 - inode update
3855f82a9901SFilipe Manana 		 */
3856f82a9901SFilipe Manana 		trans = btrfs_start_transaction(root, 2);
3857f82a9901SFilipe Manana 		if (IS_ERR(trans)) {
3858f82a9901SFilipe Manana 			ret = PTR_ERR(trans);
3859f82a9901SFilipe Manana 			goto out;
3860f82a9901SFilipe Manana 		}
3861f82a9901SFilipe Manana 		ret = btrfs_drop_extents(trans, root, inode,
3862f82a9901SFilipe Manana 					 last_dest_end, destoff + len, 1);
3863f82a9901SFilipe Manana 		if (ret) {
3864f82a9901SFilipe Manana 			if (ret != -EOPNOTSUPP)
386566642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
38663a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
3867f82a9901SFilipe Manana 			goto out;
3868f82a9901SFilipe Manana 		}
3869a2f392e4SNikolay Borisov 		clone_update_extent_map(BTRFS_I(inode), trans, NULL,
3870a2f392e4SNikolay Borisov 				last_dest_end,
387114f59796SFilipe Manana 				destoff + len - last_dest_end);
3872f82a9901SFilipe Manana 		ret = clone_finish_inode_update(trans, inode, destoff + len,
38731c919a5eSMark Fasheh 						destoff, olen, no_time_update);
3874f82a9901SFilipe Manana 	}
3875f82a9901SFilipe Manana 
3876f46b5a66SChristoph Hellwig out:
387732b7c687SMark Fasheh 	btrfs_free_path(path);
387815351955SDavid Sterba 	kvfree(buf);
387932b7c687SMark Fasheh 	return ret;
388032b7c687SMark Fasheh }
388132b7c687SMark Fasheh 
38823db11b2eSZach Brown static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
388332b7c687SMark Fasheh 					u64 off, u64 olen, u64 destoff)
388432b7c687SMark Fasheh {
388554563d41SAl Viro 	struct inode *inode = file_inode(file);
38863db11b2eSZach Brown 	struct inode *src = file_inode(file_src);
38870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
388832b7c687SMark Fasheh 	int ret;
388932b7c687SMark Fasheh 	u64 len = olen;
38900b246afaSJeff Mahoney 	u64 bs = fs_info->sb->s_blocksize;
389132b7c687SMark Fasheh 
389232b7c687SMark Fasheh 	/*
389332b7c687SMark Fasheh 	 * TODO:
389432b7c687SMark Fasheh 	 * - split compressed inline extents.  annoying: we need to
389532b7c687SMark Fasheh 	 *   decompress into destination's address_space (the file offset
389632b7c687SMark Fasheh 	 *   may change, so source mapping won't do), then recompress (or
389732b7c687SMark Fasheh 	 *   otherwise reinsert) a subrange.
389800fdf13aSLiu Bo 	 *
389900fdf13aSLiu Bo 	 * - split destination inode's inline extents.  The inline extents can
390000fdf13aSLiu Bo 	 *   be either compressed or non-compressed.
390132b7c687SMark Fasheh 	 */
390232b7c687SMark Fasheh 
3903ac765f83SFilipe Manana 	/*
390434a28e3dSFilipe Manana 	 * VFS's generic_remap_file_range_prep() protects us from cloning the
390534a28e3dSFilipe Manana 	 * eof block into the middle of a file, which would result in corruption
390634a28e3dSFilipe Manana 	 * if the file size is not blocksize aligned. So we don't need to check
390734a28e3dSFilipe Manana 	 * for that case here.
3908ac765f83SFilipe Manana 	 */
390934a28e3dSFilipe Manana 	if (off + len == src->i_size)
391032b7c687SMark Fasheh 		len = ALIGN(src->i_size, bs) - off;
391132b7c687SMark Fasheh 
391232b7c687SMark Fasheh 	if (destoff > inode->i_size) {
3913f7fa1107SFilipe Manana 		const u64 wb_start = ALIGN_DOWN(inode->i_size, bs);
3914f7fa1107SFilipe Manana 
391532b7c687SMark Fasheh 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
391632b7c687SMark Fasheh 		if (ret)
391734a28e3dSFilipe Manana 			return ret;
3918f7fa1107SFilipe Manana 		/*
3919f7fa1107SFilipe Manana 		 * We may have truncated the last block if the inode's size is
3920f7fa1107SFilipe Manana 		 * not sector size aligned, so we need to wait for writeback to
3921f7fa1107SFilipe Manana 		 * complete before proceeding further, otherwise we can race
3922f7fa1107SFilipe Manana 		 * with cloning and attempt to increment a reference to an
3923f7fa1107SFilipe Manana 		 * extent that no longer exists (writeback completed right after
3924f7fa1107SFilipe Manana 		 * we found the previous extent covering eof and before we
3925f7fa1107SFilipe Manana 		 * attempted to increment its reference count).
3926f7fa1107SFilipe Manana 		 */
3927f7fa1107SFilipe Manana 		ret = btrfs_wait_ordered_range(inode, wb_start,
3928f7fa1107SFilipe Manana 					       destoff - wb_start);
3929f7fa1107SFilipe Manana 		if (ret)
3930f7fa1107SFilipe Manana 			return ret;
393132b7c687SMark Fasheh 	}
393232b7c687SMark Fasheh 
3933c125b8bfSFilipe Manana 	/*
3934d8b55242SFilipe Manana 	 * Lock destination range to serialize with concurrent readpages() and
3935d8b55242SFilipe Manana 	 * source range to serialize with relocation.
3936c125b8bfSFilipe Manana 	 */
3937d8b55242SFilipe Manana 	btrfs_double_extent_lock(src, off, inode, destoff, len);
39381c919a5eSMark Fasheh 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
3939d8b55242SFilipe Manana 	btrfs_double_extent_unlock(src, off, inode, destoff, len);
3940c125b8bfSFilipe Manana 	/*
3941c125b8bfSFilipe Manana 	 * Truncate page cache pages so that future reads will see the cloned
3942c125b8bfSFilipe Manana 	 * data immediately and not the previous data.
3943c125b8bfSFilipe Manana 	 */
394465bfa658SChandan Rajendra 	truncate_inode_pages_range(&inode->i_data,
394509cbfeafSKirill A. Shutemov 				round_down(destoff, PAGE_SIZE),
394609cbfeafSKirill A. Shutemov 				round_up(destoff + len, PAGE_SIZE) - 1);
394734a28e3dSFilipe Manana 
394834a28e3dSFilipe Manana 	return ret;
394934a28e3dSFilipe Manana }
395034a28e3dSFilipe Manana 
395134a28e3dSFilipe Manana static int btrfs_remap_file_range_prep(struct file *file_in, loff_t pos_in,
395234a28e3dSFilipe Manana 				       struct file *file_out, loff_t pos_out,
395334a28e3dSFilipe Manana 				       loff_t *len, unsigned int remap_flags)
395434a28e3dSFilipe Manana {
395534a28e3dSFilipe Manana 	struct inode *inode_in = file_inode(file_in);
395634a28e3dSFilipe Manana 	struct inode *inode_out = file_inode(file_out);
395734a28e3dSFilipe Manana 	u64 bs = BTRFS_I(inode_out)->root->fs_info->sb->s_blocksize;
395834a28e3dSFilipe Manana 	bool same_inode = inode_out == inode_in;
395934a28e3dSFilipe Manana 	u64 wb_len;
396034a28e3dSFilipe Manana 	int ret;
396134a28e3dSFilipe Manana 
396234a28e3dSFilipe Manana 	if (!(remap_flags & REMAP_FILE_DEDUP)) {
396334a28e3dSFilipe Manana 		struct btrfs_root *root_out = BTRFS_I(inode_out)->root;
396434a28e3dSFilipe Manana 
396534a28e3dSFilipe Manana 		if (btrfs_root_readonly(root_out))
396634a28e3dSFilipe Manana 			return -EROFS;
396734a28e3dSFilipe Manana 
396834a28e3dSFilipe Manana 		if (file_in->f_path.mnt != file_out->f_path.mnt ||
396934a28e3dSFilipe Manana 		    inode_in->i_sb != inode_out->i_sb)
397034a28e3dSFilipe Manana 			return -EXDEV;
397134a28e3dSFilipe Manana 	}
397234a28e3dSFilipe Manana 
3973500710d3SFilipe Manana 	/* don't make the dst file partly checksummed */
3974500710d3SFilipe Manana 	if ((BTRFS_I(inode_in)->flags & BTRFS_INODE_NODATASUM) !=
3975500710d3SFilipe Manana 	    (BTRFS_I(inode_out)->flags & BTRFS_INODE_NODATASUM)) {
39767984ae52SGoldwyn Rodrigues 		return -EINVAL;
3977500710d3SFilipe Manana 	}
3978500710d3SFilipe Manana 
397934a28e3dSFilipe Manana 	/*
398034a28e3dSFilipe Manana 	 * Now that the inodes are locked, we need to start writeback ourselves
398134a28e3dSFilipe Manana 	 * and can not rely on the writeback from the VFS's generic helper
398234a28e3dSFilipe Manana 	 * generic_remap_file_range_prep() because:
398334a28e3dSFilipe Manana 	 *
398434a28e3dSFilipe Manana 	 * 1) For compression we must call filemap_fdatawrite_range() range
398534a28e3dSFilipe Manana 	 *    twice (btrfs_fdatawrite_range() does it for us), and the generic
398634a28e3dSFilipe Manana 	 *    helper only calls it once;
398734a28e3dSFilipe Manana 	 *
398834a28e3dSFilipe Manana 	 * 2) filemap_fdatawrite_range(), called by the generic helper only
398934a28e3dSFilipe Manana 	 *    waits for the writeback to complete, i.e. for IO to be done, and
399034a28e3dSFilipe Manana 	 *    not for the ordered extents to complete. We need to wait for them
399134a28e3dSFilipe Manana 	 *    to complete so that new file extent items are in the fs tree.
399234a28e3dSFilipe Manana 	 */
399334a28e3dSFilipe Manana 	if (*len == 0 && !(remap_flags & REMAP_FILE_DEDUP))
399434a28e3dSFilipe Manana 		wb_len = ALIGN(inode_in->i_size, bs) - ALIGN_DOWN(pos_in, bs);
399534a28e3dSFilipe Manana 	else
399634a28e3dSFilipe Manana 		wb_len = ALIGN(*len, bs);
399734a28e3dSFilipe Manana 
399834a28e3dSFilipe Manana 	/*
399934a28e3dSFilipe Manana 	 * Since we don't lock ranges, wait for ongoing lockless dio writes (as
400034a28e3dSFilipe Manana 	 * any in progress could create its ordered extents after we wait for
400134a28e3dSFilipe Manana 	 * existing ordered extents below).
400234a28e3dSFilipe Manana 	 */
400334a28e3dSFilipe Manana 	inode_dio_wait(inode_in);
400434a28e3dSFilipe Manana 	if (!same_inode)
400534a28e3dSFilipe Manana 		inode_dio_wait(inode_out);
400634a28e3dSFilipe Manana 
400734a28e3dSFilipe Manana 	ret = btrfs_wait_ordered_range(inode_in, ALIGN_DOWN(pos_in, bs),
400834a28e3dSFilipe Manana 				       wb_len);
400934a28e3dSFilipe Manana 	if (ret < 0)
40107984ae52SGoldwyn Rodrigues 		return ret;
401134a28e3dSFilipe Manana 	ret = btrfs_wait_ordered_range(inode_out, ALIGN_DOWN(pos_out, bs),
401234a28e3dSFilipe Manana 				       wb_len);
401334a28e3dSFilipe Manana 	if (ret < 0)
40143db11b2eSZach Brown 		return ret;
40157984ae52SGoldwyn Rodrigues 
40167984ae52SGoldwyn Rodrigues 	return generic_remap_file_range_prep(file_in, pos_in, file_out, pos_out,
40177984ae52SGoldwyn Rodrigues 					    len, remap_flags);
40183db11b2eSZach Brown }
40193db11b2eSZach Brown 
402042ec3d4cSDarrick J. Wong loff_t btrfs_remap_file_range(struct file *src_file, loff_t off,
402142ec3d4cSDarrick J. Wong 		struct file *dst_file, loff_t destoff, loff_t len,
40222e5dfc99SDarrick J. Wong 		unsigned int remap_flags)
40233db11b2eSZach Brown {
402434a28e3dSFilipe Manana 	struct inode *src_inode = file_inode(src_file);
402534a28e3dSFilipe Manana 	struct inode *dst_inode = file_inode(dst_file);
402634a28e3dSFilipe Manana 	bool same_inode = dst_inode == src_inode;
402742ec3d4cSDarrick J. Wong 	int ret;
402842ec3d4cSDarrick J. Wong 
40292e5dfc99SDarrick J. Wong 	if (remap_flags & ~(REMAP_FILE_DEDUP | REMAP_FILE_ADVISORY))
40302e5dfc99SDarrick J. Wong 		return -EINVAL;
40312e5dfc99SDarrick J. Wong 
40327984ae52SGoldwyn Rodrigues 	if (same_inode)
40337984ae52SGoldwyn Rodrigues 		inode_lock(src_inode);
40347984ae52SGoldwyn Rodrigues 	else
40357984ae52SGoldwyn Rodrigues 		lock_two_nondirectories(src_inode, dst_inode);
40367984ae52SGoldwyn Rodrigues 
403734a28e3dSFilipe Manana 	ret = btrfs_remap_file_range_prep(src_file, off, dst_file, destoff,
403834a28e3dSFilipe Manana 					  &len, remap_flags);
403934a28e3dSFilipe Manana 	if (ret < 0 || len == 0)
40407984ae52SGoldwyn Rodrigues 		goto out_unlock;
40412e5dfc99SDarrick J. Wong 
404234a28e3dSFilipe Manana 	if (remap_flags & REMAP_FILE_DEDUP)
404334a28e3dSFilipe Manana 		ret = btrfs_extent_same(src_inode, off, len, dst_inode, destoff);
404434a28e3dSFilipe Manana 	else
404542ec3d4cSDarrick J. Wong 		ret = btrfs_clone_files(dst_file, src_file, off, len, destoff);
404634a28e3dSFilipe Manana 
40477984ae52SGoldwyn Rodrigues out_unlock:
404834a28e3dSFilipe Manana 	if (same_inode)
404934a28e3dSFilipe Manana 		inode_unlock(src_inode);
405034a28e3dSFilipe Manana 	else
40514ea748e1SFilipe Manana 		unlock_two_nondirectories(src_inode, dst_inode);
405234a28e3dSFilipe Manana 
405342ec3d4cSDarrick J. Wong 	return ret < 0 ? ret : len;
4054c5c9cd4dSSage Weil }
4055c5c9cd4dSSage Weil 
40566ef5ed0dSJosef Bacik static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
40576ef5ed0dSJosef Bacik {
4058496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
40590b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
40606ef5ed0dSJosef Bacik 	struct btrfs_root *root = BTRFS_I(inode)->root;
40616ef5ed0dSJosef Bacik 	struct btrfs_root *new_root;
40626ef5ed0dSJosef Bacik 	struct btrfs_dir_item *di;
40636ef5ed0dSJosef Bacik 	struct btrfs_trans_handle *trans;
40646ef5ed0dSJosef Bacik 	struct btrfs_path *path;
40656ef5ed0dSJosef Bacik 	struct btrfs_key location;
40666ef5ed0dSJosef Bacik 	struct btrfs_disk_key disk_key;
40676ef5ed0dSJosef Bacik 	u64 objectid = 0;
40686ef5ed0dSJosef Bacik 	u64 dir_id;
40693c04ce01SMiao Xie 	int ret;
40706ef5ed0dSJosef Bacik 
40716ef5ed0dSJosef Bacik 	if (!capable(CAP_SYS_ADMIN))
40726ef5ed0dSJosef Bacik 		return -EPERM;
40736ef5ed0dSJosef Bacik 
40743c04ce01SMiao Xie 	ret = mnt_want_write_file(file);
40753c04ce01SMiao Xie 	if (ret)
40763c04ce01SMiao Xie 		return ret;
40773c04ce01SMiao Xie 
40783c04ce01SMiao Xie 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
40793c04ce01SMiao Xie 		ret = -EFAULT;
40803c04ce01SMiao Xie 		goto out;
40813c04ce01SMiao Xie 	}
40826ef5ed0dSJosef Bacik 
40836ef5ed0dSJosef Bacik 	if (!objectid)
40841cecf579Schandan 		objectid = BTRFS_FS_TREE_OBJECTID;
40856ef5ed0dSJosef Bacik 
40866ef5ed0dSJosef Bacik 	location.objectid = objectid;
40876ef5ed0dSJosef Bacik 	location.type = BTRFS_ROOT_ITEM_KEY;
40886ef5ed0dSJosef Bacik 	location.offset = (u64)-1;
40896ef5ed0dSJosef Bacik 
40900b246afaSJeff Mahoney 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
40913c04ce01SMiao Xie 	if (IS_ERR(new_root)) {
40923c04ce01SMiao Xie 		ret = PTR_ERR(new_root);
40933c04ce01SMiao Xie 		goto out;
40943c04ce01SMiao Xie 	}
40954fd786e6SMisono Tomohiro 	if (!is_fstree(new_root->root_key.objectid)) {
40966d6d2829Ssatoru takeuchi 		ret = -ENOENT;
40976d6d2829Ssatoru takeuchi 		goto out;
40986d6d2829Ssatoru takeuchi 	}
40996ef5ed0dSJosef Bacik 
41006ef5ed0dSJosef Bacik 	path = btrfs_alloc_path();
41013c04ce01SMiao Xie 	if (!path) {
41023c04ce01SMiao Xie 		ret = -ENOMEM;
41033c04ce01SMiao Xie 		goto out;
41043c04ce01SMiao Xie 	}
41056ef5ed0dSJosef Bacik 	path->leave_spinning = 1;
41066ef5ed0dSJosef Bacik 
41076ef5ed0dSJosef Bacik 	trans = btrfs_start_transaction(root, 1);
410898d5dc13STsutomu Itoh 	if (IS_ERR(trans)) {
41096ef5ed0dSJosef Bacik 		btrfs_free_path(path);
41103c04ce01SMiao Xie 		ret = PTR_ERR(trans);
41113c04ce01SMiao Xie 		goto out;
41126ef5ed0dSJosef Bacik 	}
41136ef5ed0dSJosef Bacik 
41140b246afaSJeff Mahoney 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
41150b246afaSJeff Mahoney 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
41166ef5ed0dSJosef Bacik 				   dir_id, "default", 7, 1);
4117cf1e99a4SDan Carpenter 	if (IS_ERR_OR_NULL(di)) {
41186ef5ed0dSJosef Bacik 		btrfs_free_path(path);
41193a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
41200b246afaSJeff Mahoney 		btrfs_err(fs_info,
41215d163e0eSJeff Mahoney 			  "Umm, you don't have the default diritem, this isn't going to work");
41223c04ce01SMiao Xie 		ret = -ENOENT;
41233c04ce01SMiao Xie 		goto out;
41246ef5ed0dSJosef Bacik 	}
41256ef5ed0dSJosef Bacik 
41266ef5ed0dSJosef Bacik 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
41276ef5ed0dSJosef Bacik 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
41286ef5ed0dSJosef Bacik 	btrfs_mark_buffer_dirty(path->nodes[0]);
41296ef5ed0dSJosef Bacik 	btrfs_free_path(path);
41306ef5ed0dSJosef Bacik 
41310b246afaSJeff Mahoney 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
41323a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
41333c04ce01SMiao Xie out:
41343c04ce01SMiao Xie 	mnt_drop_write_file(file);
41353c04ce01SMiao Xie 	return ret;
41366ef5ed0dSJosef Bacik }
41376ef5ed0dSJosef Bacik 
4138c065f5b1SSu Yue static void get_block_group_info(struct list_head *groups_list,
4139bf5fc093SJosef Bacik 				 struct btrfs_ioctl_space_info *space)
4140bf5fc093SJosef Bacik {
4141bf5fc093SJosef Bacik 	struct btrfs_block_group_cache *block_group;
4142bf5fc093SJosef Bacik 
4143bf5fc093SJosef Bacik 	space->total_bytes = 0;
4144bf5fc093SJosef Bacik 	space->used_bytes = 0;
4145bf5fc093SJosef Bacik 	space->flags = 0;
4146bf5fc093SJosef Bacik 	list_for_each_entry(block_group, groups_list, list) {
4147bf5fc093SJosef Bacik 		space->flags = block_group->flags;
4148bf5fc093SJosef Bacik 		space->total_bytes += block_group->key.offset;
4149bf5fc093SJosef Bacik 		space->used_bytes +=
4150bf5fc093SJosef Bacik 			btrfs_block_group_used(&block_group->item);
4151bf5fc093SJosef Bacik 	}
4152bf5fc093SJosef Bacik }
4153bf5fc093SJosef Bacik 
41542ff7e61eSJeff Mahoney static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
41552ff7e61eSJeff Mahoney 				   void __user *arg)
41561406e432SJosef Bacik {
41571406e432SJosef Bacik 	struct btrfs_ioctl_space_args space_args;
41581406e432SJosef Bacik 	struct btrfs_ioctl_space_info space;
41591406e432SJosef Bacik 	struct btrfs_ioctl_space_info *dest;
41607fde62bfSChris Mason 	struct btrfs_ioctl_space_info *dest_orig;
416113f2696fSDaniel J Blueman 	struct btrfs_ioctl_space_info __user *user_dest;
41621406e432SJosef Bacik 	struct btrfs_space_info *info;
4163315d8e98SColin Ian King 	static const u64 types[] = {
4164315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA,
4165bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_SYSTEM,
4166bf5fc093SJosef Bacik 		BTRFS_BLOCK_GROUP_METADATA,
4167315d8e98SColin Ian King 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4168315d8e98SColin Ian King 	};
4169bf5fc093SJosef Bacik 	int num_types = 4;
41707fde62bfSChris Mason 	int alloc_size;
41711406e432SJosef Bacik 	int ret = 0;
417251788b1bSDan Rosenberg 	u64 slot_count = 0;
4173bf5fc093SJosef Bacik 	int i, c;
41741406e432SJosef Bacik 
41751406e432SJosef Bacik 	if (copy_from_user(&space_args,
41761406e432SJosef Bacik 			   (struct btrfs_ioctl_space_args __user *)arg,
41771406e432SJosef Bacik 			   sizeof(space_args)))
41781406e432SJosef Bacik 		return -EFAULT;
41791406e432SJosef Bacik 
4180bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4181bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4182bf5fc093SJosef Bacik 
4183bf5fc093SJosef Bacik 		info = NULL;
41847fde62bfSChris Mason 		rcu_read_lock();
41850b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4186bf5fc093SJosef Bacik 					list) {
4187bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4188bf5fc093SJosef Bacik 				info = tmp;
4189bf5fc093SJosef Bacik 				break;
4190bf5fc093SJosef Bacik 			}
4191bf5fc093SJosef Bacik 		}
41927fde62bfSChris Mason 		rcu_read_unlock();
41931406e432SJosef Bacik 
4194bf5fc093SJosef Bacik 		if (!info)
4195bf5fc093SJosef Bacik 			continue;
4196bf5fc093SJosef Bacik 
4197bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4198bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4199bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c]))
4200bf5fc093SJosef Bacik 				slot_count++;
4201bf5fc093SJosef Bacik 		}
4202bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4203bf5fc093SJosef Bacik 	}
4204bf5fc093SJosef Bacik 
420536523e95SDavid Sterba 	/*
420636523e95SDavid Sterba 	 * Global block reserve, exported as a space_info
420736523e95SDavid Sterba 	 */
420836523e95SDavid Sterba 	slot_count++;
420936523e95SDavid Sterba 
42107fde62bfSChris Mason 	/* space_slots == 0 means they are asking for a count */
42117fde62bfSChris Mason 	if (space_args.space_slots == 0) {
42127fde62bfSChris Mason 		space_args.total_spaces = slot_count;
42137fde62bfSChris Mason 		goto out;
42147fde62bfSChris Mason 	}
4215bf5fc093SJosef Bacik 
421651788b1bSDan Rosenberg 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4217bf5fc093SJosef Bacik 
42187fde62bfSChris Mason 	alloc_size = sizeof(*dest) * slot_count;
4219bf5fc093SJosef Bacik 
42207fde62bfSChris Mason 	/* we generally have at most 6 or so space infos, one for each raid
42217fde62bfSChris Mason 	 * level.  So, a whole page should be more than enough for everyone
42227fde62bfSChris Mason 	 */
422309cbfeafSKirill A. Shutemov 	if (alloc_size > PAGE_SIZE)
42247fde62bfSChris Mason 		return -ENOMEM;
42257fde62bfSChris Mason 
42267fde62bfSChris Mason 	space_args.total_spaces = 0;
42278d2db785SDavid Sterba 	dest = kmalloc(alloc_size, GFP_KERNEL);
42287fde62bfSChris Mason 	if (!dest)
42297fde62bfSChris Mason 		return -ENOMEM;
42307fde62bfSChris Mason 	dest_orig = dest;
42317fde62bfSChris Mason 
42327fde62bfSChris Mason 	/* now we have a buffer to copy into */
4233bf5fc093SJosef Bacik 	for (i = 0; i < num_types; i++) {
4234bf5fc093SJosef Bacik 		struct btrfs_space_info *tmp;
4235bf5fc093SJosef Bacik 
423651788b1bSDan Rosenberg 		if (!slot_count)
423751788b1bSDan Rosenberg 			break;
423851788b1bSDan Rosenberg 
4239bf5fc093SJosef Bacik 		info = NULL;
42401406e432SJosef Bacik 		rcu_read_lock();
42410b246afaSJeff Mahoney 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4242bf5fc093SJosef Bacik 					list) {
4243bf5fc093SJosef Bacik 			if (tmp->flags == types[i]) {
4244bf5fc093SJosef Bacik 				info = tmp;
42457fde62bfSChris Mason 				break;
4246bf5fc093SJosef Bacik 			}
4247bf5fc093SJosef Bacik 		}
4248bf5fc093SJosef Bacik 		rcu_read_unlock();
42497fde62bfSChris Mason 
4250bf5fc093SJosef Bacik 		if (!info)
4251bf5fc093SJosef Bacik 			continue;
4252bf5fc093SJosef Bacik 		down_read(&info->groups_sem);
4253bf5fc093SJosef Bacik 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4254bf5fc093SJosef Bacik 			if (!list_empty(&info->block_groups[c])) {
4255c065f5b1SSu Yue 				get_block_group_info(&info->block_groups[c],
4256c065f5b1SSu Yue 						     &space);
42577fde62bfSChris Mason 				memcpy(dest, &space, sizeof(space));
42581406e432SJosef Bacik 				dest++;
42591406e432SJosef Bacik 				space_args.total_spaces++;
426051788b1bSDan Rosenberg 				slot_count--;
42611406e432SJosef Bacik 			}
426251788b1bSDan Rosenberg 			if (!slot_count)
426351788b1bSDan Rosenberg 				break;
4264bf5fc093SJosef Bacik 		}
4265bf5fc093SJosef Bacik 		up_read(&info->groups_sem);
4266bf5fc093SJosef Bacik 	}
42671406e432SJosef Bacik 
426836523e95SDavid Sterba 	/*
426936523e95SDavid Sterba 	 * Add global block reserve
427036523e95SDavid Sterba 	 */
427136523e95SDavid Sterba 	if (slot_count) {
42720b246afaSJeff Mahoney 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
427336523e95SDavid Sterba 
427436523e95SDavid Sterba 		spin_lock(&block_rsv->lock);
427536523e95SDavid Sterba 		space.total_bytes = block_rsv->size;
427636523e95SDavid Sterba 		space.used_bytes = block_rsv->size - block_rsv->reserved;
427736523e95SDavid Sterba 		spin_unlock(&block_rsv->lock);
427836523e95SDavid Sterba 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
427936523e95SDavid Sterba 		memcpy(dest, &space, sizeof(space));
428036523e95SDavid Sterba 		space_args.total_spaces++;
428136523e95SDavid Sterba 	}
428236523e95SDavid Sterba 
42832eec6c81SDaniel J Blueman 	user_dest = (struct btrfs_ioctl_space_info __user *)
42847fde62bfSChris Mason 		(arg + sizeof(struct btrfs_ioctl_space_args));
42857fde62bfSChris Mason 
42867fde62bfSChris Mason 	if (copy_to_user(user_dest, dest_orig, alloc_size))
42877fde62bfSChris Mason 		ret = -EFAULT;
42887fde62bfSChris Mason 
42897fde62bfSChris Mason 	kfree(dest_orig);
42907fde62bfSChris Mason out:
42917fde62bfSChris Mason 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
42921406e432SJosef Bacik 		ret = -EFAULT;
42931406e432SJosef Bacik 
42941406e432SJosef Bacik 	return ret;
42951406e432SJosef Bacik }
42961406e432SJosef Bacik 
42979a8c28beSMiao Xie static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
42989a8c28beSMiao Xie 					    void __user *argp)
429946204592SSage Weil {
430046204592SSage Weil 	struct btrfs_trans_handle *trans;
430146204592SSage Weil 	u64 transid;
4302db5b493aSTsutomu Itoh 	int ret;
430346204592SSage Weil 
4304d4edf39bSMiao Xie 	trans = btrfs_attach_transaction_barrier(root);
4305ff7c1d33SMiao Xie 	if (IS_ERR(trans)) {
4306ff7c1d33SMiao Xie 		if (PTR_ERR(trans) != -ENOENT)
430798d5dc13STsutomu Itoh 			return PTR_ERR(trans);
4308ff7c1d33SMiao Xie 
4309ff7c1d33SMiao Xie 		/* No running transaction, don't bother */
4310ff7c1d33SMiao Xie 		transid = root->fs_info->last_trans_committed;
4311ff7c1d33SMiao Xie 		goto out;
4312ff7c1d33SMiao Xie 	}
431346204592SSage Weil 	transid = trans->transid;
43143a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction_async(trans, 0);
43158b2b2d3cSTsutomu Itoh 	if (ret) {
43163a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
4317db5b493aSTsutomu Itoh 		return ret;
43188b2b2d3cSTsutomu Itoh 	}
4319ff7c1d33SMiao Xie out:
432046204592SSage Weil 	if (argp)
432146204592SSage Weil 		if (copy_to_user(argp, &transid, sizeof(transid)))
432246204592SSage Weil 			return -EFAULT;
432346204592SSage Weil 	return 0;
432446204592SSage Weil }
432546204592SSage Weil 
43262ff7e61eSJeff Mahoney static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
43279a8c28beSMiao Xie 					   void __user *argp)
432846204592SSage Weil {
432946204592SSage Weil 	u64 transid;
433046204592SSage Weil 
433146204592SSage Weil 	if (argp) {
433246204592SSage Weil 		if (copy_from_user(&transid, argp, sizeof(transid)))
433346204592SSage Weil 			return -EFAULT;
433446204592SSage Weil 	} else {
433546204592SSage Weil 		transid = 0;  /* current trans */
433646204592SSage Weil 	}
43372ff7e61eSJeff Mahoney 	return btrfs_wait_for_commit(fs_info, transid);
433846204592SSage Weil }
433946204592SSage Weil 
4340b8e95489SMiao Xie static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4341475f6387SJan Schmidt {
43420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4343475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4344b8e95489SMiao Xie 	int ret;
4345475f6387SJan Schmidt 
4346475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4347475f6387SJan Schmidt 		return -EPERM;
4348475f6387SJan Schmidt 
4349475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4350475f6387SJan Schmidt 	if (IS_ERR(sa))
4351475f6387SJan Schmidt 		return PTR_ERR(sa);
4352475f6387SJan Schmidt 
4353b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4354b8e95489SMiao Xie 		ret = mnt_want_write_file(file);
4355b8e95489SMiao Xie 		if (ret)
4356b8e95489SMiao Xie 			goto out;
4357b8e95489SMiao Xie 	}
4358b8e95489SMiao Xie 
43590b246afaSJeff Mahoney 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
436063a212abSStefan Behrens 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
436163a212abSStefan Behrens 			      0);
4362475f6387SJan Schmidt 
436306fe39abSFilipe Manana 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4364475f6387SJan Schmidt 		ret = -EFAULT;
4365475f6387SJan Schmidt 
4366b8e95489SMiao Xie 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4367b8e95489SMiao Xie 		mnt_drop_write_file(file);
4368b8e95489SMiao Xie out:
4369475f6387SJan Schmidt 	kfree(sa);
4370475f6387SJan Schmidt 	return ret;
4371475f6387SJan Schmidt }
4372475f6387SJan Schmidt 
43732ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4374475f6387SJan Schmidt {
4375475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4376475f6387SJan Schmidt 		return -EPERM;
4377475f6387SJan Schmidt 
43782ff7e61eSJeff Mahoney 	return btrfs_scrub_cancel(fs_info);
4379475f6387SJan Schmidt }
4380475f6387SJan Schmidt 
43812ff7e61eSJeff Mahoney static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4382475f6387SJan Schmidt 				       void __user *arg)
4383475f6387SJan Schmidt {
4384475f6387SJan Schmidt 	struct btrfs_ioctl_scrub_args *sa;
4385475f6387SJan Schmidt 	int ret;
4386475f6387SJan Schmidt 
4387475f6387SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4388475f6387SJan Schmidt 		return -EPERM;
4389475f6387SJan Schmidt 
4390475f6387SJan Schmidt 	sa = memdup_user(arg, sizeof(*sa));
4391475f6387SJan Schmidt 	if (IS_ERR(sa))
4392475f6387SJan Schmidt 		return PTR_ERR(sa);
4393475f6387SJan Schmidt 
43942ff7e61eSJeff Mahoney 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4395475f6387SJan Schmidt 
43964fa99b00SFilipe Manana 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4397475f6387SJan Schmidt 		ret = -EFAULT;
4398475f6387SJan Schmidt 
4399475f6387SJan Schmidt 	kfree(sa);
4400475f6387SJan Schmidt 	return ret;
4401475f6387SJan Schmidt }
4402475f6387SJan Schmidt 
44032ff7e61eSJeff Mahoney static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4404b27f7c0cSDavid Sterba 				      void __user *arg)
4405c11d2c23SStefan Behrens {
4406c11d2c23SStefan Behrens 	struct btrfs_ioctl_get_dev_stats *sa;
4407c11d2c23SStefan Behrens 	int ret;
4408c11d2c23SStefan Behrens 
4409c11d2c23SStefan Behrens 	sa = memdup_user(arg, sizeof(*sa));
4410c11d2c23SStefan Behrens 	if (IS_ERR(sa))
4411c11d2c23SStefan Behrens 		return PTR_ERR(sa);
4412c11d2c23SStefan Behrens 
4413b27f7c0cSDavid Sterba 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4414b27f7c0cSDavid Sterba 		kfree(sa);
4415b27f7c0cSDavid Sterba 		return -EPERM;
4416b27f7c0cSDavid Sterba 	}
4417b27f7c0cSDavid Sterba 
44182ff7e61eSJeff Mahoney 	ret = btrfs_get_dev_stats(fs_info, sa);
4419c11d2c23SStefan Behrens 
4420eee99577SFilipe Manana 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4421c11d2c23SStefan Behrens 		ret = -EFAULT;
4422c11d2c23SStefan Behrens 
4423c11d2c23SStefan Behrens 	kfree(sa);
4424c11d2c23SStefan Behrens 	return ret;
4425c11d2c23SStefan Behrens }
4426c11d2c23SStefan Behrens 
44272ff7e61eSJeff Mahoney static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
44282ff7e61eSJeff Mahoney 				    void __user *arg)
44293f6bcfbdSStefan Behrens {
44303f6bcfbdSStefan Behrens 	struct btrfs_ioctl_dev_replace_args *p;
44313f6bcfbdSStefan Behrens 	int ret;
44323f6bcfbdSStefan Behrens 
44333f6bcfbdSStefan Behrens 	if (!capable(CAP_SYS_ADMIN))
44343f6bcfbdSStefan Behrens 		return -EPERM;
44353f6bcfbdSStefan Behrens 
44363f6bcfbdSStefan Behrens 	p = memdup_user(arg, sizeof(*p));
44373f6bcfbdSStefan Behrens 	if (IS_ERR(p))
44383f6bcfbdSStefan Behrens 		return PTR_ERR(p);
44393f6bcfbdSStefan Behrens 
44403f6bcfbdSStefan Behrens 	switch (p->cmd) {
44413f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4442bc98a42cSDavid Howells 		if (sb_rdonly(fs_info->sb)) {
4443adfa97cbSIlya Dryomov 			ret = -EROFS;
4444adfa97cbSIlya Dryomov 			goto out;
4445adfa97cbSIlya Dryomov 		}
4446171938e5SDavid Sterba 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4447e57138b3SAnand Jain 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
44483f6bcfbdSStefan Behrens 		} else {
44492ff7e61eSJeff Mahoney 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4450171938e5SDavid Sterba 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
44513f6bcfbdSStefan Behrens 		}
44523f6bcfbdSStefan Behrens 		break;
44533f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
44540b246afaSJeff Mahoney 		btrfs_dev_replace_status(fs_info, p);
44553f6bcfbdSStefan Behrens 		ret = 0;
44563f6bcfbdSStefan Behrens 		break;
44573f6bcfbdSStefan Behrens 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
445817d202b9SAnand Jain 		p->result = btrfs_dev_replace_cancel(fs_info);
445997282031SAnand Jain 		ret = 0;
44603f6bcfbdSStefan Behrens 		break;
44613f6bcfbdSStefan Behrens 	default:
44623f6bcfbdSStefan Behrens 		ret = -EINVAL;
44633f6bcfbdSStefan Behrens 		break;
44643f6bcfbdSStefan Behrens 	}
44653f6bcfbdSStefan Behrens 
4466d3a53286SFilipe Manana 	if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
44673f6bcfbdSStefan Behrens 		ret = -EFAULT;
4468adfa97cbSIlya Dryomov out:
44693f6bcfbdSStefan Behrens 	kfree(p);
44703f6bcfbdSStefan Behrens 	return ret;
44713f6bcfbdSStefan Behrens }
44723f6bcfbdSStefan Behrens 
4473d7728c96SJan Schmidt static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4474d7728c96SJan Schmidt {
4475d7728c96SJan Schmidt 	int ret = 0;
4476d7728c96SJan Schmidt 	int i;
4477740c3d22SChris Mason 	u64 rel_ptr;
4478d7728c96SJan Schmidt 	int size;
4479806468f8SChris Mason 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4480d7728c96SJan Schmidt 	struct inode_fs_paths *ipath = NULL;
4481d7728c96SJan Schmidt 	struct btrfs_path *path;
4482d7728c96SJan Schmidt 
448382b22ac8SKusanagi Kouichi 	if (!capable(CAP_DAC_READ_SEARCH))
4484d7728c96SJan Schmidt 		return -EPERM;
4485d7728c96SJan Schmidt 
4486d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4487d7728c96SJan Schmidt 	if (!path) {
4488d7728c96SJan Schmidt 		ret = -ENOMEM;
4489d7728c96SJan Schmidt 		goto out;
4490d7728c96SJan Schmidt 	}
4491d7728c96SJan Schmidt 
4492d7728c96SJan Schmidt 	ipa = memdup_user(arg, sizeof(*ipa));
4493d7728c96SJan Schmidt 	if (IS_ERR(ipa)) {
4494d7728c96SJan Schmidt 		ret = PTR_ERR(ipa);
4495d7728c96SJan Schmidt 		ipa = NULL;
4496d7728c96SJan Schmidt 		goto out;
4497d7728c96SJan Schmidt 	}
4498d7728c96SJan Schmidt 
4499d7728c96SJan Schmidt 	size = min_t(u32, ipa->size, 4096);
4500d7728c96SJan Schmidt 	ipath = init_ipath(size, root, path);
4501d7728c96SJan Schmidt 	if (IS_ERR(ipath)) {
4502d7728c96SJan Schmidt 		ret = PTR_ERR(ipath);
4503d7728c96SJan Schmidt 		ipath = NULL;
4504d7728c96SJan Schmidt 		goto out;
4505d7728c96SJan Schmidt 	}
4506d7728c96SJan Schmidt 
4507d7728c96SJan Schmidt 	ret = paths_from_inode(ipa->inum, ipath);
4508d7728c96SJan Schmidt 	if (ret < 0)
4509d7728c96SJan Schmidt 		goto out;
4510d7728c96SJan Schmidt 
4511d7728c96SJan Schmidt 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4512745c4d8eSJeff Mahoney 		rel_ptr = ipath->fspath->val[i] -
4513745c4d8eSJeff Mahoney 			  (u64)(unsigned long)ipath->fspath->val;
4514740c3d22SChris Mason 		ipath->fspath->val[i] = rel_ptr;
4515d7728c96SJan Schmidt 	}
4516d7728c96SJan Schmidt 
4517718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4518718dc5faSOmar Sandoval 			   ipath->fspath, size);
4519d7728c96SJan Schmidt 	if (ret) {
4520d7728c96SJan Schmidt 		ret = -EFAULT;
4521d7728c96SJan Schmidt 		goto out;
4522d7728c96SJan Schmidt 	}
4523d7728c96SJan Schmidt 
4524d7728c96SJan Schmidt out:
4525d7728c96SJan Schmidt 	btrfs_free_path(path);
4526d7728c96SJan Schmidt 	free_ipath(ipath);
4527d7728c96SJan Schmidt 	kfree(ipa);
4528d7728c96SJan Schmidt 
4529d7728c96SJan Schmidt 	return ret;
4530d7728c96SJan Schmidt }
4531d7728c96SJan Schmidt 
4532d7728c96SJan Schmidt static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4533d7728c96SJan Schmidt {
4534d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = ctx;
4535d7728c96SJan Schmidt 	const size_t c = 3 * sizeof(u64);
4536d7728c96SJan Schmidt 
4537d7728c96SJan Schmidt 	if (inodes->bytes_left >= c) {
4538d7728c96SJan Schmidt 		inodes->bytes_left -= c;
4539d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt] = inum;
4540d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 1] = offset;
4541d7728c96SJan Schmidt 		inodes->val[inodes->elem_cnt + 2] = root;
4542d7728c96SJan Schmidt 		inodes->elem_cnt += 3;
4543d7728c96SJan Schmidt 	} else {
4544d7728c96SJan Schmidt 		inodes->bytes_missing += c - inodes->bytes_left;
4545d7728c96SJan Schmidt 		inodes->bytes_left = 0;
4546d7728c96SJan Schmidt 		inodes->elem_missed += 3;
4547d7728c96SJan Schmidt 	}
4548d7728c96SJan Schmidt 
4549d7728c96SJan Schmidt 	return 0;
4550d7728c96SJan Schmidt }
4551d7728c96SJan Schmidt 
45522ff7e61eSJeff Mahoney static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4553d24a67b2SZygo Blaxell 					void __user *arg, int version)
4554d7728c96SJan Schmidt {
4555d7728c96SJan Schmidt 	int ret = 0;
4556d7728c96SJan Schmidt 	int size;
4557d7728c96SJan Schmidt 	struct btrfs_ioctl_logical_ino_args *loi;
4558d7728c96SJan Schmidt 	struct btrfs_data_container *inodes = NULL;
4559d7728c96SJan Schmidt 	struct btrfs_path *path = NULL;
4560d24a67b2SZygo Blaxell 	bool ignore_offset;
4561d7728c96SJan Schmidt 
4562d7728c96SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
4563d7728c96SJan Schmidt 		return -EPERM;
4564d7728c96SJan Schmidt 
4565d7728c96SJan Schmidt 	loi = memdup_user(arg, sizeof(*loi));
45667b9ea627SShailendra Verma 	if (IS_ERR(loi))
45677b9ea627SShailendra Verma 		return PTR_ERR(loi);
4568d7728c96SJan Schmidt 
4569d24a67b2SZygo Blaxell 	if (version == 1) {
4570d24a67b2SZygo Blaxell 		ignore_offset = false;
4571b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_64K);
4572d24a67b2SZygo Blaxell 	} else {
4573d24a67b2SZygo Blaxell 		/* All reserved bits must be 0 for now */
4574d24a67b2SZygo Blaxell 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4575d24a67b2SZygo Blaxell 			ret = -EINVAL;
4576d24a67b2SZygo Blaxell 			goto out_loi;
4577d24a67b2SZygo Blaxell 		}
4578d24a67b2SZygo Blaxell 		/* Only accept flags we have defined so far */
4579d24a67b2SZygo Blaxell 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4580d24a67b2SZygo Blaxell 			ret = -EINVAL;
4581d24a67b2SZygo Blaxell 			goto out_loi;
4582d24a67b2SZygo Blaxell 		}
4583d24a67b2SZygo Blaxell 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4584b115e3bcSZygo Blaxell 		size = min_t(u32, loi->size, SZ_16M);
4585d24a67b2SZygo Blaxell 	}
4586d24a67b2SZygo Blaxell 
4587d7728c96SJan Schmidt 	path = btrfs_alloc_path();
4588d7728c96SJan Schmidt 	if (!path) {
4589d7728c96SJan Schmidt 		ret = -ENOMEM;
4590d7728c96SJan Schmidt 		goto out;
4591d7728c96SJan Schmidt 	}
4592d7728c96SJan Schmidt 
4593d7728c96SJan Schmidt 	inodes = init_data_container(size);
4594d7728c96SJan Schmidt 	if (IS_ERR(inodes)) {
4595d7728c96SJan Schmidt 		ret = PTR_ERR(inodes);
4596d7728c96SJan Schmidt 		inodes = NULL;
4597d7728c96SJan Schmidt 		goto out;
4598d7728c96SJan Schmidt 	}
4599d7728c96SJan Schmidt 
46002ff7e61eSJeff Mahoney 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4601d24a67b2SZygo Blaxell 					  build_ino_list, inodes, ignore_offset);
4602df031f07SLiu Bo 	if (ret == -EINVAL)
4603d7728c96SJan Schmidt 		ret = -ENOENT;
4604d7728c96SJan Schmidt 	if (ret < 0)
4605d7728c96SJan Schmidt 		goto out;
4606d7728c96SJan Schmidt 
4607718dc5faSOmar Sandoval 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4608718dc5faSOmar Sandoval 			   size);
4609d7728c96SJan Schmidt 	if (ret)
4610d7728c96SJan Schmidt 		ret = -EFAULT;
4611d7728c96SJan Schmidt 
4612d7728c96SJan Schmidt out:
4613d7728c96SJan Schmidt 	btrfs_free_path(path);
4614f54de068SDavid Sterba 	kvfree(inodes);
4615d24a67b2SZygo Blaxell out_loi:
4616d7728c96SJan Schmidt 	kfree(loi);
4617d7728c96SJan Schmidt 
4618d7728c96SJan Schmidt 	return ret;
4619d7728c96SJan Schmidt }
4620d7728c96SJan Schmidt 
4621008ef096SDavid Sterba void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4622c9e9f97bSIlya Dryomov 			       struct btrfs_ioctl_balance_args *bargs)
4623c9e9f97bSIlya Dryomov {
4624c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4625c9e9f97bSIlya Dryomov 
4626c9e9f97bSIlya Dryomov 	bargs->flags = bctl->flags;
4627c9e9f97bSIlya Dryomov 
46283009a62fSDavid Sterba 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4629837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4630837d5b6eSIlya Dryomov 	if (atomic_read(&fs_info->balance_pause_req))
4631837d5b6eSIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4632a7e99c69SIlya Dryomov 	if (atomic_read(&fs_info->balance_cancel_req))
4633a7e99c69SIlya Dryomov 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4634837d5b6eSIlya Dryomov 
4635c9e9f97bSIlya Dryomov 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4636c9e9f97bSIlya Dryomov 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4637c9e9f97bSIlya Dryomov 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
463819a39dceSIlya Dryomov 
463919a39dceSIlya Dryomov 	spin_lock(&fs_info->balance_lock);
464019a39dceSIlya Dryomov 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
464119a39dceSIlya Dryomov 	spin_unlock(&fs_info->balance_lock);
4642c9e9f97bSIlya Dryomov }
4643c9e9f97bSIlya Dryomov 
46449ba1f6e4SLiu Bo static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4645c9e9f97bSIlya Dryomov {
4646496ad9aaSAl Viro 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4647c9e9f97bSIlya Dryomov 	struct btrfs_fs_info *fs_info = root->fs_info;
4648c9e9f97bSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
4649c9e9f97bSIlya Dryomov 	struct btrfs_balance_control *bctl;
4650ed0fb78fSIlya Dryomov 	bool need_unlock; /* for mut. excl. ops lock */
4651c9e9f97bSIlya Dryomov 	int ret;
4652c9e9f97bSIlya Dryomov 
4653c9e9f97bSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4654c9e9f97bSIlya Dryomov 		return -EPERM;
4655c9e9f97bSIlya Dryomov 
4656e54bfa31SLiu Bo 	ret = mnt_want_write_file(file);
46579ba1f6e4SLiu Bo 	if (ret)
46589ba1f6e4SLiu Bo 		return ret;
46599ba1f6e4SLiu Bo 
4660ed0fb78fSIlya Dryomov again:
4661171938e5SDavid Sterba 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4662c9e9f97bSIlya Dryomov 		mutex_lock(&fs_info->balance_mutex);
4663ed0fb78fSIlya Dryomov 		need_unlock = true;
4664ed0fb78fSIlya Dryomov 		goto locked;
4665ed0fb78fSIlya Dryomov 	}
4666ed0fb78fSIlya Dryomov 
4667ed0fb78fSIlya Dryomov 	/*
466801327610SNicholas D Steeves 	 * mut. excl. ops lock is locked.  Three possibilities:
4669ed0fb78fSIlya Dryomov 	 *   (1) some other op is running
4670ed0fb78fSIlya Dryomov 	 *   (2) balance is running
4671ed0fb78fSIlya Dryomov 	 *   (3) balance is paused -- special case (think resume)
4672ed0fb78fSIlya Dryomov 	 */
4673ed0fb78fSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
4674ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4675ed0fb78fSIlya Dryomov 		/* this is either (2) or (3) */
46763009a62fSDavid Sterba 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4677ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4678dccdb07bSDavid Sterba 			/*
4679dccdb07bSDavid Sterba 			 * Lock released to allow other waiters to continue,
4680dccdb07bSDavid Sterba 			 * we'll reexamine the status again.
4681dccdb07bSDavid Sterba 			 */
4682ed0fb78fSIlya Dryomov 			mutex_lock(&fs_info->balance_mutex);
4683ed0fb78fSIlya Dryomov 
4684ed0fb78fSIlya Dryomov 			if (fs_info->balance_ctl &&
46853009a62fSDavid Sterba 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4686ed0fb78fSIlya Dryomov 				/* this is (3) */
4687ed0fb78fSIlya Dryomov 				need_unlock = false;
4688ed0fb78fSIlya Dryomov 				goto locked;
4689ed0fb78fSIlya Dryomov 			}
4690ed0fb78fSIlya Dryomov 
4691ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4692ed0fb78fSIlya Dryomov 			goto again;
4693ed0fb78fSIlya Dryomov 		} else {
4694ed0fb78fSIlya Dryomov 			/* this is (2) */
4695ed0fb78fSIlya Dryomov 			mutex_unlock(&fs_info->balance_mutex);
4696ed0fb78fSIlya Dryomov 			ret = -EINPROGRESS;
4697ed0fb78fSIlya Dryomov 			goto out;
4698ed0fb78fSIlya Dryomov 		}
4699ed0fb78fSIlya Dryomov 	} else {
4700ed0fb78fSIlya Dryomov 		/* this is (1) */
4701ed0fb78fSIlya Dryomov 		mutex_unlock(&fs_info->balance_mutex);
4702e57138b3SAnand Jain 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4703ed0fb78fSIlya Dryomov 		goto out;
4704ed0fb78fSIlya Dryomov 	}
4705ed0fb78fSIlya Dryomov 
4706ed0fb78fSIlya Dryomov locked:
4707171938e5SDavid Sterba 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4708c9e9f97bSIlya Dryomov 
4709c9e9f97bSIlya Dryomov 	if (arg) {
4710c9e9f97bSIlya Dryomov 		bargs = memdup_user(arg, sizeof(*bargs));
4711c9e9f97bSIlya Dryomov 		if (IS_ERR(bargs)) {
4712c9e9f97bSIlya Dryomov 			ret = PTR_ERR(bargs);
4713ed0fb78fSIlya Dryomov 			goto out_unlock;
4714c9e9f97bSIlya Dryomov 		}
4715de322263SIlya Dryomov 
4716de322263SIlya Dryomov 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4717de322263SIlya Dryomov 			if (!fs_info->balance_ctl) {
4718de322263SIlya Dryomov 				ret = -ENOTCONN;
4719de322263SIlya Dryomov 				goto out_bargs;
4720de322263SIlya Dryomov 			}
4721de322263SIlya Dryomov 
4722de322263SIlya Dryomov 			bctl = fs_info->balance_ctl;
4723de322263SIlya Dryomov 			spin_lock(&fs_info->balance_lock);
4724de322263SIlya Dryomov 			bctl->flags |= BTRFS_BALANCE_RESUME;
4725de322263SIlya Dryomov 			spin_unlock(&fs_info->balance_lock);
4726de322263SIlya Dryomov 
4727de322263SIlya Dryomov 			goto do_balance;
4728de322263SIlya Dryomov 		}
4729c9e9f97bSIlya Dryomov 	} else {
4730c9e9f97bSIlya Dryomov 		bargs = NULL;
4731c9e9f97bSIlya Dryomov 	}
4732c9e9f97bSIlya Dryomov 
4733ed0fb78fSIlya Dryomov 	if (fs_info->balance_ctl) {
4734837d5b6eSIlya Dryomov 		ret = -EINPROGRESS;
4735837d5b6eSIlya Dryomov 		goto out_bargs;
4736837d5b6eSIlya Dryomov 	}
4737837d5b6eSIlya Dryomov 
47388d2db785SDavid Sterba 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4739c9e9f97bSIlya Dryomov 	if (!bctl) {
4740c9e9f97bSIlya Dryomov 		ret = -ENOMEM;
4741c9e9f97bSIlya Dryomov 		goto out_bargs;
4742c9e9f97bSIlya Dryomov 	}
4743c9e9f97bSIlya Dryomov 
4744c9e9f97bSIlya Dryomov 	if (arg) {
4745c9e9f97bSIlya Dryomov 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4746c9e9f97bSIlya Dryomov 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4747c9e9f97bSIlya Dryomov 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4748c9e9f97bSIlya Dryomov 
4749c9e9f97bSIlya Dryomov 		bctl->flags = bargs->flags;
4750f43ffb60SIlya Dryomov 	} else {
4751f43ffb60SIlya Dryomov 		/* balance everything - no filters */
4752f43ffb60SIlya Dryomov 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4753c9e9f97bSIlya Dryomov 	}
4754c9e9f97bSIlya Dryomov 
47558eb93459SDavid Sterba 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
47568eb93459SDavid Sterba 		ret = -EINVAL;
47570f89abf5SChristian Engelmayer 		goto out_bctl;
47588eb93459SDavid Sterba 	}
47598eb93459SDavid Sterba 
4760de322263SIlya Dryomov do_balance:
4761c9e9f97bSIlya Dryomov 	/*
4762149196a2SDavid Sterba 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
4763149196a2SDavid Sterba 	 * btrfs_balance.  bctl is freed in reset_balance_state, or, if
4764149196a2SDavid Sterba 	 * restriper was paused all the way until unmount, in free_fs_info.
4765149196a2SDavid Sterba 	 * The flag should be cleared after reset_balance_state.
4766c9e9f97bSIlya Dryomov 	 */
4767ed0fb78fSIlya Dryomov 	need_unlock = false;
4768ed0fb78fSIlya Dryomov 
47696fcf6e2bSDavid Sterba 	ret = btrfs_balance(fs_info, bctl, bargs);
47700f89abf5SChristian Engelmayer 	bctl = NULL;
4771ed0fb78fSIlya Dryomov 
4772d00c2d9cSFilipe Manana 	if ((ret == 0 || ret == -ECANCELED) && arg) {
4773c9e9f97bSIlya Dryomov 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4774c9e9f97bSIlya Dryomov 			ret = -EFAULT;
4775c9e9f97bSIlya Dryomov 	}
4776c9e9f97bSIlya Dryomov 
47770f89abf5SChristian Engelmayer out_bctl:
47780f89abf5SChristian Engelmayer 	kfree(bctl);
4779c9e9f97bSIlya Dryomov out_bargs:
4780c9e9f97bSIlya Dryomov 	kfree(bargs);
4781ed0fb78fSIlya Dryomov out_unlock:
4782c9e9f97bSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
4783ed0fb78fSIlya Dryomov 	if (need_unlock)
4784171938e5SDavid Sterba 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4785ed0fb78fSIlya Dryomov out:
4786e54bfa31SLiu Bo 	mnt_drop_write_file(file);
4787c9e9f97bSIlya Dryomov 	return ret;
4788c9e9f97bSIlya Dryomov }
4789c9e9f97bSIlya Dryomov 
47902ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4791837d5b6eSIlya Dryomov {
4792837d5b6eSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
4793837d5b6eSIlya Dryomov 		return -EPERM;
4794837d5b6eSIlya Dryomov 
4795837d5b6eSIlya Dryomov 	switch (cmd) {
4796837d5b6eSIlya Dryomov 	case BTRFS_BALANCE_CTL_PAUSE:
47970b246afaSJeff Mahoney 		return btrfs_pause_balance(fs_info);
4798a7e99c69SIlya Dryomov 	case BTRFS_BALANCE_CTL_CANCEL:
47990b246afaSJeff Mahoney 		return btrfs_cancel_balance(fs_info);
4800837d5b6eSIlya Dryomov 	}
4801837d5b6eSIlya Dryomov 
4802837d5b6eSIlya Dryomov 	return -EINVAL;
4803837d5b6eSIlya Dryomov }
4804837d5b6eSIlya Dryomov 
48052ff7e61eSJeff Mahoney static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
480619a39dceSIlya Dryomov 					 void __user *arg)
480719a39dceSIlya Dryomov {
480819a39dceSIlya Dryomov 	struct btrfs_ioctl_balance_args *bargs;
480919a39dceSIlya Dryomov 	int ret = 0;
481019a39dceSIlya Dryomov 
481119a39dceSIlya Dryomov 	if (!capable(CAP_SYS_ADMIN))
481219a39dceSIlya Dryomov 		return -EPERM;
481319a39dceSIlya Dryomov 
481419a39dceSIlya Dryomov 	mutex_lock(&fs_info->balance_mutex);
481519a39dceSIlya Dryomov 	if (!fs_info->balance_ctl) {
481619a39dceSIlya Dryomov 		ret = -ENOTCONN;
481719a39dceSIlya Dryomov 		goto out;
481819a39dceSIlya Dryomov 	}
481919a39dceSIlya Dryomov 
48208d2db785SDavid Sterba 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
482119a39dceSIlya Dryomov 	if (!bargs) {
482219a39dceSIlya Dryomov 		ret = -ENOMEM;
482319a39dceSIlya Dryomov 		goto out;
482419a39dceSIlya Dryomov 	}
482519a39dceSIlya Dryomov 
4826008ef096SDavid Sterba 	btrfs_update_ioctl_balance_args(fs_info, bargs);
482719a39dceSIlya Dryomov 
482819a39dceSIlya Dryomov 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
482919a39dceSIlya Dryomov 		ret = -EFAULT;
483019a39dceSIlya Dryomov 
483119a39dceSIlya Dryomov 	kfree(bargs);
483219a39dceSIlya Dryomov out:
483319a39dceSIlya Dryomov 	mutex_unlock(&fs_info->balance_mutex);
483419a39dceSIlya Dryomov 	return ret;
483519a39dceSIlya Dryomov }
483619a39dceSIlya Dryomov 
4837905b0ddaSMiao Xie static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
48385d13a37bSArne Jansen {
48390b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48400b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48415d13a37bSArne Jansen 	struct btrfs_ioctl_quota_ctl_args *sa;
48425d13a37bSArne Jansen 	int ret;
48435d13a37bSArne Jansen 
48445d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48455d13a37bSArne Jansen 		return -EPERM;
48465d13a37bSArne Jansen 
4847905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4848905b0ddaSMiao Xie 	if (ret)
4849905b0ddaSMiao Xie 		return ret;
48505d13a37bSArne Jansen 
48515d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4852905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4853905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4854905b0ddaSMiao Xie 		goto drop_write;
4855905b0ddaSMiao Xie 	}
48565d13a37bSArne Jansen 
48570b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
48585d13a37bSArne Jansen 
48595d13a37bSArne Jansen 	switch (sa->cmd) {
48605d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_ENABLE:
4861340f1aa2SNikolay Borisov 		ret = btrfs_quota_enable(fs_info);
48625d13a37bSArne Jansen 		break;
48635d13a37bSArne Jansen 	case BTRFS_QUOTA_CTL_DISABLE:
4864340f1aa2SNikolay Borisov 		ret = btrfs_quota_disable(fs_info);
48655d13a37bSArne Jansen 		break;
48665d13a37bSArne Jansen 	default:
48675d13a37bSArne Jansen 		ret = -EINVAL;
48685d13a37bSArne Jansen 		break;
48695d13a37bSArne Jansen 	}
48705d13a37bSArne Jansen 
48715d13a37bSArne Jansen 	kfree(sa);
48720b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
4873905b0ddaSMiao Xie drop_write:
4874905b0ddaSMiao Xie 	mnt_drop_write_file(file);
48755d13a37bSArne Jansen 	return ret;
48765d13a37bSArne Jansen }
48775d13a37bSArne Jansen 
4878905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
48795d13a37bSArne Jansen {
48800b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
48810b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
48820b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
48835d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_assign_args *sa;
48845d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
48855d13a37bSArne Jansen 	int ret;
48865d13a37bSArne Jansen 	int err;
48875d13a37bSArne Jansen 
48885d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
48895d13a37bSArne Jansen 		return -EPERM;
48905d13a37bSArne Jansen 
4891905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4892905b0ddaSMiao Xie 	if (ret)
4893905b0ddaSMiao Xie 		return ret;
48945d13a37bSArne Jansen 
48955d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4896905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4897905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4898905b0ddaSMiao Xie 		goto drop_write;
4899905b0ddaSMiao Xie 	}
49005d13a37bSArne Jansen 
49015d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
49025d13a37bSArne Jansen 	if (IS_ERR(trans)) {
49035d13a37bSArne Jansen 		ret = PTR_ERR(trans);
49045d13a37bSArne Jansen 		goto out;
49055d13a37bSArne Jansen 	}
49065d13a37bSArne Jansen 
49075d13a37bSArne Jansen 	if (sa->assign) {
49089f8a6ce6SLu Fengqi 		ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
49095d13a37bSArne Jansen 	} else {
491039616c27SLu Fengqi 		ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
49115d13a37bSArne Jansen 	}
49125d13a37bSArne Jansen 
4913e082f563SQu Wenruo 	/* update qgroup status and info */
4914280f8bd2SLu Fengqi 	err = btrfs_run_qgroups(trans);
4915e082f563SQu Wenruo 	if (err < 0)
49160b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, err,
4917ad8403dfSAnand Jain 				      "failed to update qgroup status and info");
49183a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
49195d13a37bSArne Jansen 	if (err && !ret)
49205d13a37bSArne Jansen 		ret = err;
49215d13a37bSArne Jansen 
49225d13a37bSArne Jansen out:
49235d13a37bSArne Jansen 	kfree(sa);
4924905b0ddaSMiao Xie drop_write:
4925905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49265d13a37bSArne Jansen 	return ret;
49275d13a37bSArne Jansen }
49285d13a37bSArne Jansen 
4929905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
49305d13a37bSArne Jansen {
49310b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49320b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
49335d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_create_args *sa;
49345d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
49355d13a37bSArne Jansen 	int ret;
49365d13a37bSArne Jansen 	int err;
49375d13a37bSArne Jansen 
49385d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
49395d13a37bSArne Jansen 		return -EPERM;
49405d13a37bSArne Jansen 
4941905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4942905b0ddaSMiao Xie 	if (ret)
4943905b0ddaSMiao Xie 		return ret;
49445d13a37bSArne Jansen 
49455d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4946905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4947905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4948905b0ddaSMiao Xie 		goto drop_write;
4949905b0ddaSMiao Xie 	}
49505d13a37bSArne Jansen 
4951d86e56cfSMiao Xie 	if (!sa->qgroupid) {
4952d86e56cfSMiao Xie 		ret = -EINVAL;
4953d86e56cfSMiao Xie 		goto out;
4954d86e56cfSMiao Xie 	}
4955d86e56cfSMiao Xie 
49565d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
49575d13a37bSArne Jansen 	if (IS_ERR(trans)) {
49585d13a37bSArne Jansen 		ret = PTR_ERR(trans);
49595d13a37bSArne Jansen 		goto out;
49605d13a37bSArne Jansen 	}
49615d13a37bSArne Jansen 
49625d13a37bSArne Jansen 	if (sa->create) {
496349a05ecdSLu Fengqi 		ret = btrfs_create_qgroup(trans, sa->qgroupid);
49645d13a37bSArne Jansen 	} else {
49653efbee1dSLu Fengqi 		ret = btrfs_remove_qgroup(trans, sa->qgroupid);
49665d13a37bSArne Jansen 	}
49675d13a37bSArne Jansen 
49683a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
49695d13a37bSArne Jansen 	if (err && !ret)
49705d13a37bSArne Jansen 		ret = err;
49715d13a37bSArne Jansen 
49725d13a37bSArne Jansen out:
49735d13a37bSArne Jansen 	kfree(sa);
4974905b0ddaSMiao Xie drop_write:
4975905b0ddaSMiao Xie 	mnt_drop_write_file(file);
49765d13a37bSArne Jansen 	return ret;
49775d13a37bSArne Jansen }
49785d13a37bSArne Jansen 
4979905b0ddaSMiao Xie static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
49805d13a37bSArne Jansen {
49810b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
49820b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
49835d13a37bSArne Jansen 	struct btrfs_ioctl_qgroup_limit_args *sa;
49845d13a37bSArne Jansen 	struct btrfs_trans_handle *trans;
49855d13a37bSArne Jansen 	int ret;
49865d13a37bSArne Jansen 	int err;
49875d13a37bSArne Jansen 	u64 qgroupid;
49885d13a37bSArne Jansen 
49895d13a37bSArne Jansen 	if (!capable(CAP_SYS_ADMIN))
49905d13a37bSArne Jansen 		return -EPERM;
49915d13a37bSArne Jansen 
4992905b0ddaSMiao Xie 	ret = mnt_want_write_file(file);
4993905b0ddaSMiao Xie 	if (ret)
4994905b0ddaSMiao Xie 		return ret;
49955d13a37bSArne Jansen 
49965d13a37bSArne Jansen 	sa = memdup_user(arg, sizeof(*sa));
4997905b0ddaSMiao Xie 	if (IS_ERR(sa)) {
4998905b0ddaSMiao Xie 		ret = PTR_ERR(sa);
4999905b0ddaSMiao Xie 		goto drop_write;
5000905b0ddaSMiao Xie 	}
50015d13a37bSArne Jansen 
50025d13a37bSArne Jansen 	trans = btrfs_join_transaction(root);
50035d13a37bSArne Jansen 	if (IS_ERR(trans)) {
50045d13a37bSArne Jansen 		ret = PTR_ERR(trans);
50055d13a37bSArne Jansen 		goto out;
50065d13a37bSArne Jansen 	}
50075d13a37bSArne Jansen 
50085d13a37bSArne Jansen 	qgroupid = sa->qgroupid;
50095d13a37bSArne Jansen 	if (!qgroupid) {
50105d13a37bSArne Jansen 		/* take the current subvol as qgroup */
50115d13a37bSArne Jansen 		qgroupid = root->root_key.objectid;
50125d13a37bSArne Jansen 	}
50135d13a37bSArne Jansen 
5014f0042d5eSLu Fengqi 	ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
50155d13a37bSArne Jansen 
50163a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
50175d13a37bSArne Jansen 	if (err && !ret)
50185d13a37bSArne Jansen 		ret = err;
50195d13a37bSArne Jansen 
50205d13a37bSArne Jansen out:
50215d13a37bSArne Jansen 	kfree(sa);
5022905b0ddaSMiao Xie drop_write:
5023905b0ddaSMiao Xie 	mnt_drop_write_file(file);
50245d13a37bSArne Jansen 	return ret;
50255d13a37bSArne Jansen }
50265d13a37bSArne Jansen 
50272f232036SJan Schmidt static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
50282f232036SJan Schmidt {
50290b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50312f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
50322f232036SJan Schmidt 	int ret;
50332f232036SJan Schmidt 
50342f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
50352f232036SJan Schmidt 		return -EPERM;
50362f232036SJan Schmidt 
50372f232036SJan Schmidt 	ret = mnt_want_write_file(file);
50382f232036SJan Schmidt 	if (ret)
50392f232036SJan Schmidt 		return ret;
50402f232036SJan Schmidt 
50412f232036SJan Schmidt 	qsa = memdup_user(arg, sizeof(*qsa));
50422f232036SJan Schmidt 	if (IS_ERR(qsa)) {
50432f232036SJan Schmidt 		ret = PTR_ERR(qsa);
50442f232036SJan Schmidt 		goto drop_write;
50452f232036SJan Schmidt 	}
50462f232036SJan Schmidt 
50472f232036SJan Schmidt 	if (qsa->flags) {
50482f232036SJan Schmidt 		ret = -EINVAL;
50492f232036SJan Schmidt 		goto out;
50502f232036SJan Schmidt 	}
50512f232036SJan Schmidt 
50520b246afaSJeff Mahoney 	ret = btrfs_qgroup_rescan(fs_info);
50532f232036SJan Schmidt 
50542f232036SJan Schmidt out:
50552f232036SJan Schmidt 	kfree(qsa);
50562f232036SJan Schmidt drop_write:
50572f232036SJan Schmidt 	mnt_drop_write_file(file);
50582f232036SJan Schmidt 	return ret;
50592f232036SJan Schmidt }
50602f232036SJan Schmidt 
50612f232036SJan Schmidt static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
50622f232036SJan Schmidt {
50630b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50652f232036SJan Schmidt 	struct btrfs_ioctl_quota_rescan_args *qsa;
50662f232036SJan Schmidt 	int ret = 0;
50672f232036SJan Schmidt 
50682f232036SJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
50692f232036SJan Schmidt 		return -EPERM;
50702f232036SJan Schmidt 
50718d2db785SDavid Sterba 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
50722f232036SJan Schmidt 	if (!qsa)
50732f232036SJan Schmidt 		return -ENOMEM;
50742f232036SJan Schmidt 
50750b246afaSJeff Mahoney 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
50762f232036SJan Schmidt 		qsa->flags = 1;
50770b246afaSJeff Mahoney 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
50782f232036SJan Schmidt 	}
50792f232036SJan Schmidt 
50802f232036SJan Schmidt 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
50812f232036SJan Schmidt 		ret = -EFAULT;
50822f232036SJan Schmidt 
50832f232036SJan Schmidt 	kfree(qsa);
50842f232036SJan Schmidt 	return ret;
50852f232036SJan Schmidt }
50862f232036SJan Schmidt 
508757254b6eSJan Schmidt static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
508857254b6eSJan Schmidt {
50890b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
50900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
509157254b6eSJan Schmidt 
509257254b6eSJan Schmidt 	if (!capable(CAP_SYS_ADMIN))
509357254b6eSJan Schmidt 		return -EPERM;
509457254b6eSJan Schmidt 
50950b246afaSJeff Mahoney 	return btrfs_qgroup_wait_for_completion(fs_info, true);
509657254b6eSJan Schmidt }
509757254b6eSJan Schmidt 
5098abccd00fSHugo Mills static long _btrfs_ioctl_set_received_subvol(struct file *file,
5099abccd00fSHugo Mills 					    struct btrfs_ioctl_received_subvol_args *sa)
51008ea05e3aSAlexander Block {
5101496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
51020b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
51038ea05e3aSAlexander Block 	struct btrfs_root *root = BTRFS_I(inode)->root;
51048ea05e3aSAlexander Block 	struct btrfs_root_item *root_item = &root->root_item;
51058ea05e3aSAlexander Block 	struct btrfs_trans_handle *trans;
510695582b00SDeepa Dinamani 	struct timespec64 ct = current_time(inode);
51078ea05e3aSAlexander Block 	int ret = 0;
5108dd5f9615SStefan Behrens 	int received_uuid_changed;
51098ea05e3aSAlexander Block 
5110bd60ea0fSDavid Sterba 	if (!inode_owner_or_capable(inode))
5111bd60ea0fSDavid Sterba 		return -EPERM;
5112bd60ea0fSDavid Sterba 
51138ea05e3aSAlexander Block 	ret = mnt_want_write_file(file);
51148ea05e3aSAlexander Block 	if (ret < 0)
51158ea05e3aSAlexander Block 		return ret;
51168ea05e3aSAlexander Block 
51170b246afaSJeff Mahoney 	down_write(&fs_info->subvol_sem);
51188ea05e3aSAlexander Block 
51194a0cc7caSNikolay Borisov 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
51208ea05e3aSAlexander Block 		ret = -EINVAL;
51218ea05e3aSAlexander Block 		goto out;
51228ea05e3aSAlexander Block 	}
51238ea05e3aSAlexander Block 
51248ea05e3aSAlexander Block 	if (btrfs_root_readonly(root)) {
51258ea05e3aSAlexander Block 		ret = -EROFS;
51268ea05e3aSAlexander Block 		goto out;
51278ea05e3aSAlexander Block 	}
51288ea05e3aSAlexander Block 
5129dd5f9615SStefan Behrens 	/*
5130dd5f9615SStefan Behrens 	 * 1 - root item
5131dd5f9615SStefan Behrens 	 * 2 - uuid items (received uuid + subvol uuid)
5132dd5f9615SStefan Behrens 	 */
5133dd5f9615SStefan Behrens 	trans = btrfs_start_transaction(root, 3);
51348ea05e3aSAlexander Block 	if (IS_ERR(trans)) {
51358ea05e3aSAlexander Block 		ret = PTR_ERR(trans);
51368ea05e3aSAlexander Block 		trans = NULL;
51378ea05e3aSAlexander Block 		goto out;
51388ea05e3aSAlexander Block 	}
51398ea05e3aSAlexander Block 
51408ea05e3aSAlexander Block 	sa->rtransid = trans->transid;
51418ea05e3aSAlexander Block 	sa->rtime.sec = ct.tv_sec;
51428ea05e3aSAlexander Block 	sa->rtime.nsec = ct.tv_nsec;
51438ea05e3aSAlexander Block 
5144dd5f9615SStefan Behrens 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5145dd5f9615SStefan Behrens 				       BTRFS_UUID_SIZE);
5146dd5f9615SStefan Behrens 	if (received_uuid_changed &&
5147d87ff758SNikolay Borisov 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
5148d1957791SLu Fengqi 		ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
5149dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5150dd5f9615SStefan Behrens 					  root->root_key.objectid);
5151d87ff758SNikolay Borisov 		if (ret && ret != -ENOENT) {
5152d87ff758SNikolay Borisov 		        btrfs_abort_transaction(trans, ret);
5153d87ff758SNikolay Borisov 		        btrfs_end_transaction(trans);
5154d87ff758SNikolay Borisov 		        goto out;
5155d87ff758SNikolay Borisov 		}
5156d87ff758SNikolay Borisov 	}
51578ea05e3aSAlexander Block 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
51588ea05e3aSAlexander Block 	btrfs_set_root_stransid(root_item, sa->stransid);
51598ea05e3aSAlexander Block 	btrfs_set_root_rtransid(root_item, sa->rtransid);
51603cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
51613cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
51623cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
51633cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
51648ea05e3aSAlexander Block 
51650b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
51668ea05e3aSAlexander Block 				&root->root_key, &root->root_item);
51678ea05e3aSAlexander Block 	if (ret < 0) {
51683a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
51698ea05e3aSAlexander Block 		goto out;
5170dd5f9615SStefan Behrens 	}
5171dd5f9615SStefan Behrens 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5172cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, sa->uuid,
5173dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5174dd5f9615SStefan Behrens 					  root->root_key.objectid);
5175dd5f9615SStefan Behrens 		if (ret < 0 && ret != -EEXIST) {
517666642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
5177efd38150SNikolay Borisov 			btrfs_end_transaction(trans);
5178dd5f9615SStefan Behrens 			goto out;
5179dd5f9615SStefan Behrens 		}
5180dd5f9615SStefan Behrens 	}
51813a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5182abccd00fSHugo Mills out:
51830b246afaSJeff Mahoney 	up_write(&fs_info->subvol_sem);
5184abccd00fSHugo Mills 	mnt_drop_write_file(file);
5185abccd00fSHugo Mills 	return ret;
5186abccd00fSHugo Mills }
5187abccd00fSHugo Mills 
5188abccd00fSHugo Mills #ifdef CONFIG_64BIT
5189abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5190abccd00fSHugo Mills 						void __user *arg)
5191abccd00fSHugo Mills {
5192abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5193abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5194abccd00fSHugo Mills 	int ret = 0;
5195abccd00fSHugo Mills 
5196abccd00fSHugo Mills 	args32 = memdup_user(arg, sizeof(*args32));
51977b9ea627SShailendra Verma 	if (IS_ERR(args32))
51987b9ea627SShailendra Verma 		return PTR_ERR(args32);
5199abccd00fSHugo Mills 
52008d2db785SDavid Sterba 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
520184dbeb87SDan Carpenter 	if (!args64) {
520284dbeb87SDan Carpenter 		ret = -ENOMEM;
5203abccd00fSHugo Mills 		goto out;
5204abccd00fSHugo Mills 	}
5205abccd00fSHugo Mills 
5206abccd00fSHugo Mills 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5207abccd00fSHugo Mills 	args64->stransid = args32->stransid;
5208abccd00fSHugo Mills 	args64->rtransid = args32->rtransid;
5209abccd00fSHugo Mills 	args64->stime.sec = args32->stime.sec;
5210abccd00fSHugo Mills 	args64->stime.nsec = args32->stime.nsec;
5211abccd00fSHugo Mills 	args64->rtime.sec = args32->rtime.sec;
5212abccd00fSHugo Mills 	args64->rtime.nsec = args32->rtime.nsec;
5213abccd00fSHugo Mills 	args64->flags = args32->flags;
5214abccd00fSHugo Mills 
5215abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5216abccd00fSHugo Mills 	if (ret)
5217abccd00fSHugo Mills 		goto out;
5218abccd00fSHugo Mills 
5219abccd00fSHugo Mills 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5220abccd00fSHugo Mills 	args32->stransid = args64->stransid;
5221abccd00fSHugo Mills 	args32->rtransid = args64->rtransid;
5222abccd00fSHugo Mills 	args32->stime.sec = args64->stime.sec;
5223abccd00fSHugo Mills 	args32->stime.nsec = args64->stime.nsec;
5224abccd00fSHugo Mills 	args32->rtime.sec = args64->rtime.sec;
5225abccd00fSHugo Mills 	args32->rtime.nsec = args64->rtime.nsec;
5226abccd00fSHugo Mills 	args32->flags = args64->flags;
5227abccd00fSHugo Mills 
5228abccd00fSHugo Mills 	ret = copy_to_user(arg, args32, sizeof(*args32));
5229abccd00fSHugo Mills 	if (ret)
5230abccd00fSHugo Mills 		ret = -EFAULT;
5231abccd00fSHugo Mills 
5232abccd00fSHugo Mills out:
5233abccd00fSHugo Mills 	kfree(args32);
5234abccd00fSHugo Mills 	kfree(args64);
5235abccd00fSHugo Mills 	return ret;
5236abccd00fSHugo Mills }
5237abccd00fSHugo Mills #endif
5238abccd00fSHugo Mills 
5239abccd00fSHugo Mills static long btrfs_ioctl_set_received_subvol(struct file *file,
5240abccd00fSHugo Mills 					    void __user *arg)
5241abccd00fSHugo Mills {
5242abccd00fSHugo Mills 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5243abccd00fSHugo Mills 	int ret = 0;
5244abccd00fSHugo Mills 
5245abccd00fSHugo Mills 	sa = memdup_user(arg, sizeof(*sa));
52467b9ea627SShailendra Verma 	if (IS_ERR(sa))
52477b9ea627SShailendra Verma 		return PTR_ERR(sa);
5248abccd00fSHugo Mills 
5249abccd00fSHugo Mills 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5250abccd00fSHugo Mills 
5251abccd00fSHugo Mills 	if (ret)
5252abccd00fSHugo Mills 		goto out;
5253abccd00fSHugo Mills 
52548ea05e3aSAlexander Block 	ret = copy_to_user(arg, sa, sizeof(*sa));
52558ea05e3aSAlexander Block 	if (ret)
52568ea05e3aSAlexander Block 		ret = -EFAULT;
52578ea05e3aSAlexander Block 
52588ea05e3aSAlexander Block out:
52598ea05e3aSAlexander Block 	kfree(sa);
52608ea05e3aSAlexander Block 	return ret;
52618ea05e3aSAlexander Block }
52628ea05e3aSAlexander Block 
5263867ab667Sjeff.liu static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5264867ab667Sjeff.liu {
52650b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5267a1b83ac5SAnand Jain 	size_t len;
5268867ab667Sjeff.liu 	int ret;
5269a1b83ac5SAnand Jain 	char label[BTRFS_LABEL_SIZE];
5270a1b83ac5SAnand Jain 
52710b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
52720b246afaSJeff Mahoney 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
52730b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
5274a1b83ac5SAnand Jain 
5275a1b83ac5SAnand Jain 	len = strnlen(label, BTRFS_LABEL_SIZE);
5276867ab667Sjeff.liu 
5277867ab667Sjeff.liu 	if (len == BTRFS_LABEL_SIZE) {
52780b246afaSJeff Mahoney 		btrfs_warn(fs_info,
52790b246afaSJeff Mahoney 			   "label is too long, return the first %zu bytes",
52800b246afaSJeff Mahoney 			   --len);
5281867ab667Sjeff.liu 	}
5282867ab667Sjeff.liu 
5283867ab667Sjeff.liu 	ret = copy_to_user(arg, label, len);
5284867ab667Sjeff.liu 
5285867ab667Sjeff.liu 	return ret ? -EFAULT : 0;
5286867ab667Sjeff.liu }
5287867ab667Sjeff.liu 
5288a8bfd4abSjeff.liu static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5289a8bfd4abSjeff.liu {
52900b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
52910b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
52920b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
52930b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
5294a8bfd4abSjeff.liu 	struct btrfs_trans_handle *trans;
5295a8bfd4abSjeff.liu 	char label[BTRFS_LABEL_SIZE];
5296a8bfd4abSjeff.liu 	int ret;
5297a8bfd4abSjeff.liu 
5298a8bfd4abSjeff.liu 	if (!capable(CAP_SYS_ADMIN))
5299a8bfd4abSjeff.liu 		return -EPERM;
5300a8bfd4abSjeff.liu 
5301a8bfd4abSjeff.liu 	if (copy_from_user(label, arg, sizeof(label)))
5302a8bfd4abSjeff.liu 		return -EFAULT;
5303a8bfd4abSjeff.liu 
5304a8bfd4abSjeff.liu 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
53050b246afaSJeff Mahoney 		btrfs_err(fs_info,
53065d163e0eSJeff Mahoney 			  "unable to set label with more than %d bytes",
5307a8bfd4abSjeff.liu 			  BTRFS_LABEL_SIZE - 1);
5308a8bfd4abSjeff.liu 		return -EINVAL;
5309a8bfd4abSjeff.liu 	}
5310a8bfd4abSjeff.liu 
5311a8bfd4abSjeff.liu 	ret = mnt_want_write_file(file);
5312a8bfd4abSjeff.liu 	if (ret)
5313a8bfd4abSjeff.liu 		return ret;
5314a8bfd4abSjeff.liu 
5315a8bfd4abSjeff.liu 	trans = btrfs_start_transaction(root, 0);
5316a8bfd4abSjeff.liu 	if (IS_ERR(trans)) {
5317a8bfd4abSjeff.liu 		ret = PTR_ERR(trans);
5318a8bfd4abSjeff.liu 		goto out_unlock;
5319a8bfd4abSjeff.liu 	}
5320a8bfd4abSjeff.liu 
53210b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
5322a8bfd4abSjeff.liu 	strcpy(super_block->label, label);
53230b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
53243a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
5325a8bfd4abSjeff.liu 
5326a8bfd4abSjeff.liu out_unlock:
5327a8bfd4abSjeff.liu 	mnt_drop_write_file(file);
5328a8bfd4abSjeff.liu 	return ret;
5329a8bfd4abSjeff.liu }
5330a8bfd4abSjeff.liu 
53312eaa055fSJeff Mahoney #define INIT_FEATURE_FLAGS(suffix) \
53322eaa055fSJeff Mahoney 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
53332eaa055fSJeff Mahoney 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
53342eaa055fSJeff Mahoney 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
53352eaa055fSJeff Mahoney 
5336d5131b65SDavid Sterba int btrfs_ioctl_get_supported_features(void __user *arg)
53372eaa055fSJeff Mahoney {
53384d4ab6d6SDavid Sterba 	static const struct btrfs_ioctl_feature_flags features[3] = {
53392eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SUPP),
53402eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_SET),
53412eaa055fSJeff Mahoney 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
53422eaa055fSJeff Mahoney 	};
53432eaa055fSJeff Mahoney 
53442eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
53452eaa055fSJeff Mahoney 		return -EFAULT;
53462eaa055fSJeff Mahoney 
53472eaa055fSJeff Mahoney 	return 0;
53482eaa055fSJeff Mahoney }
53492eaa055fSJeff Mahoney 
53502eaa055fSJeff Mahoney static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
53512eaa055fSJeff Mahoney {
53520b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
53530b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
53540b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
53552eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags features;
53562eaa055fSJeff Mahoney 
53572eaa055fSJeff Mahoney 	features.compat_flags = btrfs_super_compat_flags(super_block);
53582eaa055fSJeff Mahoney 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
53592eaa055fSJeff Mahoney 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
53602eaa055fSJeff Mahoney 
53612eaa055fSJeff Mahoney 	if (copy_to_user(arg, &features, sizeof(features)))
53622eaa055fSJeff Mahoney 		return -EFAULT;
53632eaa055fSJeff Mahoney 
53642eaa055fSJeff Mahoney 	return 0;
53652eaa055fSJeff Mahoney }
53662eaa055fSJeff Mahoney 
53672ff7e61eSJeff Mahoney static int check_feature_bits(struct btrfs_fs_info *fs_info,
53683b02a68aSJeff Mahoney 			      enum btrfs_feature_set set,
53692eaa055fSJeff Mahoney 			      u64 change_mask, u64 flags, u64 supported_flags,
53702eaa055fSJeff Mahoney 			      u64 safe_set, u64 safe_clear)
53712eaa055fSJeff Mahoney {
53723b02a68aSJeff Mahoney 	const char *type = btrfs_feature_set_names[set];
53733b02a68aSJeff Mahoney 	char *names;
53742eaa055fSJeff Mahoney 	u64 disallowed, unsupported;
53752eaa055fSJeff Mahoney 	u64 set_mask = flags & change_mask;
53762eaa055fSJeff Mahoney 	u64 clear_mask = ~flags & change_mask;
53772eaa055fSJeff Mahoney 
53782eaa055fSJeff Mahoney 	unsupported = set_mask & ~supported_flags;
53792eaa055fSJeff Mahoney 	if (unsupported) {
53803b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, unsupported);
53813b02a68aSJeff Mahoney 		if (names) {
53820b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53833b02a68aSJeff Mahoney 				   "this kernel does not support the %s feature bit%s",
53843b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
53853b02a68aSJeff Mahoney 			kfree(names);
53863b02a68aSJeff Mahoney 		} else
53870b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53882eaa055fSJeff Mahoney 				   "this kernel does not support %s bits 0x%llx",
53892eaa055fSJeff Mahoney 				   type, unsupported);
53902eaa055fSJeff Mahoney 		return -EOPNOTSUPP;
53912eaa055fSJeff Mahoney 	}
53922eaa055fSJeff Mahoney 
53932eaa055fSJeff Mahoney 	disallowed = set_mask & ~safe_set;
53942eaa055fSJeff Mahoney 	if (disallowed) {
53953b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
53963b02a68aSJeff Mahoney 		if (names) {
53970b246afaSJeff Mahoney 			btrfs_warn(fs_info,
53983b02a68aSJeff Mahoney 				   "can't set the %s feature bit%s while mounted",
53993b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
54003b02a68aSJeff Mahoney 			kfree(names);
54013b02a68aSJeff Mahoney 		} else
54020b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54032eaa055fSJeff Mahoney 				   "can't set %s bits 0x%llx while mounted",
54042eaa055fSJeff Mahoney 				   type, disallowed);
54052eaa055fSJeff Mahoney 		return -EPERM;
54062eaa055fSJeff Mahoney 	}
54072eaa055fSJeff Mahoney 
54082eaa055fSJeff Mahoney 	disallowed = clear_mask & ~safe_clear;
54092eaa055fSJeff Mahoney 	if (disallowed) {
54103b02a68aSJeff Mahoney 		names = btrfs_printable_features(set, disallowed);
54113b02a68aSJeff Mahoney 		if (names) {
54120b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54133b02a68aSJeff Mahoney 				   "can't clear the %s feature bit%s while mounted",
54143b02a68aSJeff Mahoney 				   names, strchr(names, ',') ? "s" : "");
54153b02a68aSJeff Mahoney 			kfree(names);
54163b02a68aSJeff Mahoney 		} else
54170b246afaSJeff Mahoney 			btrfs_warn(fs_info,
54182eaa055fSJeff Mahoney 				   "can't clear %s bits 0x%llx while mounted",
54192eaa055fSJeff Mahoney 				   type, disallowed);
54202eaa055fSJeff Mahoney 		return -EPERM;
54212eaa055fSJeff Mahoney 	}
54222eaa055fSJeff Mahoney 
54232eaa055fSJeff Mahoney 	return 0;
54242eaa055fSJeff Mahoney }
54252eaa055fSJeff Mahoney 
54262ff7e61eSJeff Mahoney #define check_feature(fs_info, change_mask, flags, mask_base)	\
54272ff7e61eSJeff Mahoney check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
54282eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
54292eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
54302eaa055fSJeff Mahoney 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
54312eaa055fSJeff Mahoney 
54322eaa055fSJeff Mahoney static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
54332eaa055fSJeff Mahoney {
54340b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
54350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
54360b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
54370b246afaSJeff Mahoney 	struct btrfs_super_block *super_block = fs_info->super_copy;
54382eaa055fSJeff Mahoney 	struct btrfs_ioctl_feature_flags flags[2];
54392eaa055fSJeff Mahoney 	struct btrfs_trans_handle *trans;
54402eaa055fSJeff Mahoney 	u64 newflags;
54412eaa055fSJeff Mahoney 	int ret;
54422eaa055fSJeff Mahoney 
54432eaa055fSJeff Mahoney 	if (!capable(CAP_SYS_ADMIN))
54442eaa055fSJeff Mahoney 		return -EPERM;
54452eaa055fSJeff Mahoney 
54462eaa055fSJeff Mahoney 	if (copy_from_user(flags, arg, sizeof(flags)))
54472eaa055fSJeff Mahoney 		return -EFAULT;
54482eaa055fSJeff Mahoney 
54492eaa055fSJeff Mahoney 	/* Nothing to do */
54502eaa055fSJeff Mahoney 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
54512eaa055fSJeff Mahoney 	    !flags[0].incompat_flags)
54522eaa055fSJeff Mahoney 		return 0;
54532eaa055fSJeff Mahoney 
54542ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_flags,
54552eaa055fSJeff Mahoney 			    flags[1].compat_flags, COMPAT);
54562eaa055fSJeff Mahoney 	if (ret)
54572eaa055fSJeff Mahoney 		return ret;
54582eaa055fSJeff Mahoney 
54592ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
54602eaa055fSJeff Mahoney 			    flags[1].compat_ro_flags, COMPAT_RO);
54612eaa055fSJeff Mahoney 	if (ret)
54622eaa055fSJeff Mahoney 		return ret;
54632eaa055fSJeff Mahoney 
54642ff7e61eSJeff Mahoney 	ret = check_feature(fs_info, flags[0].incompat_flags,
54652eaa055fSJeff Mahoney 			    flags[1].incompat_flags, INCOMPAT);
54662eaa055fSJeff Mahoney 	if (ret)
54672eaa055fSJeff Mahoney 		return ret;
54682eaa055fSJeff Mahoney 
54697ab19625SDavid Sterba 	ret = mnt_want_write_file(file);
54707ab19625SDavid Sterba 	if (ret)
54717ab19625SDavid Sterba 		return ret;
54727ab19625SDavid Sterba 
54738051aa1aSDavid Sterba 	trans = btrfs_start_transaction(root, 0);
54747ab19625SDavid Sterba 	if (IS_ERR(trans)) {
54757ab19625SDavid Sterba 		ret = PTR_ERR(trans);
54767ab19625SDavid Sterba 		goto out_drop_write;
54777ab19625SDavid Sterba 	}
54782eaa055fSJeff Mahoney 
54790b246afaSJeff Mahoney 	spin_lock(&fs_info->super_lock);
54802eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_flags(super_block);
54812eaa055fSJeff Mahoney 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
54822eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
54832eaa055fSJeff Mahoney 	btrfs_set_super_compat_flags(super_block, newflags);
54842eaa055fSJeff Mahoney 
54852eaa055fSJeff Mahoney 	newflags = btrfs_super_compat_ro_flags(super_block);
54862eaa055fSJeff Mahoney 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
54872eaa055fSJeff Mahoney 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
54882eaa055fSJeff Mahoney 	btrfs_set_super_compat_ro_flags(super_block, newflags);
54892eaa055fSJeff Mahoney 
54902eaa055fSJeff Mahoney 	newflags = btrfs_super_incompat_flags(super_block);
54912eaa055fSJeff Mahoney 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
54922eaa055fSJeff Mahoney 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
54932eaa055fSJeff Mahoney 	btrfs_set_super_incompat_flags(super_block, newflags);
54940b246afaSJeff Mahoney 	spin_unlock(&fs_info->super_lock);
54952eaa055fSJeff Mahoney 
54963a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
54977ab19625SDavid Sterba out_drop_write:
54987ab19625SDavid Sterba 	mnt_drop_write_file(file);
54997ab19625SDavid Sterba 
55007ab19625SDavid Sterba 	return ret;
55012eaa055fSJeff Mahoney }
55022eaa055fSJeff Mahoney 
55032351f431SJosef Bacik static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
55042351f431SJosef Bacik {
55052351f431SJosef Bacik 	struct btrfs_ioctl_send_args *arg;
55062351f431SJosef Bacik 	int ret;
55072351f431SJosef Bacik 
55082351f431SJosef Bacik 	if (compat) {
55092351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
55102351f431SJosef Bacik 		struct btrfs_ioctl_send_args_32 args32;
55112351f431SJosef Bacik 
55122351f431SJosef Bacik 		ret = copy_from_user(&args32, argp, sizeof(args32));
55132351f431SJosef Bacik 		if (ret)
55142351f431SJosef Bacik 			return -EFAULT;
55152351f431SJosef Bacik 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
55162351f431SJosef Bacik 		if (!arg)
55172351f431SJosef Bacik 			return -ENOMEM;
55182351f431SJosef Bacik 		arg->send_fd = args32.send_fd;
55192351f431SJosef Bacik 		arg->clone_sources_count = args32.clone_sources_count;
55202351f431SJosef Bacik 		arg->clone_sources = compat_ptr(args32.clone_sources);
55212351f431SJosef Bacik 		arg->parent_root = args32.parent_root;
55222351f431SJosef Bacik 		arg->flags = args32.flags;
55232351f431SJosef Bacik 		memcpy(arg->reserved, args32.reserved,
55242351f431SJosef Bacik 		       sizeof(args32.reserved));
55252351f431SJosef Bacik #else
55262351f431SJosef Bacik 		return -ENOTTY;
55272351f431SJosef Bacik #endif
55282351f431SJosef Bacik 	} else {
55292351f431SJosef Bacik 		arg = memdup_user(argp, sizeof(*arg));
55302351f431SJosef Bacik 		if (IS_ERR(arg))
55312351f431SJosef Bacik 			return PTR_ERR(arg);
55322351f431SJosef Bacik 	}
55332351f431SJosef Bacik 	ret = btrfs_ioctl_send(file, arg);
55342351f431SJosef Bacik 	kfree(arg);
55352351f431SJosef Bacik 	return ret;
55362351f431SJosef Bacik }
55372351f431SJosef Bacik 
5538f46b5a66SChristoph Hellwig long btrfs_ioctl(struct file *file, unsigned int
5539f46b5a66SChristoph Hellwig 		cmd, unsigned long arg)
5540f46b5a66SChristoph Hellwig {
55410b246afaSJeff Mahoney 	struct inode *inode = file_inode(file);
55420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
55430b246afaSJeff Mahoney 	struct btrfs_root *root = BTRFS_I(inode)->root;
55444bcabaa3SChristoph Hellwig 	void __user *argp = (void __user *)arg;
5545f46b5a66SChristoph Hellwig 
5546f46b5a66SChristoph Hellwig 	switch (cmd) {
55476cbff00fSChristoph Hellwig 	case FS_IOC_GETFLAGS:
55486cbff00fSChristoph Hellwig 		return btrfs_ioctl_getflags(file, argp);
55496cbff00fSChristoph Hellwig 	case FS_IOC_SETFLAGS:
55506cbff00fSChristoph Hellwig 		return btrfs_ioctl_setflags(file, argp);
55516cbff00fSChristoph Hellwig 	case FS_IOC_GETVERSION:
55526cbff00fSChristoph Hellwig 		return btrfs_ioctl_getversion(file, argp);
5553f7039b1dSLi Dongyang 	case FITRIM:
5554f7039b1dSLi Dongyang 		return btrfs_ioctl_fitrim(file, argp);
5555f46b5a66SChristoph Hellwig 	case BTRFS_IOC_SNAP_CREATE:
5556fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 0);
5557fdfb1e4fSLi Zefan 	case BTRFS_IOC_SNAP_CREATE_V2:
5558fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
55593de4586cSChris Mason 	case BTRFS_IOC_SUBVOL_CREATE:
5560fa0d2b9bSLi Zefan 		return btrfs_ioctl_snap_create(file, argp, 1);
55616f72c7e2SArne Jansen 	case BTRFS_IOC_SUBVOL_CREATE_V2:
55626f72c7e2SArne Jansen 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
556376dda93cSYan, Zheng 	case BTRFS_IOC_SNAP_DESTROY:
556476dda93cSYan, Zheng 		return btrfs_ioctl_snap_destroy(file, argp);
55650caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_GETFLAGS:
55660caa102dSLi Zefan 		return btrfs_ioctl_subvol_getflags(file, argp);
55670caa102dSLi Zefan 	case BTRFS_IOC_SUBVOL_SETFLAGS:
55680caa102dSLi Zefan 		return btrfs_ioctl_subvol_setflags(file, argp);
55696ef5ed0dSJosef Bacik 	case BTRFS_IOC_DEFAULT_SUBVOL:
55706ef5ed0dSJosef Bacik 		return btrfs_ioctl_default_subvol(file, argp);
5571f46b5a66SChristoph Hellwig 	case BTRFS_IOC_DEFRAG:
55721e701a32SChris Mason 		return btrfs_ioctl_defrag(file, NULL);
55731e701a32SChris Mason 	case BTRFS_IOC_DEFRAG_RANGE:
55741e701a32SChris Mason 		return btrfs_ioctl_defrag(file, argp);
5575f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RESIZE:
5576198605a8SMiao Xie 		return btrfs_ioctl_resize(file, argp);
5577f46b5a66SChristoph Hellwig 	case BTRFS_IOC_ADD_DEV:
55782ff7e61eSJeff Mahoney 		return btrfs_ioctl_add_dev(fs_info, argp);
5579f46b5a66SChristoph Hellwig 	case BTRFS_IOC_RM_DEV:
5580da24927bSMiao Xie 		return btrfs_ioctl_rm_dev(file, argp);
55816b526ed7SAnand Jain 	case BTRFS_IOC_RM_DEV_V2:
55826b526ed7SAnand Jain 		return btrfs_ioctl_rm_dev_v2(file, argp);
5583475f6387SJan Schmidt 	case BTRFS_IOC_FS_INFO:
55842ff7e61eSJeff Mahoney 		return btrfs_ioctl_fs_info(fs_info, argp);
5585475f6387SJan Schmidt 	case BTRFS_IOC_DEV_INFO:
55862ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_info(fs_info, argp);
5587f46b5a66SChristoph Hellwig 	case BTRFS_IOC_BALANCE:
55889ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, NULL);
5589ac8e9819SChris Mason 	case BTRFS_IOC_TREE_SEARCH:
5590ac8e9819SChris Mason 		return btrfs_ioctl_tree_search(file, argp);
5591cc68a8a5SGerhard Heift 	case BTRFS_IOC_TREE_SEARCH_V2:
5592cc68a8a5SGerhard Heift 		return btrfs_ioctl_tree_search_v2(file, argp);
5593ac8e9819SChris Mason 	case BTRFS_IOC_INO_LOOKUP:
5594ac8e9819SChris Mason 		return btrfs_ioctl_ino_lookup(file, argp);
5595d7728c96SJan Schmidt 	case BTRFS_IOC_INO_PATHS:
5596d7728c96SJan Schmidt 		return btrfs_ioctl_ino_to_path(root, argp);
5597d7728c96SJan Schmidt 	case BTRFS_IOC_LOGICAL_INO:
5598d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5599d24a67b2SZygo Blaxell 	case BTRFS_IOC_LOGICAL_INO_V2:
5600d24a67b2SZygo Blaxell 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
56011406e432SJosef Bacik 	case BTRFS_IOC_SPACE_INFO:
56022ff7e61eSJeff Mahoney 		return btrfs_ioctl_space_info(fs_info, argp);
56039b199859SFilipe David Borba Manana 	case BTRFS_IOC_SYNC: {
56049b199859SFilipe David Borba Manana 		int ret;
56059b199859SFilipe David Borba Manana 
560682b3e53bSNikolay Borisov 		ret = btrfs_start_delalloc_roots(fs_info, -1);
56079b199859SFilipe David Borba Manana 		if (ret)
56089b199859SFilipe David Borba Manana 			return ret;
56090b246afaSJeff Mahoney 		ret = btrfs_sync_fs(inode->i_sb, 1);
56102fad4e83SDavid Sterba 		/*
56112fad4e83SDavid Sterba 		 * The transaction thread may want to do more work,
561201327610SNicholas D Steeves 		 * namely it pokes the cleaner kthread that will start
56132fad4e83SDavid Sterba 		 * processing uncleaned subvols.
56142fad4e83SDavid Sterba 		 */
56150b246afaSJeff Mahoney 		wake_up_process(fs_info->transaction_kthread);
56169b199859SFilipe David Borba Manana 		return ret;
56179b199859SFilipe David Borba Manana 	}
561846204592SSage Weil 	case BTRFS_IOC_START_SYNC:
56199a8c28beSMiao Xie 		return btrfs_ioctl_start_sync(root, argp);
562046204592SSage Weil 	case BTRFS_IOC_WAIT_SYNC:
56212ff7e61eSJeff Mahoney 		return btrfs_ioctl_wait_sync(fs_info, argp);
5622475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB:
5623b8e95489SMiao Xie 		return btrfs_ioctl_scrub(file, argp);
5624475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_CANCEL:
56252ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_cancel(fs_info);
5626475f6387SJan Schmidt 	case BTRFS_IOC_SCRUB_PROGRESS:
56272ff7e61eSJeff Mahoney 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5628c9e9f97bSIlya Dryomov 	case BTRFS_IOC_BALANCE_V2:
56299ba1f6e4SLiu Bo 		return btrfs_ioctl_balance(file, argp);
5630837d5b6eSIlya Dryomov 	case BTRFS_IOC_BALANCE_CTL:
56312ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_ctl(fs_info, arg);
563219a39dceSIlya Dryomov 	case BTRFS_IOC_BALANCE_PROGRESS:
56332ff7e61eSJeff Mahoney 		return btrfs_ioctl_balance_progress(fs_info, argp);
56348ea05e3aSAlexander Block 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
56358ea05e3aSAlexander Block 		return btrfs_ioctl_set_received_subvol(file, argp);
5636abccd00fSHugo Mills #ifdef CONFIG_64BIT
5637abccd00fSHugo Mills 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5638abccd00fSHugo Mills 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5639abccd00fSHugo Mills #endif
564031db9f7cSAlexander Block 	case BTRFS_IOC_SEND:
56412351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, false);
56422351f431SJosef Bacik #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
56432351f431SJosef Bacik 	case BTRFS_IOC_SEND_32:
56442351f431SJosef Bacik 		return _btrfs_ioctl_send(file, argp, true);
56452351f431SJosef Bacik #endif
5646c11d2c23SStefan Behrens 	case BTRFS_IOC_GET_DEV_STATS:
56472ff7e61eSJeff Mahoney 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
56485d13a37bSArne Jansen 	case BTRFS_IOC_QUOTA_CTL:
5649905b0ddaSMiao Xie 		return btrfs_ioctl_quota_ctl(file, argp);
56505d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_ASSIGN:
5651905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_assign(file, argp);
56525d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_CREATE:
5653905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_create(file, argp);
56545d13a37bSArne Jansen 	case BTRFS_IOC_QGROUP_LIMIT:
5655905b0ddaSMiao Xie 		return btrfs_ioctl_qgroup_limit(file, argp);
56562f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN:
56572f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan(file, argp);
56582f232036SJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
56592f232036SJan Schmidt 		return btrfs_ioctl_quota_rescan_status(file, argp);
566057254b6eSJan Schmidt 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
566157254b6eSJan Schmidt 		return btrfs_ioctl_quota_rescan_wait(file, argp);
56623f6bcfbdSStefan Behrens 	case BTRFS_IOC_DEV_REPLACE:
56632ff7e61eSJeff Mahoney 		return btrfs_ioctl_dev_replace(fs_info, argp);
5664867ab667Sjeff.liu 	case BTRFS_IOC_GET_FSLABEL:
5665867ab667Sjeff.liu 		return btrfs_ioctl_get_fslabel(file, argp);
5666a8bfd4abSjeff.liu 	case BTRFS_IOC_SET_FSLABEL:
5667a8bfd4abSjeff.liu 		return btrfs_ioctl_set_fslabel(file, argp);
56682eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5669d5131b65SDavid Sterba 		return btrfs_ioctl_get_supported_features(argp);
56702eaa055fSJeff Mahoney 	case BTRFS_IOC_GET_FEATURES:
56712eaa055fSJeff Mahoney 		return btrfs_ioctl_get_features(file, argp);
56722eaa055fSJeff Mahoney 	case BTRFS_IOC_SET_FEATURES:
56732eaa055fSJeff Mahoney 		return btrfs_ioctl_set_features(file, argp);
5674e4202ac9SDavid Sterba 	case FS_IOC_FSGETXATTR:
5675e4202ac9SDavid Sterba 		return btrfs_ioctl_fsgetxattr(file, argp);
5676025f2121SDavid Sterba 	case FS_IOC_FSSETXATTR:
5677025f2121SDavid Sterba 		return btrfs_ioctl_fssetxattr(file, argp);
5678b64ec075STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_INFO:
5679b64ec075STomohiro Misono 		return btrfs_ioctl_get_subvol_info(file, argp);
568042e4b520STomohiro Misono 	case BTRFS_IOC_GET_SUBVOL_ROOTREF:
568142e4b520STomohiro Misono 		return btrfs_ioctl_get_subvol_rootref(file, argp);
568223d0b79dSTomohiro Misono 	case BTRFS_IOC_INO_LOOKUP_USER:
568323d0b79dSTomohiro Misono 		return btrfs_ioctl_ino_lookup_user(file, argp);
5684f46b5a66SChristoph Hellwig 	}
5685f46b5a66SChristoph Hellwig 
5686f46b5a66SChristoph Hellwig 	return -ENOTTY;
5687f46b5a66SChristoph Hellwig }
56884c63c245SLuke Dashjr 
56894c63c245SLuke Dashjr #ifdef CONFIG_COMPAT
56904c63c245SLuke Dashjr long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
56914c63c245SLuke Dashjr {
56922a362249SJeff Mahoney 	/*
56932a362249SJeff Mahoney 	 * These all access 32-bit values anyway so no further
56942a362249SJeff Mahoney 	 * handling is necessary.
56952a362249SJeff Mahoney 	 */
56964c63c245SLuke Dashjr 	switch (cmd) {
56974c63c245SLuke Dashjr 	case FS_IOC32_GETFLAGS:
56984c63c245SLuke Dashjr 		cmd = FS_IOC_GETFLAGS;
56994c63c245SLuke Dashjr 		break;
57004c63c245SLuke Dashjr 	case FS_IOC32_SETFLAGS:
57014c63c245SLuke Dashjr 		cmd = FS_IOC_SETFLAGS;
57024c63c245SLuke Dashjr 		break;
57034c63c245SLuke Dashjr 	case FS_IOC32_GETVERSION:
57044c63c245SLuke Dashjr 		cmd = FS_IOC_GETVERSION;
57054c63c245SLuke Dashjr 		break;
57064c63c245SLuke Dashjr 	}
57074c63c245SLuke Dashjr 
57084c63c245SLuke Dashjr 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
57094c63c245SLuke Dashjr }
57104c63c245SLuke Dashjr #endif
5711