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