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