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