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