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