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