xref: /kernel/linux/linux-5.10/fs/btrfs/ioctl.c (revision 8c2ecf20)
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (C) 2007 Oracle.  All rights reserved.
4 */
5
6#include <linux/kernel.h>
7#include <linux/bio.h>
8#include <linux/file.h>
9#include <linux/fs.h>
10#include <linux/fsnotify.h>
11#include <linux/pagemap.h>
12#include <linux/highmem.h>
13#include <linux/time.h>
14#include <linux/string.h>
15#include <linux/backing-dev.h>
16#include <linux/mount.h>
17#include <linux/namei.h>
18#include <linux/writeback.h>
19#include <linux/compat.h>
20#include <linux/security.h>
21#include <linux/xattr.h>
22#include <linux/mm.h>
23#include <linux/slab.h>
24#include <linux/blkdev.h>
25#include <linux/uuid.h>
26#include <linux/btrfs.h>
27#include <linux/uaccess.h>
28#include <linux/iversion.h>
29#include "ctree.h"
30#include "disk-io.h"
31#include "export.h"
32#include "transaction.h"
33#include "btrfs_inode.h"
34#include "print-tree.h"
35#include "volumes.h"
36#include "locking.h"
37#include "inode-map.h"
38#include "backref.h"
39#include "rcu-string.h"
40#include "send.h"
41#include "dev-replace.h"
42#include "props.h"
43#include "sysfs.h"
44#include "qgroup.h"
45#include "tree-log.h"
46#include "compression.h"
47#include "space-info.h"
48#include "delalloc-space.h"
49#include "block-group.h"
50
51#ifdef CONFIG_64BIT
52/* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
53 * structures are incorrect, as the timespec structure from userspace
54 * is 4 bytes too small. We define these alternatives here to teach
55 * the kernel about the 32-bit struct packing.
56 */
57struct btrfs_ioctl_timespec_32 {
58	__u64 sec;
59	__u32 nsec;
60} __attribute__ ((__packed__));
61
62struct btrfs_ioctl_received_subvol_args_32 {
63	char	uuid[BTRFS_UUID_SIZE];	/* in */
64	__u64	stransid;		/* in */
65	__u64	rtransid;		/* out */
66	struct btrfs_ioctl_timespec_32 stime; /* in */
67	struct btrfs_ioctl_timespec_32 rtime; /* out */
68	__u64	flags;			/* in */
69	__u64	reserved[16];		/* in */
70} __attribute__ ((__packed__));
71
72#define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
73				struct btrfs_ioctl_received_subvol_args_32)
74#endif
75
76#if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
77struct btrfs_ioctl_send_args_32 {
78	__s64 send_fd;			/* in */
79	__u64 clone_sources_count;	/* in */
80	compat_uptr_t clone_sources;	/* in */
81	__u64 parent_root;		/* in */
82	__u64 flags;			/* in */
83	__u64 reserved[4];		/* in */
84} __attribute__ ((__packed__));
85
86#define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
87			       struct btrfs_ioctl_send_args_32)
88#endif
89
90/* Mask out flags that are inappropriate for the given type of inode. */
91static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
92		unsigned int flags)
93{
94	if (S_ISDIR(inode->i_mode))
95		return flags;
96	else if (S_ISREG(inode->i_mode))
97		return flags & ~FS_DIRSYNC_FL;
98	else
99		return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
100}
101
102/*
103 * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
104 * ioctl.
105 */
106static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags)
107{
108	unsigned int iflags = 0;
109
110	if (flags & BTRFS_INODE_SYNC)
111		iflags |= FS_SYNC_FL;
112	if (flags & BTRFS_INODE_IMMUTABLE)
113		iflags |= FS_IMMUTABLE_FL;
114	if (flags & BTRFS_INODE_APPEND)
115		iflags |= FS_APPEND_FL;
116	if (flags & BTRFS_INODE_NODUMP)
117		iflags |= FS_NODUMP_FL;
118	if (flags & BTRFS_INODE_NOATIME)
119		iflags |= FS_NOATIME_FL;
120	if (flags & BTRFS_INODE_DIRSYNC)
121		iflags |= FS_DIRSYNC_FL;
122	if (flags & BTRFS_INODE_NODATACOW)
123		iflags |= FS_NOCOW_FL;
124
125	if (flags & BTRFS_INODE_NOCOMPRESS)
126		iflags |= FS_NOCOMP_FL;
127	else if (flags & BTRFS_INODE_COMPRESS)
128		iflags |= FS_COMPR_FL;
129
130	return iflags;
131}
132
133/*
134 * Update inode->i_flags based on the btrfs internal flags.
135 */
136void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
137{
138	struct btrfs_inode *binode = BTRFS_I(inode);
139	unsigned int new_fl = 0;
140
141	if (binode->flags & BTRFS_INODE_SYNC)
142		new_fl |= S_SYNC;
143	if (binode->flags & BTRFS_INODE_IMMUTABLE)
144		new_fl |= S_IMMUTABLE;
145	if (binode->flags & BTRFS_INODE_APPEND)
146		new_fl |= S_APPEND;
147	if (binode->flags & BTRFS_INODE_NOATIME)
148		new_fl |= S_NOATIME;
149	if (binode->flags & BTRFS_INODE_DIRSYNC)
150		new_fl |= S_DIRSYNC;
151
152	set_mask_bits(&inode->i_flags,
153		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
154		      new_fl);
155}
156
157static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
158{
159	struct btrfs_inode *binode = BTRFS_I(file_inode(file));
160	unsigned int flags = btrfs_inode_flags_to_fsflags(binode->flags);
161
162	if (copy_to_user(arg, &flags, sizeof(flags)))
163		return -EFAULT;
164	return 0;
165}
166
167/*
168 * Check if @flags are a supported and valid set of FS_*_FL flags and that
169 * the old and new flags are not conflicting
170 */
171static int check_fsflags(unsigned int old_flags, unsigned int flags)
172{
173	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
174		      FS_NOATIME_FL | FS_NODUMP_FL | \
175		      FS_SYNC_FL | FS_DIRSYNC_FL | \
176		      FS_NOCOMP_FL | FS_COMPR_FL |
177		      FS_NOCOW_FL))
178		return -EOPNOTSUPP;
179
180	/* COMPR and NOCOMP on new/old are valid */
181	if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
182		return -EINVAL;
183
184	if ((flags & FS_COMPR_FL) && (flags & FS_NOCOW_FL))
185		return -EINVAL;
186
187	/* NOCOW and compression options are mutually exclusive */
188	if ((old_flags & FS_NOCOW_FL) && (flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
189		return -EINVAL;
190	if ((flags & FS_NOCOW_FL) && (old_flags & (FS_COMPR_FL | FS_NOCOMP_FL)))
191		return -EINVAL;
192
193	return 0;
194}
195
196static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
197{
198	struct inode *inode = file_inode(file);
199	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
200	struct btrfs_inode *binode = BTRFS_I(inode);
201	struct btrfs_root *root = binode->root;
202	struct btrfs_trans_handle *trans;
203	unsigned int fsflags, old_fsflags;
204	int ret;
205	const char *comp = NULL;
206	u32 binode_flags;
207
208	if (!inode_owner_or_capable(inode))
209		return -EPERM;
210
211	if (btrfs_root_readonly(root))
212		return -EROFS;
213
214	if (copy_from_user(&fsflags, arg, sizeof(fsflags)))
215		return -EFAULT;
216
217	ret = mnt_want_write_file(file);
218	if (ret)
219		return ret;
220
221	inode_lock(inode);
222	fsflags = btrfs_mask_fsflags_for_type(inode, fsflags);
223	old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags);
224
225	ret = vfs_ioc_setflags_prepare(inode, old_fsflags, fsflags);
226	if (ret)
227		goto out_unlock;
228
229	ret = check_fsflags(old_fsflags, fsflags);
230	if (ret)
231		goto out_unlock;
232
233	binode_flags = binode->flags;
234	if (fsflags & FS_SYNC_FL)
235		binode_flags |= BTRFS_INODE_SYNC;
236	else
237		binode_flags &= ~BTRFS_INODE_SYNC;
238	if (fsflags & FS_IMMUTABLE_FL)
239		binode_flags |= BTRFS_INODE_IMMUTABLE;
240	else
241		binode_flags &= ~BTRFS_INODE_IMMUTABLE;
242	if (fsflags & FS_APPEND_FL)
243		binode_flags |= BTRFS_INODE_APPEND;
244	else
245		binode_flags &= ~BTRFS_INODE_APPEND;
246	if (fsflags & FS_NODUMP_FL)
247		binode_flags |= BTRFS_INODE_NODUMP;
248	else
249		binode_flags &= ~BTRFS_INODE_NODUMP;
250	if (fsflags & FS_NOATIME_FL)
251		binode_flags |= BTRFS_INODE_NOATIME;
252	else
253		binode_flags &= ~BTRFS_INODE_NOATIME;
254	if (fsflags & FS_DIRSYNC_FL)
255		binode_flags |= BTRFS_INODE_DIRSYNC;
256	else
257		binode_flags &= ~BTRFS_INODE_DIRSYNC;
258	if (fsflags & FS_NOCOW_FL) {
259		if (S_ISREG(inode->i_mode)) {
260			/*
261			 * It's safe to turn csums off here, no extents exist.
262			 * Otherwise we want the flag to reflect the real COW
263			 * status of the file and will not set it.
264			 */
265			if (inode->i_size == 0)
266				binode_flags |= BTRFS_INODE_NODATACOW |
267						BTRFS_INODE_NODATASUM;
268		} else {
269			binode_flags |= BTRFS_INODE_NODATACOW;
270		}
271	} else {
272		/*
273		 * Revert back under same assumptions as above
274		 */
275		if (S_ISREG(inode->i_mode)) {
276			if (inode->i_size == 0)
277				binode_flags &= ~(BTRFS_INODE_NODATACOW |
278						  BTRFS_INODE_NODATASUM);
279		} else {
280			binode_flags &= ~BTRFS_INODE_NODATACOW;
281		}
282	}
283
284	/*
285	 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
286	 * flag may be changed automatically if compression code won't make
287	 * things smaller.
288	 */
289	if (fsflags & FS_NOCOMP_FL) {
290		binode_flags &= ~BTRFS_INODE_COMPRESS;
291		binode_flags |= BTRFS_INODE_NOCOMPRESS;
292	} else if (fsflags & FS_COMPR_FL) {
293
294		if (IS_SWAPFILE(inode)) {
295			ret = -ETXTBSY;
296			goto out_unlock;
297		}
298
299		binode_flags |= BTRFS_INODE_COMPRESS;
300		binode_flags &= ~BTRFS_INODE_NOCOMPRESS;
301
302		comp = btrfs_compress_type2str(fs_info->compress_type);
303		if (!comp || comp[0] == 0)
304			comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
305	} else {
306		binode_flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
307	}
308
309	/*
310	 * 1 for inode item
311	 * 2 for properties
312	 */
313	trans = btrfs_start_transaction(root, 3);
314	if (IS_ERR(trans)) {
315		ret = PTR_ERR(trans);
316		goto out_unlock;
317	}
318
319	if (comp) {
320		ret = btrfs_set_prop(trans, inode, "btrfs.compression", comp,
321				     strlen(comp), 0);
322		if (ret) {
323			btrfs_abort_transaction(trans, ret);
324			goto out_end_trans;
325		}
326	} else {
327		ret = btrfs_set_prop(trans, inode, "btrfs.compression", NULL,
328				     0, 0);
329		if (ret && ret != -ENODATA) {
330			btrfs_abort_transaction(trans, ret);
331			goto out_end_trans;
332		}
333	}
334
335	binode->flags = binode_flags;
336	btrfs_sync_inode_flags_to_i_flags(inode);
337	inode_inc_iversion(inode);
338	inode->i_ctime = current_time(inode);
339	ret = btrfs_update_inode(trans, root, inode);
340
341 out_end_trans:
342	btrfs_end_transaction(trans);
343 out_unlock:
344	inode_unlock(inode);
345	mnt_drop_write_file(file);
346	return ret;
347}
348
349/*
350 * Translate btrfs internal inode flags to xflags as expected by the
351 * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are
352 * silently dropped.
353 */
354static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags)
355{
356	unsigned int xflags = 0;
357
358	if (flags & BTRFS_INODE_APPEND)
359		xflags |= FS_XFLAG_APPEND;
360	if (flags & BTRFS_INODE_IMMUTABLE)
361		xflags |= FS_XFLAG_IMMUTABLE;
362	if (flags & BTRFS_INODE_NOATIME)
363		xflags |= FS_XFLAG_NOATIME;
364	if (flags & BTRFS_INODE_NODUMP)
365		xflags |= FS_XFLAG_NODUMP;
366	if (flags & BTRFS_INODE_SYNC)
367		xflags |= FS_XFLAG_SYNC;
368
369	return xflags;
370}
371
372/* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */
373static int check_xflags(unsigned int flags)
374{
375	if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME |
376		      FS_XFLAG_NODUMP | FS_XFLAG_SYNC))
377		return -EOPNOTSUPP;
378	return 0;
379}
380
381bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
382			enum btrfs_exclusive_operation type)
383{
384	return !cmpxchg(&fs_info->exclusive_operation, BTRFS_EXCLOP_NONE, type);
385}
386
387void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
388{
389	WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
390	sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
391}
392
393/*
394 * Set the xflags from the internal inode flags. The remaining items of fsxattr
395 * are zeroed.
396 */
397static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg)
398{
399	struct btrfs_inode *binode = BTRFS_I(file_inode(file));
400	struct fsxattr fa;
401
402	simple_fill_fsxattr(&fa, btrfs_inode_flags_to_xflags(binode->flags));
403	if (copy_to_user(arg, &fa, sizeof(fa)))
404		return -EFAULT;
405
406	return 0;
407}
408
409static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg)
410{
411	struct inode *inode = file_inode(file);
412	struct btrfs_inode *binode = BTRFS_I(inode);
413	struct btrfs_root *root = binode->root;
414	struct btrfs_trans_handle *trans;
415	struct fsxattr fa, old_fa;
416	unsigned old_flags;
417	unsigned old_i_flags;
418	int ret = 0;
419
420	if (!inode_owner_or_capable(inode))
421		return -EPERM;
422
423	if (btrfs_root_readonly(root))
424		return -EROFS;
425
426	if (copy_from_user(&fa, arg, sizeof(fa)))
427		return -EFAULT;
428
429	ret = check_xflags(fa.fsx_xflags);
430	if (ret)
431		return ret;
432
433	if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0)
434		return -EOPNOTSUPP;
435
436	ret = mnt_want_write_file(file);
437	if (ret)
438		return ret;
439
440	inode_lock(inode);
441
442	old_flags = binode->flags;
443	old_i_flags = inode->i_flags;
444
445	simple_fill_fsxattr(&old_fa,
446			    btrfs_inode_flags_to_xflags(binode->flags));
447	ret = vfs_ioc_fssetxattr_check(inode, &old_fa, &fa);
448	if (ret)
449		goto out_unlock;
450
451	if (fa.fsx_xflags & FS_XFLAG_SYNC)
452		binode->flags |= BTRFS_INODE_SYNC;
453	else
454		binode->flags &= ~BTRFS_INODE_SYNC;
455	if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE)
456		binode->flags |= BTRFS_INODE_IMMUTABLE;
457	else
458		binode->flags &= ~BTRFS_INODE_IMMUTABLE;
459	if (fa.fsx_xflags & FS_XFLAG_APPEND)
460		binode->flags |= BTRFS_INODE_APPEND;
461	else
462		binode->flags &= ~BTRFS_INODE_APPEND;
463	if (fa.fsx_xflags & FS_XFLAG_NODUMP)
464		binode->flags |= BTRFS_INODE_NODUMP;
465	else
466		binode->flags &= ~BTRFS_INODE_NODUMP;
467	if (fa.fsx_xflags & FS_XFLAG_NOATIME)
468		binode->flags |= BTRFS_INODE_NOATIME;
469	else
470		binode->flags &= ~BTRFS_INODE_NOATIME;
471
472	/* 1 item for the inode */
473	trans = btrfs_start_transaction(root, 1);
474	if (IS_ERR(trans)) {
475		ret = PTR_ERR(trans);
476		goto out_unlock;
477	}
478
479	btrfs_sync_inode_flags_to_i_flags(inode);
480	inode_inc_iversion(inode);
481	inode->i_ctime = current_time(inode);
482	ret = btrfs_update_inode(trans, root, inode);
483
484	btrfs_end_transaction(trans);
485
486out_unlock:
487	if (ret) {
488		binode->flags = old_flags;
489		inode->i_flags = old_i_flags;
490	}
491
492	inode_unlock(inode);
493	mnt_drop_write_file(file);
494
495	return ret;
496}
497
498static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
499{
500	struct inode *inode = file_inode(file);
501
502	return put_user(inode->i_generation, arg);
503}
504
505static noinline int btrfs_ioctl_fitrim(struct btrfs_fs_info *fs_info,
506					void __user *arg)
507{
508	struct btrfs_device *device;
509	struct request_queue *q;
510	struct fstrim_range range;
511	u64 minlen = ULLONG_MAX;
512	u64 num_devices = 0;
513	int ret;
514
515	if (!capable(CAP_SYS_ADMIN))
516		return -EPERM;
517
518	/*
519	 * If the fs is mounted with nologreplay, which requires it to be
520	 * mounted in RO mode as well, we can not allow discard on free space
521	 * inside block groups, because log trees refer to extents that are not
522	 * pinned in a block group's free space cache (pinning the extents is
523	 * precisely the first phase of replaying a log tree).
524	 */
525	if (btrfs_test_opt(fs_info, NOLOGREPLAY))
526		return -EROFS;
527
528	rcu_read_lock();
529	list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
530				dev_list) {
531		if (!device->bdev)
532			continue;
533		q = bdev_get_queue(device->bdev);
534		if (blk_queue_discard(q)) {
535			num_devices++;
536			minlen = min_t(u64, q->limits.discard_granularity,
537				     minlen);
538		}
539	}
540	rcu_read_unlock();
541
542	if (!num_devices)
543		return -EOPNOTSUPP;
544	if (copy_from_user(&range, arg, sizeof(range)))
545		return -EFAULT;
546
547	/*
548	 * NOTE: Don't truncate the range using super->total_bytes.  Bytenr of
549	 * block group is in the logical address space, which can be any
550	 * sectorsize aligned bytenr in  the range [0, U64_MAX].
551	 */
552	if (range.len < fs_info->sb->s_blocksize)
553		return -EINVAL;
554
555	range.minlen = max(range.minlen, minlen);
556	ret = btrfs_trim_fs(fs_info, &range);
557	if (ret < 0)
558		return ret;
559
560	if (copy_to_user(arg, &range, sizeof(range)))
561		return -EFAULT;
562
563	return 0;
564}
565
566int __pure btrfs_is_empty_uuid(u8 *uuid)
567{
568	int i;
569
570	for (i = 0; i < BTRFS_UUID_SIZE; i++) {
571		if (uuid[i])
572			return 0;
573	}
574	return 1;
575}
576
577static noinline int create_subvol(struct inode *dir,
578				  struct dentry *dentry,
579				  const char *name, int namelen,
580				  struct btrfs_qgroup_inherit *inherit)
581{
582	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
583	struct btrfs_trans_handle *trans;
584	struct btrfs_key key;
585	struct btrfs_root_item *root_item;
586	struct btrfs_inode_item *inode_item;
587	struct extent_buffer *leaf;
588	struct btrfs_root *root = BTRFS_I(dir)->root;
589	struct btrfs_root *new_root;
590	struct btrfs_block_rsv block_rsv;
591	struct timespec64 cur_time = current_time(dir);
592	struct inode *inode;
593	int ret;
594	int err;
595	dev_t anon_dev = 0;
596	u64 objectid;
597	u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
598	u64 index = 0;
599
600	root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
601	if (!root_item)
602		return -ENOMEM;
603
604	ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
605	if (ret)
606		goto fail_free;
607
608	ret = get_anon_bdev(&anon_dev);
609	if (ret < 0)
610		goto fail_free;
611
612	/*
613	 * Don't create subvolume whose level is not zero. Or qgroup will be
614	 * screwed up since it assumes subvolume qgroup's level to be 0.
615	 */
616	if (btrfs_qgroup_level(objectid)) {
617		ret = -ENOSPC;
618		goto fail_free;
619	}
620
621	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
622	/*
623	 * The same as the snapshot creation, please see the comment
624	 * of create_snapshot().
625	 */
626	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
627	if (ret)
628		goto fail_free;
629
630	trans = btrfs_start_transaction(root, 0);
631	if (IS_ERR(trans)) {
632		ret = PTR_ERR(trans);
633		btrfs_subvolume_release_metadata(root, &block_rsv);
634		goto fail_free;
635	}
636	trans->block_rsv = &block_rsv;
637	trans->bytes_reserved = block_rsv.size;
638
639	ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
640	if (ret)
641		goto fail;
642
643	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
644				      BTRFS_NESTING_NORMAL);
645	if (IS_ERR(leaf)) {
646		ret = PTR_ERR(leaf);
647		goto fail;
648	}
649
650	btrfs_mark_buffer_dirty(leaf);
651
652	inode_item = &root_item->inode;
653	btrfs_set_stack_inode_generation(inode_item, 1);
654	btrfs_set_stack_inode_size(inode_item, 3);
655	btrfs_set_stack_inode_nlink(inode_item, 1);
656	btrfs_set_stack_inode_nbytes(inode_item,
657				     fs_info->nodesize);
658	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
659
660	btrfs_set_root_flags(root_item, 0);
661	btrfs_set_root_limit(root_item, 0);
662	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
663
664	btrfs_set_root_bytenr(root_item, leaf->start);
665	btrfs_set_root_generation(root_item, trans->transid);
666	btrfs_set_root_level(root_item, 0);
667	btrfs_set_root_refs(root_item, 1);
668	btrfs_set_root_used(root_item, leaf->len);
669	btrfs_set_root_last_snapshot(root_item, 0);
670
671	btrfs_set_root_generation_v2(root_item,
672			btrfs_root_generation(root_item));
673	generate_random_guid(root_item->uuid);
674	btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
675	btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
676	root_item->ctime = root_item->otime;
677	btrfs_set_root_ctransid(root_item, trans->transid);
678	btrfs_set_root_otransid(root_item, trans->transid);
679
680	btrfs_tree_unlock(leaf);
681
682	btrfs_set_root_dirid(root_item, new_dirid);
683
684	key.objectid = objectid;
685	key.offset = 0;
686	key.type = BTRFS_ROOT_ITEM_KEY;
687	ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
688				root_item);
689	if (ret) {
690		/*
691		 * Since we don't abort the transaction in this case, free the
692		 * tree block so that we don't leak space and leave the
693		 * filesystem in an inconsistent state (an extent item in the
694		 * extent tree without backreferences). Also no need to have
695		 * the tree block locked since it is not in any tree at this
696		 * point, so no other task can find it and use it.
697		 */
698		btrfs_free_tree_block(trans, root, leaf, 0, 1);
699		free_extent_buffer(leaf);
700		goto fail;
701	}
702
703	free_extent_buffer(leaf);
704	leaf = NULL;
705
706	key.offset = (u64)-1;
707	new_root = btrfs_get_new_fs_root(fs_info, objectid, anon_dev);
708	if (IS_ERR(new_root)) {
709		free_anon_bdev(anon_dev);
710		ret = PTR_ERR(new_root);
711		btrfs_abort_transaction(trans, ret);
712		goto fail;
713	}
714	/* Freeing will be done in btrfs_put_root() of new_root */
715	anon_dev = 0;
716
717	btrfs_record_root_in_trans(trans, new_root);
718
719	ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
720	btrfs_put_root(new_root);
721	if (ret) {
722		/* We potentially lose an unused inode item here */
723		btrfs_abort_transaction(trans, ret);
724		goto fail;
725	}
726
727	mutex_lock(&new_root->objectid_mutex);
728	new_root->highest_objectid = new_dirid;
729	mutex_unlock(&new_root->objectid_mutex);
730
731	/*
732	 * insert the directory item
733	 */
734	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
735	if (ret) {
736		btrfs_abort_transaction(trans, ret);
737		goto fail;
738	}
739
740	ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
741				    BTRFS_FT_DIR, index);
742	if (ret) {
743		btrfs_abort_transaction(trans, ret);
744		goto fail;
745	}
746
747	btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
748	ret = btrfs_update_inode(trans, root, dir);
749	if (ret) {
750		btrfs_abort_transaction(trans, ret);
751		goto fail;
752	}
753
754	ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
755				 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
756	if (ret) {
757		btrfs_abort_transaction(trans, ret);
758		goto fail;
759	}
760
761	ret = btrfs_uuid_tree_add(trans, root_item->uuid,
762				  BTRFS_UUID_KEY_SUBVOL, objectid);
763	if (ret)
764		btrfs_abort_transaction(trans, ret);
765
766fail:
767	kfree(root_item);
768	trans->block_rsv = NULL;
769	trans->bytes_reserved = 0;
770	btrfs_subvolume_release_metadata(root, &block_rsv);
771
772	err = btrfs_commit_transaction(trans);
773	if (err && !ret)
774		ret = err;
775
776	if (!ret) {
777		inode = btrfs_lookup_dentry(dir, dentry);
778		if (IS_ERR(inode))
779			return PTR_ERR(inode);
780		d_instantiate(dentry, inode);
781	}
782	return ret;
783
784fail_free:
785	if (anon_dev)
786		free_anon_bdev(anon_dev);
787	kfree(root_item);
788	return ret;
789}
790
791static int create_snapshot(struct btrfs_root *root, struct inode *dir,
792			   struct dentry *dentry, bool readonly,
793			   struct btrfs_qgroup_inherit *inherit)
794{
795	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
796	struct inode *inode;
797	struct btrfs_pending_snapshot *pending_snapshot;
798	struct btrfs_trans_handle *trans;
799	int ret;
800
801	if (btrfs_root_refs(&root->root_item) == 0)
802		return -ENOENT;
803
804	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
805		return -EINVAL;
806
807	if (atomic_read(&root->nr_swapfiles)) {
808		btrfs_warn(fs_info,
809			   "cannot snapshot subvolume with active swapfile");
810		return -ETXTBSY;
811	}
812
813	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
814	if (!pending_snapshot)
815		return -ENOMEM;
816
817	ret = get_anon_bdev(&pending_snapshot->anon_dev);
818	if (ret < 0)
819		goto free_pending;
820	pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
821			GFP_KERNEL);
822	pending_snapshot->path = btrfs_alloc_path();
823	if (!pending_snapshot->root_item || !pending_snapshot->path) {
824		ret = -ENOMEM;
825		goto free_pending;
826	}
827
828	btrfs_init_block_rsv(&pending_snapshot->block_rsv,
829			     BTRFS_BLOCK_RSV_TEMP);
830	/*
831	 * 1 - parent dir inode
832	 * 2 - dir entries
833	 * 1 - root item
834	 * 2 - root ref/backref
835	 * 1 - root of snapshot
836	 * 1 - UUID item
837	 */
838	ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
839					&pending_snapshot->block_rsv, 8,
840					false);
841	if (ret)
842		goto free_pending;
843
844	pending_snapshot->dentry = dentry;
845	pending_snapshot->root = root;
846	pending_snapshot->readonly = readonly;
847	pending_snapshot->dir = dir;
848	pending_snapshot->inherit = inherit;
849
850	trans = btrfs_start_transaction(root, 0);
851	if (IS_ERR(trans)) {
852		ret = PTR_ERR(trans);
853		goto fail;
854	}
855
856	spin_lock(&fs_info->trans_lock);
857	list_add(&pending_snapshot->list,
858		 &trans->transaction->pending_snapshots);
859	spin_unlock(&fs_info->trans_lock);
860
861	ret = btrfs_commit_transaction(trans);
862	if (ret)
863		goto fail;
864
865	ret = pending_snapshot->error;
866	if (ret)
867		goto fail;
868
869	ret = btrfs_orphan_cleanup(pending_snapshot->snap);
870	if (ret)
871		goto fail;
872
873	inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
874	if (IS_ERR(inode)) {
875		ret = PTR_ERR(inode);
876		goto fail;
877	}
878
879	d_instantiate(dentry, inode);
880	ret = 0;
881	pending_snapshot->anon_dev = 0;
882fail:
883	/* Prevent double freeing of anon_dev */
884	if (ret && pending_snapshot->snap)
885		pending_snapshot->snap->anon_dev = 0;
886	btrfs_put_root(pending_snapshot->snap);
887	btrfs_subvolume_release_metadata(root, &pending_snapshot->block_rsv);
888free_pending:
889	if (pending_snapshot->anon_dev)
890		free_anon_bdev(pending_snapshot->anon_dev);
891	kfree(pending_snapshot->root_item);
892	btrfs_free_path(pending_snapshot->path);
893	kfree(pending_snapshot);
894
895	return ret;
896}
897
898/*  copy of may_delete in fs/namei.c()
899 *	Check whether we can remove a link victim from directory dir, check
900 *  whether the type of victim is right.
901 *  1. We can't do it if dir is read-only (done in permission())
902 *  2. We should have write and exec permissions on dir
903 *  3. We can't remove anything from append-only dir
904 *  4. We can't do anything with immutable dir (done in permission())
905 *  5. If the sticky bit on dir is set we should either
906 *	a. be owner of dir, or
907 *	b. be owner of victim, or
908 *	c. have CAP_FOWNER capability
909 *  6. If the victim is append-only or immutable we can't do anything with
910 *     links pointing to it.
911 *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
912 *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
913 *  9. We can't remove a root or mountpoint.
914 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
915 *     nfs_async_unlink().
916 */
917
918static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
919{
920	int error;
921
922	if (d_really_is_negative(victim))
923		return -ENOENT;
924
925	BUG_ON(d_inode(victim->d_parent) != dir);
926	audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
927
928	error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
929	if (error)
930		return error;
931	if (IS_APPEND(dir))
932		return -EPERM;
933	if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
934	    IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
935		return -EPERM;
936	if (isdir) {
937		if (!d_is_dir(victim))
938			return -ENOTDIR;
939		if (IS_ROOT(victim))
940			return -EBUSY;
941	} else if (d_is_dir(victim))
942		return -EISDIR;
943	if (IS_DEADDIR(dir))
944		return -ENOENT;
945	if (victim->d_flags & DCACHE_NFSFS_RENAMED)
946		return -EBUSY;
947	return 0;
948}
949
950/* copy of may_create in fs/namei.c() */
951static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
952{
953	if (d_really_is_positive(child))
954		return -EEXIST;
955	if (IS_DEADDIR(dir))
956		return -ENOENT;
957	return inode_permission(dir, MAY_WRITE | MAY_EXEC);
958}
959
960/*
961 * Create a new subvolume below @parent.  This is largely modeled after
962 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
963 * inside this filesystem so it's quite a bit simpler.
964 */
965static noinline int btrfs_mksubvol(const struct path *parent,
966				   const char *name, int namelen,
967				   struct btrfs_root *snap_src,
968				   bool readonly,
969				   struct btrfs_qgroup_inherit *inherit)
970{
971	struct inode *dir = d_inode(parent->dentry);
972	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
973	struct dentry *dentry;
974	int error;
975
976	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
977	if (error == -EINTR)
978		return error;
979
980	dentry = lookup_one_len(name, parent->dentry, namelen);
981	error = PTR_ERR(dentry);
982	if (IS_ERR(dentry))
983		goto out_unlock;
984
985	error = btrfs_may_create(dir, dentry);
986	if (error)
987		goto out_dput;
988
989	/*
990	 * even if this name doesn't exist, we may get hash collisions.
991	 * check for them now when we can safely fail
992	 */
993	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
994					       dir->i_ino, name,
995					       namelen);
996	if (error)
997		goto out_dput;
998
999	down_read(&fs_info->subvol_sem);
1000
1001	if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
1002		goto out_up_read;
1003
1004	if (snap_src)
1005		error = create_snapshot(snap_src, dir, dentry, readonly, inherit);
1006	else
1007		error = create_subvol(dir, dentry, name, namelen, inherit);
1008
1009	if (!error)
1010		fsnotify_mkdir(dir, dentry);
1011out_up_read:
1012	up_read(&fs_info->subvol_sem);
1013out_dput:
1014	dput(dentry);
1015out_unlock:
1016	inode_unlock(dir);
1017	return error;
1018}
1019
1020static noinline int btrfs_mksnapshot(const struct path *parent,
1021				   const char *name, int namelen,
1022				   struct btrfs_root *root,
1023				   bool readonly,
1024				   struct btrfs_qgroup_inherit *inherit)
1025{
1026	int ret;
1027	bool snapshot_force_cow = false;
1028
1029	/*
1030	 * Force new buffered writes to reserve space even when NOCOW is
1031	 * possible. This is to avoid later writeback (running dealloc) to
1032	 * fallback to COW mode and unexpectedly fail with ENOSPC.
1033	 */
1034	btrfs_drew_read_lock(&root->snapshot_lock);
1035
1036	ret = btrfs_start_delalloc_snapshot(root);
1037	if (ret)
1038		goto out;
1039
1040	/*
1041	 * All previous writes have started writeback in NOCOW mode, so now
1042	 * we force future writes to fallback to COW mode during snapshot
1043	 * creation.
1044	 */
1045	atomic_inc(&root->snapshot_force_cow);
1046	snapshot_force_cow = true;
1047
1048	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
1049
1050	ret = btrfs_mksubvol(parent, name, namelen,
1051			     root, readonly, inherit);
1052out:
1053	if (snapshot_force_cow)
1054		atomic_dec(&root->snapshot_force_cow);
1055	btrfs_drew_read_unlock(&root->snapshot_lock);
1056	return ret;
1057}
1058
1059/*
1060 * When we're defragging a range, we don't want to kick it off again
1061 * if it is really just waiting for delalloc to send it down.
1062 * If we find a nice big extent or delalloc range for the bytes in the
1063 * file you want to defrag, we return 0 to let you know to skip this
1064 * part of the file
1065 */
1066static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
1067{
1068	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1069	struct extent_map *em = NULL;
1070	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1071	u64 end;
1072
1073	read_lock(&em_tree->lock);
1074	em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
1075	read_unlock(&em_tree->lock);
1076
1077	if (em) {
1078		end = extent_map_end(em);
1079		free_extent_map(em);
1080		if (end - offset > thresh)
1081			return 0;
1082	}
1083	/* if we already have a nice delalloc here, just stop */
1084	thresh /= 2;
1085	end = count_range_bits(io_tree, &offset, offset + thresh,
1086			       thresh, EXTENT_DELALLOC, 1);
1087	if (end >= thresh)
1088		return 0;
1089	return 1;
1090}
1091
1092/*
1093 * helper function to walk through a file and find extents
1094 * newer than a specific transid, and smaller than thresh.
1095 *
1096 * This is used by the defragging code to find new and small
1097 * extents
1098 */
1099static int find_new_extents(struct btrfs_root *root,
1100			    struct inode *inode, u64 newer_than,
1101			    u64 *off, u32 thresh)
1102{
1103	struct btrfs_path *path;
1104	struct btrfs_key min_key;
1105	struct extent_buffer *leaf;
1106	struct btrfs_file_extent_item *extent;
1107	int type;
1108	int ret;
1109	u64 ino = btrfs_ino(BTRFS_I(inode));
1110
1111	path = btrfs_alloc_path();
1112	if (!path)
1113		return -ENOMEM;
1114
1115	min_key.objectid = ino;
1116	min_key.type = BTRFS_EXTENT_DATA_KEY;
1117	min_key.offset = *off;
1118
1119	while (1) {
1120		ret = btrfs_search_forward(root, &min_key, path, newer_than);
1121		if (ret != 0)
1122			goto none;
1123process_slot:
1124		if (min_key.objectid != ino)
1125			goto none;
1126		if (min_key.type != BTRFS_EXTENT_DATA_KEY)
1127			goto none;
1128
1129		leaf = path->nodes[0];
1130		extent = btrfs_item_ptr(leaf, path->slots[0],
1131					struct btrfs_file_extent_item);
1132
1133		type = btrfs_file_extent_type(leaf, extent);
1134		if (type == BTRFS_FILE_EXTENT_REG &&
1135		    btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
1136		    check_defrag_in_cache(inode, min_key.offset, thresh)) {
1137			*off = min_key.offset;
1138			btrfs_free_path(path);
1139			return 0;
1140		}
1141
1142		path->slots[0]++;
1143		if (path->slots[0] < btrfs_header_nritems(leaf)) {
1144			btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1145			goto process_slot;
1146		}
1147
1148		if (min_key.offset == (u64)-1)
1149			goto none;
1150
1151		min_key.offset++;
1152		btrfs_release_path(path);
1153	}
1154none:
1155	btrfs_free_path(path);
1156	return -ENOENT;
1157}
1158
1159static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
1160{
1161	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1162	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1163	struct extent_map *em;
1164	u64 len = PAGE_SIZE;
1165
1166	/*
1167	 * hopefully we have this extent in the tree already, try without
1168	 * the full extent lock
1169	 */
1170	read_lock(&em_tree->lock);
1171	em = lookup_extent_mapping(em_tree, start, len);
1172	read_unlock(&em_tree->lock);
1173
1174	if (!em) {
1175		struct extent_state *cached = NULL;
1176		u64 end = start + len - 1;
1177
1178		/* get the big lock and read metadata off disk */
1179		lock_extent_bits(io_tree, start, end, &cached);
1180		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
1181		unlock_extent_cached(io_tree, start, end, &cached);
1182
1183		if (IS_ERR(em))
1184			return NULL;
1185	}
1186
1187	return em;
1188}
1189
1190static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1191{
1192	struct extent_map *next;
1193	bool ret = true;
1194
1195	/* this is the last extent */
1196	if (em->start + em->len >= i_size_read(inode))
1197		return false;
1198
1199	next = defrag_lookup_extent(inode, em->start + em->len);
1200	if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1201		ret = false;
1202	else if ((em->block_start + em->block_len == next->block_start) &&
1203		 (em->block_len > SZ_128K && next->block_len > SZ_128K))
1204		ret = false;
1205
1206	free_extent_map(next);
1207	return ret;
1208}
1209
1210static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1211			       u64 *last_len, u64 *skip, u64 *defrag_end,
1212			       int compress)
1213{
1214	struct extent_map *em;
1215	int ret = 1;
1216	bool next_mergeable = true;
1217	bool prev_mergeable = true;
1218
1219	/*
1220	 * make sure that once we start defragging an extent, we keep on
1221	 * defragging it
1222	 */
1223	if (start < *defrag_end)
1224		return 1;
1225
1226	*skip = 0;
1227
1228	em = defrag_lookup_extent(inode, start);
1229	if (!em)
1230		return 0;
1231
1232	/* this will cover holes, and inline extents */
1233	if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1234		ret = 0;
1235		goto out;
1236	}
1237
1238	if (!*defrag_end)
1239		prev_mergeable = false;
1240
1241	next_mergeable = defrag_check_next_extent(inode, em);
1242	/*
1243	 * we hit a real extent, if it is big or the next extent is not a
1244	 * real extent, don't bother defragging it
1245	 */
1246	if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1247	    (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1248		ret = 0;
1249out:
1250	/*
1251	 * last_len ends up being a counter of how many bytes we've defragged.
1252	 * every time we choose not to defrag an extent, we reset *last_len
1253	 * so that the next tiny extent will force a defrag.
1254	 *
1255	 * The end result of this is that tiny extents before a single big
1256	 * extent will force at least part of that big extent to be defragged.
1257	 */
1258	if (ret) {
1259		*defrag_end = extent_map_end(em);
1260	} else {
1261		*last_len = 0;
1262		*skip = extent_map_end(em);
1263		*defrag_end = 0;
1264	}
1265
1266	free_extent_map(em);
1267	return ret;
1268}
1269
1270/*
1271 * it doesn't do much good to defrag one or two pages
1272 * at a time.  This pulls in a nice chunk of pages
1273 * to COW and defrag.
1274 *
1275 * It also makes sure the delalloc code has enough
1276 * dirty data to avoid making new small extents as part
1277 * of the defrag
1278 *
1279 * It's a good idea to start RA on this range
1280 * before calling this.
1281 */
1282static int cluster_pages_for_defrag(struct inode *inode,
1283				    struct page **pages,
1284				    unsigned long start_index,
1285				    unsigned long num_pages)
1286{
1287	unsigned long file_end;
1288	u64 isize = i_size_read(inode);
1289	u64 page_start;
1290	u64 page_end;
1291	u64 page_cnt;
1292	u64 start = (u64)start_index << PAGE_SHIFT;
1293	u64 search_start;
1294	int ret;
1295	int i;
1296	int i_done;
1297	struct btrfs_ordered_extent *ordered;
1298	struct extent_state *cached_state = NULL;
1299	struct extent_io_tree *tree;
1300	struct extent_changeset *data_reserved = NULL;
1301	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1302
1303	file_end = (isize - 1) >> PAGE_SHIFT;
1304	if (!isize || start_index > file_end)
1305		return 0;
1306
1307	page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1308
1309	ret = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
1310			start, page_cnt << PAGE_SHIFT);
1311	if (ret)
1312		return ret;
1313	i_done = 0;
1314	tree = &BTRFS_I(inode)->io_tree;
1315
1316	/* step one, lock all the pages */
1317	for (i = 0; i < page_cnt; i++) {
1318		struct page *page;
1319again:
1320		page = find_or_create_page(inode->i_mapping,
1321					   start_index + i, mask);
1322		if (!page)
1323			break;
1324
1325		page_start = page_offset(page);
1326		page_end = page_start + PAGE_SIZE - 1;
1327		while (1) {
1328			lock_extent_bits(tree, page_start, page_end,
1329					 &cached_state);
1330			ordered = btrfs_lookup_ordered_extent(BTRFS_I(inode),
1331							      page_start);
1332			unlock_extent_cached(tree, page_start, page_end,
1333					     &cached_state);
1334			if (!ordered)
1335				break;
1336
1337			unlock_page(page);
1338			btrfs_start_ordered_extent(ordered, 1);
1339			btrfs_put_ordered_extent(ordered);
1340			lock_page(page);
1341			/*
1342			 * we unlocked the page above, so we need check if
1343			 * it was released or not.
1344			 */
1345			if (page->mapping != inode->i_mapping) {
1346				unlock_page(page);
1347				put_page(page);
1348				goto again;
1349			}
1350		}
1351
1352		if (!PageUptodate(page)) {
1353			btrfs_readpage(NULL, page);
1354			lock_page(page);
1355			if (!PageUptodate(page)) {
1356				unlock_page(page);
1357				put_page(page);
1358				ret = -EIO;
1359				break;
1360			}
1361		}
1362
1363		if (page->mapping != inode->i_mapping) {
1364			unlock_page(page);
1365			put_page(page);
1366			goto again;
1367		}
1368
1369		pages[i] = page;
1370		i_done++;
1371	}
1372	if (!i_done || ret)
1373		goto out;
1374
1375	if (!(inode->i_sb->s_flags & SB_ACTIVE))
1376		goto out;
1377
1378	/*
1379	 * so now we have a nice long stream of locked
1380	 * and up to date pages, lets wait on them
1381	 */
1382	for (i = 0; i < i_done; i++)
1383		wait_on_page_writeback(pages[i]);
1384
1385	page_start = page_offset(pages[0]);
1386	page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
1387
1388	lock_extent_bits(&BTRFS_I(inode)->io_tree,
1389			 page_start, page_end - 1, &cached_state);
1390
1391	/*
1392	 * When defragmenting we skip ranges that have holes or inline extents,
1393	 * (check should_defrag_range()), to avoid unnecessary IO and wasting
1394	 * space. At btrfs_defrag_file(), we check if a range should be defragged
1395	 * before locking the inode and then, if it should, we trigger a sync
1396	 * page cache readahead - we lock the inode only after that to avoid
1397	 * blocking for too long other tasks that possibly want to operate on
1398	 * other file ranges. But before we were able to get the inode lock,
1399	 * some other task may have punched a hole in the range, or we may have
1400	 * now an inline extent, in which case we should not defrag. So check
1401	 * for that here, where we have the inode and the range locked, and bail
1402	 * out if that happened.
1403	 */
1404	search_start = page_start;
1405	while (search_start < page_end) {
1406		struct extent_map *em;
1407
1408		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, search_start,
1409				      page_end - search_start);
1410		if (IS_ERR(em)) {
1411			ret = PTR_ERR(em);
1412			goto out_unlock_range;
1413		}
1414		if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1415			free_extent_map(em);
1416			/* Ok, 0 means we did not defrag anything */
1417			ret = 0;
1418			goto out_unlock_range;
1419		}
1420		search_start = extent_map_end(em);
1421		free_extent_map(em);
1422	}
1423
1424	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1425			  page_end - 1, EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
1426			  EXTENT_DEFRAG, 0, 0, &cached_state);
1427
1428	if (i_done != page_cnt) {
1429		spin_lock(&BTRFS_I(inode)->lock);
1430		btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1431		spin_unlock(&BTRFS_I(inode)->lock);
1432		btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved,
1433				start, (page_cnt - i_done) << PAGE_SHIFT, true);
1434	}
1435
1436
1437	set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1438			  &cached_state);
1439
1440	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1441			     page_start, page_end - 1, &cached_state);
1442
1443	for (i = 0; i < i_done; i++) {
1444		clear_page_dirty_for_io(pages[i]);
1445		ClearPageChecked(pages[i]);
1446		set_page_extent_mapped(pages[i]);
1447		set_page_dirty(pages[i]);
1448		unlock_page(pages[i]);
1449		put_page(pages[i]);
1450	}
1451	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT);
1452	extent_changeset_free(data_reserved);
1453	return i_done;
1454
1455out_unlock_range:
1456	unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1457			     page_start, page_end - 1, &cached_state);
1458out:
1459	for (i = 0; i < i_done; i++) {
1460		unlock_page(pages[i]);
1461		put_page(pages[i]);
1462	}
1463	btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved,
1464			start, page_cnt << PAGE_SHIFT, true);
1465	btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT);
1466	extent_changeset_free(data_reserved);
1467	return ret;
1468
1469}
1470
1471int btrfs_defrag_file(struct inode *inode, struct file *file,
1472		      struct btrfs_ioctl_defrag_range_args *range,
1473		      u64 newer_than, unsigned long max_to_defrag)
1474{
1475	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1476	struct btrfs_root *root = BTRFS_I(inode)->root;
1477	struct file_ra_state *ra = NULL;
1478	unsigned long last_index;
1479	u64 isize = i_size_read(inode);
1480	u64 last_len = 0;
1481	u64 skip = 0;
1482	u64 defrag_end = 0;
1483	u64 newer_off = range->start;
1484	unsigned long i;
1485	unsigned long ra_index = 0;
1486	int ret;
1487	int defrag_count = 0;
1488	int compress_type = BTRFS_COMPRESS_ZLIB;
1489	u32 extent_thresh = range->extent_thresh;
1490	unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1491	unsigned long cluster = max_cluster;
1492	u64 new_align = ~((u64)SZ_128K - 1);
1493	struct page **pages = NULL;
1494	bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1495
1496	if (isize == 0)
1497		return 0;
1498
1499	if (range->start >= isize)
1500		return -EINVAL;
1501
1502	if (do_compress) {
1503		if (range->compress_type >= BTRFS_NR_COMPRESS_TYPES)
1504			return -EINVAL;
1505		if (range->compress_type)
1506			compress_type = range->compress_type;
1507	}
1508
1509	if (extent_thresh == 0)
1510		extent_thresh = SZ_256K;
1511
1512	/*
1513	 * If we were not given a file, allocate a readahead context. As
1514	 * readahead is just an optimization, defrag will work without it so
1515	 * we don't error out.
1516	 */
1517	if (!file) {
1518		ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1519		if (ra)
1520			file_ra_state_init(ra, inode->i_mapping);
1521	} else {
1522		ra = &file->f_ra;
1523	}
1524
1525	pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
1526	if (!pages) {
1527		ret = -ENOMEM;
1528		goto out_ra;
1529	}
1530
1531	/* find the last page to defrag */
1532	if (range->start + range->len > range->start) {
1533		last_index = min_t(u64, isize - 1,
1534			 range->start + range->len - 1) >> PAGE_SHIFT;
1535	} else {
1536		last_index = (isize - 1) >> PAGE_SHIFT;
1537	}
1538
1539	if (newer_than) {
1540		ret = find_new_extents(root, inode, newer_than,
1541				       &newer_off, SZ_64K);
1542		if (!ret) {
1543			range->start = newer_off;
1544			/*
1545			 * we always align our defrag to help keep
1546			 * the extents in the file evenly spaced
1547			 */
1548			i = (newer_off & new_align) >> PAGE_SHIFT;
1549		} else
1550			goto out_ra;
1551	} else {
1552		i = range->start >> PAGE_SHIFT;
1553	}
1554	if (!max_to_defrag)
1555		max_to_defrag = last_index - i + 1;
1556
1557	/*
1558	 * make writeback starts from i, so the defrag range can be
1559	 * written sequentially.
1560	 */
1561	if (i < inode->i_mapping->writeback_index)
1562		inode->i_mapping->writeback_index = i;
1563
1564	while (i <= last_index && defrag_count < max_to_defrag &&
1565	       (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
1566		/*
1567		 * make sure we stop running if someone unmounts
1568		 * the FS
1569		 */
1570		if (!(inode->i_sb->s_flags & SB_ACTIVE))
1571			break;
1572
1573		if (btrfs_defrag_cancelled(fs_info)) {
1574			btrfs_debug(fs_info, "defrag_file cancelled");
1575			ret = -EAGAIN;
1576			break;
1577		}
1578
1579		if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
1580					 extent_thresh, &last_len, &skip,
1581					 &defrag_end, do_compress)){
1582			unsigned long next;
1583			/*
1584			 * the should_defrag function tells us how much to skip
1585			 * bump our counter by the suggested amount
1586			 */
1587			next = DIV_ROUND_UP(skip, PAGE_SIZE);
1588			i = max(i + 1, next);
1589			continue;
1590		}
1591
1592		if (!newer_than) {
1593			cluster = (PAGE_ALIGN(defrag_end) >>
1594				   PAGE_SHIFT) - i;
1595			cluster = min(cluster, max_cluster);
1596		} else {
1597			cluster = max_cluster;
1598		}
1599
1600		if (i + cluster > ra_index) {
1601			ra_index = max(i, ra_index);
1602			if (ra)
1603				page_cache_sync_readahead(inode->i_mapping, ra,
1604						file, ra_index, cluster);
1605			ra_index += cluster;
1606		}
1607
1608		inode_lock(inode);
1609		if (IS_SWAPFILE(inode)) {
1610			ret = -ETXTBSY;
1611		} else {
1612			if (do_compress)
1613				BTRFS_I(inode)->defrag_compress = compress_type;
1614			ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1615		}
1616		if (ret < 0) {
1617			inode_unlock(inode);
1618			goto out_ra;
1619		}
1620
1621		defrag_count += ret;
1622		balance_dirty_pages_ratelimited(inode->i_mapping);
1623		inode_unlock(inode);
1624
1625		if (newer_than) {
1626			if (newer_off == (u64)-1)
1627				break;
1628
1629			if (ret > 0)
1630				i += ret;
1631
1632			newer_off = max(newer_off + 1,
1633					(u64)i << PAGE_SHIFT);
1634
1635			ret = find_new_extents(root, inode, newer_than,
1636					       &newer_off, SZ_64K);
1637			if (!ret) {
1638				range->start = newer_off;
1639				i = (newer_off & new_align) >> PAGE_SHIFT;
1640			} else {
1641				break;
1642			}
1643		} else {
1644			if (ret > 0) {
1645				i += ret;
1646				last_len += ret << PAGE_SHIFT;
1647			} else {
1648				i++;
1649				last_len = 0;
1650			}
1651		}
1652	}
1653
1654	if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1655		filemap_flush(inode->i_mapping);
1656		if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1657			     &BTRFS_I(inode)->runtime_flags))
1658			filemap_flush(inode->i_mapping);
1659	}
1660
1661	if (range->compress_type == BTRFS_COMPRESS_LZO) {
1662		btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1663	} else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
1664		btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1665	}
1666
1667	ret = defrag_count;
1668
1669out_ra:
1670	if (do_compress) {
1671		inode_lock(inode);
1672		BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1673		inode_unlock(inode);
1674	}
1675	if (!file)
1676		kfree(ra);
1677	kfree(pages);
1678	return ret;
1679}
1680
1681static noinline int btrfs_ioctl_resize(struct file *file,
1682					void __user *arg)
1683{
1684	struct inode *inode = file_inode(file);
1685	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1686	u64 new_size;
1687	u64 old_size;
1688	u64 devid = 1;
1689	struct btrfs_root *root = BTRFS_I(inode)->root;
1690	struct btrfs_ioctl_vol_args *vol_args;
1691	struct btrfs_trans_handle *trans;
1692	struct btrfs_device *device = NULL;
1693	char *sizestr;
1694	char *retptr;
1695	char *devstr = NULL;
1696	int ret = 0;
1697	int mod = 0;
1698
1699	if (!capable(CAP_SYS_ADMIN))
1700		return -EPERM;
1701
1702	ret = mnt_want_write_file(file);
1703	if (ret)
1704		return ret;
1705
1706	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_RESIZE)) {
1707		mnt_drop_write_file(file);
1708		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1709	}
1710
1711	vol_args = memdup_user(arg, sizeof(*vol_args));
1712	if (IS_ERR(vol_args)) {
1713		ret = PTR_ERR(vol_args);
1714		goto out;
1715	}
1716
1717	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1718
1719	sizestr = vol_args->name;
1720	devstr = strchr(sizestr, ':');
1721	if (devstr) {
1722		sizestr = devstr + 1;
1723		*devstr = '\0';
1724		devstr = vol_args->name;
1725		ret = kstrtoull(devstr, 10, &devid);
1726		if (ret)
1727			goto out_free;
1728		if (!devid) {
1729			ret = -EINVAL;
1730			goto out_free;
1731		}
1732		btrfs_info(fs_info, "resizing devid %llu", devid);
1733	}
1734
1735	device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
1736	if (!device) {
1737		btrfs_info(fs_info, "resizer unable to find device %llu",
1738			   devid);
1739		ret = -ENODEV;
1740		goto out_free;
1741	}
1742
1743	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1744		btrfs_info(fs_info,
1745			   "resizer unable to apply on readonly device %llu",
1746		       devid);
1747		ret = -EPERM;
1748		goto out_free;
1749	}
1750
1751	if (!strcmp(sizestr, "max"))
1752		new_size = device->bdev->bd_inode->i_size;
1753	else {
1754		if (sizestr[0] == '-') {
1755			mod = -1;
1756			sizestr++;
1757		} else if (sizestr[0] == '+') {
1758			mod = 1;
1759			sizestr++;
1760		}
1761		new_size = memparse(sizestr, &retptr);
1762		if (*retptr != '\0' || new_size == 0) {
1763			ret = -EINVAL;
1764			goto out_free;
1765		}
1766	}
1767
1768	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1769		ret = -EPERM;
1770		goto out_free;
1771	}
1772
1773	old_size = btrfs_device_get_total_bytes(device);
1774
1775	if (mod < 0) {
1776		if (new_size > old_size) {
1777			ret = -EINVAL;
1778			goto out_free;
1779		}
1780		new_size = old_size - new_size;
1781	} else if (mod > 0) {
1782		if (new_size > ULLONG_MAX - old_size) {
1783			ret = -ERANGE;
1784			goto out_free;
1785		}
1786		new_size = old_size + new_size;
1787	}
1788
1789	if (new_size < SZ_256M) {
1790		ret = -EINVAL;
1791		goto out_free;
1792	}
1793	if (new_size > device->bdev->bd_inode->i_size) {
1794		ret = -EFBIG;
1795		goto out_free;
1796	}
1797
1798	new_size = round_down(new_size, fs_info->sectorsize);
1799
1800	if (new_size > old_size) {
1801		trans = btrfs_start_transaction(root, 0);
1802		if (IS_ERR(trans)) {
1803			ret = PTR_ERR(trans);
1804			goto out_free;
1805		}
1806		ret = btrfs_grow_device(trans, device, new_size);
1807		btrfs_commit_transaction(trans);
1808	} else if (new_size < old_size) {
1809		ret = btrfs_shrink_device(device, new_size);
1810	} /* equal, nothing need to do */
1811
1812	if (ret == 0 && new_size != old_size)
1813		btrfs_info_in_rcu(fs_info,
1814			"resize device %s (devid %llu) from %llu to %llu",
1815			rcu_str_deref(device->name), device->devid,
1816			old_size, new_size);
1817out_free:
1818	kfree(vol_args);
1819out:
1820	btrfs_exclop_finish(fs_info);
1821	mnt_drop_write_file(file);
1822	return ret;
1823}
1824
1825static noinline int __btrfs_ioctl_snap_create(struct file *file,
1826				const char *name, unsigned long fd, int subvol,
1827				bool readonly,
1828				struct btrfs_qgroup_inherit *inherit)
1829{
1830	int namelen;
1831	int ret = 0;
1832
1833	if (!S_ISDIR(file_inode(file)->i_mode))
1834		return -ENOTDIR;
1835
1836	ret = mnt_want_write_file(file);
1837	if (ret)
1838		goto out;
1839
1840	namelen = strlen(name);
1841	if (strchr(name, '/')) {
1842		ret = -EINVAL;
1843		goto out_drop_write;
1844	}
1845
1846	if (name[0] == '.' &&
1847	   (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1848		ret = -EEXIST;
1849		goto out_drop_write;
1850	}
1851
1852	if (subvol) {
1853		ret = btrfs_mksubvol(&file->f_path, name, namelen,
1854				     NULL, readonly, inherit);
1855	} else {
1856		struct fd src = fdget(fd);
1857		struct inode *src_inode;
1858		if (!src.file) {
1859			ret = -EINVAL;
1860			goto out_drop_write;
1861		}
1862
1863		src_inode = file_inode(src.file);
1864		if (src_inode->i_sb != file_inode(file)->i_sb) {
1865			btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1866				   "Snapshot src from another FS");
1867			ret = -EXDEV;
1868		} else if (!inode_owner_or_capable(src_inode)) {
1869			/*
1870			 * Subvolume creation is not restricted, but snapshots
1871			 * are limited to own subvolumes only
1872			 */
1873			ret = -EPERM;
1874		} else if (btrfs_ino(BTRFS_I(src_inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1875			/*
1876			 * Snapshots must be made with the src_inode referring
1877			 * to the subvolume inode, otherwise the permission
1878			 * checking above is useless because we may have
1879			 * permission on a lower directory but not the subvol
1880			 * itself.
1881			 */
1882			ret = -EINVAL;
1883		} else {
1884			ret = btrfs_mksnapshot(&file->f_path, name, namelen,
1885					     BTRFS_I(src_inode)->root,
1886					     readonly, inherit);
1887		}
1888		fdput(src);
1889	}
1890out_drop_write:
1891	mnt_drop_write_file(file);
1892out:
1893	return ret;
1894}
1895
1896static noinline int btrfs_ioctl_snap_create(struct file *file,
1897					    void __user *arg, int subvol)
1898{
1899	struct btrfs_ioctl_vol_args *vol_args;
1900	int ret;
1901
1902	if (!S_ISDIR(file_inode(file)->i_mode))
1903		return -ENOTDIR;
1904
1905	vol_args = memdup_user(arg, sizeof(*vol_args));
1906	if (IS_ERR(vol_args))
1907		return PTR_ERR(vol_args);
1908	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1909
1910	ret = __btrfs_ioctl_snap_create(file, vol_args->name, vol_args->fd,
1911					subvol, false, NULL);
1912
1913	kfree(vol_args);
1914	return ret;
1915}
1916
1917static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1918					       void __user *arg, int subvol)
1919{
1920	struct btrfs_ioctl_vol_args_v2 *vol_args;
1921	int ret;
1922	bool readonly = false;
1923	struct btrfs_qgroup_inherit *inherit = NULL;
1924
1925	if (!S_ISDIR(file_inode(file)->i_mode))
1926		return -ENOTDIR;
1927
1928	vol_args = memdup_user(arg, sizeof(*vol_args));
1929	if (IS_ERR(vol_args))
1930		return PTR_ERR(vol_args);
1931	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1932
1933	if (vol_args->flags & ~BTRFS_SUBVOL_CREATE_ARGS_MASK) {
1934		ret = -EOPNOTSUPP;
1935		goto free_args;
1936	}
1937
1938	if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1939		readonly = true;
1940	if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1941		u64 nums;
1942
1943		if (vol_args->size < sizeof(*inherit) ||
1944		    vol_args->size > PAGE_SIZE) {
1945			ret = -EINVAL;
1946			goto free_args;
1947		}
1948		inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1949		if (IS_ERR(inherit)) {
1950			ret = PTR_ERR(inherit);
1951			goto free_args;
1952		}
1953
1954		if (inherit->num_qgroups > PAGE_SIZE ||
1955		    inherit->num_ref_copies > PAGE_SIZE ||
1956		    inherit->num_excl_copies > PAGE_SIZE) {
1957			ret = -EINVAL;
1958			goto free_inherit;
1959		}
1960
1961		nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
1962		       2 * inherit->num_excl_copies;
1963		if (vol_args->size != struct_size(inherit, qgroups, nums)) {
1964			ret = -EINVAL;
1965			goto free_inherit;
1966		}
1967	}
1968
1969	ret = __btrfs_ioctl_snap_create(file, vol_args->name, vol_args->fd,
1970					subvol, readonly, inherit);
1971	if (ret)
1972		goto free_inherit;
1973free_inherit:
1974	kfree(inherit);
1975free_args:
1976	kfree(vol_args);
1977	return ret;
1978}
1979
1980static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1981						void __user *arg)
1982{
1983	struct inode *inode = file_inode(file);
1984	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1985	struct btrfs_root *root = BTRFS_I(inode)->root;
1986	int ret = 0;
1987	u64 flags = 0;
1988
1989	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1990		return -EINVAL;
1991
1992	down_read(&fs_info->subvol_sem);
1993	if (btrfs_root_readonly(root))
1994		flags |= BTRFS_SUBVOL_RDONLY;
1995	up_read(&fs_info->subvol_sem);
1996
1997	if (copy_to_user(arg, &flags, sizeof(flags)))
1998		ret = -EFAULT;
1999
2000	return ret;
2001}
2002
2003static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
2004					      void __user *arg)
2005{
2006	struct inode *inode = file_inode(file);
2007	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2008	struct btrfs_root *root = BTRFS_I(inode)->root;
2009	struct btrfs_trans_handle *trans;
2010	u64 root_flags;
2011	u64 flags;
2012	int ret = 0;
2013
2014	if (!inode_owner_or_capable(inode))
2015		return -EPERM;
2016
2017	ret = mnt_want_write_file(file);
2018	if (ret)
2019		goto out;
2020
2021	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2022		ret = -EINVAL;
2023		goto out_drop_write;
2024	}
2025
2026	if (copy_from_user(&flags, arg, sizeof(flags))) {
2027		ret = -EFAULT;
2028		goto out_drop_write;
2029	}
2030
2031	if (flags & ~BTRFS_SUBVOL_RDONLY) {
2032		ret = -EOPNOTSUPP;
2033		goto out_drop_write;
2034	}
2035
2036	down_write(&fs_info->subvol_sem);
2037
2038	/* nothing to do */
2039	if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
2040		goto out_drop_sem;
2041
2042	root_flags = btrfs_root_flags(&root->root_item);
2043	if (flags & BTRFS_SUBVOL_RDONLY) {
2044		btrfs_set_root_flags(&root->root_item,
2045				     root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
2046	} else {
2047		/*
2048		 * Block RO -> RW transition if this subvolume is involved in
2049		 * send
2050		 */
2051		spin_lock(&root->root_item_lock);
2052		if (root->send_in_progress == 0) {
2053			btrfs_set_root_flags(&root->root_item,
2054				     root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
2055			spin_unlock(&root->root_item_lock);
2056		} else {
2057			spin_unlock(&root->root_item_lock);
2058			btrfs_warn(fs_info,
2059				   "Attempt to set subvolume %llu read-write during send",
2060				   root->root_key.objectid);
2061			ret = -EPERM;
2062			goto out_drop_sem;
2063		}
2064	}
2065
2066	trans = btrfs_start_transaction(root, 1);
2067	if (IS_ERR(trans)) {
2068		ret = PTR_ERR(trans);
2069		goto out_reset;
2070	}
2071
2072	ret = btrfs_update_root(trans, fs_info->tree_root,
2073				&root->root_key, &root->root_item);
2074	if (ret < 0) {
2075		btrfs_end_transaction(trans);
2076		goto out_reset;
2077	}
2078
2079	ret = btrfs_commit_transaction(trans);
2080
2081out_reset:
2082	if (ret)
2083		btrfs_set_root_flags(&root->root_item, root_flags);
2084out_drop_sem:
2085	up_write(&fs_info->subvol_sem);
2086out_drop_write:
2087	mnt_drop_write_file(file);
2088out:
2089	return ret;
2090}
2091
2092static noinline int key_in_sk(struct btrfs_key *key,
2093			      struct btrfs_ioctl_search_key *sk)
2094{
2095	struct btrfs_key test;
2096	int ret;
2097
2098	test.objectid = sk->min_objectid;
2099	test.type = sk->min_type;
2100	test.offset = sk->min_offset;
2101
2102	ret = btrfs_comp_cpu_keys(key, &test);
2103	if (ret < 0)
2104		return 0;
2105
2106	test.objectid = sk->max_objectid;
2107	test.type = sk->max_type;
2108	test.offset = sk->max_offset;
2109
2110	ret = btrfs_comp_cpu_keys(key, &test);
2111	if (ret > 0)
2112		return 0;
2113	return 1;
2114}
2115
2116static noinline int copy_to_sk(struct btrfs_path *path,
2117			       struct btrfs_key *key,
2118			       struct btrfs_ioctl_search_key *sk,
2119			       u64 *buf_size,
2120			       char __user *ubuf,
2121			       unsigned long *sk_offset,
2122			       int *num_found)
2123{
2124	u64 found_transid;
2125	struct extent_buffer *leaf;
2126	struct btrfs_ioctl_search_header sh;
2127	struct btrfs_key test;
2128	unsigned long item_off;
2129	unsigned long item_len;
2130	int nritems;
2131	int i;
2132	int slot;
2133	int ret = 0;
2134
2135	leaf = path->nodes[0];
2136	slot = path->slots[0];
2137	nritems = btrfs_header_nritems(leaf);
2138
2139	if (btrfs_header_generation(leaf) > sk->max_transid) {
2140		i = nritems;
2141		goto advance_key;
2142	}
2143	found_transid = btrfs_header_generation(leaf);
2144
2145	for (i = slot; i < nritems; i++) {
2146		item_off = btrfs_item_ptr_offset(leaf, i);
2147		item_len = btrfs_item_size_nr(leaf, i);
2148
2149		btrfs_item_key_to_cpu(leaf, key, i);
2150		if (!key_in_sk(key, sk))
2151			continue;
2152
2153		if (sizeof(sh) + item_len > *buf_size) {
2154			if (*num_found) {
2155				ret = 1;
2156				goto out;
2157			}
2158
2159			/*
2160			 * return one empty item back for v1, which does not
2161			 * handle -EOVERFLOW
2162			 */
2163
2164			*buf_size = sizeof(sh) + item_len;
2165			item_len = 0;
2166			ret = -EOVERFLOW;
2167		}
2168
2169		if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2170			ret = 1;
2171			goto out;
2172		}
2173
2174		sh.objectid = key->objectid;
2175		sh.offset = key->offset;
2176		sh.type = key->type;
2177		sh.len = item_len;
2178		sh.transid = found_transid;
2179
2180		/*
2181		 * Copy search result header. If we fault then loop again so we
2182		 * can fault in the pages and -EFAULT there if there's a
2183		 * problem. Otherwise we'll fault and then copy the buffer in
2184		 * properly this next time through
2185		 */
2186		if (copy_to_user_nofault(ubuf + *sk_offset, &sh, sizeof(sh))) {
2187			ret = 0;
2188			goto out;
2189		}
2190
2191		*sk_offset += sizeof(sh);
2192
2193		if (item_len) {
2194			char __user *up = ubuf + *sk_offset;
2195			/*
2196			 * Copy the item, same behavior as above, but reset the
2197			 * * sk_offset so we copy the full thing again.
2198			 */
2199			if (read_extent_buffer_to_user_nofault(leaf, up,
2200						item_off, item_len)) {
2201				ret = 0;
2202				*sk_offset -= sizeof(sh);
2203				goto out;
2204			}
2205
2206			*sk_offset += item_len;
2207		}
2208		(*num_found)++;
2209
2210		if (ret) /* -EOVERFLOW from above */
2211			goto out;
2212
2213		if (*num_found >= sk->nr_items) {
2214			ret = 1;
2215			goto out;
2216		}
2217	}
2218advance_key:
2219	ret = 0;
2220	test.objectid = sk->max_objectid;
2221	test.type = sk->max_type;
2222	test.offset = sk->max_offset;
2223	if (btrfs_comp_cpu_keys(key, &test) >= 0)
2224		ret = 1;
2225	else if (key->offset < (u64)-1)
2226		key->offset++;
2227	else if (key->type < (u8)-1) {
2228		key->offset = 0;
2229		key->type++;
2230	} else if (key->objectid < (u64)-1) {
2231		key->offset = 0;
2232		key->type = 0;
2233		key->objectid++;
2234	} else
2235		ret = 1;
2236out:
2237	/*
2238	 *  0: all items from this leaf copied, continue with next
2239	 *  1: * more items can be copied, but unused buffer is too small
2240	 *     * all items were found
2241	 *     Either way, it will stops the loop which iterates to the next
2242	 *     leaf
2243	 *  -EOVERFLOW: item was to large for buffer
2244	 *  -EFAULT: could not copy extent buffer back to userspace
2245	 */
2246	return ret;
2247}
2248
2249static noinline int search_ioctl(struct inode *inode,
2250				 struct btrfs_ioctl_search_key *sk,
2251				 u64 *buf_size,
2252				 char __user *ubuf)
2253{
2254	struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2255	struct btrfs_root *root;
2256	struct btrfs_key key;
2257	struct btrfs_path *path;
2258	int ret;
2259	int num_found = 0;
2260	unsigned long sk_offset = 0;
2261
2262	if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2263		*buf_size = sizeof(struct btrfs_ioctl_search_header);
2264		return -EOVERFLOW;
2265	}
2266
2267	path = btrfs_alloc_path();
2268	if (!path)
2269		return -ENOMEM;
2270
2271	if (sk->tree_id == 0) {
2272		/* search the root of the inode that was passed */
2273		root = btrfs_grab_root(BTRFS_I(inode)->root);
2274	} else {
2275		root = btrfs_get_fs_root(info, sk->tree_id, true);
2276		if (IS_ERR(root)) {
2277			btrfs_free_path(path);
2278			return PTR_ERR(root);
2279		}
2280	}
2281
2282	key.objectid = sk->min_objectid;
2283	key.type = sk->min_type;
2284	key.offset = sk->min_offset;
2285
2286	while (1) {
2287		ret = fault_in_pages_writeable(ubuf + sk_offset,
2288					       *buf_size - sk_offset);
2289		if (ret)
2290			break;
2291
2292		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2293		if (ret != 0) {
2294			if (ret > 0)
2295				ret = 0;
2296			goto err;
2297		}
2298		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2299				 &sk_offset, &num_found);
2300		btrfs_release_path(path);
2301		if (ret)
2302			break;
2303
2304	}
2305	if (ret > 0)
2306		ret = 0;
2307err:
2308	sk->nr_items = num_found;
2309	btrfs_put_root(root);
2310	btrfs_free_path(path);
2311	return ret;
2312}
2313
2314static noinline int btrfs_ioctl_tree_search(struct file *file,
2315					   void __user *argp)
2316{
2317	struct btrfs_ioctl_search_args __user *uargs;
2318	struct btrfs_ioctl_search_key sk;
2319	struct inode *inode;
2320	int ret;
2321	u64 buf_size;
2322
2323	if (!capable(CAP_SYS_ADMIN))
2324		return -EPERM;
2325
2326	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2327
2328	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2329		return -EFAULT;
2330
2331	buf_size = sizeof(uargs->buf);
2332
2333	inode = file_inode(file);
2334	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2335
2336	/*
2337	 * In the origin implementation an overflow is handled by returning a
2338	 * search header with a len of zero, so reset ret.
2339	 */
2340	if (ret == -EOVERFLOW)
2341		ret = 0;
2342
2343	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2344		ret = -EFAULT;
2345	return ret;
2346}
2347
2348static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2349					       void __user *argp)
2350{
2351	struct btrfs_ioctl_search_args_v2 __user *uarg;
2352	struct btrfs_ioctl_search_args_v2 args;
2353	struct inode *inode;
2354	int ret;
2355	u64 buf_size;
2356	const u64 buf_limit = SZ_16M;
2357
2358	if (!capable(CAP_SYS_ADMIN))
2359		return -EPERM;
2360
2361	/* copy search header and buffer size */
2362	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2363	if (copy_from_user(&args, uarg, sizeof(args)))
2364		return -EFAULT;
2365
2366	buf_size = args.buf_size;
2367
2368	/* limit result size to 16MB */
2369	if (buf_size > buf_limit)
2370		buf_size = buf_limit;
2371
2372	inode = file_inode(file);
2373	ret = search_ioctl(inode, &args.key, &buf_size,
2374			   (char __user *)(&uarg->buf[0]));
2375	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2376		ret = -EFAULT;
2377	else if (ret == -EOVERFLOW &&
2378		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2379		ret = -EFAULT;
2380
2381	return ret;
2382}
2383
2384/*
2385 * Search INODE_REFs to identify path name of 'dirid' directory
2386 * in a 'tree_id' tree. and sets path name to 'name'.
2387 */
2388static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2389				u64 tree_id, u64 dirid, char *name)
2390{
2391	struct btrfs_root *root;
2392	struct btrfs_key key;
2393	char *ptr;
2394	int ret = -1;
2395	int slot;
2396	int len;
2397	int total_len = 0;
2398	struct btrfs_inode_ref *iref;
2399	struct extent_buffer *l;
2400	struct btrfs_path *path;
2401
2402	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2403		name[0]='\0';
2404		return 0;
2405	}
2406
2407	path = btrfs_alloc_path();
2408	if (!path)
2409		return -ENOMEM;
2410
2411	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2412
2413	root = btrfs_get_fs_root(info, tree_id, true);
2414	if (IS_ERR(root)) {
2415		ret = PTR_ERR(root);
2416		root = NULL;
2417		goto out;
2418	}
2419
2420	key.objectid = dirid;
2421	key.type = BTRFS_INODE_REF_KEY;
2422	key.offset = (u64)-1;
2423
2424	while (1) {
2425		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2426		if (ret < 0)
2427			goto out;
2428		else if (ret > 0) {
2429			ret = btrfs_previous_item(root, path, dirid,
2430						  BTRFS_INODE_REF_KEY);
2431			if (ret < 0)
2432				goto out;
2433			else if (ret > 0) {
2434				ret = -ENOENT;
2435				goto out;
2436			}
2437		}
2438
2439		l = path->nodes[0];
2440		slot = path->slots[0];
2441		btrfs_item_key_to_cpu(l, &key, slot);
2442
2443		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2444		len = btrfs_inode_ref_name_len(l, iref);
2445		ptr -= len + 1;
2446		total_len += len + 1;
2447		if (ptr < name) {
2448			ret = -ENAMETOOLONG;
2449			goto out;
2450		}
2451
2452		*(ptr + len) = '/';
2453		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2454
2455		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2456			break;
2457
2458		btrfs_release_path(path);
2459		key.objectid = key.offset;
2460		key.offset = (u64)-1;
2461		dirid = key.objectid;
2462	}
2463	memmove(name, ptr, total_len);
2464	name[total_len] = '\0';
2465	ret = 0;
2466out:
2467	btrfs_put_root(root);
2468	btrfs_free_path(path);
2469	return ret;
2470}
2471
2472static int btrfs_search_path_in_tree_user(struct inode *inode,
2473				struct btrfs_ioctl_ino_lookup_user_args *args)
2474{
2475	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2476	struct super_block *sb = inode->i_sb;
2477	struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2478	u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2479	u64 dirid = args->dirid;
2480	unsigned long item_off;
2481	unsigned long item_len;
2482	struct btrfs_inode_ref *iref;
2483	struct btrfs_root_ref *rref;
2484	struct btrfs_root *root = NULL;
2485	struct btrfs_path *path;
2486	struct btrfs_key key, key2;
2487	struct extent_buffer *leaf;
2488	struct inode *temp_inode;
2489	char *ptr;
2490	int slot;
2491	int len;
2492	int total_len = 0;
2493	int ret;
2494
2495	path = btrfs_alloc_path();
2496	if (!path)
2497		return -ENOMEM;
2498
2499	/*
2500	 * If the bottom subvolume does not exist directly under upper_limit,
2501	 * construct the path in from the bottom up.
2502	 */
2503	if (dirid != upper_limit.objectid) {
2504		ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2505
2506		root = btrfs_get_fs_root(fs_info, treeid, true);
2507		if (IS_ERR(root)) {
2508			ret = PTR_ERR(root);
2509			goto out;
2510		}
2511
2512		key.objectid = dirid;
2513		key.type = BTRFS_INODE_REF_KEY;
2514		key.offset = (u64)-1;
2515		while (1) {
2516			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2517			if (ret < 0) {
2518				goto out_put;
2519			} else if (ret > 0) {
2520				ret = btrfs_previous_item(root, path, dirid,
2521							  BTRFS_INODE_REF_KEY);
2522				if (ret < 0) {
2523					goto out_put;
2524				} else if (ret > 0) {
2525					ret = -ENOENT;
2526					goto out_put;
2527				}
2528			}
2529
2530			leaf = path->nodes[0];
2531			slot = path->slots[0];
2532			btrfs_item_key_to_cpu(leaf, &key, slot);
2533
2534			iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2535			len = btrfs_inode_ref_name_len(leaf, iref);
2536			ptr -= len + 1;
2537			total_len += len + 1;
2538			if (ptr < args->path) {
2539				ret = -ENAMETOOLONG;
2540				goto out_put;
2541			}
2542
2543			*(ptr + len) = '/';
2544			read_extent_buffer(leaf, ptr,
2545					(unsigned long)(iref + 1), len);
2546
2547			/* Check the read+exec permission of this directory */
2548			ret = btrfs_previous_item(root, path, dirid,
2549						  BTRFS_INODE_ITEM_KEY);
2550			if (ret < 0) {
2551				goto out_put;
2552			} else if (ret > 0) {
2553				ret = -ENOENT;
2554				goto out_put;
2555			}
2556
2557			leaf = path->nodes[0];
2558			slot = path->slots[0];
2559			btrfs_item_key_to_cpu(leaf, &key2, slot);
2560			if (key2.objectid != dirid) {
2561				ret = -ENOENT;
2562				goto out_put;
2563			}
2564
2565			/*
2566			 * We don't need the path anymore, so release it and
2567			 * avoid deadlocks and lockdep warnings in case
2568			 * btrfs_iget() needs to lookup the inode from its root
2569			 * btree and lock the same leaf.
2570			 */
2571			btrfs_release_path(path);
2572			temp_inode = btrfs_iget(sb, key2.objectid, root);
2573			if (IS_ERR(temp_inode)) {
2574				ret = PTR_ERR(temp_inode);
2575				goto out_put;
2576			}
2577			ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC);
2578			iput(temp_inode);
2579			if (ret) {
2580				ret = -EACCES;
2581				goto out_put;
2582			}
2583
2584			if (key.offset == upper_limit.objectid)
2585				break;
2586			if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2587				ret = -EACCES;
2588				goto out_put;
2589			}
2590
2591			key.objectid = key.offset;
2592			key.offset = (u64)-1;
2593			dirid = key.objectid;
2594		}
2595
2596		memmove(args->path, ptr, total_len);
2597		args->path[total_len] = '\0';
2598		btrfs_put_root(root);
2599		root = NULL;
2600		btrfs_release_path(path);
2601	}
2602
2603	/* Get the bottom subvolume's name from ROOT_REF */
2604	key.objectid = treeid;
2605	key.type = BTRFS_ROOT_REF_KEY;
2606	key.offset = args->treeid;
2607	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2608	if (ret < 0) {
2609		goto out;
2610	} else if (ret > 0) {
2611		ret = -ENOENT;
2612		goto out;
2613	}
2614
2615	leaf = path->nodes[0];
2616	slot = path->slots[0];
2617	btrfs_item_key_to_cpu(leaf, &key, slot);
2618
2619	item_off = btrfs_item_ptr_offset(leaf, slot);
2620	item_len = btrfs_item_size_nr(leaf, slot);
2621	/* Check if dirid in ROOT_REF corresponds to passed dirid */
2622	rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2623	if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2624		ret = -EINVAL;
2625		goto out;
2626	}
2627
2628	/* Copy subvolume's name */
2629	item_off += sizeof(struct btrfs_root_ref);
2630	item_len -= sizeof(struct btrfs_root_ref);
2631	read_extent_buffer(leaf, args->name, item_off, item_len);
2632	args->name[item_len] = 0;
2633
2634out_put:
2635	btrfs_put_root(root);
2636out:
2637	btrfs_free_path(path);
2638	return ret;
2639}
2640
2641static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2642					   void __user *argp)
2643{
2644	struct btrfs_ioctl_ino_lookup_args *args;
2645	struct inode *inode;
2646	int ret = 0;
2647
2648	args = memdup_user(argp, sizeof(*args));
2649	if (IS_ERR(args))
2650		return PTR_ERR(args);
2651
2652	inode = file_inode(file);
2653
2654	/*
2655	 * Unprivileged query to obtain the containing subvolume root id. The
2656	 * path is reset so it's consistent with btrfs_search_path_in_tree.
2657	 */
2658	if (args->treeid == 0)
2659		args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2660
2661	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2662		args->name[0] = 0;
2663		goto out;
2664	}
2665
2666	if (!capable(CAP_SYS_ADMIN)) {
2667		ret = -EPERM;
2668		goto out;
2669	}
2670
2671	ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2672					args->treeid, args->objectid,
2673					args->name);
2674
2675out:
2676	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2677		ret = -EFAULT;
2678
2679	kfree(args);
2680	return ret;
2681}
2682
2683/*
2684 * Version of ino_lookup ioctl (unprivileged)
2685 *
2686 * The main differences from ino_lookup ioctl are:
2687 *
2688 *   1. Read + Exec permission will be checked using inode_permission() during
2689 *      path construction. -EACCES will be returned in case of failure.
2690 *   2. Path construction will be stopped at the inode number which corresponds
2691 *      to the fd with which this ioctl is called. If constructed path does not
2692 *      exist under fd's inode, -EACCES will be returned.
2693 *   3. The name of bottom subvolume is also searched and filled.
2694 */
2695static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2696{
2697	struct btrfs_ioctl_ino_lookup_user_args *args;
2698	struct inode *inode;
2699	int ret;
2700
2701	args = memdup_user(argp, sizeof(*args));
2702	if (IS_ERR(args))
2703		return PTR_ERR(args);
2704
2705	inode = file_inode(file);
2706
2707	if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2708	    BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2709		/*
2710		 * The subvolume does not exist under fd with which this is
2711		 * called
2712		 */
2713		kfree(args);
2714		return -EACCES;
2715	}
2716
2717	ret = btrfs_search_path_in_tree_user(inode, args);
2718
2719	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2720		ret = -EFAULT;
2721
2722	kfree(args);
2723	return ret;
2724}
2725
2726/* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2727static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2728{
2729	struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2730	struct btrfs_fs_info *fs_info;
2731	struct btrfs_root *root;
2732	struct btrfs_path *path;
2733	struct btrfs_key key;
2734	struct btrfs_root_item *root_item;
2735	struct btrfs_root_ref *rref;
2736	struct extent_buffer *leaf;
2737	unsigned long item_off;
2738	unsigned long item_len;
2739	struct inode *inode;
2740	int slot;
2741	int ret = 0;
2742
2743	path = btrfs_alloc_path();
2744	if (!path)
2745		return -ENOMEM;
2746
2747	subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2748	if (!subvol_info) {
2749		btrfs_free_path(path);
2750		return -ENOMEM;
2751	}
2752
2753	inode = file_inode(file);
2754	fs_info = BTRFS_I(inode)->root->fs_info;
2755
2756	/* Get root_item of inode's subvolume */
2757	key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2758	root = btrfs_get_fs_root(fs_info, key.objectid, true);
2759	if (IS_ERR(root)) {
2760		ret = PTR_ERR(root);
2761		goto out_free;
2762	}
2763	root_item = &root->root_item;
2764
2765	subvol_info->treeid = key.objectid;
2766
2767	subvol_info->generation = btrfs_root_generation(root_item);
2768	subvol_info->flags = btrfs_root_flags(root_item);
2769
2770	memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2771	memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2772						    BTRFS_UUID_SIZE);
2773	memcpy(subvol_info->received_uuid, root_item->received_uuid,
2774						    BTRFS_UUID_SIZE);
2775
2776	subvol_info->ctransid = btrfs_root_ctransid(root_item);
2777	subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2778	subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2779
2780	subvol_info->otransid = btrfs_root_otransid(root_item);
2781	subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2782	subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2783
2784	subvol_info->stransid = btrfs_root_stransid(root_item);
2785	subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2786	subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2787
2788	subvol_info->rtransid = btrfs_root_rtransid(root_item);
2789	subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2790	subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2791
2792	if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2793		/* Search root tree for ROOT_BACKREF of this subvolume */
2794		key.type = BTRFS_ROOT_BACKREF_KEY;
2795		key.offset = 0;
2796		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2797		if (ret < 0) {
2798			goto out;
2799		} else if (path->slots[0] >=
2800			   btrfs_header_nritems(path->nodes[0])) {
2801			ret = btrfs_next_leaf(fs_info->tree_root, path);
2802			if (ret < 0) {
2803				goto out;
2804			} else if (ret > 0) {
2805				ret = -EUCLEAN;
2806				goto out;
2807			}
2808		}
2809
2810		leaf = path->nodes[0];
2811		slot = path->slots[0];
2812		btrfs_item_key_to_cpu(leaf, &key, slot);
2813		if (key.objectid == subvol_info->treeid &&
2814		    key.type == BTRFS_ROOT_BACKREF_KEY) {
2815			subvol_info->parent_id = key.offset;
2816
2817			rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2818			subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2819
2820			item_off = btrfs_item_ptr_offset(leaf, slot)
2821					+ sizeof(struct btrfs_root_ref);
2822			item_len = btrfs_item_size_nr(leaf, slot)
2823					- sizeof(struct btrfs_root_ref);
2824			read_extent_buffer(leaf, subvol_info->name,
2825					   item_off, item_len);
2826		} else {
2827			ret = -ENOENT;
2828			goto out;
2829		}
2830	}
2831
2832	btrfs_free_path(path);
2833	path = NULL;
2834	if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2835		ret = -EFAULT;
2836
2837out:
2838	btrfs_put_root(root);
2839out_free:
2840	btrfs_free_path(path);
2841	kfree(subvol_info);
2842	return ret;
2843}
2844
2845/*
2846 * Return ROOT_REF information of the subvolume containing this inode
2847 * except the subvolume name.
2848 */
2849static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
2850{
2851	struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
2852	struct btrfs_root_ref *rref;
2853	struct btrfs_root *root;
2854	struct btrfs_path *path;
2855	struct btrfs_key key;
2856	struct extent_buffer *leaf;
2857	struct inode *inode;
2858	u64 objectid;
2859	int slot;
2860	int ret;
2861	u8 found;
2862
2863	path = btrfs_alloc_path();
2864	if (!path)
2865		return -ENOMEM;
2866
2867	rootrefs = memdup_user(argp, sizeof(*rootrefs));
2868	if (IS_ERR(rootrefs)) {
2869		btrfs_free_path(path);
2870		return PTR_ERR(rootrefs);
2871	}
2872
2873	inode = file_inode(file);
2874	root = BTRFS_I(inode)->root->fs_info->tree_root;
2875	objectid = BTRFS_I(inode)->root->root_key.objectid;
2876
2877	key.objectid = objectid;
2878	key.type = BTRFS_ROOT_REF_KEY;
2879	key.offset = rootrefs->min_treeid;
2880	found = 0;
2881
2882	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2883	if (ret < 0) {
2884		goto out;
2885	} else if (path->slots[0] >=
2886		   btrfs_header_nritems(path->nodes[0])) {
2887		ret = btrfs_next_leaf(root, path);
2888		if (ret < 0) {
2889			goto out;
2890		} else if (ret > 0) {
2891			ret = -EUCLEAN;
2892			goto out;
2893		}
2894	}
2895	while (1) {
2896		leaf = path->nodes[0];
2897		slot = path->slots[0];
2898
2899		btrfs_item_key_to_cpu(leaf, &key, slot);
2900		if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
2901			ret = 0;
2902			goto out;
2903		}
2904
2905		if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
2906			ret = -EOVERFLOW;
2907			goto out;
2908		}
2909
2910		rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2911		rootrefs->rootref[found].treeid = key.offset;
2912		rootrefs->rootref[found].dirid =
2913				  btrfs_root_ref_dirid(leaf, rref);
2914		found++;
2915
2916		ret = btrfs_next_item(root, path);
2917		if (ret < 0) {
2918			goto out;
2919		} else if (ret > 0) {
2920			ret = -EUCLEAN;
2921			goto out;
2922		}
2923	}
2924
2925out:
2926	btrfs_free_path(path);
2927
2928	if (!ret || ret == -EOVERFLOW) {
2929		rootrefs->num_items = found;
2930		/* update min_treeid for next search */
2931		if (found)
2932			rootrefs->min_treeid =
2933				rootrefs->rootref[found - 1].treeid + 1;
2934		if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
2935			ret = -EFAULT;
2936	}
2937
2938	kfree(rootrefs);
2939
2940	return ret;
2941}
2942
2943static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2944					     void __user *arg,
2945					     bool destroy_v2)
2946{
2947	struct dentry *parent = file->f_path.dentry;
2948	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2949	struct dentry *dentry;
2950	struct inode *dir = d_inode(parent);
2951	struct inode *inode;
2952	struct btrfs_root *root = BTRFS_I(dir)->root;
2953	struct btrfs_root *dest = NULL;
2954	struct btrfs_ioctl_vol_args *vol_args = NULL;
2955	struct btrfs_ioctl_vol_args_v2 *vol_args2 = NULL;
2956	char *subvol_name, *subvol_name_ptr = NULL;
2957	int subvol_namelen;
2958	int err = 0;
2959	bool destroy_parent = false;
2960
2961	if (destroy_v2) {
2962		vol_args2 = memdup_user(arg, sizeof(*vol_args2));
2963		if (IS_ERR(vol_args2))
2964			return PTR_ERR(vol_args2);
2965
2966		if (vol_args2->flags & ~BTRFS_SUBVOL_DELETE_ARGS_MASK) {
2967			err = -EOPNOTSUPP;
2968			goto out;
2969		}
2970
2971		/*
2972		 * If SPEC_BY_ID is not set, we are looking for the subvolume by
2973		 * name, same as v1 currently does.
2974		 */
2975		if (!(vol_args2->flags & BTRFS_SUBVOL_SPEC_BY_ID)) {
2976			vol_args2->name[BTRFS_SUBVOL_NAME_MAX] = 0;
2977			subvol_name = vol_args2->name;
2978
2979			err = mnt_want_write_file(file);
2980			if (err)
2981				goto out;
2982		} else {
2983			if (vol_args2->subvolid < BTRFS_FIRST_FREE_OBJECTID) {
2984				err = -EINVAL;
2985				goto out;
2986			}
2987
2988			err = mnt_want_write_file(file);
2989			if (err)
2990				goto out;
2991
2992			dentry = btrfs_get_dentry(fs_info->sb,
2993					BTRFS_FIRST_FREE_OBJECTID,
2994					vol_args2->subvolid, 0, 0);
2995			if (IS_ERR(dentry)) {
2996				err = PTR_ERR(dentry);
2997				goto out_drop_write;
2998			}
2999
3000			/*
3001			 * Change the default parent since the subvolume being
3002			 * deleted can be outside of the current mount point.
3003			 */
3004			parent = btrfs_get_parent(dentry);
3005
3006			/*
3007			 * At this point dentry->d_name can point to '/' if the
3008			 * subvolume we want to destroy is outsite of the
3009			 * current mount point, so we need to release the
3010			 * current dentry and execute the lookup to return a new
3011			 * one with ->d_name pointing to the
3012			 * <mount point>/subvol_name.
3013			 */
3014			dput(dentry);
3015			if (IS_ERR(parent)) {
3016				err = PTR_ERR(parent);
3017				goto out_drop_write;
3018			}
3019			dir = d_inode(parent);
3020
3021			/*
3022			 * If v2 was used with SPEC_BY_ID, a new parent was
3023			 * allocated since the subvolume can be outside of the
3024			 * current mount point. Later on we need to release this
3025			 * new parent dentry.
3026			 */
3027			destroy_parent = true;
3028
3029			subvol_name_ptr = btrfs_get_subvol_name_from_objectid(
3030						fs_info, vol_args2->subvolid);
3031			if (IS_ERR(subvol_name_ptr)) {
3032				err = PTR_ERR(subvol_name_ptr);
3033				goto free_parent;
3034			}
3035			/* subvol_name_ptr is already NULL termined */
3036			subvol_name = (char *)kbasename(subvol_name_ptr);
3037		}
3038	} else {
3039		vol_args = memdup_user(arg, sizeof(*vol_args));
3040		if (IS_ERR(vol_args))
3041			return PTR_ERR(vol_args);
3042
3043		vol_args->name[BTRFS_PATH_NAME_MAX] = 0;
3044		subvol_name = vol_args->name;
3045
3046		err = mnt_want_write_file(file);
3047		if (err)
3048			goto out;
3049	}
3050
3051	subvol_namelen = strlen(subvol_name);
3052
3053	if (strchr(subvol_name, '/') ||
3054	    strncmp(subvol_name, "..", subvol_namelen) == 0) {
3055		err = -EINVAL;
3056		goto free_subvol_name;
3057	}
3058
3059	if (!S_ISDIR(dir->i_mode)) {
3060		err = -ENOTDIR;
3061		goto free_subvol_name;
3062	}
3063
3064	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
3065	if (err == -EINTR)
3066		goto free_subvol_name;
3067	dentry = lookup_one_len(subvol_name, parent, subvol_namelen);
3068	if (IS_ERR(dentry)) {
3069		err = PTR_ERR(dentry);
3070		goto out_unlock_dir;
3071	}
3072
3073	if (d_really_is_negative(dentry)) {
3074		err = -ENOENT;
3075		goto out_dput;
3076	}
3077
3078	inode = d_inode(dentry);
3079	dest = BTRFS_I(inode)->root;
3080	if (!capable(CAP_SYS_ADMIN)) {
3081		/*
3082		 * Regular user.  Only allow this with a special mount
3083		 * option, when the user has write+exec access to the
3084		 * subvol root, and when rmdir(2) would have been
3085		 * allowed.
3086		 *
3087		 * Note that this is _not_ check that the subvol is
3088		 * empty or doesn't contain data that we wouldn't
3089		 * otherwise be able to delete.
3090		 *
3091		 * Users who want to delete empty subvols should try
3092		 * rmdir(2).
3093		 */
3094		err = -EPERM;
3095		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
3096			goto out_dput;
3097
3098		/*
3099		 * Do not allow deletion if the parent dir is the same
3100		 * as the dir to be deleted.  That means the ioctl
3101		 * must be called on the dentry referencing the root
3102		 * of the subvol, not a random directory contained
3103		 * within it.
3104		 */
3105		err = -EINVAL;
3106		if (root == dest)
3107			goto out_dput;
3108
3109		err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
3110		if (err)
3111			goto out_dput;
3112	}
3113
3114	/* check if subvolume may be deleted by a user */
3115	err = btrfs_may_delete(dir, dentry, 1);
3116	if (err)
3117		goto out_dput;
3118
3119	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
3120		err = -EINVAL;
3121		goto out_dput;
3122	}
3123
3124	inode_lock(inode);
3125	err = btrfs_delete_subvolume(dir, dentry);
3126	inode_unlock(inode);
3127	if (!err)
3128		d_delete_notify(dir, dentry);
3129
3130out_dput:
3131	dput(dentry);
3132out_unlock_dir:
3133	inode_unlock(dir);
3134free_subvol_name:
3135	kfree(subvol_name_ptr);
3136free_parent:
3137	if (destroy_parent)
3138		dput(parent);
3139out_drop_write:
3140	mnt_drop_write_file(file);
3141out:
3142	kfree(vol_args2);
3143	kfree(vol_args);
3144	return err;
3145}
3146
3147static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
3148{
3149	struct inode *inode = file_inode(file);
3150	struct btrfs_root *root = BTRFS_I(inode)->root;
3151	struct btrfs_ioctl_defrag_range_args *range;
3152	int ret;
3153
3154	ret = mnt_want_write_file(file);
3155	if (ret)
3156		return ret;
3157
3158	if (btrfs_root_readonly(root)) {
3159		ret = -EROFS;
3160		goto out;
3161	}
3162
3163	switch (inode->i_mode & S_IFMT) {
3164	case S_IFDIR:
3165		if (!capable(CAP_SYS_ADMIN)) {
3166			ret = -EPERM;
3167			goto out;
3168		}
3169		ret = btrfs_defrag_root(root);
3170		break;
3171	case S_IFREG:
3172		/*
3173		 * Note that this does not check the file descriptor for write
3174		 * access. This prevents defragmenting executables that are
3175		 * running and allows defrag on files open in read-only mode.
3176		 */
3177		if (!capable(CAP_SYS_ADMIN) &&
3178		    inode_permission(inode, MAY_WRITE)) {
3179			ret = -EPERM;
3180			goto out;
3181		}
3182
3183		range = kzalloc(sizeof(*range), GFP_KERNEL);
3184		if (!range) {
3185			ret = -ENOMEM;
3186			goto out;
3187		}
3188
3189		if (argp) {
3190			if (copy_from_user(range, argp,
3191					   sizeof(*range))) {
3192				ret = -EFAULT;
3193				kfree(range);
3194				goto out;
3195			}
3196			if (range->flags & ~BTRFS_DEFRAG_RANGE_FLAGS_SUPP) {
3197				ret = -EOPNOTSUPP;
3198				goto out;
3199			}
3200			/* compression requires us to start the IO */
3201			if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3202				range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
3203				range->extent_thresh = (u32)-1;
3204			}
3205		} else {
3206			/* the rest are all set to zero by kzalloc */
3207			range->len = (u64)-1;
3208		}
3209		ret = btrfs_defrag_file(file_inode(file), file,
3210					range, BTRFS_OLDEST_GENERATION, 0);
3211		if (ret > 0)
3212			ret = 0;
3213		kfree(range);
3214		break;
3215	default:
3216		ret = -EINVAL;
3217	}
3218out:
3219	mnt_drop_write_file(file);
3220	return ret;
3221}
3222
3223static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3224{
3225	struct btrfs_ioctl_vol_args *vol_args;
3226	int ret;
3227
3228	if (!capable(CAP_SYS_ADMIN))
3229		return -EPERM;
3230
3231	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_ADD))
3232		return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3233
3234	vol_args = memdup_user(arg, sizeof(*vol_args));
3235	if (IS_ERR(vol_args)) {
3236		ret = PTR_ERR(vol_args);
3237		goto out;
3238	}
3239
3240	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3241	ret = btrfs_init_new_device(fs_info, vol_args->name);
3242
3243	if (!ret)
3244		btrfs_info(fs_info, "disk added %s", vol_args->name);
3245
3246	kfree(vol_args);
3247out:
3248	btrfs_exclop_finish(fs_info);
3249	return ret;
3250}
3251
3252static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3253{
3254	struct inode *inode = file_inode(file);
3255	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3256	struct btrfs_ioctl_vol_args_v2 *vol_args;
3257	int ret;
3258
3259	if (!capable(CAP_SYS_ADMIN))
3260		return -EPERM;
3261
3262	ret = mnt_want_write_file(file);
3263	if (ret)
3264		return ret;
3265
3266	vol_args = memdup_user(arg, sizeof(*vol_args));
3267	if (IS_ERR(vol_args)) {
3268		ret = PTR_ERR(vol_args);
3269		goto err_drop;
3270	}
3271
3272	if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
3273		ret = -EOPNOTSUPP;
3274		goto out;
3275	}
3276
3277	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REMOVE)) {
3278		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3279		goto out;
3280	}
3281
3282	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3283		ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
3284	} else {
3285		vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3286		ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3287	}
3288	btrfs_exclop_finish(fs_info);
3289
3290	if (!ret) {
3291		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3292			btrfs_info(fs_info, "device deleted: id %llu",
3293					vol_args->devid);
3294		else
3295			btrfs_info(fs_info, "device deleted: %s",
3296					vol_args->name);
3297	}
3298out:
3299	kfree(vol_args);
3300err_drop:
3301	mnt_drop_write_file(file);
3302	return ret;
3303}
3304
3305static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3306{
3307	struct inode *inode = file_inode(file);
3308	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3309	struct btrfs_ioctl_vol_args *vol_args;
3310	int ret;
3311
3312	if (!capable(CAP_SYS_ADMIN))
3313		return -EPERM;
3314
3315	ret = mnt_want_write_file(file);
3316	if (ret)
3317		return ret;
3318
3319	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REMOVE)) {
3320		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3321		goto out_drop_write;
3322	}
3323
3324	vol_args = memdup_user(arg, sizeof(*vol_args));
3325	if (IS_ERR(vol_args)) {
3326		ret = PTR_ERR(vol_args);
3327		goto out;
3328	}
3329
3330	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3331	ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3332
3333	if (!ret)
3334		btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3335	kfree(vol_args);
3336out:
3337	btrfs_exclop_finish(fs_info);
3338out_drop_write:
3339	mnt_drop_write_file(file);
3340
3341	return ret;
3342}
3343
3344static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3345				void __user *arg)
3346{
3347	struct btrfs_ioctl_fs_info_args *fi_args;
3348	struct btrfs_device *device;
3349	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3350	u64 flags_in;
3351	int ret = 0;
3352
3353	fi_args = memdup_user(arg, sizeof(*fi_args));
3354	if (IS_ERR(fi_args))
3355		return PTR_ERR(fi_args);
3356
3357	flags_in = fi_args->flags;
3358	memset(fi_args, 0, sizeof(*fi_args));
3359
3360	rcu_read_lock();
3361	fi_args->num_devices = fs_devices->num_devices;
3362
3363	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3364		if (device->devid > fi_args->max_id)
3365			fi_args->max_id = device->devid;
3366	}
3367	rcu_read_unlock();
3368
3369	memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3370	fi_args->nodesize = fs_info->nodesize;
3371	fi_args->sectorsize = fs_info->sectorsize;
3372	fi_args->clone_alignment = fs_info->sectorsize;
3373
3374	if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3375		fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3376		fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3377		fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3378	}
3379
3380	if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
3381		fi_args->generation = fs_info->generation;
3382		fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
3383	}
3384
3385	if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
3386		memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
3387		       sizeof(fi_args->metadata_uuid));
3388		fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
3389	}
3390
3391	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3392		ret = -EFAULT;
3393
3394	kfree(fi_args);
3395	return ret;
3396}
3397
3398static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3399				 void __user *arg)
3400{
3401	struct btrfs_ioctl_dev_info_args *di_args;
3402	struct btrfs_device *dev;
3403	int ret = 0;
3404	char *s_uuid = NULL;
3405
3406	di_args = memdup_user(arg, sizeof(*di_args));
3407	if (IS_ERR(di_args))
3408		return PTR_ERR(di_args);
3409
3410	if (!btrfs_is_empty_uuid(di_args->uuid))
3411		s_uuid = di_args->uuid;
3412
3413	rcu_read_lock();
3414	dev = btrfs_find_device(fs_info->fs_devices, di_args->devid, s_uuid,
3415				NULL, true);
3416
3417	if (!dev) {
3418		ret = -ENODEV;
3419		goto out;
3420	}
3421
3422	di_args->devid = dev->devid;
3423	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3424	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3425	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3426	if (dev->name)
3427		strscpy(di_args->path, rcu_str_deref(dev->name), sizeof(di_args->path));
3428	else
3429		di_args->path[0] = '\0';
3430
3431out:
3432	rcu_read_unlock();
3433	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3434		ret = -EFAULT;
3435
3436	kfree(di_args);
3437	return ret;
3438}
3439
3440static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3441{
3442	struct inode *inode = file_inode(file);
3443	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3444	struct btrfs_root *root = BTRFS_I(inode)->root;
3445	struct btrfs_root *new_root;
3446	struct btrfs_dir_item *di;
3447	struct btrfs_trans_handle *trans;
3448	struct btrfs_path *path = NULL;
3449	struct btrfs_disk_key disk_key;
3450	u64 objectid = 0;
3451	u64 dir_id;
3452	int ret;
3453
3454	if (!capable(CAP_SYS_ADMIN))
3455		return -EPERM;
3456
3457	ret = mnt_want_write_file(file);
3458	if (ret)
3459		return ret;
3460
3461	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3462		ret = -EFAULT;
3463		goto out;
3464	}
3465
3466	if (!objectid)
3467		objectid = BTRFS_FS_TREE_OBJECTID;
3468
3469	new_root = btrfs_get_fs_root(fs_info, objectid, true);
3470	if (IS_ERR(new_root)) {
3471		ret = PTR_ERR(new_root);
3472		goto out;
3473	}
3474	if (!is_fstree(new_root->root_key.objectid)) {
3475		ret = -ENOENT;
3476		goto out_free;
3477	}
3478
3479	path = btrfs_alloc_path();
3480	if (!path) {
3481		ret = -ENOMEM;
3482		goto out_free;
3483	}
3484	path->leave_spinning = 1;
3485
3486	trans = btrfs_start_transaction(root, 1);
3487	if (IS_ERR(trans)) {
3488		ret = PTR_ERR(trans);
3489		goto out_free;
3490	}
3491
3492	dir_id = btrfs_super_root_dir(fs_info->super_copy);
3493	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
3494				   dir_id, "default", 7, 1);
3495	if (IS_ERR_OR_NULL(di)) {
3496		btrfs_release_path(path);
3497		btrfs_end_transaction(trans);
3498		btrfs_err(fs_info,
3499			  "Umm, you don't have the default diritem, this isn't going to work");
3500		ret = -ENOENT;
3501		goto out_free;
3502	}
3503
3504	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3505	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3506	btrfs_mark_buffer_dirty(path->nodes[0]);
3507	btrfs_release_path(path);
3508
3509	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
3510	btrfs_end_transaction(trans);
3511out_free:
3512	btrfs_put_root(new_root);
3513	btrfs_free_path(path);
3514out:
3515	mnt_drop_write_file(file);
3516	return ret;
3517}
3518
3519static void get_block_group_info(struct list_head *groups_list,
3520				 struct btrfs_ioctl_space_info *space)
3521{
3522	struct btrfs_block_group *block_group;
3523
3524	space->total_bytes = 0;
3525	space->used_bytes = 0;
3526	space->flags = 0;
3527	list_for_each_entry(block_group, groups_list, list) {
3528		space->flags = block_group->flags;
3529		space->total_bytes += block_group->length;
3530		space->used_bytes += block_group->used;
3531	}
3532}
3533
3534static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
3535				   void __user *arg)
3536{
3537	struct btrfs_ioctl_space_args space_args = { 0 };
3538	struct btrfs_ioctl_space_info space;
3539	struct btrfs_ioctl_space_info *dest;
3540	struct btrfs_ioctl_space_info *dest_orig;
3541	struct btrfs_ioctl_space_info __user *user_dest;
3542	struct btrfs_space_info *info;
3543	static const u64 types[] = {
3544		BTRFS_BLOCK_GROUP_DATA,
3545		BTRFS_BLOCK_GROUP_SYSTEM,
3546		BTRFS_BLOCK_GROUP_METADATA,
3547		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3548	};
3549	int num_types = 4;
3550	int alloc_size;
3551	int ret = 0;
3552	u64 slot_count = 0;
3553	int i, c;
3554
3555	if (copy_from_user(&space_args,
3556			   (struct btrfs_ioctl_space_args __user *)arg,
3557			   sizeof(space_args)))
3558		return -EFAULT;
3559
3560	for (i = 0; i < num_types; i++) {
3561		struct btrfs_space_info *tmp;
3562
3563		info = NULL;
3564		list_for_each_entry(tmp, &fs_info->space_info, list) {
3565			if (tmp->flags == types[i]) {
3566				info = tmp;
3567				break;
3568			}
3569		}
3570
3571		if (!info)
3572			continue;
3573
3574		down_read(&info->groups_sem);
3575		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3576			if (!list_empty(&info->block_groups[c]))
3577				slot_count++;
3578		}
3579		up_read(&info->groups_sem);
3580	}
3581
3582	/*
3583	 * Global block reserve, exported as a space_info
3584	 */
3585	slot_count++;
3586
3587	/* space_slots == 0 means they are asking for a count */
3588	if (space_args.space_slots == 0) {
3589		space_args.total_spaces = slot_count;
3590		goto out;
3591	}
3592
3593	slot_count = min_t(u64, space_args.space_slots, slot_count);
3594
3595	alloc_size = sizeof(*dest) * slot_count;
3596
3597	/* we generally have at most 6 or so space infos, one for each raid
3598	 * level.  So, a whole page should be more than enough for everyone
3599	 */
3600	if (alloc_size > PAGE_SIZE)
3601		return -ENOMEM;
3602
3603	space_args.total_spaces = 0;
3604	dest = kmalloc(alloc_size, GFP_KERNEL);
3605	if (!dest)
3606		return -ENOMEM;
3607	dest_orig = dest;
3608
3609	/* now we have a buffer to copy into */
3610	for (i = 0; i < num_types; i++) {
3611		struct btrfs_space_info *tmp;
3612
3613		if (!slot_count)
3614			break;
3615
3616		info = NULL;
3617		list_for_each_entry(tmp, &fs_info->space_info, list) {
3618			if (tmp->flags == types[i]) {
3619				info = tmp;
3620				break;
3621			}
3622		}
3623
3624		if (!info)
3625			continue;
3626		down_read(&info->groups_sem);
3627		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3628			if (!list_empty(&info->block_groups[c])) {
3629				get_block_group_info(&info->block_groups[c],
3630						     &space);
3631				memcpy(dest, &space, sizeof(space));
3632				dest++;
3633				space_args.total_spaces++;
3634				slot_count--;
3635			}
3636			if (!slot_count)
3637				break;
3638		}
3639		up_read(&info->groups_sem);
3640	}
3641
3642	/*
3643	 * Add global block reserve
3644	 */
3645	if (slot_count) {
3646		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3647
3648		spin_lock(&block_rsv->lock);
3649		space.total_bytes = block_rsv->size;
3650		space.used_bytes = block_rsv->size - block_rsv->reserved;
3651		spin_unlock(&block_rsv->lock);
3652		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
3653		memcpy(dest, &space, sizeof(space));
3654		space_args.total_spaces++;
3655	}
3656
3657	user_dest = (struct btrfs_ioctl_space_info __user *)
3658		(arg + sizeof(struct btrfs_ioctl_space_args));
3659
3660	if (copy_to_user(user_dest, dest_orig, alloc_size))
3661		ret = -EFAULT;
3662
3663	kfree(dest_orig);
3664out:
3665	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3666		ret = -EFAULT;
3667
3668	return ret;
3669}
3670
3671static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3672					    void __user *argp)
3673{
3674	struct btrfs_trans_handle *trans;
3675	u64 transid;
3676	int ret;
3677
3678	trans = btrfs_attach_transaction_barrier(root);
3679	if (IS_ERR(trans)) {
3680		if (PTR_ERR(trans) != -ENOENT)
3681			return PTR_ERR(trans);
3682
3683		/* No running transaction, don't bother */
3684		transid = root->fs_info->last_trans_committed;
3685		goto out;
3686	}
3687	transid = trans->transid;
3688	ret = btrfs_commit_transaction_async(trans, 0);
3689	if (ret) {
3690		btrfs_end_transaction(trans);
3691		return ret;
3692	}
3693out:
3694	if (argp)
3695		if (copy_to_user(argp, &transid, sizeof(transid)))
3696			return -EFAULT;
3697	return 0;
3698}
3699
3700static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
3701					   void __user *argp)
3702{
3703	u64 transid;
3704
3705	if (argp) {
3706		if (copy_from_user(&transid, argp, sizeof(transid)))
3707			return -EFAULT;
3708	} else {
3709		transid = 0;  /* current trans */
3710	}
3711	return btrfs_wait_for_commit(fs_info, transid);
3712}
3713
3714static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3715{
3716	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
3717	struct btrfs_ioctl_scrub_args *sa;
3718	int ret;
3719
3720	if (!capable(CAP_SYS_ADMIN))
3721		return -EPERM;
3722
3723	sa = memdup_user(arg, sizeof(*sa));
3724	if (IS_ERR(sa))
3725		return PTR_ERR(sa);
3726
3727	if (sa->flags & ~BTRFS_SCRUB_SUPPORTED_FLAGS) {
3728		ret = -EOPNOTSUPP;
3729		goto out;
3730	}
3731
3732	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3733		ret = mnt_want_write_file(file);
3734		if (ret)
3735			goto out;
3736	}
3737
3738	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
3739			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3740			      0);
3741
3742	/*
3743	 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
3744	 * error. This is important as it allows user space to know how much
3745	 * progress scrub has done. For example, if scrub is canceled we get
3746	 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
3747	 * space. Later user space can inspect the progress from the structure
3748	 * btrfs_ioctl_scrub_args and resume scrub from where it left off
3749	 * previously (btrfs-progs does this).
3750	 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
3751	 * then return -EFAULT to signal the structure was not copied or it may
3752	 * be corrupt and unreliable due to a partial copy.
3753	 */
3754	if (copy_to_user(arg, sa, sizeof(*sa)))
3755		ret = -EFAULT;
3756
3757	if (!(sa->flags & BTRFS_SCRUB_READONLY))
3758		mnt_drop_write_file(file);
3759out:
3760	kfree(sa);
3761	return ret;
3762}
3763
3764static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
3765{
3766	if (!capable(CAP_SYS_ADMIN))
3767		return -EPERM;
3768
3769	return btrfs_scrub_cancel(fs_info);
3770}
3771
3772static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
3773				       void __user *arg)
3774{
3775	struct btrfs_ioctl_scrub_args *sa;
3776	int ret;
3777
3778	if (!capable(CAP_SYS_ADMIN))
3779		return -EPERM;
3780
3781	sa = memdup_user(arg, sizeof(*sa));
3782	if (IS_ERR(sa))
3783		return PTR_ERR(sa);
3784
3785	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
3786
3787	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3788		ret = -EFAULT;
3789
3790	kfree(sa);
3791	return ret;
3792}
3793
3794static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
3795				      void __user *arg)
3796{
3797	struct btrfs_ioctl_get_dev_stats *sa;
3798	int ret;
3799
3800	sa = memdup_user(arg, sizeof(*sa));
3801	if (IS_ERR(sa))
3802		return PTR_ERR(sa);
3803
3804	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3805		kfree(sa);
3806		return -EPERM;
3807	}
3808
3809	ret = btrfs_get_dev_stats(fs_info, sa);
3810
3811	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
3812		ret = -EFAULT;
3813
3814	kfree(sa);
3815	return ret;
3816}
3817
3818static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
3819				    void __user *arg)
3820{
3821	struct btrfs_ioctl_dev_replace_args *p;
3822	int ret;
3823
3824	if (!capable(CAP_SYS_ADMIN))
3825		return -EPERM;
3826
3827	p = memdup_user(arg, sizeof(*p));
3828	if (IS_ERR(p))
3829		return PTR_ERR(p);
3830
3831	switch (p->cmd) {
3832	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3833		if (sb_rdonly(fs_info->sb)) {
3834			ret = -EROFS;
3835			goto out;
3836		}
3837		if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
3838			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3839		} else {
3840			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
3841			btrfs_exclop_finish(fs_info);
3842		}
3843		break;
3844	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3845		btrfs_dev_replace_status(fs_info, p);
3846		ret = 0;
3847		break;
3848	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3849		p->result = btrfs_dev_replace_cancel(fs_info);
3850		ret = 0;
3851		break;
3852	default:
3853		ret = -EINVAL;
3854		break;
3855	}
3856
3857	if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
3858		ret = -EFAULT;
3859out:
3860	kfree(p);
3861	return ret;
3862}
3863
3864static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3865{
3866	int ret = 0;
3867	int i;
3868	u64 rel_ptr;
3869	int size;
3870	struct btrfs_ioctl_ino_path_args *ipa = NULL;
3871	struct inode_fs_paths *ipath = NULL;
3872	struct btrfs_path *path;
3873
3874	if (!capable(CAP_DAC_READ_SEARCH))
3875		return -EPERM;
3876
3877	path = btrfs_alloc_path();
3878	if (!path) {
3879		ret = -ENOMEM;
3880		goto out;
3881	}
3882
3883	ipa = memdup_user(arg, sizeof(*ipa));
3884	if (IS_ERR(ipa)) {
3885		ret = PTR_ERR(ipa);
3886		ipa = NULL;
3887		goto out;
3888	}
3889
3890	size = min_t(u32, ipa->size, 4096);
3891	ipath = init_ipath(size, root, path);
3892	if (IS_ERR(ipath)) {
3893		ret = PTR_ERR(ipath);
3894		ipath = NULL;
3895		goto out;
3896	}
3897
3898	ret = paths_from_inode(ipa->inum, ipath);
3899	if (ret < 0)
3900		goto out;
3901
3902	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3903		rel_ptr = ipath->fspath->val[i] -
3904			  (u64)(unsigned long)ipath->fspath->val;
3905		ipath->fspath->val[i] = rel_ptr;
3906	}
3907
3908	btrfs_free_path(path);
3909	path = NULL;
3910	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
3911			   ipath->fspath, size);
3912	if (ret) {
3913		ret = -EFAULT;
3914		goto out;
3915	}
3916
3917out:
3918	btrfs_free_path(path);
3919	free_ipath(ipath);
3920	kfree(ipa);
3921
3922	return ret;
3923}
3924
3925static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
3926					void __user *arg, int version)
3927{
3928	int ret = 0;
3929	int size;
3930	struct btrfs_ioctl_logical_ino_args *loi;
3931	struct btrfs_data_container *inodes = NULL;
3932	struct btrfs_path *path = NULL;
3933	bool ignore_offset;
3934
3935	if (!capable(CAP_SYS_ADMIN))
3936		return -EPERM;
3937
3938	loi = memdup_user(arg, sizeof(*loi));
3939	if (IS_ERR(loi))
3940		return PTR_ERR(loi);
3941
3942	if (version == 1) {
3943		ignore_offset = false;
3944		size = min_t(u32, loi->size, SZ_64K);
3945	} else {
3946		/* All reserved bits must be 0 for now */
3947		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
3948			ret = -EINVAL;
3949			goto out_loi;
3950		}
3951		/* Only accept flags we have defined so far */
3952		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
3953			ret = -EINVAL;
3954			goto out_loi;
3955		}
3956		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
3957		size = min_t(u32, loi->size, SZ_16M);
3958	}
3959
3960	inodes = init_data_container(size);
3961	if (IS_ERR(inodes)) {
3962		ret = PTR_ERR(inodes);
3963		goto out_loi;
3964	}
3965
3966	path = btrfs_alloc_path();
3967	if (!path) {
3968		ret = -ENOMEM;
3969		goto out;
3970	}
3971	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
3972					  inodes, ignore_offset);
3973	btrfs_free_path(path);
3974	if (ret == -EINVAL)
3975		ret = -ENOENT;
3976	if (ret < 0)
3977		goto out;
3978
3979	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
3980			   size);
3981	if (ret)
3982		ret = -EFAULT;
3983
3984out:
3985	kvfree(inodes);
3986out_loi:
3987	kfree(loi);
3988
3989	return ret;
3990}
3991
3992void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
3993			       struct btrfs_ioctl_balance_args *bargs)
3994{
3995	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3996
3997	bargs->flags = bctl->flags;
3998
3999	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4000		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4001	if (atomic_read(&fs_info->balance_pause_req))
4002		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4003	if (atomic_read(&fs_info->balance_cancel_req))
4004		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4005
4006	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4007	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4008	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4009
4010	spin_lock(&fs_info->balance_lock);
4011	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4012	spin_unlock(&fs_info->balance_lock);
4013}
4014
4015static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4016{
4017	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4018	struct btrfs_fs_info *fs_info = root->fs_info;
4019	struct btrfs_ioctl_balance_args *bargs;
4020	struct btrfs_balance_control *bctl;
4021	bool need_unlock; /* for mut. excl. ops lock */
4022	int ret;
4023
4024	if (!capable(CAP_SYS_ADMIN))
4025		return -EPERM;
4026
4027	ret = mnt_want_write_file(file);
4028	if (ret)
4029		return ret;
4030
4031again:
4032	if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
4033		mutex_lock(&fs_info->balance_mutex);
4034		need_unlock = true;
4035		goto locked;
4036	}
4037
4038	/*
4039	 * mut. excl. ops lock is locked.  Three possibilities:
4040	 *   (1) some other op is running
4041	 *   (2) balance is running
4042	 *   (3) balance is paused -- special case (think resume)
4043	 */
4044	mutex_lock(&fs_info->balance_mutex);
4045	if (fs_info->balance_ctl) {
4046		/* this is either (2) or (3) */
4047		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4048			mutex_unlock(&fs_info->balance_mutex);
4049			/*
4050			 * Lock released to allow other waiters to continue,
4051			 * we'll reexamine the status again.
4052			 */
4053			mutex_lock(&fs_info->balance_mutex);
4054
4055			if (fs_info->balance_ctl &&
4056			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4057				/* this is (3) */
4058				need_unlock = false;
4059				goto locked;
4060			}
4061
4062			mutex_unlock(&fs_info->balance_mutex);
4063			goto again;
4064		} else {
4065			/* this is (2) */
4066			mutex_unlock(&fs_info->balance_mutex);
4067			ret = -EINPROGRESS;
4068			goto out;
4069		}
4070	} else {
4071		/* this is (1) */
4072		mutex_unlock(&fs_info->balance_mutex);
4073		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4074		goto out;
4075	}
4076
4077locked:
4078
4079	if (arg) {
4080		bargs = memdup_user(arg, sizeof(*bargs));
4081		if (IS_ERR(bargs)) {
4082			ret = PTR_ERR(bargs);
4083			goto out_unlock;
4084		}
4085
4086		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4087			if (!fs_info->balance_ctl) {
4088				ret = -ENOTCONN;
4089				goto out_bargs;
4090			}
4091
4092			bctl = fs_info->balance_ctl;
4093			spin_lock(&fs_info->balance_lock);
4094			bctl->flags |= BTRFS_BALANCE_RESUME;
4095			spin_unlock(&fs_info->balance_lock);
4096
4097			goto do_balance;
4098		}
4099	} else {
4100		bargs = NULL;
4101	}
4102
4103	if (fs_info->balance_ctl) {
4104		ret = -EINPROGRESS;
4105		goto out_bargs;
4106	}
4107
4108	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4109	if (!bctl) {
4110		ret = -ENOMEM;
4111		goto out_bargs;
4112	}
4113
4114	if (arg) {
4115		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4116		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4117		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4118
4119		bctl->flags = bargs->flags;
4120	} else {
4121		/* balance everything - no filters */
4122		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4123	}
4124
4125	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4126		ret = -EINVAL;
4127		goto out_bctl;
4128	}
4129
4130do_balance:
4131	/*
4132	 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4133	 * bctl is freed in reset_balance_state, or, if restriper was paused
4134	 * all the way until unmount, in free_fs_info.  The flag should be
4135	 * cleared after reset_balance_state.
4136	 */
4137	need_unlock = false;
4138
4139	ret = btrfs_balance(fs_info, bctl, bargs);
4140	bctl = NULL;
4141
4142	if ((ret == 0 || ret == -ECANCELED) && arg) {
4143		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4144			ret = -EFAULT;
4145	}
4146
4147out_bctl:
4148	kfree(bctl);
4149out_bargs:
4150	kfree(bargs);
4151out_unlock:
4152	mutex_unlock(&fs_info->balance_mutex);
4153	if (need_unlock)
4154		btrfs_exclop_finish(fs_info);
4155out:
4156	mnt_drop_write_file(file);
4157	return ret;
4158}
4159
4160static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4161{
4162	if (!capable(CAP_SYS_ADMIN))
4163		return -EPERM;
4164
4165	switch (cmd) {
4166	case BTRFS_BALANCE_CTL_PAUSE:
4167		return btrfs_pause_balance(fs_info);
4168	case BTRFS_BALANCE_CTL_CANCEL:
4169		return btrfs_cancel_balance(fs_info);
4170	}
4171
4172	return -EINVAL;
4173}
4174
4175static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4176					 void __user *arg)
4177{
4178	struct btrfs_ioctl_balance_args *bargs;
4179	int ret = 0;
4180
4181	if (!capable(CAP_SYS_ADMIN))
4182		return -EPERM;
4183
4184	mutex_lock(&fs_info->balance_mutex);
4185	if (!fs_info->balance_ctl) {
4186		ret = -ENOTCONN;
4187		goto out;
4188	}
4189
4190	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4191	if (!bargs) {
4192		ret = -ENOMEM;
4193		goto out;
4194	}
4195
4196	btrfs_update_ioctl_balance_args(fs_info, bargs);
4197
4198	if (copy_to_user(arg, bargs, sizeof(*bargs)))
4199		ret = -EFAULT;
4200
4201	kfree(bargs);
4202out:
4203	mutex_unlock(&fs_info->balance_mutex);
4204	return ret;
4205}
4206
4207static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4208{
4209	struct inode *inode = file_inode(file);
4210	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4211	struct btrfs_ioctl_quota_ctl_args *sa;
4212	int ret;
4213
4214	if (!capable(CAP_SYS_ADMIN))
4215		return -EPERM;
4216
4217	ret = mnt_want_write_file(file);
4218	if (ret)
4219		return ret;
4220
4221	sa = memdup_user(arg, sizeof(*sa));
4222	if (IS_ERR(sa)) {
4223		ret = PTR_ERR(sa);
4224		goto drop_write;
4225	}
4226
4227	down_write(&fs_info->subvol_sem);
4228
4229	switch (sa->cmd) {
4230	case BTRFS_QUOTA_CTL_ENABLE:
4231		ret = btrfs_quota_enable(fs_info);
4232		break;
4233	case BTRFS_QUOTA_CTL_DISABLE:
4234		ret = btrfs_quota_disable(fs_info);
4235		break;
4236	default:
4237		ret = -EINVAL;
4238		break;
4239	}
4240
4241	kfree(sa);
4242	up_write(&fs_info->subvol_sem);
4243drop_write:
4244	mnt_drop_write_file(file);
4245	return ret;
4246}
4247
4248static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4249{
4250	struct inode *inode = file_inode(file);
4251	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4252	struct btrfs_root *root = BTRFS_I(inode)->root;
4253	struct btrfs_ioctl_qgroup_assign_args *sa;
4254	struct btrfs_trans_handle *trans;
4255	int ret;
4256	int err;
4257
4258	if (!capable(CAP_SYS_ADMIN))
4259		return -EPERM;
4260
4261	ret = mnt_want_write_file(file);
4262	if (ret)
4263		return ret;
4264
4265	sa = memdup_user(arg, sizeof(*sa));
4266	if (IS_ERR(sa)) {
4267		ret = PTR_ERR(sa);
4268		goto drop_write;
4269	}
4270
4271	trans = btrfs_join_transaction(root);
4272	if (IS_ERR(trans)) {
4273		ret = PTR_ERR(trans);
4274		goto out;
4275	}
4276
4277	if (sa->assign) {
4278		ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
4279	} else {
4280		ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
4281	}
4282
4283	/* update qgroup status and info */
4284	mutex_lock(&fs_info->qgroup_ioctl_lock);
4285	err = btrfs_run_qgroups(trans);
4286	mutex_unlock(&fs_info->qgroup_ioctl_lock);
4287	if (err < 0)
4288		btrfs_handle_fs_error(fs_info, err,
4289				      "failed to update qgroup status and info");
4290	err = btrfs_end_transaction(trans);
4291	if (err && !ret)
4292		ret = err;
4293
4294out:
4295	kfree(sa);
4296drop_write:
4297	mnt_drop_write_file(file);
4298	return ret;
4299}
4300
4301static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4302{
4303	struct inode *inode = file_inode(file);
4304	struct btrfs_root *root = BTRFS_I(inode)->root;
4305	struct btrfs_ioctl_qgroup_create_args *sa;
4306	struct btrfs_trans_handle *trans;
4307	int ret;
4308	int err;
4309
4310	if (!capable(CAP_SYS_ADMIN))
4311		return -EPERM;
4312
4313	ret = mnt_want_write_file(file);
4314	if (ret)
4315		return ret;
4316
4317	sa = memdup_user(arg, sizeof(*sa));
4318	if (IS_ERR(sa)) {
4319		ret = PTR_ERR(sa);
4320		goto drop_write;
4321	}
4322
4323	if (!sa->qgroupid) {
4324		ret = -EINVAL;
4325		goto out;
4326	}
4327
4328	if (sa->create && is_fstree(sa->qgroupid)) {
4329		ret = -EINVAL;
4330		goto out;
4331	}
4332
4333	trans = btrfs_join_transaction(root);
4334	if (IS_ERR(trans)) {
4335		ret = PTR_ERR(trans);
4336		goto out;
4337	}
4338
4339	if (sa->create) {
4340		ret = btrfs_create_qgroup(trans, sa->qgroupid);
4341	} else {
4342		ret = btrfs_remove_qgroup(trans, sa->qgroupid);
4343	}
4344
4345	err = btrfs_end_transaction(trans);
4346	if (err && !ret)
4347		ret = err;
4348
4349out:
4350	kfree(sa);
4351drop_write:
4352	mnt_drop_write_file(file);
4353	return ret;
4354}
4355
4356static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4357{
4358	struct inode *inode = file_inode(file);
4359	struct btrfs_root *root = BTRFS_I(inode)->root;
4360	struct btrfs_ioctl_qgroup_limit_args *sa;
4361	struct btrfs_trans_handle *trans;
4362	int ret;
4363	int err;
4364	u64 qgroupid;
4365
4366	if (!capable(CAP_SYS_ADMIN))
4367		return -EPERM;
4368
4369	ret = mnt_want_write_file(file);
4370	if (ret)
4371		return ret;
4372
4373	sa = memdup_user(arg, sizeof(*sa));
4374	if (IS_ERR(sa)) {
4375		ret = PTR_ERR(sa);
4376		goto drop_write;
4377	}
4378
4379	trans = btrfs_join_transaction(root);
4380	if (IS_ERR(trans)) {
4381		ret = PTR_ERR(trans);
4382		goto out;
4383	}
4384
4385	qgroupid = sa->qgroupid;
4386	if (!qgroupid) {
4387		/* take the current subvol as qgroup */
4388		qgroupid = root->root_key.objectid;
4389	}
4390
4391	ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
4392
4393	err = btrfs_end_transaction(trans);
4394	if (err && !ret)
4395		ret = err;
4396
4397out:
4398	kfree(sa);
4399drop_write:
4400	mnt_drop_write_file(file);
4401	return ret;
4402}
4403
4404static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4405{
4406	struct inode *inode = file_inode(file);
4407	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4408	struct btrfs_ioctl_quota_rescan_args *qsa;
4409	int ret;
4410
4411	if (!capable(CAP_SYS_ADMIN))
4412		return -EPERM;
4413
4414	ret = mnt_want_write_file(file);
4415	if (ret)
4416		return ret;
4417
4418	qsa = memdup_user(arg, sizeof(*qsa));
4419	if (IS_ERR(qsa)) {
4420		ret = PTR_ERR(qsa);
4421		goto drop_write;
4422	}
4423
4424	if (qsa->flags) {
4425		ret = -EINVAL;
4426		goto out;
4427	}
4428
4429	ret = btrfs_qgroup_rescan(fs_info);
4430
4431out:
4432	kfree(qsa);
4433drop_write:
4434	mnt_drop_write_file(file);
4435	return ret;
4436}
4437
4438static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4439						void __user *arg)
4440{
4441	struct btrfs_ioctl_quota_rescan_args *qsa;
4442	int ret = 0;
4443
4444	if (!capable(CAP_SYS_ADMIN))
4445		return -EPERM;
4446
4447	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
4448	if (!qsa)
4449		return -ENOMEM;
4450
4451	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4452		qsa->flags = 1;
4453		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
4454	}
4455
4456	if (copy_to_user(arg, qsa, sizeof(*qsa)))
4457		ret = -EFAULT;
4458
4459	kfree(qsa);
4460	return ret;
4461}
4462
4463static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4464						void __user *arg)
4465{
4466	if (!capable(CAP_SYS_ADMIN))
4467		return -EPERM;
4468
4469	return btrfs_qgroup_wait_for_completion(fs_info, true);
4470}
4471
4472static long _btrfs_ioctl_set_received_subvol(struct file *file,
4473					    struct btrfs_ioctl_received_subvol_args *sa)
4474{
4475	struct inode *inode = file_inode(file);
4476	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4477	struct btrfs_root *root = BTRFS_I(inode)->root;
4478	struct btrfs_root_item *root_item = &root->root_item;
4479	struct btrfs_trans_handle *trans;
4480	struct timespec64 ct = current_time(inode);
4481	int ret = 0;
4482	int received_uuid_changed;
4483
4484	if (!inode_owner_or_capable(inode))
4485		return -EPERM;
4486
4487	ret = mnt_want_write_file(file);
4488	if (ret < 0)
4489		return ret;
4490
4491	down_write(&fs_info->subvol_sem);
4492
4493	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
4494		ret = -EINVAL;
4495		goto out;
4496	}
4497
4498	if (btrfs_root_readonly(root)) {
4499		ret = -EROFS;
4500		goto out;
4501	}
4502
4503	/*
4504	 * 1 - root item
4505	 * 2 - uuid items (received uuid + subvol uuid)
4506	 */
4507	trans = btrfs_start_transaction(root, 3);
4508	if (IS_ERR(trans)) {
4509		ret = PTR_ERR(trans);
4510		trans = NULL;
4511		goto out;
4512	}
4513
4514	sa->rtransid = trans->transid;
4515	sa->rtime.sec = ct.tv_sec;
4516	sa->rtime.nsec = ct.tv_nsec;
4517
4518	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4519				       BTRFS_UUID_SIZE);
4520	if (received_uuid_changed &&
4521	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
4522		ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
4523					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4524					  root->root_key.objectid);
4525		if (ret && ret != -ENOENT) {
4526		        btrfs_abort_transaction(trans, ret);
4527		        btrfs_end_transaction(trans);
4528		        goto out;
4529		}
4530	}
4531	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4532	btrfs_set_root_stransid(root_item, sa->stransid);
4533	btrfs_set_root_rtransid(root_item, sa->rtransid);
4534	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4535	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4536	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4537	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4538
4539	ret = btrfs_update_root(trans, fs_info->tree_root,
4540				&root->root_key, &root->root_item);
4541	if (ret < 0) {
4542		btrfs_end_transaction(trans);
4543		goto out;
4544	}
4545	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4546		ret = btrfs_uuid_tree_add(trans, sa->uuid,
4547					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4548					  root->root_key.objectid);
4549		if (ret < 0 && ret != -EEXIST) {
4550			btrfs_abort_transaction(trans, ret);
4551			btrfs_end_transaction(trans);
4552			goto out;
4553		}
4554	}
4555	ret = btrfs_commit_transaction(trans);
4556out:
4557	up_write(&fs_info->subvol_sem);
4558	mnt_drop_write_file(file);
4559	return ret;
4560}
4561
4562#ifdef CONFIG_64BIT
4563static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4564						void __user *arg)
4565{
4566	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4567	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4568	int ret = 0;
4569
4570	args32 = memdup_user(arg, sizeof(*args32));
4571	if (IS_ERR(args32))
4572		return PTR_ERR(args32);
4573
4574	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
4575	if (!args64) {
4576		ret = -ENOMEM;
4577		goto out;
4578	}
4579
4580	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4581	args64->stransid = args32->stransid;
4582	args64->rtransid = args32->rtransid;
4583	args64->stime.sec = args32->stime.sec;
4584	args64->stime.nsec = args32->stime.nsec;
4585	args64->rtime.sec = args32->rtime.sec;
4586	args64->rtime.nsec = args32->rtime.nsec;
4587	args64->flags = args32->flags;
4588
4589	ret = _btrfs_ioctl_set_received_subvol(file, args64);
4590	if (ret)
4591		goto out;
4592
4593	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4594	args32->stransid = args64->stransid;
4595	args32->rtransid = args64->rtransid;
4596	args32->stime.sec = args64->stime.sec;
4597	args32->stime.nsec = args64->stime.nsec;
4598	args32->rtime.sec = args64->rtime.sec;
4599	args32->rtime.nsec = args64->rtime.nsec;
4600	args32->flags = args64->flags;
4601
4602	ret = copy_to_user(arg, args32, sizeof(*args32));
4603	if (ret)
4604		ret = -EFAULT;
4605
4606out:
4607	kfree(args32);
4608	kfree(args64);
4609	return ret;
4610}
4611#endif
4612
4613static long btrfs_ioctl_set_received_subvol(struct file *file,
4614					    void __user *arg)
4615{
4616	struct btrfs_ioctl_received_subvol_args *sa = NULL;
4617	int ret = 0;
4618
4619	sa = memdup_user(arg, sizeof(*sa));
4620	if (IS_ERR(sa))
4621		return PTR_ERR(sa);
4622
4623	ret = _btrfs_ioctl_set_received_subvol(file, sa);
4624
4625	if (ret)
4626		goto out;
4627
4628	ret = copy_to_user(arg, sa, sizeof(*sa));
4629	if (ret)
4630		ret = -EFAULT;
4631
4632out:
4633	kfree(sa);
4634	return ret;
4635}
4636
4637static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4638					void __user *arg)
4639{
4640	size_t len;
4641	int ret;
4642	char label[BTRFS_LABEL_SIZE];
4643
4644	spin_lock(&fs_info->super_lock);
4645	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4646	spin_unlock(&fs_info->super_lock);
4647
4648	len = strnlen(label, BTRFS_LABEL_SIZE);
4649
4650	if (len == BTRFS_LABEL_SIZE) {
4651		btrfs_warn(fs_info,
4652			   "label is too long, return the first %zu bytes",
4653			   --len);
4654	}
4655
4656	ret = copy_to_user(arg, label, len);
4657
4658	return ret ? -EFAULT : 0;
4659}
4660
4661static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4662{
4663	struct inode *inode = file_inode(file);
4664	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4665	struct btrfs_root *root = BTRFS_I(inode)->root;
4666	struct btrfs_super_block *super_block = fs_info->super_copy;
4667	struct btrfs_trans_handle *trans;
4668	char label[BTRFS_LABEL_SIZE];
4669	int ret;
4670
4671	if (!capable(CAP_SYS_ADMIN))
4672		return -EPERM;
4673
4674	if (copy_from_user(label, arg, sizeof(label)))
4675		return -EFAULT;
4676
4677	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4678		btrfs_err(fs_info,
4679			  "unable to set label with more than %d bytes",
4680			  BTRFS_LABEL_SIZE - 1);
4681		return -EINVAL;
4682	}
4683
4684	ret = mnt_want_write_file(file);
4685	if (ret)
4686		return ret;
4687
4688	trans = btrfs_start_transaction(root, 0);
4689	if (IS_ERR(trans)) {
4690		ret = PTR_ERR(trans);
4691		goto out_unlock;
4692	}
4693
4694	spin_lock(&fs_info->super_lock);
4695	strcpy(super_block->label, label);
4696	spin_unlock(&fs_info->super_lock);
4697	ret = btrfs_commit_transaction(trans);
4698
4699out_unlock:
4700	mnt_drop_write_file(file);
4701	return ret;
4702}
4703
4704#define INIT_FEATURE_FLAGS(suffix) \
4705	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
4706	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
4707	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
4708
4709int btrfs_ioctl_get_supported_features(void __user *arg)
4710{
4711	static const struct btrfs_ioctl_feature_flags features[3] = {
4712		INIT_FEATURE_FLAGS(SUPP),
4713		INIT_FEATURE_FLAGS(SAFE_SET),
4714		INIT_FEATURE_FLAGS(SAFE_CLEAR)
4715	};
4716
4717	if (copy_to_user(arg, &features, sizeof(features)))
4718		return -EFAULT;
4719
4720	return 0;
4721}
4722
4723static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
4724					void __user *arg)
4725{
4726	struct btrfs_super_block *super_block = fs_info->super_copy;
4727	struct btrfs_ioctl_feature_flags features;
4728
4729	features.compat_flags = btrfs_super_compat_flags(super_block);
4730	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
4731	features.incompat_flags = btrfs_super_incompat_flags(super_block);
4732
4733	if (copy_to_user(arg, &features, sizeof(features)))
4734		return -EFAULT;
4735
4736	return 0;
4737}
4738
4739static int check_feature_bits(struct btrfs_fs_info *fs_info,
4740			      enum btrfs_feature_set set,
4741			      u64 change_mask, u64 flags, u64 supported_flags,
4742			      u64 safe_set, u64 safe_clear)
4743{
4744	const char *type = btrfs_feature_set_name(set);
4745	char *names;
4746	u64 disallowed, unsupported;
4747	u64 set_mask = flags & change_mask;
4748	u64 clear_mask = ~flags & change_mask;
4749
4750	unsupported = set_mask & ~supported_flags;
4751	if (unsupported) {
4752		names = btrfs_printable_features(set, unsupported);
4753		if (names) {
4754			btrfs_warn(fs_info,
4755				   "this kernel does not support the %s feature bit%s",
4756				   names, strchr(names, ',') ? "s" : "");
4757			kfree(names);
4758		} else
4759			btrfs_warn(fs_info,
4760				   "this kernel does not support %s bits 0x%llx",
4761				   type, unsupported);
4762		return -EOPNOTSUPP;
4763	}
4764
4765	disallowed = set_mask & ~safe_set;
4766	if (disallowed) {
4767		names = btrfs_printable_features(set, disallowed);
4768		if (names) {
4769			btrfs_warn(fs_info,
4770				   "can't set the %s feature bit%s while mounted",
4771				   names, strchr(names, ',') ? "s" : "");
4772			kfree(names);
4773		} else
4774			btrfs_warn(fs_info,
4775				   "can't set %s bits 0x%llx while mounted",
4776				   type, disallowed);
4777		return -EPERM;
4778	}
4779
4780	disallowed = clear_mask & ~safe_clear;
4781	if (disallowed) {
4782		names = btrfs_printable_features(set, disallowed);
4783		if (names) {
4784			btrfs_warn(fs_info,
4785				   "can't clear the %s feature bit%s while mounted",
4786				   names, strchr(names, ',') ? "s" : "");
4787			kfree(names);
4788		} else
4789			btrfs_warn(fs_info,
4790				   "can't clear %s bits 0x%llx while mounted",
4791				   type, disallowed);
4792		return -EPERM;
4793	}
4794
4795	return 0;
4796}
4797
4798#define check_feature(fs_info, change_mask, flags, mask_base)	\
4799check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
4800		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
4801		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
4802		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
4803
4804static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
4805{
4806	struct inode *inode = file_inode(file);
4807	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4808	struct btrfs_root *root = BTRFS_I(inode)->root;
4809	struct btrfs_super_block *super_block = fs_info->super_copy;
4810	struct btrfs_ioctl_feature_flags flags[2];
4811	struct btrfs_trans_handle *trans;
4812	u64 newflags;
4813	int ret;
4814
4815	if (!capable(CAP_SYS_ADMIN))
4816		return -EPERM;
4817
4818	if (copy_from_user(flags, arg, sizeof(flags)))
4819		return -EFAULT;
4820
4821	/* Nothing to do */
4822	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
4823	    !flags[0].incompat_flags)
4824		return 0;
4825
4826	ret = check_feature(fs_info, flags[0].compat_flags,
4827			    flags[1].compat_flags, COMPAT);
4828	if (ret)
4829		return ret;
4830
4831	ret = check_feature(fs_info, flags[0].compat_ro_flags,
4832			    flags[1].compat_ro_flags, COMPAT_RO);
4833	if (ret)
4834		return ret;
4835
4836	ret = check_feature(fs_info, flags[0].incompat_flags,
4837			    flags[1].incompat_flags, INCOMPAT);
4838	if (ret)
4839		return ret;
4840
4841	ret = mnt_want_write_file(file);
4842	if (ret)
4843		return ret;
4844
4845	trans = btrfs_start_transaction(root, 0);
4846	if (IS_ERR(trans)) {
4847		ret = PTR_ERR(trans);
4848		goto out_drop_write;
4849	}
4850
4851	spin_lock(&fs_info->super_lock);
4852	newflags = btrfs_super_compat_flags(super_block);
4853	newflags |= flags[0].compat_flags & flags[1].compat_flags;
4854	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
4855	btrfs_set_super_compat_flags(super_block, newflags);
4856
4857	newflags = btrfs_super_compat_ro_flags(super_block);
4858	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
4859	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
4860	btrfs_set_super_compat_ro_flags(super_block, newflags);
4861
4862	newflags = btrfs_super_incompat_flags(super_block);
4863	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
4864	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
4865	btrfs_set_super_incompat_flags(super_block, newflags);
4866	spin_unlock(&fs_info->super_lock);
4867
4868	ret = btrfs_commit_transaction(trans);
4869out_drop_write:
4870	mnt_drop_write_file(file);
4871
4872	return ret;
4873}
4874
4875static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
4876{
4877	struct btrfs_ioctl_send_args *arg;
4878	int ret;
4879
4880	if (compat) {
4881#if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
4882		struct btrfs_ioctl_send_args_32 args32 = { 0 };
4883
4884		ret = copy_from_user(&args32, argp, sizeof(args32));
4885		if (ret)
4886			return -EFAULT;
4887		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
4888		if (!arg)
4889			return -ENOMEM;
4890		arg->send_fd = args32.send_fd;
4891		arg->clone_sources_count = args32.clone_sources_count;
4892		arg->clone_sources = compat_ptr(args32.clone_sources);
4893		arg->parent_root = args32.parent_root;
4894		arg->flags = args32.flags;
4895		memcpy(arg->reserved, args32.reserved,
4896		       sizeof(args32.reserved));
4897#else
4898		return -ENOTTY;
4899#endif
4900	} else {
4901		arg = memdup_user(argp, sizeof(*arg));
4902		if (IS_ERR(arg))
4903			return PTR_ERR(arg);
4904	}
4905	ret = btrfs_ioctl_send(file, arg);
4906	kfree(arg);
4907	return ret;
4908}
4909
4910long btrfs_ioctl(struct file *file, unsigned int
4911		cmd, unsigned long arg)
4912{
4913	struct inode *inode = file_inode(file);
4914	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4915	struct btrfs_root *root = BTRFS_I(inode)->root;
4916	void __user *argp = (void __user *)arg;
4917
4918	switch (cmd) {
4919	case FS_IOC_GETFLAGS:
4920		return btrfs_ioctl_getflags(file, argp);
4921	case FS_IOC_SETFLAGS:
4922		return btrfs_ioctl_setflags(file, argp);
4923	case FS_IOC_GETVERSION:
4924		return btrfs_ioctl_getversion(file, argp);
4925	case FS_IOC_GETFSLABEL:
4926		return btrfs_ioctl_get_fslabel(fs_info, argp);
4927	case FS_IOC_SETFSLABEL:
4928		return btrfs_ioctl_set_fslabel(file, argp);
4929	case FITRIM:
4930		return btrfs_ioctl_fitrim(fs_info, argp);
4931	case BTRFS_IOC_SNAP_CREATE:
4932		return btrfs_ioctl_snap_create(file, argp, 0);
4933	case BTRFS_IOC_SNAP_CREATE_V2:
4934		return btrfs_ioctl_snap_create_v2(file, argp, 0);
4935	case BTRFS_IOC_SUBVOL_CREATE:
4936		return btrfs_ioctl_snap_create(file, argp, 1);
4937	case BTRFS_IOC_SUBVOL_CREATE_V2:
4938		return btrfs_ioctl_snap_create_v2(file, argp, 1);
4939	case BTRFS_IOC_SNAP_DESTROY:
4940		return btrfs_ioctl_snap_destroy(file, argp, false);
4941	case BTRFS_IOC_SNAP_DESTROY_V2:
4942		return btrfs_ioctl_snap_destroy(file, argp, true);
4943	case BTRFS_IOC_SUBVOL_GETFLAGS:
4944		return btrfs_ioctl_subvol_getflags(file, argp);
4945	case BTRFS_IOC_SUBVOL_SETFLAGS:
4946		return btrfs_ioctl_subvol_setflags(file, argp);
4947	case BTRFS_IOC_DEFAULT_SUBVOL:
4948		return btrfs_ioctl_default_subvol(file, argp);
4949	case BTRFS_IOC_DEFRAG:
4950		return btrfs_ioctl_defrag(file, NULL);
4951	case BTRFS_IOC_DEFRAG_RANGE:
4952		return btrfs_ioctl_defrag(file, argp);
4953	case BTRFS_IOC_RESIZE:
4954		return btrfs_ioctl_resize(file, argp);
4955	case BTRFS_IOC_ADD_DEV:
4956		return btrfs_ioctl_add_dev(fs_info, argp);
4957	case BTRFS_IOC_RM_DEV:
4958		return btrfs_ioctl_rm_dev(file, argp);
4959	case BTRFS_IOC_RM_DEV_V2:
4960		return btrfs_ioctl_rm_dev_v2(file, argp);
4961	case BTRFS_IOC_FS_INFO:
4962		return btrfs_ioctl_fs_info(fs_info, argp);
4963	case BTRFS_IOC_DEV_INFO:
4964		return btrfs_ioctl_dev_info(fs_info, argp);
4965	case BTRFS_IOC_BALANCE:
4966		return btrfs_ioctl_balance(file, NULL);
4967	case BTRFS_IOC_TREE_SEARCH:
4968		return btrfs_ioctl_tree_search(file, argp);
4969	case BTRFS_IOC_TREE_SEARCH_V2:
4970		return btrfs_ioctl_tree_search_v2(file, argp);
4971	case BTRFS_IOC_INO_LOOKUP:
4972		return btrfs_ioctl_ino_lookup(file, argp);
4973	case BTRFS_IOC_INO_PATHS:
4974		return btrfs_ioctl_ino_to_path(root, argp);
4975	case BTRFS_IOC_LOGICAL_INO:
4976		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
4977	case BTRFS_IOC_LOGICAL_INO_V2:
4978		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
4979	case BTRFS_IOC_SPACE_INFO:
4980		return btrfs_ioctl_space_info(fs_info, argp);
4981	case BTRFS_IOC_SYNC: {
4982		int ret;
4983
4984		ret = btrfs_start_delalloc_roots(fs_info, U64_MAX, false);
4985		if (ret)
4986			return ret;
4987		ret = btrfs_sync_fs(inode->i_sb, 1);
4988		/*
4989		 * The transaction thread may want to do more work,
4990		 * namely it pokes the cleaner kthread that will start
4991		 * processing uncleaned subvols.
4992		 */
4993		wake_up_process(fs_info->transaction_kthread);
4994		return ret;
4995	}
4996	case BTRFS_IOC_START_SYNC:
4997		return btrfs_ioctl_start_sync(root, argp);
4998	case BTRFS_IOC_WAIT_SYNC:
4999		return btrfs_ioctl_wait_sync(fs_info, argp);
5000	case BTRFS_IOC_SCRUB:
5001		return btrfs_ioctl_scrub(file, argp);
5002	case BTRFS_IOC_SCRUB_CANCEL:
5003		return btrfs_ioctl_scrub_cancel(fs_info);
5004	case BTRFS_IOC_SCRUB_PROGRESS:
5005		return btrfs_ioctl_scrub_progress(fs_info, argp);
5006	case BTRFS_IOC_BALANCE_V2:
5007		return btrfs_ioctl_balance(file, argp);
5008	case BTRFS_IOC_BALANCE_CTL:
5009		return btrfs_ioctl_balance_ctl(fs_info, arg);
5010	case BTRFS_IOC_BALANCE_PROGRESS:
5011		return btrfs_ioctl_balance_progress(fs_info, argp);
5012	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5013		return btrfs_ioctl_set_received_subvol(file, argp);
5014#ifdef CONFIG_64BIT
5015	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5016		return btrfs_ioctl_set_received_subvol_32(file, argp);
5017#endif
5018	case BTRFS_IOC_SEND:
5019		return _btrfs_ioctl_send(file, argp, false);
5020#if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5021	case BTRFS_IOC_SEND_32:
5022		return _btrfs_ioctl_send(file, argp, true);
5023#endif
5024	case BTRFS_IOC_GET_DEV_STATS:
5025		return btrfs_ioctl_get_dev_stats(fs_info, argp);
5026	case BTRFS_IOC_QUOTA_CTL:
5027		return btrfs_ioctl_quota_ctl(file, argp);
5028	case BTRFS_IOC_QGROUP_ASSIGN:
5029		return btrfs_ioctl_qgroup_assign(file, argp);
5030	case BTRFS_IOC_QGROUP_CREATE:
5031		return btrfs_ioctl_qgroup_create(file, argp);
5032	case BTRFS_IOC_QGROUP_LIMIT:
5033		return btrfs_ioctl_qgroup_limit(file, argp);
5034	case BTRFS_IOC_QUOTA_RESCAN:
5035		return btrfs_ioctl_quota_rescan(file, argp);
5036	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5037		return btrfs_ioctl_quota_rescan_status(fs_info, argp);
5038	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5039		return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
5040	case BTRFS_IOC_DEV_REPLACE:
5041		return btrfs_ioctl_dev_replace(fs_info, argp);
5042	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5043		return btrfs_ioctl_get_supported_features(argp);
5044	case BTRFS_IOC_GET_FEATURES:
5045		return btrfs_ioctl_get_features(fs_info, argp);
5046	case BTRFS_IOC_SET_FEATURES:
5047		return btrfs_ioctl_set_features(file, argp);
5048	case FS_IOC_FSGETXATTR:
5049		return btrfs_ioctl_fsgetxattr(file, argp);
5050	case FS_IOC_FSSETXATTR:
5051		return btrfs_ioctl_fssetxattr(file, argp);
5052	case BTRFS_IOC_GET_SUBVOL_INFO:
5053		return btrfs_ioctl_get_subvol_info(file, argp);
5054	case BTRFS_IOC_GET_SUBVOL_ROOTREF:
5055		return btrfs_ioctl_get_subvol_rootref(file, argp);
5056	case BTRFS_IOC_INO_LOOKUP_USER:
5057		return btrfs_ioctl_ino_lookup_user(file, argp);
5058	}
5059
5060	return -ENOTTY;
5061}
5062
5063#ifdef CONFIG_COMPAT
5064long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5065{
5066	/*
5067	 * These all access 32-bit values anyway so no further
5068	 * handling is necessary.
5069	 */
5070	switch (cmd) {
5071	case FS_IOC32_GETFLAGS:
5072		cmd = FS_IOC_GETFLAGS;
5073		break;
5074	case FS_IOC32_SETFLAGS:
5075		cmd = FS_IOC_SETFLAGS;
5076		break;
5077	case FS_IOC32_GETVERSION:
5078		cmd = FS_IOC_GETVERSION;
5079		break;
5080	}
5081
5082	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
5083}
5084#endif
5085