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