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