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