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