xref: /openbmc/linux/fs/btrfs/ioctl.c (revision 0be3ff0c)
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 		if (fault_in_writeable(ubuf + sk_offset, *buf_size - sk_offset))
2565 			break;
2566 
2567 		ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2568 		if (ret != 0) {
2569 			if (ret > 0)
2570 				ret = 0;
2571 			goto err;
2572 		}
2573 		ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2574 				 &sk_offset, &num_found);
2575 		btrfs_release_path(path);
2576 		if (ret)
2577 			break;
2578 
2579 	}
2580 	if (ret > 0)
2581 		ret = 0;
2582 err:
2583 	sk->nr_items = num_found;
2584 	btrfs_put_root(root);
2585 	btrfs_free_path(path);
2586 	return ret;
2587 }
2588 
2589 static noinline int btrfs_ioctl_tree_search(struct inode *inode,
2590 					    void __user *argp)
2591 {
2592 	struct btrfs_ioctl_search_args __user *uargs;
2593 	struct btrfs_ioctl_search_key sk;
2594 	int ret;
2595 	size_t buf_size;
2596 
2597 	if (!capable(CAP_SYS_ADMIN))
2598 		return -EPERM;
2599 
2600 	uargs = (struct btrfs_ioctl_search_args __user *)argp;
2601 
2602 	if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2603 		return -EFAULT;
2604 
2605 	buf_size = sizeof(uargs->buf);
2606 
2607 	ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2608 
2609 	/*
2610 	 * In the origin implementation an overflow is handled by returning a
2611 	 * search header with a len of zero, so reset ret.
2612 	 */
2613 	if (ret == -EOVERFLOW)
2614 		ret = 0;
2615 
2616 	if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2617 		ret = -EFAULT;
2618 	return ret;
2619 }
2620 
2621 static noinline int btrfs_ioctl_tree_search_v2(struct inode *inode,
2622 					       void __user *argp)
2623 {
2624 	struct btrfs_ioctl_search_args_v2 __user *uarg;
2625 	struct btrfs_ioctl_search_args_v2 args;
2626 	int ret;
2627 	size_t buf_size;
2628 	const size_t buf_limit = SZ_16M;
2629 
2630 	if (!capable(CAP_SYS_ADMIN))
2631 		return -EPERM;
2632 
2633 	/* copy search header and buffer size */
2634 	uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2635 	if (copy_from_user(&args, uarg, sizeof(args)))
2636 		return -EFAULT;
2637 
2638 	buf_size = args.buf_size;
2639 
2640 	/* limit result size to 16MB */
2641 	if (buf_size > buf_limit)
2642 		buf_size = buf_limit;
2643 
2644 	ret = search_ioctl(inode, &args.key, &buf_size,
2645 			   (char __user *)(&uarg->buf[0]));
2646 	if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2647 		ret = -EFAULT;
2648 	else if (ret == -EOVERFLOW &&
2649 		copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2650 		ret = -EFAULT;
2651 
2652 	return ret;
2653 }
2654 
2655 /*
2656  * Search INODE_REFs to identify path name of 'dirid' directory
2657  * in a 'tree_id' tree. and sets path name to 'name'.
2658  */
2659 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2660 				u64 tree_id, u64 dirid, char *name)
2661 {
2662 	struct btrfs_root *root;
2663 	struct btrfs_key key;
2664 	char *ptr;
2665 	int ret = -1;
2666 	int slot;
2667 	int len;
2668 	int total_len = 0;
2669 	struct btrfs_inode_ref *iref;
2670 	struct extent_buffer *l;
2671 	struct btrfs_path *path;
2672 
2673 	if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2674 		name[0]='\0';
2675 		return 0;
2676 	}
2677 
2678 	path = btrfs_alloc_path();
2679 	if (!path)
2680 		return -ENOMEM;
2681 
2682 	ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2683 
2684 	root = btrfs_get_fs_root(info, tree_id, true);
2685 	if (IS_ERR(root)) {
2686 		ret = PTR_ERR(root);
2687 		root = NULL;
2688 		goto out;
2689 	}
2690 
2691 	key.objectid = dirid;
2692 	key.type = BTRFS_INODE_REF_KEY;
2693 	key.offset = (u64)-1;
2694 
2695 	while (1) {
2696 		ret = btrfs_search_backwards(root, &key, path);
2697 		if (ret < 0)
2698 			goto out;
2699 		else if (ret > 0) {
2700 			ret = -ENOENT;
2701 			goto out;
2702 		}
2703 
2704 		l = path->nodes[0];
2705 		slot = path->slots[0];
2706 
2707 		iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2708 		len = btrfs_inode_ref_name_len(l, iref);
2709 		ptr -= len + 1;
2710 		total_len += len + 1;
2711 		if (ptr < name) {
2712 			ret = -ENAMETOOLONG;
2713 			goto out;
2714 		}
2715 
2716 		*(ptr + len) = '/';
2717 		read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2718 
2719 		if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2720 			break;
2721 
2722 		btrfs_release_path(path);
2723 		key.objectid = key.offset;
2724 		key.offset = (u64)-1;
2725 		dirid = key.objectid;
2726 	}
2727 	memmove(name, ptr, total_len);
2728 	name[total_len] = '\0';
2729 	ret = 0;
2730 out:
2731 	btrfs_put_root(root);
2732 	btrfs_free_path(path);
2733 	return ret;
2734 }
2735 
2736 static int btrfs_search_path_in_tree_user(struct user_namespace *mnt_userns,
2737 				struct inode *inode,
2738 				struct btrfs_ioctl_ino_lookup_user_args *args)
2739 {
2740 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2741 	struct super_block *sb = inode->i_sb;
2742 	struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2743 	u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2744 	u64 dirid = args->dirid;
2745 	unsigned long item_off;
2746 	unsigned long item_len;
2747 	struct btrfs_inode_ref *iref;
2748 	struct btrfs_root_ref *rref;
2749 	struct btrfs_root *root = NULL;
2750 	struct btrfs_path *path;
2751 	struct btrfs_key key, key2;
2752 	struct extent_buffer *leaf;
2753 	struct inode *temp_inode;
2754 	char *ptr;
2755 	int slot;
2756 	int len;
2757 	int total_len = 0;
2758 	int ret;
2759 
2760 	path = btrfs_alloc_path();
2761 	if (!path)
2762 		return -ENOMEM;
2763 
2764 	/*
2765 	 * If the bottom subvolume does not exist directly under upper_limit,
2766 	 * construct the path in from the bottom up.
2767 	 */
2768 	if (dirid != upper_limit.objectid) {
2769 		ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2770 
2771 		root = btrfs_get_fs_root(fs_info, treeid, true);
2772 		if (IS_ERR(root)) {
2773 			ret = PTR_ERR(root);
2774 			goto out;
2775 		}
2776 
2777 		key.objectid = dirid;
2778 		key.type = BTRFS_INODE_REF_KEY;
2779 		key.offset = (u64)-1;
2780 		while (1) {
2781 			ret = btrfs_search_backwards(root, &key, path);
2782 			if (ret < 0)
2783 				goto out_put;
2784 			else if (ret > 0) {
2785 				ret = -ENOENT;
2786 				goto out_put;
2787 			}
2788 
2789 			leaf = path->nodes[0];
2790 			slot = path->slots[0];
2791 
2792 			iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2793 			len = btrfs_inode_ref_name_len(leaf, iref);
2794 			ptr -= len + 1;
2795 			total_len += len + 1;
2796 			if (ptr < args->path) {
2797 				ret = -ENAMETOOLONG;
2798 				goto out_put;
2799 			}
2800 
2801 			*(ptr + len) = '/';
2802 			read_extent_buffer(leaf, ptr,
2803 					(unsigned long)(iref + 1), len);
2804 
2805 			/* Check the read+exec permission of this directory */
2806 			ret = btrfs_previous_item(root, path, dirid,
2807 						  BTRFS_INODE_ITEM_KEY);
2808 			if (ret < 0) {
2809 				goto out_put;
2810 			} else if (ret > 0) {
2811 				ret = -ENOENT;
2812 				goto out_put;
2813 			}
2814 
2815 			leaf = path->nodes[0];
2816 			slot = path->slots[0];
2817 			btrfs_item_key_to_cpu(leaf, &key2, slot);
2818 			if (key2.objectid != dirid) {
2819 				ret = -ENOENT;
2820 				goto out_put;
2821 			}
2822 
2823 			temp_inode = btrfs_iget(sb, key2.objectid, root);
2824 			if (IS_ERR(temp_inode)) {
2825 				ret = PTR_ERR(temp_inode);
2826 				goto out_put;
2827 			}
2828 			ret = inode_permission(mnt_userns, temp_inode,
2829 					       MAY_READ | MAY_EXEC);
2830 			iput(temp_inode);
2831 			if (ret) {
2832 				ret = -EACCES;
2833 				goto out_put;
2834 			}
2835 
2836 			if (key.offset == upper_limit.objectid)
2837 				break;
2838 			if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2839 				ret = -EACCES;
2840 				goto out_put;
2841 			}
2842 
2843 			btrfs_release_path(path);
2844 			key.objectid = key.offset;
2845 			key.offset = (u64)-1;
2846 			dirid = key.objectid;
2847 		}
2848 
2849 		memmove(args->path, ptr, total_len);
2850 		args->path[total_len] = '\0';
2851 		btrfs_put_root(root);
2852 		root = NULL;
2853 		btrfs_release_path(path);
2854 	}
2855 
2856 	/* Get the bottom subvolume's name from ROOT_REF */
2857 	key.objectid = treeid;
2858 	key.type = BTRFS_ROOT_REF_KEY;
2859 	key.offset = args->treeid;
2860 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2861 	if (ret < 0) {
2862 		goto out;
2863 	} else if (ret > 0) {
2864 		ret = -ENOENT;
2865 		goto out;
2866 	}
2867 
2868 	leaf = path->nodes[0];
2869 	slot = path->slots[0];
2870 	btrfs_item_key_to_cpu(leaf, &key, slot);
2871 
2872 	item_off = btrfs_item_ptr_offset(leaf, slot);
2873 	item_len = btrfs_item_size(leaf, slot);
2874 	/* Check if dirid in ROOT_REF corresponds to passed dirid */
2875 	rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2876 	if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2877 		ret = -EINVAL;
2878 		goto out;
2879 	}
2880 
2881 	/* Copy subvolume's name */
2882 	item_off += sizeof(struct btrfs_root_ref);
2883 	item_len -= sizeof(struct btrfs_root_ref);
2884 	read_extent_buffer(leaf, args->name, item_off, item_len);
2885 	args->name[item_len] = 0;
2886 
2887 out_put:
2888 	btrfs_put_root(root);
2889 out:
2890 	btrfs_free_path(path);
2891 	return ret;
2892 }
2893 
2894 static noinline int btrfs_ioctl_ino_lookup(struct btrfs_root *root,
2895 					   void __user *argp)
2896 {
2897 	struct btrfs_ioctl_ino_lookup_args *args;
2898 	int ret = 0;
2899 
2900 	args = memdup_user(argp, sizeof(*args));
2901 	if (IS_ERR(args))
2902 		return PTR_ERR(args);
2903 
2904 	/*
2905 	 * Unprivileged query to obtain the containing subvolume root id. The
2906 	 * path is reset so it's consistent with btrfs_search_path_in_tree.
2907 	 */
2908 	if (args->treeid == 0)
2909 		args->treeid = root->root_key.objectid;
2910 
2911 	if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2912 		args->name[0] = 0;
2913 		goto out;
2914 	}
2915 
2916 	if (!capable(CAP_SYS_ADMIN)) {
2917 		ret = -EPERM;
2918 		goto out;
2919 	}
2920 
2921 	ret = btrfs_search_path_in_tree(root->fs_info,
2922 					args->treeid, args->objectid,
2923 					args->name);
2924 
2925 out:
2926 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2927 		ret = -EFAULT;
2928 
2929 	kfree(args);
2930 	return ret;
2931 }
2932 
2933 /*
2934  * Version of ino_lookup ioctl (unprivileged)
2935  *
2936  * The main differences from ino_lookup ioctl are:
2937  *
2938  *   1. Read + Exec permission will be checked using inode_permission() during
2939  *      path construction. -EACCES will be returned in case of failure.
2940  *   2. Path construction will be stopped at the inode number which corresponds
2941  *      to the fd with which this ioctl is called. If constructed path does not
2942  *      exist under fd's inode, -EACCES will be returned.
2943  *   3. The name of bottom subvolume is also searched and filled.
2944  */
2945 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2946 {
2947 	struct btrfs_ioctl_ino_lookup_user_args *args;
2948 	struct inode *inode;
2949 	int ret;
2950 
2951 	args = memdup_user(argp, sizeof(*args));
2952 	if (IS_ERR(args))
2953 		return PTR_ERR(args);
2954 
2955 	inode = file_inode(file);
2956 
2957 	if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2958 	    BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2959 		/*
2960 		 * The subvolume does not exist under fd with which this is
2961 		 * called
2962 		 */
2963 		kfree(args);
2964 		return -EACCES;
2965 	}
2966 
2967 	ret = btrfs_search_path_in_tree_user(file_mnt_user_ns(file), inode, args);
2968 
2969 	if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2970 		ret = -EFAULT;
2971 
2972 	kfree(args);
2973 	return ret;
2974 }
2975 
2976 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2977 static int btrfs_ioctl_get_subvol_info(struct inode *inode, void __user *argp)
2978 {
2979 	struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2980 	struct btrfs_fs_info *fs_info;
2981 	struct btrfs_root *root;
2982 	struct btrfs_path *path;
2983 	struct btrfs_key key;
2984 	struct btrfs_root_item *root_item;
2985 	struct btrfs_root_ref *rref;
2986 	struct extent_buffer *leaf;
2987 	unsigned long item_off;
2988 	unsigned long item_len;
2989 	int slot;
2990 	int ret = 0;
2991 
2992 	path = btrfs_alloc_path();
2993 	if (!path)
2994 		return -ENOMEM;
2995 
2996 	subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2997 	if (!subvol_info) {
2998 		btrfs_free_path(path);
2999 		return -ENOMEM;
3000 	}
3001 
3002 	fs_info = BTRFS_I(inode)->root->fs_info;
3003 
3004 	/* Get root_item of inode's subvolume */
3005 	key.objectid = BTRFS_I(inode)->root->root_key.objectid;
3006 	root = btrfs_get_fs_root(fs_info, key.objectid, true);
3007 	if (IS_ERR(root)) {
3008 		ret = PTR_ERR(root);
3009 		goto out_free;
3010 	}
3011 	root_item = &root->root_item;
3012 
3013 	subvol_info->treeid = key.objectid;
3014 
3015 	subvol_info->generation = btrfs_root_generation(root_item);
3016 	subvol_info->flags = btrfs_root_flags(root_item);
3017 
3018 	memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
3019 	memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
3020 						    BTRFS_UUID_SIZE);
3021 	memcpy(subvol_info->received_uuid, root_item->received_uuid,
3022 						    BTRFS_UUID_SIZE);
3023 
3024 	subvol_info->ctransid = btrfs_root_ctransid(root_item);
3025 	subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
3026 	subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
3027 
3028 	subvol_info->otransid = btrfs_root_otransid(root_item);
3029 	subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
3030 	subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
3031 
3032 	subvol_info->stransid = btrfs_root_stransid(root_item);
3033 	subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
3034 	subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
3035 
3036 	subvol_info->rtransid = btrfs_root_rtransid(root_item);
3037 	subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
3038 	subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
3039 
3040 	if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
3041 		/* Search root tree for ROOT_BACKREF of this subvolume */
3042 		key.type = BTRFS_ROOT_BACKREF_KEY;
3043 		key.offset = 0;
3044 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3045 		if (ret < 0) {
3046 			goto out;
3047 		} else if (path->slots[0] >=
3048 			   btrfs_header_nritems(path->nodes[0])) {
3049 			ret = btrfs_next_leaf(fs_info->tree_root, path);
3050 			if (ret < 0) {
3051 				goto out;
3052 			} else if (ret > 0) {
3053 				ret = -EUCLEAN;
3054 				goto out;
3055 			}
3056 		}
3057 
3058 		leaf = path->nodes[0];
3059 		slot = path->slots[0];
3060 		btrfs_item_key_to_cpu(leaf, &key, slot);
3061 		if (key.objectid == subvol_info->treeid &&
3062 		    key.type == BTRFS_ROOT_BACKREF_KEY) {
3063 			subvol_info->parent_id = key.offset;
3064 
3065 			rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
3066 			subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
3067 
3068 			item_off = btrfs_item_ptr_offset(leaf, slot)
3069 					+ sizeof(struct btrfs_root_ref);
3070 			item_len = btrfs_item_size(leaf, slot)
3071 					- sizeof(struct btrfs_root_ref);
3072 			read_extent_buffer(leaf, subvol_info->name,
3073 					   item_off, item_len);
3074 		} else {
3075 			ret = -ENOENT;
3076 			goto out;
3077 		}
3078 	}
3079 
3080 	if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
3081 		ret = -EFAULT;
3082 
3083 out:
3084 	btrfs_put_root(root);
3085 out_free:
3086 	btrfs_free_path(path);
3087 	kfree(subvol_info);
3088 	return ret;
3089 }
3090 
3091 /*
3092  * Return ROOT_REF information of the subvolume containing this inode
3093  * except the subvolume name.
3094  */
3095 static int btrfs_ioctl_get_subvol_rootref(struct btrfs_root *root,
3096 					  void __user *argp)
3097 {
3098 	struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
3099 	struct btrfs_root_ref *rref;
3100 	struct btrfs_path *path;
3101 	struct btrfs_key key;
3102 	struct extent_buffer *leaf;
3103 	u64 objectid;
3104 	int slot;
3105 	int ret;
3106 	u8 found;
3107 
3108 	path = btrfs_alloc_path();
3109 	if (!path)
3110 		return -ENOMEM;
3111 
3112 	rootrefs = memdup_user(argp, sizeof(*rootrefs));
3113 	if (IS_ERR(rootrefs)) {
3114 		btrfs_free_path(path);
3115 		return PTR_ERR(rootrefs);
3116 	}
3117 
3118 	objectid = root->root_key.objectid;
3119 	key.objectid = objectid;
3120 	key.type = BTRFS_ROOT_REF_KEY;
3121 	key.offset = rootrefs->min_treeid;
3122 	found = 0;
3123 
3124 	root = root->fs_info->tree_root;
3125 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3126 	if (ret < 0) {
3127 		goto out;
3128 	} else if (path->slots[0] >=
3129 		   btrfs_header_nritems(path->nodes[0])) {
3130 		ret = btrfs_next_leaf(root, path);
3131 		if (ret < 0) {
3132 			goto out;
3133 		} else if (ret > 0) {
3134 			ret = -EUCLEAN;
3135 			goto out;
3136 		}
3137 	}
3138 	while (1) {
3139 		leaf = path->nodes[0];
3140 		slot = path->slots[0];
3141 
3142 		btrfs_item_key_to_cpu(leaf, &key, slot);
3143 		if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
3144 			ret = 0;
3145 			goto out;
3146 		}
3147 
3148 		if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
3149 			ret = -EOVERFLOW;
3150 			goto out;
3151 		}
3152 
3153 		rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
3154 		rootrefs->rootref[found].treeid = key.offset;
3155 		rootrefs->rootref[found].dirid =
3156 				  btrfs_root_ref_dirid(leaf, rref);
3157 		found++;
3158 
3159 		ret = btrfs_next_item(root, path);
3160 		if (ret < 0) {
3161 			goto out;
3162 		} else if (ret > 0) {
3163 			ret = -EUCLEAN;
3164 			goto out;
3165 		}
3166 	}
3167 
3168 out:
3169 	if (!ret || ret == -EOVERFLOW) {
3170 		rootrefs->num_items = found;
3171 		/* update min_treeid for next search */
3172 		if (found)
3173 			rootrefs->min_treeid =
3174 				rootrefs->rootref[found - 1].treeid + 1;
3175 		if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
3176 			ret = -EFAULT;
3177 	}
3178 
3179 	kfree(rootrefs);
3180 	btrfs_free_path(path);
3181 
3182 	return ret;
3183 }
3184 
3185 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
3186 					     void __user *arg,
3187 					     bool destroy_v2)
3188 {
3189 	struct dentry *parent = file->f_path.dentry;
3190 	struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
3191 	struct dentry *dentry;
3192 	struct inode *dir = d_inode(parent);
3193 	struct inode *inode;
3194 	struct btrfs_root *root = BTRFS_I(dir)->root;
3195 	struct btrfs_root *dest = NULL;
3196 	struct btrfs_ioctl_vol_args *vol_args = NULL;
3197 	struct btrfs_ioctl_vol_args_v2 *vol_args2 = NULL;
3198 	struct user_namespace *mnt_userns = file_mnt_user_ns(file);
3199 	char *subvol_name, *subvol_name_ptr = NULL;
3200 	int subvol_namelen;
3201 	int err = 0;
3202 	bool destroy_parent = false;
3203 
3204 	/* We don't support snapshots with extent tree v2 yet. */
3205 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3206 		btrfs_err(fs_info,
3207 			  "extent tree v2 doesn't support snapshot deletion yet");
3208 		return -EOPNOTSUPP;
3209 	}
3210 
3211 	if (destroy_v2) {
3212 		vol_args2 = memdup_user(arg, sizeof(*vol_args2));
3213 		if (IS_ERR(vol_args2))
3214 			return PTR_ERR(vol_args2);
3215 
3216 		if (vol_args2->flags & ~BTRFS_SUBVOL_DELETE_ARGS_MASK) {
3217 			err = -EOPNOTSUPP;
3218 			goto out;
3219 		}
3220 
3221 		/*
3222 		 * If SPEC_BY_ID is not set, we are looking for the subvolume by
3223 		 * name, same as v1 currently does.
3224 		 */
3225 		if (!(vol_args2->flags & BTRFS_SUBVOL_SPEC_BY_ID)) {
3226 			vol_args2->name[BTRFS_SUBVOL_NAME_MAX] = 0;
3227 			subvol_name = vol_args2->name;
3228 
3229 			err = mnt_want_write_file(file);
3230 			if (err)
3231 				goto out;
3232 		} else {
3233 			struct inode *old_dir;
3234 
3235 			if (vol_args2->subvolid < BTRFS_FIRST_FREE_OBJECTID) {
3236 				err = -EINVAL;
3237 				goto out;
3238 			}
3239 
3240 			err = mnt_want_write_file(file);
3241 			if (err)
3242 				goto out;
3243 
3244 			dentry = btrfs_get_dentry(fs_info->sb,
3245 					BTRFS_FIRST_FREE_OBJECTID,
3246 					vol_args2->subvolid, 0, 0);
3247 			if (IS_ERR(dentry)) {
3248 				err = PTR_ERR(dentry);
3249 				goto out_drop_write;
3250 			}
3251 
3252 			/*
3253 			 * Change the default parent since the subvolume being
3254 			 * deleted can be outside of the current mount point.
3255 			 */
3256 			parent = btrfs_get_parent(dentry);
3257 
3258 			/*
3259 			 * At this point dentry->d_name can point to '/' if the
3260 			 * subvolume we want to destroy is outsite of the
3261 			 * current mount point, so we need to release the
3262 			 * current dentry and execute the lookup to return a new
3263 			 * one with ->d_name pointing to the
3264 			 * <mount point>/subvol_name.
3265 			 */
3266 			dput(dentry);
3267 			if (IS_ERR(parent)) {
3268 				err = PTR_ERR(parent);
3269 				goto out_drop_write;
3270 			}
3271 			old_dir = dir;
3272 			dir = d_inode(parent);
3273 
3274 			/*
3275 			 * If v2 was used with SPEC_BY_ID, a new parent was
3276 			 * allocated since the subvolume can be outside of the
3277 			 * current mount point. Later on we need to release this
3278 			 * new parent dentry.
3279 			 */
3280 			destroy_parent = true;
3281 
3282 			/*
3283 			 * On idmapped mounts, deletion via subvolid is
3284 			 * restricted to subvolumes that are immediate
3285 			 * ancestors of the inode referenced by the file
3286 			 * descriptor in the ioctl. Otherwise the idmapping
3287 			 * could potentially be abused to delete subvolumes
3288 			 * anywhere in the filesystem the user wouldn't be able
3289 			 * to delete without an idmapped mount.
3290 			 */
3291 			if (old_dir != dir && mnt_userns != &init_user_ns) {
3292 				err = -EOPNOTSUPP;
3293 				goto free_parent;
3294 			}
3295 
3296 			subvol_name_ptr = btrfs_get_subvol_name_from_objectid(
3297 						fs_info, vol_args2->subvolid);
3298 			if (IS_ERR(subvol_name_ptr)) {
3299 				err = PTR_ERR(subvol_name_ptr);
3300 				goto free_parent;
3301 			}
3302 			/* subvol_name_ptr is already nul terminated */
3303 			subvol_name = (char *)kbasename(subvol_name_ptr);
3304 		}
3305 	} else {
3306 		vol_args = memdup_user(arg, sizeof(*vol_args));
3307 		if (IS_ERR(vol_args))
3308 			return PTR_ERR(vol_args);
3309 
3310 		vol_args->name[BTRFS_PATH_NAME_MAX] = 0;
3311 		subvol_name = vol_args->name;
3312 
3313 		err = mnt_want_write_file(file);
3314 		if (err)
3315 			goto out;
3316 	}
3317 
3318 	subvol_namelen = strlen(subvol_name);
3319 
3320 	if (strchr(subvol_name, '/') ||
3321 	    strncmp(subvol_name, "..", subvol_namelen) == 0) {
3322 		err = -EINVAL;
3323 		goto free_subvol_name;
3324 	}
3325 
3326 	if (!S_ISDIR(dir->i_mode)) {
3327 		err = -ENOTDIR;
3328 		goto free_subvol_name;
3329 	}
3330 
3331 	err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
3332 	if (err == -EINTR)
3333 		goto free_subvol_name;
3334 	dentry = lookup_one(mnt_userns, subvol_name, parent, subvol_namelen);
3335 	if (IS_ERR(dentry)) {
3336 		err = PTR_ERR(dentry);
3337 		goto out_unlock_dir;
3338 	}
3339 
3340 	if (d_really_is_negative(dentry)) {
3341 		err = -ENOENT;
3342 		goto out_dput;
3343 	}
3344 
3345 	inode = d_inode(dentry);
3346 	dest = BTRFS_I(inode)->root;
3347 	if (!capable(CAP_SYS_ADMIN)) {
3348 		/*
3349 		 * Regular user.  Only allow this with a special mount
3350 		 * option, when the user has write+exec access to the
3351 		 * subvol root, and when rmdir(2) would have been
3352 		 * allowed.
3353 		 *
3354 		 * Note that this is _not_ check that the subvol is
3355 		 * empty or doesn't contain data that we wouldn't
3356 		 * otherwise be able to delete.
3357 		 *
3358 		 * Users who want to delete empty subvols should try
3359 		 * rmdir(2).
3360 		 */
3361 		err = -EPERM;
3362 		if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
3363 			goto out_dput;
3364 
3365 		/*
3366 		 * Do not allow deletion if the parent dir is the same
3367 		 * as the dir to be deleted.  That means the ioctl
3368 		 * must be called on the dentry referencing the root
3369 		 * of the subvol, not a random directory contained
3370 		 * within it.
3371 		 */
3372 		err = -EINVAL;
3373 		if (root == dest)
3374 			goto out_dput;
3375 
3376 		err = inode_permission(mnt_userns, inode, MAY_WRITE | MAY_EXEC);
3377 		if (err)
3378 			goto out_dput;
3379 	}
3380 
3381 	/* check if subvolume may be deleted by a user */
3382 	err = btrfs_may_delete(mnt_userns, dir, dentry, 1);
3383 	if (err)
3384 		goto out_dput;
3385 
3386 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
3387 		err = -EINVAL;
3388 		goto out_dput;
3389 	}
3390 
3391 	btrfs_inode_lock(inode, 0);
3392 	err = btrfs_delete_subvolume(dir, dentry);
3393 	btrfs_inode_unlock(inode, 0);
3394 	if (!err)
3395 		d_delete_notify(dir, dentry);
3396 
3397 out_dput:
3398 	dput(dentry);
3399 out_unlock_dir:
3400 	btrfs_inode_unlock(dir, 0);
3401 free_subvol_name:
3402 	kfree(subvol_name_ptr);
3403 free_parent:
3404 	if (destroy_parent)
3405 		dput(parent);
3406 out_drop_write:
3407 	mnt_drop_write_file(file);
3408 out:
3409 	kfree(vol_args2);
3410 	kfree(vol_args);
3411 	return err;
3412 }
3413 
3414 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
3415 {
3416 	struct inode *inode = file_inode(file);
3417 	struct btrfs_root *root = BTRFS_I(inode)->root;
3418 	struct btrfs_ioctl_defrag_range_args range = {0};
3419 	int ret;
3420 
3421 	ret = mnt_want_write_file(file);
3422 	if (ret)
3423 		return ret;
3424 
3425 	if (btrfs_root_readonly(root)) {
3426 		ret = -EROFS;
3427 		goto out;
3428 	}
3429 
3430 	switch (inode->i_mode & S_IFMT) {
3431 	case S_IFDIR:
3432 		if (!capable(CAP_SYS_ADMIN)) {
3433 			ret = -EPERM;
3434 			goto out;
3435 		}
3436 		ret = btrfs_defrag_root(root);
3437 		break;
3438 	case S_IFREG:
3439 		/*
3440 		 * Note that this does not check the file descriptor for write
3441 		 * access. This prevents defragmenting executables that are
3442 		 * running and allows defrag on files open in read-only mode.
3443 		 */
3444 		if (!capable(CAP_SYS_ADMIN) &&
3445 		    inode_permission(&init_user_ns, inode, MAY_WRITE)) {
3446 			ret = -EPERM;
3447 			goto out;
3448 		}
3449 
3450 		if (argp) {
3451 			if (copy_from_user(&range, argp, sizeof(range))) {
3452 				ret = -EFAULT;
3453 				goto out;
3454 			}
3455 			/* compression requires us to start the IO */
3456 			if ((range.flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3457 				range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
3458 				range.extent_thresh = (u32)-1;
3459 			}
3460 		} else {
3461 			/* the rest are all set to zero by kzalloc */
3462 			range.len = (u64)-1;
3463 		}
3464 		ret = btrfs_defrag_file(file_inode(file), &file->f_ra,
3465 					&range, BTRFS_OLDEST_GENERATION, 0);
3466 		if (ret > 0)
3467 			ret = 0;
3468 		break;
3469 	default:
3470 		ret = -EINVAL;
3471 	}
3472 out:
3473 	mnt_drop_write_file(file);
3474 	return ret;
3475 }
3476 
3477 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3478 {
3479 	struct btrfs_ioctl_vol_args *vol_args;
3480 	bool restore_op = false;
3481 	int ret;
3482 
3483 	if (!capable(CAP_SYS_ADMIN))
3484 		return -EPERM;
3485 
3486 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3487 		btrfs_err(fs_info, "device add not supported on extent tree v2 yet");
3488 		return -EINVAL;
3489 	}
3490 
3491 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_ADD)) {
3492 		if (!btrfs_exclop_start_try_lock(fs_info, BTRFS_EXCLOP_DEV_ADD))
3493 			return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3494 
3495 		/*
3496 		 * We can do the device add because we have a paused balanced,
3497 		 * change the exclusive op type and remember we should bring
3498 		 * back the paused balance
3499 		 */
3500 		fs_info->exclusive_operation = BTRFS_EXCLOP_DEV_ADD;
3501 		btrfs_exclop_start_unlock(fs_info);
3502 		restore_op = true;
3503 	}
3504 
3505 	vol_args = memdup_user(arg, sizeof(*vol_args));
3506 	if (IS_ERR(vol_args)) {
3507 		ret = PTR_ERR(vol_args);
3508 		goto out;
3509 	}
3510 
3511 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3512 	ret = btrfs_init_new_device(fs_info, vol_args->name);
3513 
3514 	if (!ret)
3515 		btrfs_info(fs_info, "disk added %s", vol_args->name);
3516 
3517 	kfree(vol_args);
3518 out:
3519 	if (restore_op)
3520 		btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
3521 	else
3522 		btrfs_exclop_finish(fs_info);
3523 	return ret;
3524 }
3525 
3526 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3527 {
3528 	BTRFS_DEV_LOOKUP_ARGS(args);
3529 	struct inode *inode = file_inode(file);
3530 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3531 	struct btrfs_ioctl_vol_args_v2 *vol_args;
3532 	struct block_device *bdev = NULL;
3533 	fmode_t mode;
3534 	int ret;
3535 	bool cancel = false;
3536 
3537 	if (!capable(CAP_SYS_ADMIN))
3538 		return -EPERM;
3539 
3540 	vol_args = memdup_user(arg, sizeof(*vol_args));
3541 	if (IS_ERR(vol_args))
3542 		return PTR_ERR(vol_args);
3543 
3544 	if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
3545 		ret = -EOPNOTSUPP;
3546 		goto out;
3547 	}
3548 
3549 	vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3550 	if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3551 		args.devid = vol_args->devid;
3552 	} else if (!strcmp("cancel", vol_args->name)) {
3553 		cancel = true;
3554 	} else {
3555 		ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3556 		if (ret)
3557 			goto out;
3558 	}
3559 
3560 	ret = mnt_want_write_file(file);
3561 	if (ret)
3562 		goto out;
3563 
3564 	ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3565 					   cancel);
3566 	if (ret)
3567 		goto err_drop;
3568 
3569 	/* Exclusive operation is now claimed */
3570 	ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3571 
3572 	btrfs_exclop_finish(fs_info);
3573 
3574 	if (!ret) {
3575 		if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3576 			btrfs_info(fs_info, "device deleted: id %llu",
3577 					vol_args->devid);
3578 		else
3579 			btrfs_info(fs_info, "device deleted: %s",
3580 					vol_args->name);
3581 	}
3582 err_drop:
3583 	mnt_drop_write_file(file);
3584 	if (bdev)
3585 		blkdev_put(bdev, mode);
3586 out:
3587 	btrfs_put_dev_args_from_path(&args);
3588 	kfree(vol_args);
3589 	return ret;
3590 }
3591 
3592 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3593 {
3594 	BTRFS_DEV_LOOKUP_ARGS(args);
3595 	struct inode *inode = file_inode(file);
3596 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3597 	struct btrfs_ioctl_vol_args *vol_args;
3598 	struct block_device *bdev = NULL;
3599 	fmode_t mode;
3600 	int ret;
3601 	bool cancel = false;
3602 
3603 	if (!capable(CAP_SYS_ADMIN))
3604 		return -EPERM;
3605 
3606 	vol_args = memdup_user(arg, sizeof(*vol_args));
3607 	if (IS_ERR(vol_args))
3608 		return PTR_ERR(vol_args);
3609 
3610 	vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3611 	if (!strcmp("cancel", vol_args->name)) {
3612 		cancel = true;
3613 	} else {
3614 		ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3615 		if (ret)
3616 			goto out;
3617 	}
3618 
3619 	ret = mnt_want_write_file(file);
3620 	if (ret)
3621 		goto out;
3622 
3623 	ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3624 					   cancel);
3625 	if (ret == 0) {
3626 		ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
3627 		if (!ret)
3628 			btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3629 		btrfs_exclop_finish(fs_info);
3630 	}
3631 
3632 	mnt_drop_write_file(file);
3633 	if (bdev)
3634 		blkdev_put(bdev, mode);
3635 out:
3636 	btrfs_put_dev_args_from_path(&args);
3637 	kfree(vol_args);
3638 	return ret;
3639 }
3640 
3641 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3642 				void __user *arg)
3643 {
3644 	struct btrfs_ioctl_fs_info_args *fi_args;
3645 	struct btrfs_device *device;
3646 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3647 	u64 flags_in;
3648 	int ret = 0;
3649 
3650 	fi_args = memdup_user(arg, sizeof(*fi_args));
3651 	if (IS_ERR(fi_args))
3652 		return PTR_ERR(fi_args);
3653 
3654 	flags_in = fi_args->flags;
3655 	memset(fi_args, 0, sizeof(*fi_args));
3656 
3657 	rcu_read_lock();
3658 	fi_args->num_devices = fs_devices->num_devices;
3659 
3660 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3661 		if (device->devid > fi_args->max_id)
3662 			fi_args->max_id = device->devid;
3663 	}
3664 	rcu_read_unlock();
3665 
3666 	memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3667 	fi_args->nodesize = fs_info->nodesize;
3668 	fi_args->sectorsize = fs_info->sectorsize;
3669 	fi_args->clone_alignment = fs_info->sectorsize;
3670 
3671 	if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3672 		fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3673 		fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3674 		fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3675 	}
3676 
3677 	if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
3678 		fi_args->generation = fs_info->generation;
3679 		fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
3680 	}
3681 
3682 	if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
3683 		memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
3684 		       sizeof(fi_args->metadata_uuid));
3685 		fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
3686 	}
3687 
3688 	if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3689 		ret = -EFAULT;
3690 
3691 	kfree(fi_args);
3692 	return ret;
3693 }
3694 
3695 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3696 				 void __user *arg)
3697 {
3698 	BTRFS_DEV_LOOKUP_ARGS(args);
3699 	struct btrfs_ioctl_dev_info_args *di_args;
3700 	struct btrfs_device *dev;
3701 	int ret = 0;
3702 
3703 	di_args = memdup_user(arg, sizeof(*di_args));
3704 	if (IS_ERR(di_args))
3705 		return PTR_ERR(di_args);
3706 
3707 	args.devid = di_args->devid;
3708 	if (!btrfs_is_empty_uuid(di_args->uuid))
3709 		args.uuid = di_args->uuid;
3710 
3711 	rcu_read_lock();
3712 	dev = btrfs_find_device(fs_info->fs_devices, &args);
3713 	if (!dev) {
3714 		ret = -ENODEV;
3715 		goto out;
3716 	}
3717 
3718 	di_args->devid = dev->devid;
3719 	di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3720 	di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3721 	memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3722 	if (dev->name) {
3723 		strncpy(di_args->path, rcu_str_deref(dev->name),
3724 				sizeof(di_args->path) - 1);
3725 		di_args->path[sizeof(di_args->path) - 1] = 0;
3726 	} else {
3727 		di_args->path[0] = '\0';
3728 	}
3729 
3730 out:
3731 	rcu_read_unlock();
3732 	if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3733 		ret = -EFAULT;
3734 
3735 	kfree(di_args);
3736 	return ret;
3737 }
3738 
3739 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3740 {
3741 	struct inode *inode = file_inode(file);
3742 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3743 	struct btrfs_root *root = BTRFS_I(inode)->root;
3744 	struct btrfs_root *new_root;
3745 	struct btrfs_dir_item *di;
3746 	struct btrfs_trans_handle *trans;
3747 	struct btrfs_path *path = NULL;
3748 	struct btrfs_disk_key disk_key;
3749 	u64 objectid = 0;
3750 	u64 dir_id;
3751 	int ret;
3752 
3753 	if (!capable(CAP_SYS_ADMIN))
3754 		return -EPERM;
3755 
3756 	ret = mnt_want_write_file(file);
3757 	if (ret)
3758 		return ret;
3759 
3760 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3761 		ret = -EFAULT;
3762 		goto out;
3763 	}
3764 
3765 	if (!objectid)
3766 		objectid = BTRFS_FS_TREE_OBJECTID;
3767 
3768 	new_root = btrfs_get_fs_root(fs_info, objectid, true);
3769 	if (IS_ERR(new_root)) {
3770 		ret = PTR_ERR(new_root);
3771 		goto out;
3772 	}
3773 	if (!is_fstree(new_root->root_key.objectid)) {
3774 		ret = -ENOENT;
3775 		goto out_free;
3776 	}
3777 
3778 	path = btrfs_alloc_path();
3779 	if (!path) {
3780 		ret = -ENOMEM;
3781 		goto out_free;
3782 	}
3783 
3784 	trans = btrfs_start_transaction(root, 1);
3785 	if (IS_ERR(trans)) {
3786 		ret = PTR_ERR(trans);
3787 		goto out_free;
3788 	}
3789 
3790 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
3791 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
3792 				   dir_id, "default", 7, 1);
3793 	if (IS_ERR_OR_NULL(di)) {
3794 		btrfs_release_path(path);
3795 		btrfs_end_transaction(trans);
3796 		btrfs_err(fs_info,
3797 			  "Umm, you don't have the default diritem, this isn't going to work");
3798 		ret = -ENOENT;
3799 		goto out_free;
3800 	}
3801 
3802 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3803 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3804 	btrfs_mark_buffer_dirty(path->nodes[0]);
3805 	btrfs_release_path(path);
3806 
3807 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
3808 	btrfs_end_transaction(trans);
3809 out_free:
3810 	btrfs_put_root(new_root);
3811 	btrfs_free_path(path);
3812 out:
3813 	mnt_drop_write_file(file);
3814 	return ret;
3815 }
3816 
3817 static void get_block_group_info(struct list_head *groups_list,
3818 				 struct btrfs_ioctl_space_info *space)
3819 {
3820 	struct btrfs_block_group *block_group;
3821 
3822 	space->total_bytes = 0;
3823 	space->used_bytes = 0;
3824 	space->flags = 0;
3825 	list_for_each_entry(block_group, groups_list, list) {
3826 		space->flags = block_group->flags;
3827 		space->total_bytes += block_group->length;
3828 		space->used_bytes += block_group->used;
3829 	}
3830 }
3831 
3832 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
3833 				   void __user *arg)
3834 {
3835 	struct btrfs_ioctl_space_args space_args;
3836 	struct btrfs_ioctl_space_info space;
3837 	struct btrfs_ioctl_space_info *dest;
3838 	struct btrfs_ioctl_space_info *dest_orig;
3839 	struct btrfs_ioctl_space_info __user *user_dest;
3840 	struct btrfs_space_info *info;
3841 	static const u64 types[] = {
3842 		BTRFS_BLOCK_GROUP_DATA,
3843 		BTRFS_BLOCK_GROUP_SYSTEM,
3844 		BTRFS_BLOCK_GROUP_METADATA,
3845 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3846 	};
3847 	int num_types = 4;
3848 	int alloc_size;
3849 	int ret = 0;
3850 	u64 slot_count = 0;
3851 	int i, c;
3852 
3853 	if (copy_from_user(&space_args,
3854 			   (struct btrfs_ioctl_space_args __user *)arg,
3855 			   sizeof(space_args)))
3856 		return -EFAULT;
3857 
3858 	for (i = 0; i < num_types; i++) {
3859 		struct btrfs_space_info *tmp;
3860 
3861 		info = NULL;
3862 		list_for_each_entry(tmp, &fs_info->space_info, list) {
3863 			if (tmp->flags == types[i]) {
3864 				info = tmp;
3865 				break;
3866 			}
3867 		}
3868 
3869 		if (!info)
3870 			continue;
3871 
3872 		down_read(&info->groups_sem);
3873 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3874 			if (!list_empty(&info->block_groups[c]))
3875 				slot_count++;
3876 		}
3877 		up_read(&info->groups_sem);
3878 	}
3879 
3880 	/*
3881 	 * Global block reserve, exported as a space_info
3882 	 */
3883 	slot_count++;
3884 
3885 	/* space_slots == 0 means they are asking for a count */
3886 	if (space_args.space_slots == 0) {
3887 		space_args.total_spaces = slot_count;
3888 		goto out;
3889 	}
3890 
3891 	slot_count = min_t(u64, space_args.space_slots, slot_count);
3892 
3893 	alloc_size = sizeof(*dest) * slot_count;
3894 
3895 	/* we generally have at most 6 or so space infos, one for each raid
3896 	 * level.  So, a whole page should be more than enough for everyone
3897 	 */
3898 	if (alloc_size > PAGE_SIZE)
3899 		return -ENOMEM;
3900 
3901 	space_args.total_spaces = 0;
3902 	dest = kmalloc(alloc_size, GFP_KERNEL);
3903 	if (!dest)
3904 		return -ENOMEM;
3905 	dest_orig = dest;
3906 
3907 	/* now we have a buffer to copy into */
3908 	for (i = 0; i < num_types; i++) {
3909 		struct btrfs_space_info *tmp;
3910 
3911 		if (!slot_count)
3912 			break;
3913 
3914 		info = NULL;
3915 		list_for_each_entry(tmp, &fs_info->space_info, list) {
3916 			if (tmp->flags == types[i]) {
3917 				info = tmp;
3918 				break;
3919 			}
3920 		}
3921 
3922 		if (!info)
3923 			continue;
3924 		down_read(&info->groups_sem);
3925 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3926 			if (!list_empty(&info->block_groups[c])) {
3927 				get_block_group_info(&info->block_groups[c],
3928 						     &space);
3929 				memcpy(dest, &space, sizeof(space));
3930 				dest++;
3931 				space_args.total_spaces++;
3932 				slot_count--;
3933 			}
3934 			if (!slot_count)
3935 				break;
3936 		}
3937 		up_read(&info->groups_sem);
3938 	}
3939 
3940 	/*
3941 	 * Add global block reserve
3942 	 */
3943 	if (slot_count) {
3944 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3945 
3946 		spin_lock(&block_rsv->lock);
3947 		space.total_bytes = block_rsv->size;
3948 		space.used_bytes = block_rsv->size - block_rsv->reserved;
3949 		spin_unlock(&block_rsv->lock);
3950 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
3951 		memcpy(dest, &space, sizeof(space));
3952 		space_args.total_spaces++;
3953 	}
3954 
3955 	user_dest = (struct btrfs_ioctl_space_info __user *)
3956 		(arg + sizeof(struct btrfs_ioctl_space_args));
3957 
3958 	if (copy_to_user(user_dest, dest_orig, alloc_size))
3959 		ret = -EFAULT;
3960 
3961 	kfree(dest_orig);
3962 out:
3963 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3964 		ret = -EFAULT;
3965 
3966 	return ret;
3967 }
3968 
3969 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3970 					    void __user *argp)
3971 {
3972 	struct btrfs_trans_handle *trans;
3973 	u64 transid;
3974 
3975 	trans = btrfs_attach_transaction_barrier(root);
3976 	if (IS_ERR(trans)) {
3977 		if (PTR_ERR(trans) != -ENOENT)
3978 			return PTR_ERR(trans);
3979 
3980 		/* No running transaction, don't bother */
3981 		transid = root->fs_info->last_trans_committed;
3982 		goto out;
3983 	}
3984 	transid = trans->transid;
3985 	btrfs_commit_transaction_async(trans);
3986 out:
3987 	if (argp)
3988 		if (copy_to_user(argp, &transid, sizeof(transid)))
3989 			return -EFAULT;
3990 	return 0;
3991 }
3992 
3993 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
3994 					   void __user *argp)
3995 {
3996 	u64 transid;
3997 
3998 	if (argp) {
3999 		if (copy_from_user(&transid, argp, sizeof(transid)))
4000 			return -EFAULT;
4001 	} else {
4002 		transid = 0;  /* current trans */
4003 	}
4004 	return btrfs_wait_for_commit(fs_info, transid);
4005 }
4006 
4007 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4008 {
4009 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4010 	struct btrfs_ioctl_scrub_args *sa;
4011 	int ret;
4012 
4013 	if (!capable(CAP_SYS_ADMIN))
4014 		return -EPERM;
4015 
4016 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
4017 		btrfs_err(fs_info, "scrub is not supported on extent tree v2 yet");
4018 		return -EINVAL;
4019 	}
4020 
4021 	sa = memdup_user(arg, sizeof(*sa));
4022 	if (IS_ERR(sa))
4023 		return PTR_ERR(sa);
4024 
4025 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4026 		ret = mnt_want_write_file(file);
4027 		if (ret)
4028 			goto out;
4029 	}
4030 
4031 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
4032 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4033 			      0);
4034 
4035 	/*
4036 	 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
4037 	 * error. This is important as it allows user space to know how much
4038 	 * progress scrub has done. For example, if scrub is canceled we get
4039 	 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
4040 	 * space. Later user space can inspect the progress from the structure
4041 	 * btrfs_ioctl_scrub_args and resume scrub from where it left off
4042 	 * previously (btrfs-progs does this).
4043 	 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
4044 	 * then return -EFAULT to signal the structure was not copied or it may
4045 	 * be corrupt and unreliable due to a partial copy.
4046 	 */
4047 	if (copy_to_user(arg, sa, sizeof(*sa)))
4048 		ret = -EFAULT;
4049 
4050 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4051 		mnt_drop_write_file(file);
4052 out:
4053 	kfree(sa);
4054 	return ret;
4055 }
4056 
4057 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4058 {
4059 	if (!capable(CAP_SYS_ADMIN))
4060 		return -EPERM;
4061 
4062 	return btrfs_scrub_cancel(fs_info);
4063 }
4064 
4065 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4066 				       void __user *arg)
4067 {
4068 	struct btrfs_ioctl_scrub_args *sa;
4069 	int ret;
4070 
4071 	if (!capable(CAP_SYS_ADMIN))
4072 		return -EPERM;
4073 
4074 	sa = memdup_user(arg, sizeof(*sa));
4075 	if (IS_ERR(sa))
4076 		return PTR_ERR(sa);
4077 
4078 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4079 
4080 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4081 		ret = -EFAULT;
4082 
4083 	kfree(sa);
4084 	return ret;
4085 }
4086 
4087 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4088 				      void __user *arg)
4089 {
4090 	struct btrfs_ioctl_get_dev_stats *sa;
4091 	int ret;
4092 
4093 	sa = memdup_user(arg, sizeof(*sa));
4094 	if (IS_ERR(sa))
4095 		return PTR_ERR(sa);
4096 
4097 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4098 		kfree(sa);
4099 		return -EPERM;
4100 	}
4101 
4102 	ret = btrfs_get_dev_stats(fs_info, sa);
4103 
4104 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4105 		ret = -EFAULT;
4106 
4107 	kfree(sa);
4108 	return ret;
4109 }
4110 
4111 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
4112 				    void __user *arg)
4113 {
4114 	struct btrfs_ioctl_dev_replace_args *p;
4115 	int ret;
4116 
4117 	if (!capable(CAP_SYS_ADMIN))
4118 		return -EPERM;
4119 
4120 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
4121 		btrfs_err(fs_info, "device replace not supported on extent tree v2 yet");
4122 		return -EINVAL;
4123 	}
4124 
4125 	p = memdup_user(arg, sizeof(*p));
4126 	if (IS_ERR(p))
4127 		return PTR_ERR(p);
4128 
4129 	switch (p->cmd) {
4130 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4131 		if (sb_rdonly(fs_info->sb)) {
4132 			ret = -EROFS;
4133 			goto out;
4134 		}
4135 		if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
4136 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4137 		} else {
4138 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4139 			btrfs_exclop_finish(fs_info);
4140 		}
4141 		break;
4142 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4143 		btrfs_dev_replace_status(fs_info, p);
4144 		ret = 0;
4145 		break;
4146 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4147 		p->result = btrfs_dev_replace_cancel(fs_info);
4148 		ret = 0;
4149 		break;
4150 	default:
4151 		ret = -EINVAL;
4152 		break;
4153 	}
4154 
4155 	if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
4156 		ret = -EFAULT;
4157 out:
4158 	kfree(p);
4159 	return ret;
4160 }
4161 
4162 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4163 {
4164 	int ret = 0;
4165 	int i;
4166 	u64 rel_ptr;
4167 	int size;
4168 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4169 	struct inode_fs_paths *ipath = NULL;
4170 	struct btrfs_path *path;
4171 
4172 	if (!capable(CAP_DAC_READ_SEARCH))
4173 		return -EPERM;
4174 
4175 	path = btrfs_alloc_path();
4176 	if (!path) {
4177 		ret = -ENOMEM;
4178 		goto out;
4179 	}
4180 
4181 	ipa = memdup_user(arg, sizeof(*ipa));
4182 	if (IS_ERR(ipa)) {
4183 		ret = PTR_ERR(ipa);
4184 		ipa = NULL;
4185 		goto out;
4186 	}
4187 
4188 	size = min_t(u32, ipa->size, 4096);
4189 	ipath = init_ipath(size, root, path);
4190 	if (IS_ERR(ipath)) {
4191 		ret = PTR_ERR(ipath);
4192 		ipath = NULL;
4193 		goto out;
4194 	}
4195 
4196 	ret = paths_from_inode(ipa->inum, ipath);
4197 	if (ret < 0)
4198 		goto out;
4199 
4200 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4201 		rel_ptr = ipath->fspath->val[i] -
4202 			  (u64)(unsigned long)ipath->fspath->val;
4203 		ipath->fspath->val[i] = rel_ptr;
4204 	}
4205 
4206 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4207 			   ipath->fspath, size);
4208 	if (ret) {
4209 		ret = -EFAULT;
4210 		goto out;
4211 	}
4212 
4213 out:
4214 	btrfs_free_path(path);
4215 	free_ipath(ipath);
4216 	kfree(ipa);
4217 
4218 	return ret;
4219 }
4220 
4221 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4222 {
4223 	struct btrfs_data_container *inodes = ctx;
4224 	const size_t c = 3 * sizeof(u64);
4225 
4226 	if (inodes->bytes_left >= c) {
4227 		inodes->bytes_left -= c;
4228 		inodes->val[inodes->elem_cnt] = inum;
4229 		inodes->val[inodes->elem_cnt + 1] = offset;
4230 		inodes->val[inodes->elem_cnt + 2] = root;
4231 		inodes->elem_cnt += 3;
4232 	} else {
4233 		inodes->bytes_missing += c - inodes->bytes_left;
4234 		inodes->bytes_left = 0;
4235 		inodes->elem_missed += 3;
4236 	}
4237 
4238 	return 0;
4239 }
4240 
4241 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4242 					void __user *arg, int version)
4243 {
4244 	int ret = 0;
4245 	int size;
4246 	struct btrfs_ioctl_logical_ino_args *loi;
4247 	struct btrfs_data_container *inodes = NULL;
4248 	struct btrfs_path *path = NULL;
4249 	bool ignore_offset;
4250 
4251 	if (!capable(CAP_SYS_ADMIN))
4252 		return -EPERM;
4253 
4254 	loi = memdup_user(arg, sizeof(*loi));
4255 	if (IS_ERR(loi))
4256 		return PTR_ERR(loi);
4257 
4258 	if (version == 1) {
4259 		ignore_offset = false;
4260 		size = min_t(u32, loi->size, SZ_64K);
4261 	} else {
4262 		/* All reserved bits must be 0 for now */
4263 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4264 			ret = -EINVAL;
4265 			goto out_loi;
4266 		}
4267 		/* Only accept flags we have defined so far */
4268 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4269 			ret = -EINVAL;
4270 			goto out_loi;
4271 		}
4272 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4273 		size = min_t(u32, loi->size, SZ_16M);
4274 	}
4275 
4276 	path = btrfs_alloc_path();
4277 	if (!path) {
4278 		ret = -ENOMEM;
4279 		goto out;
4280 	}
4281 
4282 	inodes = init_data_container(size);
4283 	if (IS_ERR(inodes)) {
4284 		ret = PTR_ERR(inodes);
4285 		inodes = NULL;
4286 		goto out;
4287 	}
4288 
4289 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4290 					  build_ino_list, inodes, ignore_offset);
4291 	if (ret == -EINVAL)
4292 		ret = -ENOENT;
4293 	if (ret < 0)
4294 		goto out;
4295 
4296 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4297 			   size);
4298 	if (ret)
4299 		ret = -EFAULT;
4300 
4301 out:
4302 	btrfs_free_path(path);
4303 	kvfree(inodes);
4304 out_loi:
4305 	kfree(loi);
4306 
4307 	return ret;
4308 }
4309 
4310 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4311 			       struct btrfs_ioctl_balance_args *bargs)
4312 {
4313 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4314 
4315 	bargs->flags = bctl->flags;
4316 
4317 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4318 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4319 	if (atomic_read(&fs_info->balance_pause_req))
4320 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4321 	if (atomic_read(&fs_info->balance_cancel_req))
4322 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4323 
4324 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4325 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4326 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4327 
4328 	spin_lock(&fs_info->balance_lock);
4329 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4330 	spin_unlock(&fs_info->balance_lock);
4331 }
4332 
4333 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4334 {
4335 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4336 	struct btrfs_fs_info *fs_info = root->fs_info;
4337 	struct btrfs_ioctl_balance_args *bargs;
4338 	struct btrfs_balance_control *bctl;
4339 	bool need_unlock; /* for mut. excl. ops lock */
4340 	int ret;
4341 
4342 	if (!arg)
4343 		btrfs_warn(fs_info,
4344 	"IOC_BALANCE ioctl (v1) is deprecated and will be removed in kernel 5.18");
4345 
4346 	if (!capable(CAP_SYS_ADMIN))
4347 		return -EPERM;
4348 
4349 	ret = mnt_want_write_file(file);
4350 	if (ret)
4351 		return ret;
4352 
4353 again:
4354 	if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
4355 		mutex_lock(&fs_info->balance_mutex);
4356 		need_unlock = true;
4357 		goto locked;
4358 	}
4359 
4360 	/*
4361 	 * mut. excl. ops lock is locked.  Three possibilities:
4362 	 *   (1) some other op is running
4363 	 *   (2) balance is running
4364 	 *   (3) balance is paused -- special case (think resume)
4365 	 */
4366 	mutex_lock(&fs_info->balance_mutex);
4367 	if (fs_info->balance_ctl) {
4368 		/* this is either (2) or (3) */
4369 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4370 			mutex_unlock(&fs_info->balance_mutex);
4371 			/*
4372 			 * Lock released to allow other waiters to continue,
4373 			 * we'll reexamine the status again.
4374 			 */
4375 			mutex_lock(&fs_info->balance_mutex);
4376 
4377 			if (fs_info->balance_ctl &&
4378 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4379 				/* this is (3) */
4380 				need_unlock = false;
4381 				goto locked;
4382 			}
4383 
4384 			mutex_unlock(&fs_info->balance_mutex);
4385 			goto again;
4386 		} else {
4387 			/* this is (2) */
4388 			mutex_unlock(&fs_info->balance_mutex);
4389 			ret = -EINPROGRESS;
4390 			goto out;
4391 		}
4392 	} else {
4393 		/* this is (1) */
4394 		mutex_unlock(&fs_info->balance_mutex);
4395 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4396 		goto out;
4397 	}
4398 
4399 locked:
4400 
4401 	if (arg) {
4402 		bargs = memdup_user(arg, sizeof(*bargs));
4403 		if (IS_ERR(bargs)) {
4404 			ret = PTR_ERR(bargs);
4405 			goto out_unlock;
4406 		}
4407 
4408 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4409 			if (!fs_info->balance_ctl) {
4410 				ret = -ENOTCONN;
4411 				goto out_bargs;
4412 			}
4413 
4414 			bctl = fs_info->balance_ctl;
4415 			spin_lock(&fs_info->balance_lock);
4416 			bctl->flags |= BTRFS_BALANCE_RESUME;
4417 			spin_unlock(&fs_info->balance_lock);
4418 			btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE);
4419 
4420 			goto do_balance;
4421 		}
4422 	} else {
4423 		bargs = NULL;
4424 	}
4425 
4426 	if (fs_info->balance_ctl) {
4427 		ret = -EINPROGRESS;
4428 		goto out_bargs;
4429 	}
4430 
4431 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4432 	if (!bctl) {
4433 		ret = -ENOMEM;
4434 		goto out_bargs;
4435 	}
4436 
4437 	if (arg) {
4438 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4439 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4440 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4441 
4442 		bctl->flags = bargs->flags;
4443 	} else {
4444 		/* balance everything - no filters */
4445 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4446 	}
4447 
4448 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4449 		ret = -EINVAL;
4450 		goto out_bctl;
4451 	}
4452 
4453 do_balance:
4454 	/*
4455 	 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4456 	 * bctl is freed in reset_balance_state, or, if restriper was paused
4457 	 * all the way until unmount, in free_fs_info.  The flag should be
4458 	 * cleared after reset_balance_state.
4459 	 */
4460 	need_unlock = false;
4461 
4462 	ret = btrfs_balance(fs_info, bctl, bargs);
4463 	bctl = NULL;
4464 
4465 	if ((ret == 0 || ret == -ECANCELED) && arg) {
4466 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4467 			ret = -EFAULT;
4468 	}
4469 
4470 out_bctl:
4471 	kfree(bctl);
4472 out_bargs:
4473 	kfree(bargs);
4474 out_unlock:
4475 	mutex_unlock(&fs_info->balance_mutex);
4476 	if (need_unlock)
4477 		btrfs_exclop_finish(fs_info);
4478 out:
4479 	mnt_drop_write_file(file);
4480 	return ret;
4481 }
4482 
4483 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4484 {
4485 	if (!capable(CAP_SYS_ADMIN))
4486 		return -EPERM;
4487 
4488 	switch (cmd) {
4489 	case BTRFS_BALANCE_CTL_PAUSE:
4490 		return btrfs_pause_balance(fs_info);
4491 	case BTRFS_BALANCE_CTL_CANCEL:
4492 		return btrfs_cancel_balance(fs_info);
4493 	}
4494 
4495 	return -EINVAL;
4496 }
4497 
4498 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4499 					 void __user *arg)
4500 {
4501 	struct btrfs_ioctl_balance_args *bargs;
4502 	int ret = 0;
4503 
4504 	if (!capable(CAP_SYS_ADMIN))
4505 		return -EPERM;
4506 
4507 	mutex_lock(&fs_info->balance_mutex);
4508 	if (!fs_info->balance_ctl) {
4509 		ret = -ENOTCONN;
4510 		goto out;
4511 	}
4512 
4513 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4514 	if (!bargs) {
4515 		ret = -ENOMEM;
4516 		goto out;
4517 	}
4518 
4519 	btrfs_update_ioctl_balance_args(fs_info, bargs);
4520 
4521 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
4522 		ret = -EFAULT;
4523 
4524 	kfree(bargs);
4525 out:
4526 	mutex_unlock(&fs_info->balance_mutex);
4527 	return ret;
4528 }
4529 
4530 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4531 {
4532 	struct inode *inode = file_inode(file);
4533 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4534 	struct btrfs_ioctl_quota_ctl_args *sa;
4535 	int ret;
4536 
4537 	if (!capable(CAP_SYS_ADMIN))
4538 		return -EPERM;
4539 
4540 	ret = mnt_want_write_file(file);
4541 	if (ret)
4542 		return ret;
4543 
4544 	sa = memdup_user(arg, sizeof(*sa));
4545 	if (IS_ERR(sa)) {
4546 		ret = PTR_ERR(sa);
4547 		goto drop_write;
4548 	}
4549 
4550 	down_write(&fs_info->subvol_sem);
4551 
4552 	switch (sa->cmd) {
4553 	case BTRFS_QUOTA_CTL_ENABLE:
4554 		ret = btrfs_quota_enable(fs_info);
4555 		break;
4556 	case BTRFS_QUOTA_CTL_DISABLE:
4557 		ret = btrfs_quota_disable(fs_info);
4558 		break;
4559 	default:
4560 		ret = -EINVAL;
4561 		break;
4562 	}
4563 
4564 	kfree(sa);
4565 	up_write(&fs_info->subvol_sem);
4566 drop_write:
4567 	mnt_drop_write_file(file);
4568 	return ret;
4569 }
4570 
4571 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4572 {
4573 	struct inode *inode = file_inode(file);
4574 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4575 	struct btrfs_root *root = BTRFS_I(inode)->root;
4576 	struct btrfs_ioctl_qgroup_assign_args *sa;
4577 	struct btrfs_trans_handle *trans;
4578 	int ret;
4579 	int err;
4580 
4581 	if (!capable(CAP_SYS_ADMIN))
4582 		return -EPERM;
4583 
4584 	ret = mnt_want_write_file(file);
4585 	if (ret)
4586 		return ret;
4587 
4588 	sa = memdup_user(arg, sizeof(*sa));
4589 	if (IS_ERR(sa)) {
4590 		ret = PTR_ERR(sa);
4591 		goto drop_write;
4592 	}
4593 
4594 	trans = btrfs_join_transaction(root);
4595 	if (IS_ERR(trans)) {
4596 		ret = PTR_ERR(trans);
4597 		goto out;
4598 	}
4599 
4600 	if (sa->assign) {
4601 		ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
4602 	} else {
4603 		ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
4604 	}
4605 
4606 	/* update qgroup status and info */
4607 	err = btrfs_run_qgroups(trans);
4608 	if (err < 0)
4609 		btrfs_handle_fs_error(fs_info, err,
4610 				      "failed to update qgroup status and info");
4611 	err = btrfs_end_transaction(trans);
4612 	if (err && !ret)
4613 		ret = err;
4614 
4615 out:
4616 	kfree(sa);
4617 drop_write:
4618 	mnt_drop_write_file(file);
4619 	return ret;
4620 }
4621 
4622 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4623 {
4624 	struct inode *inode = file_inode(file);
4625 	struct btrfs_root *root = BTRFS_I(inode)->root;
4626 	struct btrfs_ioctl_qgroup_create_args *sa;
4627 	struct btrfs_trans_handle *trans;
4628 	int ret;
4629 	int err;
4630 
4631 	if (!capable(CAP_SYS_ADMIN))
4632 		return -EPERM;
4633 
4634 	ret = mnt_want_write_file(file);
4635 	if (ret)
4636 		return ret;
4637 
4638 	sa = memdup_user(arg, sizeof(*sa));
4639 	if (IS_ERR(sa)) {
4640 		ret = PTR_ERR(sa);
4641 		goto drop_write;
4642 	}
4643 
4644 	if (!sa->qgroupid) {
4645 		ret = -EINVAL;
4646 		goto out;
4647 	}
4648 
4649 	trans = btrfs_join_transaction(root);
4650 	if (IS_ERR(trans)) {
4651 		ret = PTR_ERR(trans);
4652 		goto out;
4653 	}
4654 
4655 	if (sa->create) {
4656 		ret = btrfs_create_qgroup(trans, sa->qgroupid);
4657 	} else {
4658 		ret = btrfs_remove_qgroup(trans, sa->qgroupid);
4659 	}
4660 
4661 	err = btrfs_end_transaction(trans);
4662 	if (err && !ret)
4663 		ret = err;
4664 
4665 out:
4666 	kfree(sa);
4667 drop_write:
4668 	mnt_drop_write_file(file);
4669 	return ret;
4670 }
4671 
4672 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4673 {
4674 	struct inode *inode = file_inode(file);
4675 	struct btrfs_root *root = BTRFS_I(inode)->root;
4676 	struct btrfs_ioctl_qgroup_limit_args *sa;
4677 	struct btrfs_trans_handle *trans;
4678 	int ret;
4679 	int err;
4680 	u64 qgroupid;
4681 
4682 	if (!capable(CAP_SYS_ADMIN))
4683 		return -EPERM;
4684 
4685 	ret = mnt_want_write_file(file);
4686 	if (ret)
4687 		return ret;
4688 
4689 	sa = memdup_user(arg, sizeof(*sa));
4690 	if (IS_ERR(sa)) {
4691 		ret = PTR_ERR(sa);
4692 		goto drop_write;
4693 	}
4694 
4695 	trans = btrfs_join_transaction(root);
4696 	if (IS_ERR(trans)) {
4697 		ret = PTR_ERR(trans);
4698 		goto out;
4699 	}
4700 
4701 	qgroupid = sa->qgroupid;
4702 	if (!qgroupid) {
4703 		/* take the current subvol as qgroup */
4704 		qgroupid = root->root_key.objectid;
4705 	}
4706 
4707 	ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
4708 
4709 	err = btrfs_end_transaction(trans);
4710 	if (err && !ret)
4711 		ret = err;
4712 
4713 out:
4714 	kfree(sa);
4715 drop_write:
4716 	mnt_drop_write_file(file);
4717 	return ret;
4718 }
4719 
4720 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4721 {
4722 	struct inode *inode = file_inode(file);
4723 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4724 	struct btrfs_ioctl_quota_rescan_args *qsa;
4725 	int ret;
4726 
4727 	if (!capable(CAP_SYS_ADMIN))
4728 		return -EPERM;
4729 
4730 	ret = mnt_want_write_file(file);
4731 	if (ret)
4732 		return ret;
4733 
4734 	qsa = memdup_user(arg, sizeof(*qsa));
4735 	if (IS_ERR(qsa)) {
4736 		ret = PTR_ERR(qsa);
4737 		goto drop_write;
4738 	}
4739 
4740 	if (qsa->flags) {
4741 		ret = -EINVAL;
4742 		goto out;
4743 	}
4744 
4745 	ret = btrfs_qgroup_rescan(fs_info);
4746 
4747 out:
4748 	kfree(qsa);
4749 drop_write:
4750 	mnt_drop_write_file(file);
4751 	return ret;
4752 }
4753 
4754 static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4755 						void __user *arg)
4756 {
4757 	struct btrfs_ioctl_quota_rescan_args qsa = {0};
4758 
4759 	if (!capable(CAP_SYS_ADMIN))
4760 		return -EPERM;
4761 
4762 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4763 		qsa.flags = 1;
4764 		qsa.progress = fs_info->qgroup_rescan_progress.objectid;
4765 	}
4766 
4767 	if (copy_to_user(arg, &qsa, sizeof(qsa)))
4768 		return -EFAULT;
4769 
4770 	return 0;
4771 }
4772 
4773 static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4774 						void __user *arg)
4775 {
4776 	if (!capable(CAP_SYS_ADMIN))
4777 		return -EPERM;
4778 
4779 	return btrfs_qgroup_wait_for_completion(fs_info, true);
4780 }
4781 
4782 static long _btrfs_ioctl_set_received_subvol(struct file *file,
4783 					    struct user_namespace *mnt_userns,
4784 					    struct btrfs_ioctl_received_subvol_args *sa)
4785 {
4786 	struct inode *inode = file_inode(file);
4787 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4788 	struct btrfs_root *root = BTRFS_I(inode)->root;
4789 	struct btrfs_root_item *root_item = &root->root_item;
4790 	struct btrfs_trans_handle *trans;
4791 	struct timespec64 ct = current_time(inode);
4792 	int ret = 0;
4793 	int received_uuid_changed;
4794 
4795 	if (!inode_owner_or_capable(mnt_userns, inode))
4796 		return -EPERM;
4797 
4798 	ret = mnt_want_write_file(file);
4799 	if (ret < 0)
4800 		return ret;
4801 
4802 	down_write(&fs_info->subvol_sem);
4803 
4804 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
4805 		ret = -EINVAL;
4806 		goto out;
4807 	}
4808 
4809 	if (btrfs_root_readonly(root)) {
4810 		ret = -EROFS;
4811 		goto out;
4812 	}
4813 
4814 	/*
4815 	 * 1 - root item
4816 	 * 2 - uuid items (received uuid + subvol uuid)
4817 	 */
4818 	trans = btrfs_start_transaction(root, 3);
4819 	if (IS_ERR(trans)) {
4820 		ret = PTR_ERR(trans);
4821 		trans = NULL;
4822 		goto out;
4823 	}
4824 
4825 	sa->rtransid = trans->transid;
4826 	sa->rtime.sec = ct.tv_sec;
4827 	sa->rtime.nsec = ct.tv_nsec;
4828 
4829 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4830 				       BTRFS_UUID_SIZE);
4831 	if (received_uuid_changed &&
4832 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
4833 		ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
4834 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4835 					  root->root_key.objectid);
4836 		if (ret && ret != -ENOENT) {
4837 		        btrfs_abort_transaction(trans, ret);
4838 		        btrfs_end_transaction(trans);
4839 		        goto out;
4840 		}
4841 	}
4842 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4843 	btrfs_set_root_stransid(root_item, sa->stransid);
4844 	btrfs_set_root_rtransid(root_item, sa->rtransid);
4845 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4846 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4847 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4848 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4849 
4850 	ret = btrfs_update_root(trans, fs_info->tree_root,
4851 				&root->root_key, &root->root_item);
4852 	if (ret < 0) {
4853 		btrfs_end_transaction(trans);
4854 		goto out;
4855 	}
4856 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4857 		ret = btrfs_uuid_tree_add(trans, sa->uuid,
4858 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4859 					  root->root_key.objectid);
4860 		if (ret < 0 && ret != -EEXIST) {
4861 			btrfs_abort_transaction(trans, ret);
4862 			btrfs_end_transaction(trans);
4863 			goto out;
4864 		}
4865 	}
4866 	ret = btrfs_commit_transaction(trans);
4867 out:
4868 	up_write(&fs_info->subvol_sem);
4869 	mnt_drop_write_file(file);
4870 	return ret;
4871 }
4872 
4873 #ifdef CONFIG_64BIT
4874 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4875 						void __user *arg)
4876 {
4877 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4878 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4879 	int ret = 0;
4880 
4881 	args32 = memdup_user(arg, sizeof(*args32));
4882 	if (IS_ERR(args32))
4883 		return PTR_ERR(args32);
4884 
4885 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
4886 	if (!args64) {
4887 		ret = -ENOMEM;
4888 		goto out;
4889 	}
4890 
4891 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4892 	args64->stransid = args32->stransid;
4893 	args64->rtransid = args32->rtransid;
4894 	args64->stime.sec = args32->stime.sec;
4895 	args64->stime.nsec = args32->stime.nsec;
4896 	args64->rtime.sec = args32->rtime.sec;
4897 	args64->rtime.nsec = args32->rtime.nsec;
4898 	args64->flags = args32->flags;
4899 
4900 	ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), args64);
4901 	if (ret)
4902 		goto out;
4903 
4904 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4905 	args32->stransid = args64->stransid;
4906 	args32->rtransid = args64->rtransid;
4907 	args32->stime.sec = args64->stime.sec;
4908 	args32->stime.nsec = args64->stime.nsec;
4909 	args32->rtime.sec = args64->rtime.sec;
4910 	args32->rtime.nsec = args64->rtime.nsec;
4911 	args32->flags = args64->flags;
4912 
4913 	ret = copy_to_user(arg, args32, sizeof(*args32));
4914 	if (ret)
4915 		ret = -EFAULT;
4916 
4917 out:
4918 	kfree(args32);
4919 	kfree(args64);
4920 	return ret;
4921 }
4922 #endif
4923 
4924 static long btrfs_ioctl_set_received_subvol(struct file *file,
4925 					    void __user *arg)
4926 {
4927 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
4928 	int ret = 0;
4929 
4930 	sa = memdup_user(arg, sizeof(*sa));
4931 	if (IS_ERR(sa))
4932 		return PTR_ERR(sa);
4933 
4934 	ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), sa);
4935 
4936 	if (ret)
4937 		goto out;
4938 
4939 	ret = copy_to_user(arg, sa, sizeof(*sa));
4940 	if (ret)
4941 		ret = -EFAULT;
4942 
4943 out:
4944 	kfree(sa);
4945 	return ret;
4946 }
4947 
4948 static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4949 					void __user *arg)
4950 {
4951 	size_t len;
4952 	int ret;
4953 	char label[BTRFS_LABEL_SIZE];
4954 
4955 	spin_lock(&fs_info->super_lock);
4956 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4957 	spin_unlock(&fs_info->super_lock);
4958 
4959 	len = strnlen(label, BTRFS_LABEL_SIZE);
4960 
4961 	if (len == BTRFS_LABEL_SIZE) {
4962 		btrfs_warn(fs_info,
4963 			   "label is too long, return the first %zu bytes",
4964 			   --len);
4965 	}
4966 
4967 	ret = copy_to_user(arg, label, len);
4968 
4969 	return ret ? -EFAULT : 0;
4970 }
4971 
4972 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4973 {
4974 	struct inode *inode = file_inode(file);
4975 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4976 	struct btrfs_root *root = BTRFS_I(inode)->root;
4977 	struct btrfs_super_block *super_block = fs_info->super_copy;
4978 	struct btrfs_trans_handle *trans;
4979 	char label[BTRFS_LABEL_SIZE];
4980 	int ret;
4981 
4982 	if (!capable(CAP_SYS_ADMIN))
4983 		return -EPERM;
4984 
4985 	if (copy_from_user(label, arg, sizeof(label)))
4986 		return -EFAULT;
4987 
4988 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4989 		btrfs_err(fs_info,
4990 			  "unable to set label with more than %d bytes",
4991 			  BTRFS_LABEL_SIZE - 1);
4992 		return -EINVAL;
4993 	}
4994 
4995 	ret = mnt_want_write_file(file);
4996 	if (ret)
4997 		return ret;
4998 
4999 	trans = btrfs_start_transaction(root, 0);
5000 	if (IS_ERR(trans)) {
5001 		ret = PTR_ERR(trans);
5002 		goto out_unlock;
5003 	}
5004 
5005 	spin_lock(&fs_info->super_lock);
5006 	strcpy(super_block->label, label);
5007 	spin_unlock(&fs_info->super_lock);
5008 	ret = btrfs_commit_transaction(trans);
5009 
5010 out_unlock:
5011 	mnt_drop_write_file(file);
5012 	return ret;
5013 }
5014 
5015 #define INIT_FEATURE_FLAGS(suffix) \
5016 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5017 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5018 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5019 
5020 int btrfs_ioctl_get_supported_features(void __user *arg)
5021 {
5022 	static const struct btrfs_ioctl_feature_flags features[3] = {
5023 		INIT_FEATURE_FLAGS(SUPP),
5024 		INIT_FEATURE_FLAGS(SAFE_SET),
5025 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
5026 	};
5027 
5028 	if (copy_to_user(arg, &features, sizeof(features)))
5029 		return -EFAULT;
5030 
5031 	return 0;
5032 }
5033 
5034 static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
5035 					void __user *arg)
5036 {
5037 	struct btrfs_super_block *super_block = fs_info->super_copy;
5038 	struct btrfs_ioctl_feature_flags features;
5039 
5040 	features.compat_flags = btrfs_super_compat_flags(super_block);
5041 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5042 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
5043 
5044 	if (copy_to_user(arg, &features, sizeof(features)))
5045 		return -EFAULT;
5046 
5047 	return 0;
5048 }
5049 
5050 static int check_feature_bits(struct btrfs_fs_info *fs_info,
5051 			      enum btrfs_feature_set set,
5052 			      u64 change_mask, u64 flags, u64 supported_flags,
5053 			      u64 safe_set, u64 safe_clear)
5054 {
5055 	const char *type = btrfs_feature_set_name(set);
5056 	char *names;
5057 	u64 disallowed, unsupported;
5058 	u64 set_mask = flags & change_mask;
5059 	u64 clear_mask = ~flags & change_mask;
5060 
5061 	unsupported = set_mask & ~supported_flags;
5062 	if (unsupported) {
5063 		names = btrfs_printable_features(set, unsupported);
5064 		if (names) {
5065 			btrfs_warn(fs_info,
5066 				   "this kernel does not support the %s feature bit%s",
5067 				   names, strchr(names, ',') ? "s" : "");
5068 			kfree(names);
5069 		} else
5070 			btrfs_warn(fs_info,
5071 				   "this kernel does not support %s bits 0x%llx",
5072 				   type, unsupported);
5073 		return -EOPNOTSUPP;
5074 	}
5075 
5076 	disallowed = set_mask & ~safe_set;
5077 	if (disallowed) {
5078 		names = btrfs_printable_features(set, disallowed);
5079 		if (names) {
5080 			btrfs_warn(fs_info,
5081 				   "can't set the %s feature bit%s while mounted",
5082 				   names, strchr(names, ',') ? "s" : "");
5083 			kfree(names);
5084 		} else
5085 			btrfs_warn(fs_info,
5086 				   "can't set %s bits 0x%llx while mounted",
5087 				   type, disallowed);
5088 		return -EPERM;
5089 	}
5090 
5091 	disallowed = clear_mask & ~safe_clear;
5092 	if (disallowed) {
5093 		names = btrfs_printable_features(set, disallowed);
5094 		if (names) {
5095 			btrfs_warn(fs_info,
5096 				   "can't clear the %s feature bit%s while mounted",
5097 				   names, strchr(names, ',') ? "s" : "");
5098 			kfree(names);
5099 		} else
5100 			btrfs_warn(fs_info,
5101 				   "can't clear %s bits 0x%llx while mounted",
5102 				   type, disallowed);
5103 		return -EPERM;
5104 	}
5105 
5106 	return 0;
5107 }
5108 
5109 #define check_feature(fs_info, change_mask, flags, mask_base)	\
5110 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
5111 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
5112 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
5113 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5114 
5115 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5116 {
5117 	struct inode *inode = file_inode(file);
5118 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5119 	struct btrfs_root *root = BTRFS_I(inode)->root;
5120 	struct btrfs_super_block *super_block = fs_info->super_copy;
5121 	struct btrfs_ioctl_feature_flags flags[2];
5122 	struct btrfs_trans_handle *trans;
5123 	u64 newflags;
5124 	int ret;
5125 
5126 	if (!capable(CAP_SYS_ADMIN))
5127 		return -EPERM;
5128 
5129 	if (copy_from_user(flags, arg, sizeof(flags)))
5130 		return -EFAULT;
5131 
5132 	/* Nothing to do */
5133 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5134 	    !flags[0].incompat_flags)
5135 		return 0;
5136 
5137 	ret = check_feature(fs_info, flags[0].compat_flags,
5138 			    flags[1].compat_flags, COMPAT);
5139 	if (ret)
5140 		return ret;
5141 
5142 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
5143 			    flags[1].compat_ro_flags, COMPAT_RO);
5144 	if (ret)
5145 		return ret;
5146 
5147 	ret = check_feature(fs_info, flags[0].incompat_flags,
5148 			    flags[1].incompat_flags, INCOMPAT);
5149 	if (ret)
5150 		return ret;
5151 
5152 	ret = mnt_want_write_file(file);
5153 	if (ret)
5154 		return ret;
5155 
5156 	trans = btrfs_start_transaction(root, 0);
5157 	if (IS_ERR(trans)) {
5158 		ret = PTR_ERR(trans);
5159 		goto out_drop_write;
5160 	}
5161 
5162 	spin_lock(&fs_info->super_lock);
5163 	newflags = btrfs_super_compat_flags(super_block);
5164 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
5165 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5166 	btrfs_set_super_compat_flags(super_block, newflags);
5167 
5168 	newflags = btrfs_super_compat_ro_flags(super_block);
5169 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5170 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5171 	btrfs_set_super_compat_ro_flags(super_block, newflags);
5172 
5173 	newflags = btrfs_super_incompat_flags(super_block);
5174 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5175 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5176 	btrfs_set_super_incompat_flags(super_block, newflags);
5177 	spin_unlock(&fs_info->super_lock);
5178 
5179 	ret = btrfs_commit_transaction(trans);
5180 out_drop_write:
5181 	mnt_drop_write_file(file);
5182 
5183 	return ret;
5184 }
5185 
5186 static int _btrfs_ioctl_send(struct inode *inode, void __user *argp, bool compat)
5187 {
5188 	struct btrfs_ioctl_send_args *arg;
5189 	int ret;
5190 
5191 	if (compat) {
5192 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5193 		struct btrfs_ioctl_send_args_32 args32;
5194 
5195 		ret = copy_from_user(&args32, argp, sizeof(args32));
5196 		if (ret)
5197 			return -EFAULT;
5198 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
5199 		if (!arg)
5200 			return -ENOMEM;
5201 		arg->send_fd = args32.send_fd;
5202 		arg->clone_sources_count = args32.clone_sources_count;
5203 		arg->clone_sources = compat_ptr(args32.clone_sources);
5204 		arg->parent_root = args32.parent_root;
5205 		arg->flags = args32.flags;
5206 		memcpy(arg->reserved, args32.reserved,
5207 		       sizeof(args32.reserved));
5208 #else
5209 		return -ENOTTY;
5210 #endif
5211 	} else {
5212 		arg = memdup_user(argp, sizeof(*arg));
5213 		if (IS_ERR(arg))
5214 			return PTR_ERR(arg);
5215 	}
5216 	ret = btrfs_ioctl_send(inode, arg);
5217 	kfree(arg);
5218 	return ret;
5219 }
5220 
5221 static int btrfs_ioctl_encoded_read(struct file *file, void __user *argp,
5222 				    bool compat)
5223 {
5224 	struct btrfs_ioctl_encoded_io_args args = { 0 };
5225 	size_t copy_end_kernel = offsetofend(struct btrfs_ioctl_encoded_io_args,
5226 					     flags);
5227 	size_t copy_end;
5228 	struct iovec iovstack[UIO_FASTIOV];
5229 	struct iovec *iov = iovstack;
5230 	struct iov_iter iter;
5231 	loff_t pos;
5232 	struct kiocb kiocb;
5233 	ssize_t ret;
5234 
5235 	if (!capable(CAP_SYS_ADMIN)) {
5236 		ret = -EPERM;
5237 		goto out_acct;
5238 	}
5239 
5240 	if (compat) {
5241 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5242 		struct btrfs_ioctl_encoded_io_args_32 args32;
5243 
5244 		copy_end = offsetofend(struct btrfs_ioctl_encoded_io_args_32,
5245 				       flags);
5246 		if (copy_from_user(&args32, argp, copy_end)) {
5247 			ret = -EFAULT;
5248 			goto out_acct;
5249 		}
5250 		args.iov = compat_ptr(args32.iov);
5251 		args.iovcnt = args32.iovcnt;
5252 		args.offset = args32.offset;
5253 		args.flags = args32.flags;
5254 #else
5255 		return -ENOTTY;
5256 #endif
5257 	} else {
5258 		copy_end = copy_end_kernel;
5259 		if (copy_from_user(&args, argp, copy_end)) {
5260 			ret = -EFAULT;
5261 			goto out_acct;
5262 		}
5263 	}
5264 	if (args.flags != 0) {
5265 		ret = -EINVAL;
5266 		goto out_acct;
5267 	}
5268 
5269 	ret = import_iovec(READ, args.iov, args.iovcnt, ARRAY_SIZE(iovstack),
5270 			   &iov, &iter);
5271 	if (ret < 0)
5272 		goto out_acct;
5273 
5274 	if (iov_iter_count(&iter) == 0) {
5275 		ret = 0;
5276 		goto out_iov;
5277 	}
5278 	pos = args.offset;
5279 	ret = rw_verify_area(READ, file, &pos, args.len);
5280 	if (ret < 0)
5281 		goto out_iov;
5282 
5283 	init_sync_kiocb(&kiocb, file);
5284 	kiocb.ki_pos = pos;
5285 
5286 	ret = btrfs_encoded_read(&kiocb, &iter, &args);
5287 	if (ret >= 0) {
5288 		fsnotify_access(file);
5289 		if (copy_to_user(argp + copy_end,
5290 				 (char *)&args + copy_end_kernel,
5291 				 sizeof(args) - copy_end_kernel))
5292 			ret = -EFAULT;
5293 	}
5294 
5295 out_iov:
5296 	kfree(iov);
5297 out_acct:
5298 	if (ret > 0)
5299 		add_rchar(current, ret);
5300 	inc_syscr(current);
5301 	return ret;
5302 }
5303 
5304 static int btrfs_ioctl_encoded_write(struct file *file, void __user *argp, bool compat)
5305 {
5306 	struct btrfs_ioctl_encoded_io_args args;
5307 	struct iovec iovstack[UIO_FASTIOV];
5308 	struct iovec *iov = iovstack;
5309 	struct iov_iter iter;
5310 	loff_t pos;
5311 	struct kiocb kiocb;
5312 	ssize_t ret;
5313 
5314 	if (!capable(CAP_SYS_ADMIN)) {
5315 		ret = -EPERM;
5316 		goto out_acct;
5317 	}
5318 
5319 	if (!(file->f_mode & FMODE_WRITE)) {
5320 		ret = -EBADF;
5321 		goto out_acct;
5322 	}
5323 
5324 	if (compat) {
5325 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5326 		struct btrfs_ioctl_encoded_io_args_32 args32;
5327 
5328 		if (copy_from_user(&args32, argp, sizeof(args32))) {
5329 			ret = -EFAULT;
5330 			goto out_acct;
5331 		}
5332 		args.iov = compat_ptr(args32.iov);
5333 		args.iovcnt = args32.iovcnt;
5334 		args.offset = args32.offset;
5335 		args.flags = args32.flags;
5336 		args.len = args32.len;
5337 		args.unencoded_len = args32.unencoded_len;
5338 		args.unencoded_offset = args32.unencoded_offset;
5339 		args.compression = args32.compression;
5340 		args.encryption = args32.encryption;
5341 		memcpy(args.reserved, args32.reserved, sizeof(args.reserved));
5342 #else
5343 		return -ENOTTY;
5344 #endif
5345 	} else {
5346 		if (copy_from_user(&args, argp, sizeof(args))) {
5347 			ret = -EFAULT;
5348 			goto out_acct;
5349 		}
5350 	}
5351 
5352 	ret = -EINVAL;
5353 	if (args.flags != 0)
5354 		goto out_acct;
5355 	if (memchr_inv(args.reserved, 0, sizeof(args.reserved)))
5356 		goto out_acct;
5357 	if (args.compression == BTRFS_ENCODED_IO_COMPRESSION_NONE &&
5358 	    args.encryption == BTRFS_ENCODED_IO_ENCRYPTION_NONE)
5359 		goto out_acct;
5360 	if (args.compression >= BTRFS_ENCODED_IO_COMPRESSION_TYPES ||
5361 	    args.encryption >= BTRFS_ENCODED_IO_ENCRYPTION_TYPES)
5362 		goto out_acct;
5363 	if (args.unencoded_offset > args.unencoded_len)
5364 		goto out_acct;
5365 	if (args.len > args.unencoded_len - args.unencoded_offset)
5366 		goto out_acct;
5367 
5368 	ret = import_iovec(WRITE, args.iov, args.iovcnt, ARRAY_SIZE(iovstack),
5369 			   &iov, &iter);
5370 	if (ret < 0)
5371 		goto out_acct;
5372 
5373 	file_start_write(file);
5374 
5375 	if (iov_iter_count(&iter) == 0) {
5376 		ret = 0;
5377 		goto out_end_write;
5378 	}
5379 	pos = args.offset;
5380 	ret = rw_verify_area(WRITE, file, &pos, args.len);
5381 	if (ret < 0)
5382 		goto out_end_write;
5383 
5384 	init_sync_kiocb(&kiocb, file);
5385 	ret = kiocb_set_rw_flags(&kiocb, 0);
5386 	if (ret)
5387 		goto out_end_write;
5388 	kiocb.ki_pos = pos;
5389 
5390 	ret = btrfs_do_write_iter(&kiocb, &iter, &args);
5391 	if (ret > 0)
5392 		fsnotify_modify(file);
5393 
5394 out_end_write:
5395 	file_end_write(file);
5396 	kfree(iov);
5397 out_acct:
5398 	if (ret > 0)
5399 		add_wchar(current, ret);
5400 	inc_syscw(current);
5401 	return ret;
5402 }
5403 
5404 long btrfs_ioctl(struct file *file, unsigned int
5405 		cmd, unsigned long arg)
5406 {
5407 	struct inode *inode = file_inode(file);
5408 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5409 	struct btrfs_root *root = BTRFS_I(inode)->root;
5410 	void __user *argp = (void __user *)arg;
5411 
5412 	switch (cmd) {
5413 	case FS_IOC_GETVERSION:
5414 		return btrfs_ioctl_getversion(inode, argp);
5415 	case FS_IOC_GETFSLABEL:
5416 		return btrfs_ioctl_get_fslabel(fs_info, argp);
5417 	case FS_IOC_SETFSLABEL:
5418 		return btrfs_ioctl_set_fslabel(file, argp);
5419 	case FITRIM:
5420 		return btrfs_ioctl_fitrim(fs_info, argp);
5421 	case BTRFS_IOC_SNAP_CREATE:
5422 		return btrfs_ioctl_snap_create(file, argp, 0);
5423 	case BTRFS_IOC_SNAP_CREATE_V2:
5424 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
5425 	case BTRFS_IOC_SUBVOL_CREATE:
5426 		return btrfs_ioctl_snap_create(file, argp, 1);
5427 	case BTRFS_IOC_SUBVOL_CREATE_V2:
5428 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
5429 	case BTRFS_IOC_SNAP_DESTROY:
5430 		return btrfs_ioctl_snap_destroy(file, argp, false);
5431 	case BTRFS_IOC_SNAP_DESTROY_V2:
5432 		return btrfs_ioctl_snap_destroy(file, argp, true);
5433 	case BTRFS_IOC_SUBVOL_GETFLAGS:
5434 		return btrfs_ioctl_subvol_getflags(inode, argp);
5435 	case BTRFS_IOC_SUBVOL_SETFLAGS:
5436 		return btrfs_ioctl_subvol_setflags(file, argp);
5437 	case BTRFS_IOC_DEFAULT_SUBVOL:
5438 		return btrfs_ioctl_default_subvol(file, argp);
5439 	case BTRFS_IOC_DEFRAG:
5440 		return btrfs_ioctl_defrag(file, NULL);
5441 	case BTRFS_IOC_DEFRAG_RANGE:
5442 		return btrfs_ioctl_defrag(file, argp);
5443 	case BTRFS_IOC_RESIZE:
5444 		return btrfs_ioctl_resize(file, argp);
5445 	case BTRFS_IOC_ADD_DEV:
5446 		return btrfs_ioctl_add_dev(fs_info, argp);
5447 	case BTRFS_IOC_RM_DEV:
5448 		return btrfs_ioctl_rm_dev(file, argp);
5449 	case BTRFS_IOC_RM_DEV_V2:
5450 		return btrfs_ioctl_rm_dev_v2(file, argp);
5451 	case BTRFS_IOC_FS_INFO:
5452 		return btrfs_ioctl_fs_info(fs_info, argp);
5453 	case BTRFS_IOC_DEV_INFO:
5454 		return btrfs_ioctl_dev_info(fs_info, argp);
5455 	case BTRFS_IOC_TREE_SEARCH:
5456 		return btrfs_ioctl_tree_search(inode, argp);
5457 	case BTRFS_IOC_TREE_SEARCH_V2:
5458 		return btrfs_ioctl_tree_search_v2(inode, argp);
5459 	case BTRFS_IOC_INO_LOOKUP:
5460 		return btrfs_ioctl_ino_lookup(root, argp);
5461 	case BTRFS_IOC_INO_PATHS:
5462 		return btrfs_ioctl_ino_to_path(root, argp);
5463 	case BTRFS_IOC_LOGICAL_INO:
5464 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5465 	case BTRFS_IOC_LOGICAL_INO_V2:
5466 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
5467 	case BTRFS_IOC_SPACE_INFO:
5468 		return btrfs_ioctl_space_info(fs_info, argp);
5469 	case BTRFS_IOC_SYNC: {
5470 		int ret;
5471 
5472 		ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
5473 		if (ret)
5474 			return ret;
5475 		ret = btrfs_sync_fs(inode->i_sb, 1);
5476 		/*
5477 		 * The transaction thread may want to do more work,
5478 		 * namely it pokes the cleaner kthread that will start
5479 		 * processing uncleaned subvols.
5480 		 */
5481 		wake_up_process(fs_info->transaction_kthread);
5482 		return ret;
5483 	}
5484 	case BTRFS_IOC_START_SYNC:
5485 		return btrfs_ioctl_start_sync(root, argp);
5486 	case BTRFS_IOC_WAIT_SYNC:
5487 		return btrfs_ioctl_wait_sync(fs_info, argp);
5488 	case BTRFS_IOC_SCRUB:
5489 		return btrfs_ioctl_scrub(file, argp);
5490 	case BTRFS_IOC_SCRUB_CANCEL:
5491 		return btrfs_ioctl_scrub_cancel(fs_info);
5492 	case BTRFS_IOC_SCRUB_PROGRESS:
5493 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5494 	case BTRFS_IOC_BALANCE_V2:
5495 		return btrfs_ioctl_balance(file, argp);
5496 	case BTRFS_IOC_BALANCE_CTL:
5497 		return btrfs_ioctl_balance_ctl(fs_info, arg);
5498 	case BTRFS_IOC_BALANCE_PROGRESS:
5499 		return btrfs_ioctl_balance_progress(fs_info, argp);
5500 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5501 		return btrfs_ioctl_set_received_subvol(file, argp);
5502 #ifdef CONFIG_64BIT
5503 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5504 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5505 #endif
5506 	case BTRFS_IOC_SEND:
5507 		return _btrfs_ioctl_send(inode, argp, false);
5508 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5509 	case BTRFS_IOC_SEND_32:
5510 		return _btrfs_ioctl_send(inode, argp, true);
5511 #endif
5512 	case BTRFS_IOC_GET_DEV_STATS:
5513 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
5514 	case BTRFS_IOC_QUOTA_CTL:
5515 		return btrfs_ioctl_quota_ctl(file, argp);
5516 	case BTRFS_IOC_QGROUP_ASSIGN:
5517 		return btrfs_ioctl_qgroup_assign(file, argp);
5518 	case BTRFS_IOC_QGROUP_CREATE:
5519 		return btrfs_ioctl_qgroup_create(file, argp);
5520 	case BTRFS_IOC_QGROUP_LIMIT:
5521 		return btrfs_ioctl_qgroup_limit(file, argp);
5522 	case BTRFS_IOC_QUOTA_RESCAN:
5523 		return btrfs_ioctl_quota_rescan(file, argp);
5524 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5525 		return btrfs_ioctl_quota_rescan_status(fs_info, argp);
5526 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5527 		return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
5528 	case BTRFS_IOC_DEV_REPLACE:
5529 		return btrfs_ioctl_dev_replace(fs_info, argp);
5530 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5531 		return btrfs_ioctl_get_supported_features(argp);
5532 	case BTRFS_IOC_GET_FEATURES:
5533 		return btrfs_ioctl_get_features(fs_info, argp);
5534 	case BTRFS_IOC_SET_FEATURES:
5535 		return btrfs_ioctl_set_features(file, argp);
5536 	case BTRFS_IOC_GET_SUBVOL_INFO:
5537 		return btrfs_ioctl_get_subvol_info(inode, argp);
5538 	case BTRFS_IOC_GET_SUBVOL_ROOTREF:
5539 		return btrfs_ioctl_get_subvol_rootref(root, argp);
5540 	case BTRFS_IOC_INO_LOOKUP_USER:
5541 		return btrfs_ioctl_ino_lookup_user(file, argp);
5542 	case FS_IOC_ENABLE_VERITY:
5543 		return fsverity_ioctl_enable(file, (const void __user *)argp);
5544 	case FS_IOC_MEASURE_VERITY:
5545 		return fsverity_ioctl_measure(file, argp);
5546 	case BTRFS_IOC_ENCODED_READ:
5547 		return btrfs_ioctl_encoded_read(file, argp, false);
5548 	case BTRFS_IOC_ENCODED_WRITE:
5549 		return btrfs_ioctl_encoded_write(file, argp, false);
5550 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5551 	case BTRFS_IOC_ENCODED_READ_32:
5552 		return btrfs_ioctl_encoded_read(file, argp, true);
5553 	case BTRFS_IOC_ENCODED_WRITE_32:
5554 		return btrfs_ioctl_encoded_write(file, argp, true);
5555 #endif
5556 	}
5557 
5558 	return -ENOTTY;
5559 }
5560 
5561 #ifdef CONFIG_COMPAT
5562 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5563 {
5564 	/*
5565 	 * These all access 32-bit values anyway so no further
5566 	 * handling is necessary.
5567 	 */
5568 	switch (cmd) {
5569 	case FS_IOC32_GETVERSION:
5570 		cmd = FS_IOC_GETVERSION;
5571 		break;
5572 	}
5573 
5574 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
5575 }
5576 #endif
5577