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