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