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