xref: /openbmc/linux/fs/btrfs/ioctl.c (revision f519cd13)
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, 0);
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 	int ret;
3247 
3248 	/*
3249 	 * Lock destination range to serialize with concurrent readpages() and
3250 	 * source range to serialize with relocation.
3251 	 */
3252 	btrfs_double_extent_lock(src, loff, dst, dst_loff, len);
3253 	ret = btrfs_clone(src, dst, loff, len, len, dst_loff, 1);
3254 	btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3255 
3256 	return ret;
3257 }
3258 
3259 #define BTRFS_MAX_DEDUPE_LEN	SZ_16M
3260 
3261 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3262 			     struct inode *dst, u64 dst_loff)
3263 {
3264 	int ret;
3265 	u64 i, tail_len, chunk_count;
3266 	struct btrfs_root *root_dst = BTRFS_I(dst)->root;
3267 
3268 	spin_lock(&root_dst->root_item_lock);
3269 	if (root_dst->send_in_progress) {
3270 		btrfs_warn_rl(root_dst->fs_info,
3271 "cannot deduplicate to root %llu while send operations are using it (%d in progress)",
3272 			      root_dst->root_key.objectid,
3273 			      root_dst->send_in_progress);
3274 		spin_unlock(&root_dst->root_item_lock);
3275 		return -EAGAIN;
3276 	}
3277 	root_dst->dedupe_in_progress++;
3278 	spin_unlock(&root_dst->root_item_lock);
3279 
3280 	tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3281 	chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
3282 
3283 	for (i = 0; i < chunk_count; i++) {
3284 		ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
3285 					      dst, dst_loff);
3286 		if (ret)
3287 			goto out;
3288 
3289 		loff += BTRFS_MAX_DEDUPE_LEN;
3290 		dst_loff += BTRFS_MAX_DEDUPE_LEN;
3291 	}
3292 
3293 	if (tail_len > 0)
3294 		ret = btrfs_extent_same_range(src, loff, tail_len, dst,
3295 					      dst_loff);
3296 out:
3297 	spin_lock(&root_dst->root_item_lock);
3298 	root_dst->dedupe_in_progress--;
3299 	spin_unlock(&root_dst->root_item_lock);
3300 
3301 	return ret;
3302 }
3303 
3304 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3305 				     struct inode *inode,
3306 				     u64 endoff,
3307 				     const u64 destoff,
3308 				     const u64 olen,
3309 				     int no_time_update)
3310 {
3311 	struct btrfs_root *root = BTRFS_I(inode)->root;
3312 	int ret;
3313 
3314 	inode_inc_iversion(inode);
3315 	if (!no_time_update)
3316 		inode->i_mtime = inode->i_ctime = current_time(inode);
3317 	/*
3318 	 * We round up to the block size at eof when determining which
3319 	 * extents to clone above, but shouldn't round up the file size.
3320 	 */
3321 	if (endoff > destoff + olen)
3322 		endoff = destoff + olen;
3323 	if (endoff > inode->i_size)
3324 		btrfs_i_size_write(BTRFS_I(inode), endoff);
3325 
3326 	ret = btrfs_update_inode(trans, root, inode);
3327 	if (ret) {
3328 		btrfs_abort_transaction(trans, ret);
3329 		btrfs_end_transaction(trans);
3330 		goto out;
3331 	}
3332 	ret = btrfs_end_transaction(trans);
3333 out:
3334 	return ret;
3335 }
3336 
3337 /*
3338  * Make sure we do not end up inserting an inline extent into a file that has
3339  * already other (non-inline) extents. If a file has an inline extent it can
3340  * not have any other extents and the (single) inline extent must start at the
3341  * file offset 0. Failing to respect these rules will lead to file corruption,
3342  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
3343  *
3344  * We can have extents that have been already written to disk or we can have
3345  * dirty ranges still in delalloc, in which case the extent maps and items are
3346  * created only when we run delalloc, and the delalloc ranges might fall outside
3347  * the range we are currently locking in the inode's io tree. So we check the
3348  * inode's i_size because of that (i_size updates are done while holding the
3349  * i_mutex, which we are holding here).
3350  * We also check to see if the inode has a size not greater than "datal" but has
3351  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
3352  * protected against such concurrent fallocate calls by the i_mutex).
3353  *
3354  * If the file has no extents but a size greater than datal, do not allow the
3355  * copy because we would need turn the inline extent into a non-inline one (even
3356  * with NO_HOLES enabled). If we find our destination inode only has one inline
3357  * extent, just overwrite it with the source inline extent if its size is less
3358  * than the source extent's size, or we could copy the source inline extent's
3359  * data into the destination inode's inline extent if the later is greater then
3360  * the former.
3361  */
3362 static int clone_copy_inline_extent(struct inode *dst,
3363 				    struct btrfs_trans_handle *trans,
3364 				    struct btrfs_path *path,
3365 				    struct btrfs_key *new_key,
3366 				    const u64 drop_start,
3367 				    const u64 datal,
3368 				    const u64 skip,
3369 				    const u64 size,
3370 				    char *inline_data)
3371 {
3372 	struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
3373 	struct btrfs_root *root = BTRFS_I(dst)->root;
3374 	const u64 aligned_end = ALIGN(new_key->offset + datal,
3375 				      fs_info->sectorsize);
3376 	int ret;
3377 	struct btrfs_key key;
3378 
3379 	if (new_key->offset > 0)
3380 		return -EOPNOTSUPP;
3381 
3382 	key.objectid = btrfs_ino(BTRFS_I(dst));
3383 	key.type = BTRFS_EXTENT_DATA_KEY;
3384 	key.offset = 0;
3385 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3386 	if (ret < 0) {
3387 		return ret;
3388 	} else if (ret > 0) {
3389 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3390 			ret = btrfs_next_leaf(root, path);
3391 			if (ret < 0)
3392 				return ret;
3393 			else if (ret > 0)
3394 				goto copy_inline_extent;
3395 		}
3396 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3397 		if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3398 		    key.type == BTRFS_EXTENT_DATA_KEY) {
3399 			ASSERT(key.offset > 0);
3400 			return -EOPNOTSUPP;
3401 		}
3402 	} else if (i_size_read(dst) <= datal) {
3403 		struct btrfs_file_extent_item *ei;
3404 		u64 ext_len;
3405 
3406 		/*
3407 		 * If the file size is <= datal, make sure there are no other
3408 		 * extents following (can happen do to an fallocate call with
3409 		 * the flag FALLOC_FL_KEEP_SIZE).
3410 		 */
3411 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3412 				    struct btrfs_file_extent_item);
3413 		/*
3414 		 * If it's an inline extent, it can not have other extents
3415 		 * following it.
3416 		 */
3417 		if (btrfs_file_extent_type(path->nodes[0], ei) ==
3418 		    BTRFS_FILE_EXTENT_INLINE)
3419 			goto copy_inline_extent;
3420 
3421 		ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3422 		if (ext_len > aligned_end)
3423 			return -EOPNOTSUPP;
3424 
3425 		ret = btrfs_next_item(root, path);
3426 		if (ret < 0) {
3427 			return ret;
3428 		} else if (ret == 0) {
3429 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3430 					      path->slots[0]);
3431 			if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3432 			    key.type == BTRFS_EXTENT_DATA_KEY)
3433 				return -EOPNOTSUPP;
3434 		}
3435 	}
3436 
3437 copy_inline_extent:
3438 	/*
3439 	 * We have no extent items, or we have an extent at offset 0 which may
3440 	 * or may not be inlined. All these cases are dealt the same way.
3441 	 */
3442 	if (i_size_read(dst) > datal) {
3443 		/*
3444 		 * If the destination inode has an inline extent...
3445 		 * This would require copying the data from the source inline
3446 		 * extent into the beginning of the destination's inline extent.
3447 		 * But this is really complex, both extents can be compressed
3448 		 * or just one of them, which would require decompressing and
3449 		 * re-compressing data (which could increase the new compressed
3450 		 * size, not allowing the compressed data to fit anymore in an
3451 		 * inline extent).
3452 		 * So just don't support this case for now (it should be rare,
3453 		 * we are not really saving space when cloning inline extents).
3454 		 */
3455 		return -EOPNOTSUPP;
3456 	}
3457 
3458 	btrfs_release_path(path);
3459 	ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
3460 	if (ret)
3461 		return ret;
3462 	ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
3463 	if (ret)
3464 		return ret;
3465 
3466 	if (skip) {
3467 		const u32 start = btrfs_file_extent_calc_inline_size(0);
3468 
3469 		memmove(inline_data + start, inline_data + start + skip, datal);
3470 	}
3471 
3472 	write_extent_buffer(path->nodes[0], inline_data,
3473 			    btrfs_item_ptr_offset(path->nodes[0],
3474 						  path->slots[0]),
3475 			    size);
3476 	inode_add_bytes(dst, datal);
3477 	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(dst)->runtime_flags);
3478 
3479 	return 0;
3480 }
3481 
3482 /**
3483  * btrfs_clone() - clone a range from inode file to another
3484  *
3485  * @src: Inode to clone from
3486  * @inode: Inode to clone to
3487  * @off: Offset within source to start clone from
3488  * @olen: Original length, passed by user, of range to clone
3489  * @olen_aligned: Block-aligned value of olen
3490  * @destoff: Offset within @inode to start clone
3491  * @no_time_update: Whether to update mtime/ctime on the target inode
3492  */
3493 static int btrfs_clone(struct inode *src, struct inode *inode,
3494 		       const u64 off, const u64 olen, const u64 olen_aligned,
3495 		       const u64 destoff, int no_time_update)
3496 {
3497 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3498 	struct btrfs_root *root = BTRFS_I(inode)->root;
3499 	struct btrfs_path *path = NULL;
3500 	struct extent_buffer *leaf;
3501 	struct btrfs_trans_handle *trans;
3502 	char *buf = NULL;
3503 	struct btrfs_key key;
3504 	u32 nritems;
3505 	int slot;
3506 	int ret;
3507 	const u64 len = olen_aligned;
3508 	u64 last_dest_end = destoff;
3509 
3510 	ret = -ENOMEM;
3511 	buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3512 	if (!buf)
3513 		return ret;
3514 
3515 	path = btrfs_alloc_path();
3516 	if (!path) {
3517 		kvfree(buf);
3518 		return ret;
3519 	}
3520 
3521 	path->reada = READA_FORWARD;
3522 	/* clone data */
3523 	key.objectid = btrfs_ino(BTRFS_I(src));
3524 	key.type = BTRFS_EXTENT_DATA_KEY;
3525 	key.offset = off;
3526 
3527 	while (1) {
3528 		u64 next_key_min_offset = key.offset + 1;
3529 		struct btrfs_file_extent_item *extent;
3530 		int type;
3531 		u32 size;
3532 		struct btrfs_key new_key;
3533 		u64 disko = 0, diskl = 0;
3534 		u64 datao = 0, datal = 0;
3535 		u8 comp;
3536 		u64 drop_start;
3537 
3538 		/*
3539 		 * note the key will change type as we walk through the
3540 		 * tree.
3541 		 */
3542 		path->leave_spinning = 1;
3543 		ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3544 				0, 0);
3545 		if (ret < 0)
3546 			goto out;
3547 		/*
3548 		 * First search, if no extent item that starts at offset off was
3549 		 * found but the previous item is an extent item, it's possible
3550 		 * it might overlap our target range, therefore process it.
3551 		 */
3552 		if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3553 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3554 					      path->slots[0] - 1);
3555 			if (key.type == BTRFS_EXTENT_DATA_KEY)
3556 				path->slots[0]--;
3557 		}
3558 
3559 		nritems = btrfs_header_nritems(path->nodes[0]);
3560 process_slot:
3561 		if (path->slots[0] >= nritems) {
3562 			ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3563 			if (ret < 0)
3564 				goto out;
3565 			if (ret > 0)
3566 				break;
3567 			nritems = btrfs_header_nritems(path->nodes[0]);
3568 		}
3569 		leaf = path->nodes[0];
3570 		slot = path->slots[0];
3571 
3572 		btrfs_item_key_to_cpu(leaf, &key, slot);
3573 		if (key.type > BTRFS_EXTENT_DATA_KEY ||
3574 		    key.objectid != btrfs_ino(BTRFS_I(src)))
3575 			break;
3576 
3577 		ASSERT(key.type == BTRFS_EXTENT_DATA_KEY);
3578 
3579 		extent = btrfs_item_ptr(leaf, slot,
3580 					struct btrfs_file_extent_item);
3581 		comp = btrfs_file_extent_compression(leaf, extent);
3582 		type = btrfs_file_extent_type(leaf, extent);
3583 		if (type == BTRFS_FILE_EXTENT_REG ||
3584 		    type == BTRFS_FILE_EXTENT_PREALLOC) {
3585 			disko = btrfs_file_extent_disk_bytenr(leaf, extent);
3586 			diskl = btrfs_file_extent_disk_num_bytes(leaf, extent);
3587 			datao = btrfs_file_extent_offset(leaf, extent);
3588 			datal = btrfs_file_extent_num_bytes(leaf, extent);
3589 		} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3590 			/* Take upper bound, may be compressed */
3591 			datal = btrfs_file_extent_ram_bytes(leaf, extent);
3592 		}
3593 
3594 		/*
3595 		 * The first search might have left us at an extent item that
3596 		 * ends before our target range's start, can happen if we have
3597 		 * holes and NO_HOLES feature enabled.
3598 		 */
3599 		if (key.offset + datal <= off) {
3600 			path->slots[0]++;
3601 			goto process_slot;
3602 		} else if (key.offset >= off + len) {
3603 			break;
3604 		}
3605 		next_key_min_offset = key.offset + datal;
3606 		size = btrfs_item_size_nr(leaf, slot);
3607 		read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot),
3608 				   size);
3609 
3610 		btrfs_release_path(path);
3611 		path->leave_spinning = 0;
3612 
3613 		memcpy(&new_key, &key, sizeof(new_key));
3614 		new_key.objectid = btrfs_ino(BTRFS_I(inode));
3615 		if (off <= key.offset)
3616 			new_key.offset = key.offset + destoff - off;
3617 		else
3618 			new_key.offset = destoff;
3619 
3620 		/*
3621 		 * Deal with a hole that doesn't have an extent item that
3622 		 * represents it (NO_HOLES feature enabled).
3623 		 * This hole is either in the middle of the cloning range or at
3624 		 * the beginning (fully overlaps it or partially overlaps it).
3625 		 */
3626 		if (new_key.offset != last_dest_end)
3627 			drop_start = last_dest_end;
3628 		else
3629 			drop_start = new_key.offset;
3630 
3631 		if (type == BTRFS_FILE_EXTENT_REG ||
3632 		    type == BTRFS_FILE_EXTENT_PREALLOC) {
3633 			struct btrfs_clone_extent_info clone_info;
3634 
3635 			/*
3636 			 *    a  | --- range to clone ---|  b
3637 			 * | ------------- extent ------------- |
3638 			 */
3639 
3640 			/* Subtract range b */
3641 			if (key.offset + datal > off + len)
3642 				datal = off + len - key.offset;
3643 
3644 			/* Subtract range a */
3645 			if (off > key.offset) {
3646 				datao += off - key.offset;
3647 				datal -= off - key.offset;
3648 			}
3649 
3650 			clone_info.disk_offset = disko;
3651 			clone_info.disk_len = diskl;
3652 			clone_info.data_offset = datao;
3653 			clone_info.data_len = datal;
3654 			clone_info.file_offset = new_key.offset;
3655 			clone_info.extent_buf = buf;
3656 			clone_info.item_size = size;
3657 			ret = btrfs_punch_hole_range(inode, path,
3658 						     drop_start,
3659 						     new_key.offset + datal - 1,
3660 						     &clone_info, &trans);
3661 			if (ret)
3662 				goto out;
3663 		} else if (type == BTRFS_FILE_EXTENT_INLINE) {
3664 			u64 skip = 0;
3665 			u64 trim = 0;
3666 
3667 			if (off > key.offset) {
3668 				skip = off - key.offset;
3669 				new_key.offset += skip;
3670 			}
3671 
3672 			if (key.offset + datal > off + len)
3673 				trim = key.offset + datal - (off + len);
3674 
3675 			if (comp && (skip || trim)) {
3676 				ret = -EINVAL;
3677 				goto out;
3678 			}
3679 			size -= skip + trim;
3680 			datal -= skip + trim;
3681 
3682 			/*
3683 			 * If our extent is inline, we know we will drop or
3684 			 * adjust at most 1 extent item in the destination root.
3685 			 *
3686 			 * 1 - adjusting old extent (we may have to split it)
3687 			 * 1 - add new extent
3688 			 * 1 - inode update
3689 			 */
3690 			trans = btrfs_start_transaction(root, 3);
3691 			if (IS_ERR(trans)) {
3692 				ret = PTR_ERR(trans);
3693 				goto out;
3694 			}
3695 
3696 			ret = clone_copy_inline_extent(inode, trans, path,
3697 						       &new_key, drop_start,
3698 						       datal, skip, size, buf);
3699 			if (ret) {
3700 				if (ret != -EOPNOTSUPP)
3701 					btrfs_abort_transaction(trans, ret);
3702 				btrfs_end_transaction(trans);
3703 				goto out;
3704 			}
3705 		}
3706 
3707 		btrfs_release_path(path);
3708 
3709 		last_dest_end = ALIGN(new_key.offset + datal,
3710 				      fs_info->sectorsize);
3711 		ret = clone_finish_inode_update(trans, inode, last_dest_end,
3712 						destoff, olen, no_time_update);
3713 		if (ret)
3714 			goto out;
3715 		if (new_key.offset + datal >= destoff + len)
3716 			break;
3717 
3718 		btrfs_release_path(path);
3719 		key.offset = next_key_min_offset;
3720 
3721 		if (fatal_signal_pending(current)) {
3722 			ret = -EINTR;
3723 			goto out;
3724 		}
3725 	}
3726 	ret = 0;
3727 
3728 	if (last_dest_end < destoff + len) {
3729 		/*
3730 		 * We have an implicit hole that fully or partially overlaps our
3731 		 * cloning range at its end. This means that we either have the
3732 		 * NO_HOLES feature enabled or the implicit hole happened due to
3733 		 * mixing buffered and direct IO writes against this file.
3734 		 */
3735 		btrfs_release_path(path);
3736 		path->leave_spinning = 0;
3737 
3738 		ret = btrfs_punch_hole_range(inode, path,
3739 					     last_dest_end, destoff + len - 1,
3740 					     NULL, &trans);
3741 		if (ret)
3742 			goto out;
3743 
3744 		ret = clone_finish_inode_update(trans, inode, destoff + len,
3745 						destoff, olen, no_time_update);
3746 	}
3747 
3748 out:
3749 	btrfs_free_path(path);
3750 	kvfree(buf);
3751 	return ret;
3752 }
3753 
3754 static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
3755 					u64 off, u64 olen, u64 destoff)
3756 {
3757 	struct inode *inode = file_inode(file);
3758 	struct inode *src = file_inode(file_src);
3759 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3760 	int ret;
3761 	u64 len = olen;
3762 	u64 bs = fs_info->sb->s_blocksize;
3763 
3764 	/*
3765 	 * TODO:
3766 	 * - split compressed inline extents.  annoying: we need to
3767 	 *   decompress into destination's address_space (the file offset
3768 	 *   may change, so source mapping won't do), then recompress (or
3769 	 *   otherwise reinsert) a subrange.
3770 	 *
3771 	 * - split destination inode's inline extents.  The inline extents can
3772 	 *   be either compressed or non-compressed.
3773 	 */
3774 
3775 	/*
3776 	 * VFS's generic_remap_file_range_prep() protects us from cloning the
3777 	 * eof block into the middle of a file, which would result in corruption
3778 	 * if the file size is not blocksize aligned. So we don't need to check
3779 	 * for that case here.
3780 	 */
3781 	if (off + len == src->i_size)
3782 		len = ALIGN(src->i_size, bs) - off;
3783 
3784 	if (destoff > inode->i_size) {
3785 		const u64 wb_start = ALIGN_DOWN(inode->i_size, bs);
3786 
3787 		ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3788 		if (ret)
3789 			return ret;
3790 		/*
3791 		 * We may have truncated the last block if the inode's size is
3792 		 * not sector size aligned, so we need to wait for writeback to
3793 		 * complete before proceeding further, otherwise we can race
3794 		 * with cloning and attempt to increment a reference to an
3795 		 * extent that no longer exists (writeback completed right after
3796 		 * we found the previous extent covering eof and before we
3797 		 * attempted to increment its reference count).
3798 		 */
3799 		ret = btrfs_wait_ordered_range(inode, wb_start,
3800 					       destoff - wb_start);
3801 		if (ret)
3802 			return ret;
3803 	}
3804 
3805 	/*
3806 	 * Lock destination range to serialize with concurrent readpages() and
3807 	 * source range to serialize with relocation.
3808 	 */
3809 	btrfs_double_extent_lock(src, off, inode, destoff, len);
3810 	ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
3811 	btrfs_double_extent_unlock(src, off, inode, destoff, len);
3812 	/*
3813 	 * Truncate page cache pages so that future reads will see the cloned
3814 	 * data immediately and not the previous data.
3815 	 */
3816 	truncate_inode_pages_range(&inode->i_data,
3817 				round_down(destoff, PAGE_SIZE),
3818 				round_up(destoff + len, PAGE_SIZE) - 1);
3819 
3820 	return ret;
3821 }
3822 
3823 static int btrfs_remap_file_range_prep(struct file *file_in, loff_t pos_in,
3824 				       struct file *file_out, loff_t pos_out,
3825 				       loff_t *len, unsigned int remap_flags)
3826 {
3827 	struct inode *inode_in = file_inode(file_in);
3828 	struct inode *inode_out = file_inode(file_out);
3829 	u64 bs = BTRFS_I(inode_out)->root->fs_info->sb->s_blocksize;
3830 	bool same_inode = inode_out == inode_in;
3831 	u64 wb_len;
3832 	int ret;
3833 
3834 	if (!(remap_flags & REMAP_FILE_DEDUP)) {
3835 		struct btrfs_root *root_out = BTRFS_I(inode_out)->root;
3836 
3837 		if (btrfs_root_readonly(root_out))
3838 			return -EROFS;
3839 
3840 		if (file_in->f_path.mnt != file_out->f_path.mnt ||
3841 		    inode_in->i_sb != inode_out->i_sb)
3842 			return -EXDEV;
3843 	}
3844 
3845 	/* don't make the dst file partly checksummed */
3846 	if ((BTRFS_I(inode_in)->flags & BTRFS_INODE_NODATASUM) !=
3847 	    (BTRFS_I(inode_out)->flags & BTRFS_INODE_NODATASUM)) {
3848 		return -EINVAL;
3849 	}
3850 
3851 	/*
3852 	 * Now that the inodes are locked, we need to start writeback ourselves
3853 	 * and can not rely on the writeback from the VFS's generic helper
3854 	 * generic_remap_file_range_prep() because:
3855 	 *
3856 	 * 1) For compression we must call filemap_fdatawrite_range() range
3857 	 *    twice (btrfs_fdatawrite_range() does it for us), and the generic
3858 	 *    helper only calls it once;
3859 	 *
3860 	 * 2) filemap_fdatawrite_range(), called by the generic helper only
3861 	 *    waits for the writeback to complete, i.e. for IO to be done, and
3862 	 *    not for the ordered extents to complete. We need to wait for them
3863 	 *    to complete so that new file extent items are in the fs tree.
3864 	 */
3865 	if (*len == 0 && !(remap_flags & REMAP_FILE_DEDUP))
3866 		wb_len = ALIGN(inode_in->i_size, bs) - ALIGN_DOWN(pos_in, bs);
3867 	else
3868 		wb_len = ALIGN(*len, bs);
3869 
3870 	/*
3871 	 * Since we don't lock ranges, wait for ongoing lockless dio writes (as
3872 	 * any in progress could create its ordered extents after we wait for
3873 	 * existing ordered extents below).
3874 	 */
3875 	inode_dio_wait(inode_in);
3876 	if (!same_inode)
3877 		inode_dio_wait(inode_out);
3878 
3879 	/*
3880 	 * Workaround to make sure NOCOW buffered write reach disk as NOCOW.
3881 	 *
3882 	 * Btrfs' back references do not have a block level granularity, they
3883 	 * work at the whole extent level.
3884 	 * NOCOW buffered write without data space reserved may not be able
3885 	 * to fall back to CoW due to lack of data space, thus could cause
3886 	 * data loss.
3887 	 *
3888 	 * Here we take a shortcut by flushing the whole inode, so that all
3889 	 * nocow write should reach disk as nocow before we increase the
3890 	 * reference of the extent. We could do better by only flushing NOCOW
3891 	 * data, but that needs extra accounting.
3892 	 *
3893 	 * Also we don't need to check ASYNC_EXTENT, as async extent will be
3894 	 * CoWed anyway, not affecting nocow part.
3895 	 */
3896 	ret = filemap_flush(inode_in->i_mapping);
3897 	if (ret < 0)
3898 		return ret;
3899 
3900 	ret = btrfs_wait_ordered_range(inode_in, ALIGN_DOWN(pos_in, bs),
3901 				       wb_len);
3902 	if (ret < 0)
3903 		return ret;
3904 	ret = btrfs_wait_ordered_range(inode_out, ALIGN_DOWN(pos_out, bs),
3905 				       wb_len);
3906 	if (ret < 0)
3907 		return ret;
3908 
3909 	return generic_remap_file_range_prep(file_in, pos_in, file_out, pos_out,
3910 					    len, remap_flags);
3911 }
3912 
3913 loff_t btrfs_remap_file_range(struct file *src_file, loff_t off,
3914 		struct file *dst_file, loff_t destoff, loff_t len,
3915 		unsigned int remap_flags)
3916 {
3917 	struct inode *src_inode = file_inode(src_file);
3918 	struct inode *dst_inode = file_inode(dst_file);
3919 	bool same_inode = dst_inode == src_inode;
3920 	int ret;
3921 
3922 	if (remap_flags & ~(REMAP_FILE_DEDUP | REMAP_FILE_ADVISORY))
3923 		return -EINVAL;
3924 
3925 	if (same_inode)
3926 		inode_lock(src_inode);
3927 	else
3928 		lock_two_nondirectories(src_inode, dst_inode);
3929 
3930 	ret = btrfs_remap_file_range_prep(src_file, off, dst_file, destoff,
3931 					  &len, remap_flags);
3932 	if (ret < 0 || len == 0)
3933 		goto out_unlock;
3934 
3935 	if (remap_flags & REMAP_FILE_DEDUP)
3936 		ret = btrfs_extent_same(src_inode, off, len, dst_inode, destoff);
3937 	else
3938 		ret = btrfs_clone_files(dst_file, src_file, off, len, destoff);
3939 
3940 out_unlock:
3941 	if (same_inode)
3942 		inode_unlock(src_inode);
3943 	else
3944 		unlock_two_nondirectories(src_inode, dst_inode);
3945 
3946 	return ret < 0 ? ret : len;
3947 }
3948 
3949 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3950 {
3951 	struct inode *inode = file_inode(file);
3952 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3953 	struct btrfs_root *root = BTRFS_I(inode)->root;
3954 	struct btrfs_root *new_root;
3955 	struct btrfs_dir_item *di;
3956 	struct btrfs_trans_handle *trans;
3957 	struct btrfs_path *path;
3958 	struct btrfs_key location;
3959 	struct btrfs_disk_key disk_key;
3960 	u64 objectid = 0;
3961 	u64 dir_id;
3962 	int ret;
3963 
3964 	if (!capable(CAP_SYS_ADMIN))
3965 		return -EPERM;
3966 
3967 	ret = mnt_want_write_file(file);
3968 	if (ret)
3969 		return ret;
3970 
3971 	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3972 		ret = -EFAULT;
3973 		goto out;
3974 	}
3975 
3976 	if (!objectid)
3977 		objectid = BTRFS_FS_TREE_OBJECTID;
3978 
3979 	location.objectid = objectid;
3980 	location.type = BTRFS_ROOT_ITEM_KEY;
3981 	location.offset = (u64)-1;
3982 
3983 	new_root = btrfs_read_fs_root_no_name(fs_info, &location);
3984 	if (IS_ERR(new_root)) {
3985 		ret = PTR_ERR(new_root);
3986 		goto out;
3987 	}
3988 	if (!is_fstree(new_root->root_key.objectid)) {
3989 		ret = -ENOENT;
3990 		goto out;
3991 	}
3992 
3993 	path = btrfs_alloc_path();
3994 	if (!path) {
3995 		ret = -ENOMEM;
3996 		goto out;
3997 	}
3998 	path->leave_spinning = 1;
3999 
4000 	trans = btrfs_start_transaction(root, 1);
4001 	if (IS_ERR(trans)) {
4002 		btrfs_free_path(path);
4003 		ret = PTR_ERR(trans);
4004 		goto out;
4005 	}
4006 
4007 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
4008 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
4009 				   dir_id, "default", 7, 1);
4010 	if (IS_ERR_OR_NULL(di)) {
4011 		btrfs_free_path(path);
4012 		btrfs_end_transaction(trans);
4013 		btrfs_err(fs_info,
4014 			  "Umm, you don't have the default diritem, this isn't going to work");
4015 		ret = -ENOENT;
4016 		goto out;
4017 	}
4018 
4019 	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
4020 	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
4021 	btrfs_mark_buffer_dirty(path->nodes[0]);
4022 	btrfs_free_path(path);
4023 
4024 	btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
4025 	btrfs_end_transaction(trans);
4026 out:
4027 	mnt_drop_write_file(file);
4028 	return ret;
4029 }
4030 
4031 static void get_block_group_info(struct list_head *groups_list,
4032 				 struct btrfs_ioctl_space_info *space)
4033 {
4034 	struct btrfs_block_group *block_group;
4035 
4036 	space->total_bytes = 0;
4037 	space->used_bytes = 0;
4038 	space->flags = 0;
4039 	list_for_each_entry(block_group, groups_list, list) {
4040 		space->flags = block_group->flags;
4041 		space->total_bytes += block_group->length;
4042 		space->used_bytes += block_group->used;
4043 	}
4044 }
4045 
4046 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
4047 				   void __user *arg)
4048 {
4049 	struct btrfs_ioctl_space_args space_args;
4050 	struct btrfs_ioctl_space_info space;
4051 	struct btrfs_ioctl_space_info *dest;
4052 	struct btrfs_ioctl_space_info *dest_orig;
4053 	struct btrfs_ioctl_space_info __user *user_dest;
4054 	struct btrfs_space_info *info;
4055 	static const u64 types[] = {
4056 		BTRFS_BLOCK_GROUP_DATA,
4057 		BTRFS_BLOCK_GROUP_SYSTEM,
4058 		BTRFS_BLOCK_GROUP_METADATA,
4059 		BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4060 	};
4061 	int num_types = 4;
4062 	int alloc_size;
4063 	int ret = 0;
4064 	u64 slot_count = 0;
4065 	int i, c;
4066 
4067 	if (copy_from_user(&space_args,
4068 			   (struct btrfs_ioctl_space_args __user *)arg,
4069 			   sizeof(space_args)))
4070 		return -EFAULT;
4071 
4072 	for (i = 0; i < num_types; i++) {
4073 		struct btrfs_space_info *tmp;
4074 
4075 		info = NULL;
4076 		rcu_read_lock();
4077 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4078 					list) {
4079 			if (tmp->flags == types[i]) {
4080 				info = tmp;
4081 				break;
4082 			}
4083 		}
4084 		rcu_read_unlock();
4085 
4086 		if (!info)
4087 			continue;
4088 
4089 		down_read(&info->groups_sem);
4090 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4091 			if (!list_empty(&info->block_groups[c]))
4092 				slot_count++;
4093 		}
4094 		up_read(&info->groups_sem);
4095 	}
4096 
4097 	/*
4098 	 * Global block reserve, exported as a space_info
4099 	 */
4100 	slot_count++;
4101 
4102 	/* space_slots == 0 means they are asking for a count */
4103 	if (space_args.space_slots == 0) {
4104 		space_args.total_spaces = slot_count;
4105 		goto out;
4106 	}
4107 
4108 	slot_count = min_t(u64, space_args.space_slots, slot_count);
4109 
4110 	alloc_size = sizeof(*dest) * slot_count;
4111 
4112 	/* we generally have at most 6 or so space infos, one for each raid
4113 	 * level.  So, a whole page should be more than enough for everyone
4114 	 */
4115 	if (alloc_size > PAGE_SIZE)
4116 		return -ENOMEM;
4117 
4118 	space_args.total_spaces = 0;
4119 	dest = kmalloc(alloc_size, GFP_KERNEL);
4120 	if (!dest)
4121 		return -ENOMEM;
4122 	dest_orig = dest;
4123 
4124 	/* now we have a buffer to copy into */
4125 	for (i = 0; i < num_types; i++) {
4126 		struct btrfs_space_info *tmp;
4127 
4128 		if (!slot_count)
4129 			break;
4130 
4131 		info = NULL;
4132 		rcu_read_lock();
4133 		list_for_each_entry_rcu(tmp, &fs_info->space_info,
4134 					list) {
4135 			if (tmp->flags == types[i]) {
4136 				info = tmp;
4137 				break;
4138 			}
4139 		}
4140 		rcu_read_unlock();
4141 
4142 		if (!info)
4143 			continue;
4144 		down_read(&info->groups_sem);
4145 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4146 			if (!list_empty(&info->block_groups[c])) {
4147 				get_block_group_info(&info->block_groups[c],
4148 						     &space);
4149 				memcpy(dest, &space, sizeof(space));
4150 				dest++;
4151 				space_args.total_spaces++;
4152 				slot_count--;
4153 			}
4154 			if (!slot_count)
4155 				break;
4156 		}
4157 		up_read(&info->groups_sem);
4158 	}
4159 
4160 	/*
4161 	 * Add global block reserve
4162 	 */
4163 	if (slot_count) {
4164 		struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4165 
4166 		spin_lock(&block_rsv->lock);
4167 		space.total_bytes = block_rsv->size;
4168 		space.used_bytes = block_rsv->size - block_rsv->reserved;
4169 		spin_unlock(&block_rsv->lock);
4170 		space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
4171 		memcpy(dest, &space, sizeof(space));
4172 		space_args.total_spaces++;
4173 	}
4174 
4175 	user_dest = (struct btrfs_ioctl_space_info __user *)
4176 		(arg + sizeof(struct btrfs_ioctl_space_args));
4177 
4178 	if (copy_to_user(user_dest, dest_orig, alloc_size))
4179 		ret = -EFAULT;
4180 
4181 	kfree(dest_orig);
4182 out:
4183 	if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
4184 		ret = -EFAULT;
4185 
4186 	return ret;
4187 }
4188 
4189 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
4190 					    void __user *argp)
4191 {
4192 	struct btrfs_trans_handle *trans;
4193 	u64 transid;
4194 	int ret;
4195 
4196 	trans = btrfs_attach_transaction_barrier(root);
4197 	if (IS_ERR(trans)) {
4198 		if (PTR_ERR(trans) != -ENOENT)
4199 			return PTR_ERR(trans);
4200 
4201 		/* No running transaction, don't bother */
4202 		transid = root->fs_info->last_trans_committed;
4203 		goto out;
4204 	}
4205 	transid = trans->transid;
4206 	ret = btrfs_commit_transaction_async(trans, 0);
4207 	if (ret) {
4208 		btrfs_end_transaction(trans);
4209 		return ret;
4210 	}
4211 out:
4212 	if (argp)
4213 		if (copy_to_user(argp, &transid, sizeof(transid)))
4214 			return -EFAULT;
4215 	return 0;
4216 }
4217 
4218 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
4219 					   void __user *argp)
4220 {
4221 	u64 transid;
4222 
4223 	if (argp) {
4224 		if (copy_from_user(&transid, argp, sizeof(transid)))
4225 			return -EFAULT;
4226 	} else {
4227 		transid = 0;  /* current trans */
4228 	}
4229 	return btrfs_wait_for_commit(fs_info, transid);
4230 }
4231 
4232 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4233 {
4234 	struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4235 	struct btrfs_ioctl_scrub_args *sa;
4236 	int ret;
4237 
4238 	if (!capable(CAP_SYS_ADMIN))
4239 		return -EPERM;
4240 
4241 	sa = memdup_user(arg, sizeof(*sa));
4242 	if (IS_ERR(sa))
4243 		return PTR_ERR(sa);
4244 
4245 	if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4246 		ret = mnt_want_write_file(file);
4247 		if (ret)
4248 			goto out;
4249 	}
4250 
4251 	ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
4252 			      &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4253 			      0);
4254 
4255 	/*
4256 	 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
4257 	 * error. This is important as it allows user space to know how much
4258 	 * progress scrub has done. For example, if scrub is canceled we get
4259 	 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
4260 	 * space. Later user space can inspect the progress from the structure
4261 	 * btrfs_ioctl_scrub_args and resume scrub from where it left off
4262 	 * previously (btrfs-progs does this).
4263 	 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
4264 	 * then return -EFAULT to signal the structure was not copied or it may
4265 	 * be corrupt and unreliable due to a partial copy.
4266 	 */
4267 	if (copy_to_user(arg, sa, sizeof(*sa)))
4268 		ret = -EFAULT;
4269 
4270 	if (!(sa->flags & BTRFS_SCRUB_READONLY))
4271 		mnt_drop_write_file(file);
4272 out:
4273 	kfree(sa);
4274 	return ret;
4275 }
4276 
4277 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4278 {
4279 	if (!capable(CAP_SYS_ADMIN))
4280 		return -EPERM;
4281 
4282 	return btrfs_scrub_cancel(fs_info);
4283 }
4284 
4285 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4286 				       void __user *arg)
4287 {
4288 	struct btrfs_ioctl_scrub_args *sa;
4289 	int ret;
4290 
4291 	if (!capable(CAP_SYS_ADMIN))
4292 		return -EPERM;
4293 
4294 	sa = memdup_user(arg, sizeof(*sa));
4295 	if (IS_ERR(sa))
4296 		return PTR_ERR(sa);
4297 
4298 	ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4299 
4300 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4301 		ret = -EFAULT;
4302 
4303 	kfree(sa);
4304 	return ret;
4305 }
4306 
4307 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4308 				      void __user *arg)
4309 {
4310 	struct btrfs_ioctl_get_dev_stats *sa;
4311 	int ret;
4312 
4313 	sa = memdup_user(arg, sizeof(*sa));
4314 	if (IS_ERR(sa))
4315 		return PTR_ERR(sa);
4316 
4317 	if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4318 		kfree(sa);
4319 		return -EPERM;
4320 	}
4321 
4322 	ret = btrfs_get_dev_stats(fs_info, sa);
4323 
4324 	if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4325 		ret = -EFAULT;
4326 
4327 	kfree(sa);
4328 	return ret;
4329 }
4330 
4331 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
4332 				    void __user *arg)
4333 {
4334 	struct btrfs_ioctl_dev_replace_args *p;
4335 	int ret;
4336 
4337 	if (!capable(CAP_SYS_ADMIN))
4338 		return -EPERM;
4339 
4340 	p = memdup_user(arg, sizeof(*p));
4341 	if (IS_ERR(p))
4342 		return PTR_ERR(p);
4343 
4344 	switch (p->cmd) {
4345 	case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4346 		if (sb_rdonly(fs_info->sb)) {
4347 			ret = -EROFS;
4348 			goto out;
4349 		}
4350 		if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4351 			ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4352 		} else {
4353 			ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4354 			clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4355 		}
4356 		break;
4357 	case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4358 		btrfs_dev_replace_status(fs_info, p);
4359 		ret = 0;
4360 		break;
4361 	case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4362 		p->result = btrfs_dev_replace_cancel(fs_info);
4363 		ret = 0;
4364 		break;
4365 	default:
4366 		ret = -EINVAL;
4367 		break;
4368 	}
4369 
4370 	if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
4371 		ret = -EFAULT;
4372 out:
4373 	kfree(p);
4374 	return ret;
4375 }
4376 
4377 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4378 {
4379 	int ret = 0;
4380 	int i;
4381 	u64 rel_ptr;
4382 	int size;
4383 	struct btrfs_ioctl_ino_path_args *ipa = NULL;
4384 	struct inode_fs_paths *ipath = NULL;
4385 	struct btrfs_path *path;
4386 
4387 	if (!capable(CAP_DAC_READ_SEARCH))
4388 		return -EPERM;
4389 
4390 	path = btrfs_alloc_path();
4391 	if (!path) {
4392 		ret = -ENOMEM;
4393 		goto out;
4394 	}
4395 
4396 	ipa = memdup_user(arg, sizeof(*ipa));
4397 	if (IS_ERR(ipa)) {
4398 		ret = PTR_ERR(ipa);
4399 		ipa = NULL;
4400 		goto out;
4401 	}
4402 
4403 	size = min_t(u32, ipa->size, 4096);
4404 	ipath = init_ipath(size, root, path);
4405 	if (IS_ERR(ipath)) {
4406 		ret = PTR_ERR(ipath);
4407 		ipath = NULL;
4408 		goto out;
4409 	}
4410 
4411 	ret = paths_from_inode(ipa->inum, ipath);
4412 	if (ret < 0)
4413 		goto out;
4414 
4415 	for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4416 		rel_ptr = ipath->fspath->val[i] -
4417 			  (u64)(unsigned long)ipath->fspath->val;
4418 		ipath->fspath->val[i] = rel_ptr;
4419 	}
4420 
4421 	ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4422 			   ipath->fspath, size);
4423 	if (ret) {
4424 		ret = -EFAULT;
4425 		goto out;
4426 	}
4427 
4428 out:
4429 	btrfs_free_path(path);
4430 	free_ipath(ipath);
4431 	kfree(ipa);
4432 
4433 	return ret;
4434 }
4435 
4436 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4437 {
4438 	struct btrfs_data_container *inodes = ctx;
4439 	const size_t c = 3 * sizeof(u64);
4440 
4441 	if (inodes->bytes_left >= c) {
4442 		inodes->bytes_left -= c;
4443 		inodes->val[inodes->elem_cnt] = inum;
4444 		inodes->val[inodes->elem_cnt + 1] = offset;
4445 		inodes->val[inodes->elem_cnt + 2] = root;
4446 		inodes->elem_cnt += 3;
4447 	} else {
4448 		inodes->bytes_missing += c - inodes->bytes_left;
4449 		inodes->bytes_left = 0;
4450 		inodes->elem_missed += 3;
4451 	}
4452 
4453 	return 0;
4454 }
4455 
4456 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4457 					void __user *arg, int version)
4458 {
4459 	int ret = 0;
4460 	int size;
4461 	struct btrfs_ioctl_logical_ino_args *loi;
4462 	struct btrfs_data_container *inodes = NULL;
4463 	struct btrfs_path *path = NULL;
4464 	bool ignore_offset;
4465 
4466 	if (!capable(CAP_SYS_ADMIN))
4467 		return -EPERM;
4468 
4469 	loi = memdup_user(arg, sizeof(*loi));
4470 	if (IS_ERR(loi))
4471 		return PTR_ERR(loi);
4472 
4473 	if (version == 1) {
4474 		ignore_offset = false;
4475 		size = min_t(u32, loi->size, SZ_64K);
4476 	} else {
4477 		/* All reserved bits must be 0 for now */
4478 		if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4479 			ret = -EINVAL;
4480 			goto out_loi;
4481 		}
4482 		/* Only accept flags we have defined so far */
4483 		if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4484 			ret = -EINVAL;
4485 			goto out_loi;
4486 		}
4487 		ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4488 		size = min_t(u32, loi->size, SZ_16M);
4489 	}
4490 
4491 	path = btrfs_alloc_path();
4492 	if (!path) {
4493 		ret = -ENOMEM;
4494 		goto out;
4495 	}
4496 
4497 	inodes = init_data_container(size);
4498 	if (IS_ERR(inodes)) {
4499 		ret = PTR_ERR(inodes);
4500 		inodes = NULL;
4501 		goto out;
4502 	}
4503 
4504 	ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4505 					  build_ino_list, inodes, ignore_offset);
4506 	if (ret == -EINVAL)
4507 		ret = -ENOENT;
4508 	if (ret < 0)
4509 		goto out;
4510 
4511 	ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4512 			   size);
4513 	if (ret)
4514 		ret = -EFAULT;
4515 
4516 out:
4517 	btrfs_free_path(path);
4518 	kvfree(inodes);
4519 out_loi:
4520 	kfree(loi);
4521 
4522 	return ret;
4523 }
4524 
4525 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4526 			       struct btrfs_ioctl_balance_args *bargs)
4527 {
4528 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4529 
4530 	bargs->flags = bctl->flags;
4531 
4532 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4533 		bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4534 	if (atomic_read(&fs_info->balance_pause_req))
4535 		bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4536 	if (atomic_read(&fs_info->balance_cancel_req))
4537 		bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4538 
4539 	memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4540 	memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4541 	memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4542 
4543 	spin_lock(&fs_info->balance_lock);
4544 	memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4545 	spin_unlock(&fs_info->balance_lock);
4546 }
4547 
4548 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4549 {
4550 	struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4551 	struct btrfs_fs_info *fs_info = root->fs_info;
4552 	struct btrfs_ioctl_balance_args *bargs;
4553 	struct btrfs_balance_control *bctl;
4554 	bool need_unlock; /* for mut. excl. ops lock */
4555 	int ret;
4556 
4557 	if (!capable(CAP_SYS_ADMIN))
4558 		return -EPERM;
4559 
4560 	ret = mnt_want_write_file(file);
4561 	if (ret)
4562 		return ret;
4563 
4564 again:
4565 	if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4566 		mutex_lock(&fs_info->balance_mutex);
4567 		need_unlock = true;
4568 		goto locked;
4569 	}
4570 
4571 	/*
4572 	 * mut. excl. ops lock is locked.  Three possibilities:
4573 	 *   (1) some other op is running
4574 	 *   (2) balance is running
4575 	 *   (3) balance is paused -- special case (think resume)
4576 	 */
4577 	mutex_lock(&fs_info->balance_mutex);
4578 	if (fs_info->balance_ctl) {
4579 		/* this is either (2) or (3) */
4580 		if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4581 			mutex_unlock(&fs_info->balance_mutex);
4582 			/*
4583 			 * Lock released to allow other waiters to continue,
4584 			 * we'll reexamine the status again.
4585 			 */
4586 			mutex_lock(&fs_info->balance_mutex);
4587 
4588 			if (fs_info->balance_ctl &&
4589 			    !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4590 				/* this is (3) */
4591 				need_unlock = false;
4592 				goto locked;
4593 			}
4594 
4595 			mutex_unlock(&fs_info->balance_mutex);
4596 			goto again;
4597 		} else {
4598 			/* this is (2) */
4599 			mutex_unlock(&fs_info->balance_mutex);
4600 			ret = -EINPROGRESS;
4601 			goto out;
4602 		}
4603 	} else {
4604 		/* this is (1) */
4605 		mutex_unlock(&fs_info->balance_mutex);
4606 		ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4607 		goto out;
4608 	}
4609 
4610 locked:
4611 	BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4612 
4613 	if (arg) {
4614 		bargs = memdup_user(arg, sizeof(*bargs));
4615 		if (IS_ERR(bargs)) {
4616 			ret = PTR_ERR(bargs);
4617 			goto out_unlock;
4618 		}
4619 
4620 		if (bargs->flags & BTRFS_BALANCE_RESUME) {
4621 			if (!fs_info->balance_ctl) {
4622 				ret = -ENOTCONN;
4623 				goto out_bargs;
4624 			}
4625 
4626 			bctl = fs_info->balance_ctl;
4627 			spin_lock(&fs_info->balance_lock);
4628 			bctl->flags |= BTRFS_BALANCE_RESUME;
4629 			spin_unlock(&fs_info->balance_lock);
4630 
4631 			goto do_balance;
4632 		}
4633 	} else {
4634 		bargs = NULL;
4635 	}
4636 
4637 	if (fs_info->balance_ctl) {
4638 		ret = -EINPROGRESS;
4639 		goto out_bargs;
4640 	}
4641 
4642 	bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4643 	if (!bctl) {
4644 		ret = -ENOMEM;
4645 		goto out_bargs;
4646 	}
4647 
4648 	if (arg) {
4649 		memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4650 		memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4651 		memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4652 
4653 		bctl->flags = bargs->flags;
4654 	} else {
4655 		/* balance everything - no filters */
4656 		bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4657 	}
4658 
4659 	if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4660 		ret = -EINVAL;
4661 		goto out_bctl;
4662 	}
4663 
4664 do_balance:
4665 	/*
4666 	 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
4667 	 * btrfs_balance.  bctl is freed in reset_balance_state, or, if
4668 	 * restriper was paused all the way until unmount, in free_fs_info.
4669 	 * The flag should be cleared after reset_balance_state.
4670 	 */
4671 	need_unlock = false;
4672 
4673 	ret = btrfs_balance(fs_info, bctl, bargs);
4674 	bctl = NULL;
4675 
4676 	if ((ret == 0 || ret == -ECANCELED) && arg) {
4677 		if (copy_to_user(arg, bargs, sizeof(*bargs)))
4678 			ret = -EFAULT;
4679 	}
4680 
4681 out_bctl:
4682 	kfree(bctl);
4683 out_bargs:
4684 	kfree(bargs);
4685 out_unlock:
4686 	mutex_unlock(&fs_info->balance_mutex);
4687 	if (need_unlock)
4688 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4689 out:
4690 	mnt_drop_write_file(file);
4691 	return ret;
4692 }
4693 
4694 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4695 {
4696 	if (!capable(CAP_SYS_ADMIN))
4697 		return -EPERM;
4698 
4699 	switch (cmd) {
4700 	case BTRFS_BALANCE_CTL_PAUSE:
4701 		return btrfs_pause_balance(fs_info);
4702 	case BTRFS_BALANCE_CTL_CANCEL:
4703 		return btrfs_cancel_balance(fs_info);
4704 	}
4705 
4706 	return -EINVAL;
4707 }
4708 
4709 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4710 					 void __user *arg)
4711 {
4712 	struct btrfs_ioctl_balance_args *bargs;
4713 	int ret = 0;
4714 
4715 	if (!capable(CAP_SYS_ADMIN))
4716 		return -EPERM;
4717 
4718 	mutex_lock(&fs_info->balance_mutex);
4719 	if (!fs_info->balance_ctl) {
4720 		ret = -ENOTCONN;
4721 		goto out;
4722 	}
4723 
4724 	bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4725 	if (!bargs) {
4726 		ret = -ENOMEM;
4727 		goto out;
4728 	}
4729 
4730 	btrfs_update_ioctl_balance_args(fs_info, bargs);
4731 
4732 	if (copy_to_user(arg, bargs, sizeof(*bargs)))
4733 		ret = -EFAULT;
4734 
4735 	kfree(bargs);
4736 out:
4737 	mutex_unlock(&fs_info->balance_mutex);
4738 	return ret;
4739 }
4740 
4741 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4742 {
4743 	struct inode *inode = file_inode(file);
4744 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4745 	struct btrfs_ioctl_quota_ctl_args *sa;
4746 	int ret;
4747 
4748 	if (!capable(CAP_SYS_ADMIN))
4749 		return -EPERM;
4750 
4751 	ret = mnt_want_write_file(file);
4752 	if (ret)
4753 		return ret;
4754 
4755 	sa = memdup_user(arg, sizeof(*sa));
4756 	if (IS_ERR(sa)) {
4757 		ret = PTR_ERR(sa);
4758 		goto drop_write;
4759 	}
4760 
4761 	down_write(&fs_info->subvol_sem);
4762 
4763 	switch (sa->cmd) {
4764 	case BTRFS_QUOTA_CTL_ENABLE:
4765 		ret = btrfs_quota_enable(fs_info);
4766 		break;
4767 	case BTRFS_QUOTA_CTL_DISABLE:
4768 		ret = btrfs_quota_disable(fs_info);
4769 		break;
4770 	default:
4771 		ret = -EINVAL;
4772 		break;
4773 	}
4774 
4775 	kfree(sa);
4776 	up_write(&fs_info->subvol_sem);
4777 drop_write:
4778 	mnt_drop_write_file(file);
4779 	return ret;
4780 }
4781 
4782 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4783 {
4784 	struct inode *inode = file_inode(file);
4785 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4786 	struct btrfs_root *root = BTRFS_I(inode)->root;
4787 	struct btrfs_ioctl_qgroup_assign_args *sa;
4788 	struct btrfs_trans_handle *trans;
4789 	int ret;
4790 	int err;
4791 
4792 	if (!capable(CAP_SYS_ADMIN))
4793 		return -EPERM;
4794 
4795 	ret = mnt_want_write_file(file);
4796 	if (ret)
4797 		return ret;
4798 
4799 	sa = memdup_user(arg, sizeof(*sa));
4800 	if (IS_ERR(sa)) {
4801 		ret = PTR_ERR(sa);
4802 		goto drop_write;
4803 	}
4804 
4805 	trans = btrfs_join_transaction(root);
4806 	if (IS_ERR(trans)) {
4807 		ret = PTR_ERR(trans);
4808 		goto out;
4809 	}
4810 
4811 	if (sa->assign) {
4812 		ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
4813 	} else {
4814 		ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
4815 	}
4816 
4817 	/* update qgroup status and info */
4818 	err = btrfs_run_qgroups(trans);
4819 	if (err < 0)
4820 		btrfs_handle_fs_error(fs_info, err,
4821 				      "failed to update qgroup status and info");
4822 	err = btrfs_end_transaction(trans);
4823 	if (err && !ret)
4824 		ret = err;
4825 
4826 out:
4827 	kfree(sa);
4828 drop_write:
4829 	mnt_drop_write_file(file);
4830 	return ret;
4831 }
4832 
4833 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4834 {
4835 	struct inode *inode = file_inode(file);
4836 	struct btrfs_root *root = BTRFS_I(inode)->root;
4837 	struct btrfs_ioctl_qgroup_create_args *sa;
4838 	struct btrfs_trans_handle *trans;
4839 	int ret;
4840 	int err;
4841 
4842 	if (!capable(CAP_SYS_ADMIN))
4843 		return -EPERM;
4844 
4845 	ret = mnt_want_write_file(file);
4846 	if (ret)
4847 		return ret;
4848 
4849 	sa = memdup_user(arg, sizeof(*sa));
4850 	if (IS_ERR(sa)) {
4851 		ret = PTR_ERR(sa);
4852 		goto drop_write;
4853 	}
4854 
4855 	if (!sa->qgroupid) {
4856 		ret = -EINVAL;
4857 		goto out;
4858 	}
4859 
4860 	trans = btrfs_join_transaction(root);
4861 	if (IS_ERR(trans)) {
4862 		ret = PTR_ERR(trans);
4863 		goto out;
4864 	}
4865 
4866 	if (sa->create) {
4867 		ret = btrfs_create_qgroup(trans, sa->qgroupid);
4868 	} else {
4869 		ret = btrfs_remove_qgroup(trans, sa->qgroupid);
4870 	}
4871 
4872 	err = btrfs_end_transaction(trans);
4873 	if (err && !ret)
4874 		ret = err;
4875 
4876 out:
4877 	kfree(sa);
4878 drop_write:
4879 	mnt_drop_write_file(file);
4880 	return ret;
4881 }
4882 
4883 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4884 {
4885 	struct inode *inode = file_inode(file);
4886 	struct btrfs_root *root = BTRFS_I(inode)->root;
4887 	struct btrfs_ioctl_qgroup_limit_args *sa;
4888 	struct btrfs_trans_handle *trans;
4889 	int ret;
4890 	int err;
4891 	u64 qgroupid;
4892 
4893 	if (!capable(CAP_SYS_ADMIN))
4894 		return -EPERM;
4895 
4896 	ret = mnt_want_write_file(file);
4897 	if (ret)
4898 		return ret;
4899 
4900 	sa = memdup_user(arg, sizeof(*sa));
4901 	if (IS_ERR(sa)) {
4902 		ret = PTR_ERR(sa);
4903 		goto drop_write;
4904 	}
4905 
4906 	trans = btrfs_join_transaction(root);
4907 	if (IS_ERR(trans)) {
4908 		ret = PTR_ERR(trans);
4909 		goto out;
4910 	}
4911 
4912 	qgroupid = sa->qgroupid;
4913 	if (!qgroupid) {
4914 		/* take the current subvol as qgroup */
4915 		qgroupid = root->root_key.objectid;
4916 	}
4917 
4918 	ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
4919 
4920 	err = btrfs_end_transaction(trans);
4921 	if (err && !ret)
4922 		ret = err;
4923 
4924 out:
4925 	kfree(sa);
4926 drop_write:
4927 	mnt_drop_write_file(file);
4928 	return ret;
4929 }
4930 
4931 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4932 {
4933 	struct inode *inode = file_inode(file);
4934 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4935 	struct btrfs_ioctl_quota_rescan_args *qsa;
4936 	int ret;
4937 
4938 	if (!capable(CAP_SYS_ADMIN))
4939 		return -EPERM;
4940 
4941 	ret = mnt_want_write_file(file);
4942 	if (ret)
4943 		return ret;
4944 
4945 	qsa = memdup_user(arg, sizeof(*qsa));
4946 	if (IS_ERR(qsa)) {
4947 		ret = PTR_ERR(qsa);
4948 		goto drop_write;
4949 	}
4950 
4951 	if (qsa->flags) {
4952 		ret = -EINVAL;
4953 		goto out;
4954 	}
4955 
4956 	ret = btrfs_qgroup_rescan(fs_info);
4957 
4958 out:
4959 	kfree(qsa);
4960 drop_write:
4961 	mnt_drop_write_file(file);
4962 	return ret;
4963 }
4964 
4965 static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4966 						void __user *arg)
4967 {
4968 	struct btrfs_ioctl_quota_rescan_args *qsa;
4969 	int ret = 0;
4970 
4971 	if (!capable(CAP_SYS_ADMIN))
4972 		return -EPERM;
4973 
4974 	qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
4975 	if (!qsa)
4976 		return -ENOMEM;
4977 
4978 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4979 		qsa->flags = 1;
4980 		qsa->progress = fs_info->qgroup_rescan_progress.objectid;
4981 	}
4982 
4983 	if (copy_to_user(arg, qsa, sizeof(*qsa)))
4984 		ret = -EFAULT;
4985 
4986 	kfree(qsa);
4987 	return ret;
4988 }
4989 
4990 static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4991 						void __user *arg)
4992 {
4993 	if (!capable(CAP_SYS_ADMIN))
4994 		return -EPERM;
4995 
4996 	return btrfs_qgroup_wait_for_completion(fs_info, true);
4997 }
4998 
4999 static long _btrfs_ioctl_set_received_subvol(struct file *file,
5000 					    struct btrfs_ioctl_received_subvol_args *sa)
5001 {
5002 	struct inode *inode = file_inode(file);
5003 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5004 	struct btrfs_root *root = BTRFS_I(inode)->root;
5005 	struct btrfs_root_item *root_item = &root->root_item;
5006 	struct btrfs_trans_handle *trans;
5007 	struct timespec64 ct = current_time(inode);
5008 	int ret = 0;
5009 	int received_uuid_changed;
5010 
5011 	if (!inode_owner_or_capable(inode))
5012 		return -EPERM;
5013 
5014 	ret = mnt_want_write_file(file);
5015 	if (ret < 0)
5016 		return ret;
5017 
5018 	down_write(&fs_info->subvol_sem);
5019 
5020 	if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
5021 		ret = -EINVAL;
5022 		goto out;
5023 	}
5024 
5025 	if (btrfs_root_readonly(root)) {
5026 		ret = -EROFS;
5027 		goto out;
5028 	}
5029 
5030 	/*
5031 	 * 1 - root item
5032 	 * 2 - uuid items (received uuid + subvol uuid)
5033 	 */
5034 	trans = btrfs_start_transaction(root, 3);
5035 	if (IS_ERR(trans)) {
5036 		ret = PTR_ERR(trans);
5037 		trans = NULL;
5038 		goto out;
5039 	}
5040 
5041 	sa->rtransid = trans->transid;
5042 	sa->rtime.sec = ct.tv_sec;
5043 	sa->rtime.nsec = ct.tv_nsec;
5044 
5045 	received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5046 				       BTRFS_UUID_SIZE);
5047 	if (received_uuid_changed &&
5048 	    !btrfs_is_empty_uuid(root_item->received_uuid)) {
5049 		ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
5050 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5051 					  root->root_key.objectid);
5052 		if (ret && ret != -ENOENT) {
5053 		        btrfs_abort_transaction(trans, ret);
5054 		        btrfs_end_transaction(trans);
5055 		        goto out;
5056 		}
5057 	}
5058 	memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
5059 	btrfs_set_root_stransid(root_item, sa->stransid);
5060 	btrfs_set_root_rtransid(root_item, sa->rtransid);
5061 	btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
5062 	btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
5063 	btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
5064 	btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
5065 
5066 	ret = btrfs_update_root(trans, fs_info->tree_root,
5067 				&root->root_key, &root->root_item);
5068 	if (ret < 0) {
5069 		btrfs_end_transaction(trans);
5070 		goto out;
5071 	}
5072 	if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5073 		ret = btrfs_uuid_tree_add(trans, sa->uuid,
5074 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5075 					  root->root_key.objectid);
5076 		if (ret < 0 && ret != -EEXIST) {
5077 			btrfs_abort_transaction(trans, ret);
5078 			btrfs_end_transaction(trans);
5079 			goto out;
5080 		}
5081 	}
5082 	ret = btrfs_commit_transaction(trans);
5083 out:
5084 	up_write(&fs_info->subvol_sem);
5085 	mnt_drop_write_file(file);
5086 	return ret;
5087 }
5088 
5089 #ifdef CONFIG_64BIT
5090 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5091 						void __user *arg)
5092 {
5093 	struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5094 	struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5095 	int ret = 0;
5096 
5097 	args32 = memdup_user(arg, sizeof(*args32));
5098 	if (IS_ERR(args32))
5099 		return PTR_ERR(args32);
5100 
5101 	args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
5102 	if (!args64) {
5103 		ret = -ENOMEM;
5104 		goto out;
5105 	}
5106 
5107 	memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5108 	args64->stransid = args32->stransid;
5109 	args64->rtransid = args32->rtransid;
5110 	args64->stime.sec = args32->stime.sec;
5111 	args64->stime.nsec = args32->stime.nsec;
5112 	args64->rtime.sec = args32->rtime.sec;
5113 	args64->rtime.nsec = args32->rtime.nsec;
5114 	args64->flags = args32->flags;
5115 
5116 	ret = _btrfs_ioctl_set_received_subvol(file, args64);
5117 	if (ret)
5118 		goto out;
5119 
5120 	memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5121 	args32->stransid = args64->stransid;
5122 	args32->rtransid = args64->rtransid;
5123 	args32->stime.sec = args64->stime.sec;
5124 	args32->stime.nsec = args64->stime.nsec;
5125 	args32->rtime.sec = args64->rtime.sec;
5126 	args32->rtime.nsec = args64->rtime.nsec;
5127 	args32->flags = args64->flags;
5128 
5129 	ret = copy_to_user(arg, args32, sizeof(*args32));
5130 	if (ret)
5131 		ret = -EFAULT;
5132 
5133 out:
5134 	kfree(args32);
5135 	kfree(args64);
5136 	return ret;
5137 }
5138 #endif
5139 
5140 static long btrfs_ioctl_set_received_subvol(struct file *file,
5141 					    void __user *arg)
5142 {
5143 	struct btrfs_ioctl_received_subvol_args *sa = NULL;
5144 	int ret = 0;
5145 
5146 	sa = memdup_user(arg, sizeof(*sa));
5147 	if (IS_ERR(sa))
5148 		return PTR_ERR(sa);
5149 
5150 	ret = _btrfs_ioctl_set_received_subvol(file, sa);
5151 
5152 	if (ret)
5153 		goto out;
5154 
5155 	ret = copy_to_user(arg, sa, sizeof(*sa));
5156 	if (ret)
5157 		ret = -EFAULT;
5158 
5159 out:
5160 	kfree(sa);
5161 	return ret;
5162 }
5163 
5164 static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
5165 					void __user *arg)
5166 {
5167 	size_t len;
5168 	int ret;
5169 	char label[BTRFS_LABEL_SIZE];
5170 
5171 	spin_lock(&fs_info->super_lock);
5172 	memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5173 	spin_unlock(&fs_info->super_lock);
5174 
5175 	len = strnlen(label, BTRFS_LABEL_SIZE);
5176 
5177 	if (len == BTRFS_LABEL_SIZE) {
5178 		btrfs_warn(fs_info,
5179 			   "label is too long, return the first %zu bytes",
5180 			   --len);
5181 	}
5182 
5183 	ret = copy_to_user(arg, label, len);
5184 
5185 	return ret ? -EFAULT : 0;
5186 }
5187 
5188 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5189 {
5190 	struct inode *inode = file_inode(file);
5191 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5192 	struct btrfs_root *root = BTRFS_I(inode)->root;
5193 	struct btrfs_super_block *super_block = fs_info->super_copy;
5194 	struct btrfs_trans_handle *trans;
5195 	char label[BTRFS_LABEL_SIZE];
5196 	int ret;
5197 
5198 	if (!capable(CAP_SYS_ADMIN))
5199 		return -EPERM;
5200 
5201 	if (copy_from_user(label, arg, sizeof(label)))
5202 		return -EFAULT;
5203 
5204 	if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
5205 		btrfs_err(fs_info,
5206 			  "unable to set label with more than %d bytes",
5207 			  BTRFS_LABEL_SIZE - 1);
5208 		return -EINVAL;
5209 	}
5210 
5211 	ret = mnt_want_write_file(file);
5212 	if (ret)
5213 		return ret;
5214 
5215 	trans = btrfs_start_transaction(root, 0);
5216 	if (IS_ERR(trans)) {
5217 		ret = PTR_ERR(trans);
5218 		goto out_unlock;
5219 	}
5220 
5221 	spin_lock(&fs_info->super_lock);
5222 	strcpy(super_block->label, label);
5223 	spin_unlock(&fs_info->super_lock);
5224 	ret = btrfs_commit_transaction(trans);
5225 
5226 out_unlock:
5227 	mnt_drop_write_file(file);
5228 	return ret;
5229 }
5230 
5231 #define INIT_FEATURE_FLAGS(suffix) \
5232 	{ .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5233 	  .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5234 	  .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5235 
5236 int btrfs_ioctl_get_supported_features(void __user *arg)
5237 {
5238 	static const struct btrfs_ioctl_feature_flags features[3] = {
5239 		INIT_FEATURE_FLAGS(SUPP),
5240 		INIT_FEATURE_FLAGS(SAFE_SET),
5241 		INIT_FEATURE_FLAGS(SAFE_CLEAR)
5242 	};
5243 
5244 	if (copy_to_user(arg, &features, sizeof(features)))
5245 		return -EFAULT;
5246 
5247 	return 0;
5248 }
5249 
5250 static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
5251 					void __user *arg)
5252 {
5253 	struct btrfs_super_block *super_block = fs_info->super_copy;
5254 	struct btrfs_ioctl_feature_flags features;
5255 
5256 	features.compat_flags = btrfs_super_compat_flags(super_block);
5257 	features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5258 	features.incompat_flags = btrfs_super_incompat_flags(super_block);
5259 
5260 	if (copy_to_user(arg, &features, sizeof(features)))
5261 		return -EFAULT;
5262 
5263 	return 0;
5264 }
5265 
5266 static int check_feature_bits(struct btrfs_fs_info *fs_info,
5267 			      enum btrfs_feature_set set,
5268 			      u64 change_mask, u64 flags, u64 supported_flags,
5269 			      u64 safe_set, u64 safe_clear)
5270 {
5271 	const char *type = btrfs_feature_set_name(set);
5272 	char *names;
5273 	u64 disallowed, unsupported;
5274 	u64 set_mask = flags & change_mask;
5275 	u64 clear_mask = ~flags & change_mask;
5276 
5277 	unsupported = set_mask & ~supported_flags;
5278 	if (unsupported) {
5279 		names = btrfs_printable_features(set, unsupported);
5280 		if (names) {
5281 			btrfs_warn(fs_info,
5282 				   "this kernel does not support the %s feature bit%s",
5283 				   names, strchr(names, ',') ? "s" : "");
5284 			kfree(names);
5285 		} else
5286 			btrfs_warn(fs_info,
5287 				   "this kernel does not support %s bits 0x%llx",
5288 				   type, unsupported);
5289 		return -EOPNOTSUPP;
5290 	}
5291 
5292 	disallowed = set_mask & ~safe_set;
5293 	if (disallowed) {
5294 		names = btrfs_printable_features(set, disallowed);
5295 		if (names) {
5296 			btrfs_warn(fs_info,
5297 				   "can't set the %s feature bit%s while mounted",
5298 				   names, strchr(names, ',') ? "s" : "");
5299 			kfree(names);
5300 		} else
5301 			btrfs_warn(fs_info,
5302 				   "can't set %s bits 0x%llx while mounted",
5303 				   type, disallowed);
5304 		return -EPERM;
5305 	}
5306 
5307 	disallowed = clear_mask & ~safe_clear;
5308 	if (disallowed) {
5309 		names = btrfs_printable_features(set, disallowed);
5310 		if (names) {
5311 			btrfs_warn(fs_info,
5312 				   "can't clear the %s feature bit%s while mounted",
5313 				   names, strchr(names, ',') ? "s" : "");
5314 			kfree(names);
5315 		} else
5316 			btrfs_warn(fs_info,
5317 				   "can't clear %s bits 0x%llx while mounted",
5318 				   type, disallowed);
5319 		return -EPERM;
5320 	}
5321 
5322 	return 0;
5323 }
5324 
5325 #define check_feature(fs_info, change_mask, flags, mask_base)	\
5326 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,	\
5327 		   BTRFS_FEATURE_ ## mask_base ## _SUPP,	\
5328 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,	\
5329 		   BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5330 
5331 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5332 {
5333 	struct inode *inode = file_inode(file);
5334 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5335 	struct btrfs_root *root = BTRFS_I(inode)->root;
5336 	struct btrfs_super_block *super_block = fs_info->super_copy;
5337 	struct btrfs_ioctl_feature_flags flags[2];
5338 	struct btrfs_trans_handle *trans;
5339 	u64 newflags;
5340 	int ret;
5341 
5342 	if (!capable(CAP_SYS_ADMIN))
5343 		return -EPERM;
5344 
5345 	if (copy_from_user(flags, arg, sizeof(flags)))
5346 		return -EFAULT;
5347 
5348 	/* Nothing to do */
5349 	if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5350 	    !flags[0].incompat_flags)
5351 		return 0;
5352 
5353 	ret = check_feature(fs_info, flags[0].compat_flags,
5354 			    flags[1].compat_flags, COMPAT);
5355 	if (ret)
5356 		return ret;
5357 
5358 	ret = check_feature(fs_info, flags[0].compat_ro_flags,
5359 			    flags[1].compat_ro_flags, COMPAT_RO);
5360 	if (ret)
5361 		return ret;
5362 
5363 	ret = check_feature(fs_info, flags[0].incompat_flags,
5364 			    flags[1].incompat_flags, INCOMPAT);
5365 	if (ret)
5366 		return ret;
5367 
5368 	ret = mnt_want_write_file(file);
5369 	if (ret)
5370 		return ret;
5371 
5372 	trans = btrfs_start_transaction(root, 0);
5373 	if (IS_ERR(trans)) {
5374 		ret = PTR_ERR(trans);
5375 		goto out_drop_write;
5376 	}
5377 
5378 	spin_lock(&fs_info->super_lock);
5379 	newflags = btrfs_super_compat_flags(super_block);
5380 	newflags |= flags[0].compat_flags & flags[1].compat_flags;
5381 	newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5382 	btrfs_set_super_compat_flags(super_block, newflags);
5383 
5384 	newflags = btrfs_super_compat_ro_flags(super_block);
5385 	newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5386 	newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5387 	btrfs_set_super_compat_ro_flags(super_block, newflags);
5388 
5389 	newflags = btrfs_super_incompat_flags(super_block);
5390 	newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5391 	newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5392 	btrfs_set_super_incompat_flags(super_block, newflags);
5393 	spin_unlock(&fs_info->super_lock);
5394 
5395 	ret = btrfs_commit_transaction(trans);
5396 out_drop_write:
5397 	mnt_drop_write_file(file);
5398 
5399 	return ret;
5400 }
5401 
5402 static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
5403 {
5404 	struct btrfs_ioctl_send_args *arg;
5405 	int ret;
5406 
5407 	if (compat) {
5408 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5409 		struct btrfs_ioctl_send_args_32 args32;
5410 
5411 		ret = copy_from_user(&args32, argp, sizeof(args32));
5412 		if (ret)
5413 			return -EFAULT;
5414 		arg = kzalloc(sizeof(*arg), GFP_KERNEL);
5415 		if (!arg)
5416 			return -ENOMEM;
5417 		arg->send_fd = args32.send_fd;
5418 		arg->clone_sources_count = args32.clone_sources_count;
5419 		arg->clone_sources = compat_ptr(args32.clone_sources);
5420 		arg->parent_root = args32.parent_root;
5421 		arg->flags = args32.flags;
5422 		memcpy(arg->reserved, args32.reserved,
5423 		       sizeof(args32.reserved));
5424 #else
5425 		return -ENOTTY;
5426 #endif
5427 	} else {
5428 		arg = memdup_user(argp, sizeof(*arg));
5429 		if (IS_ERR(arg))
5430 			return PTR_ERR(arg);
5431 	}
5432 	ret = btrfs_ioctl_send(file, arg);
5433 	kfree(arg);
5434 	return ret;
5435 }
5436 
5437 long btrfs_ioctl(struct file *file, unsigned int
5438 		cmd, unsigned long arg)
5439 {
5440 	struct inode *inode = file_inode(file);
5441 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5442 	struct btrfs_root *root = BTRFS_I(inode)->root;
5443 	void __user *argp = (void __user *)arg;
5444 
5445 	switch (cmd) {
5446 	case FS_IOC_GETFLAGS:
5447 		return btrfs_ioctl_getflags(file, argp);
5448 	case FS_IOC_SETFLAGS:
5449 		return btrfs_ioctl_setflags(file, argp);
5450 	case FS_IOC_GETVERSION:
5451 		return btrfs_ioctl_getversion(file, argp);
5452 	case FS_IOC_GETFSLABEL:
5453 		return btrfs_ioctl_get_fslabel(fs_info, argp);
5454 	case FS_IOC_SETFSLABEL:
5455 		return btrfs_ioctl_set_fslabel(file, argp);
5456 	case FITRIM:
5457 		return btrfs_ioctl_fitrim(fs_info, argp);
5458 	case BTRFS_IOC_SNAP_CREATE:
5459 		return btrfs_ioctl_snap_create(file, argp, 0);
5460 	case BTRFS_IOC_SNAP_CREATE_V2:
5461 		return btrfs_ioctl_snap_create_v2(file, argp, 0);
5462 	case BTRFS_IOC_SUBVOL_CREATE:
5463 		return btrfs_ioctl_snap_create(file, argp, 1);
5464 	case BTRFS_IOC_SUBVOL_CREATE_V2:
5465 		return btrfs_ioctl_snap_create_v2(file, argp, 1);
5466 	case BTRFS_IOC_SNAP_DESTROY:
5467 		return btrfs_ioctl_snap_destroy(file, argp);
5468 	case BTRFS_IOC_SUBVOL_GETFLAGS:
5469 		return btrfs_ioctl_subvol_getflags(file, argp);
5470 	case BTRFS_IOC_SUBVOL_SETFLAGS:
5471 		return btrfs_ioctl_subvol_setflags(file, argp);
5472 	case BTRFS_IOC_DEFAULT_SUBVOL:
5473 		return btrfs_ioctl_default_subvol(file, argp);
5474 	case BTRFS_IOC_DEFRAG:
5475 		return btrfs_ioctl_defrag(file, NULL);
5476 	case BTRFS_IOC_DEFRAG_RANGE:
5477 		return btrfs_ioctl_defrag(file, argp);
5478 	case BTRFS_IOC_RESIZE:
5479 		return btrfs_ioctl_resize(file, argp);
5480 	case BTRFS_IOC_ADD_DEV:
5481 		return btrfs_ioctl_add_dev(fs_info, argp);
5482 	case BTRFS_IOC_RM_DEV:
5483 		return btrfs_ioctl_rm_dev(file, argp);
5484 	case BTRFS_IOC_RM_DEV_V2:
5485 		return btrfs_ioctl_rm_dev_v2(file, argp);
5486 	case BTRFS_IOC_FS_INFO:
5487 		return btrfs_ioctl_fs_info(fs_info, argp);
5488 	case BTRFS_IOC_DEV_INFO:
5489 		return btrfs_ioctl_dev_info(fs_info, argp);
5490 	case BTRFS_IOC_BALANCE:
5491 		return btrfs_ioctl_balance(file, NULL);
5492 	case BTRFS_IOC_TREE_SEARCH:
5493 		return btrfs_ioctl_tree_search(file, argp);
5494 	case BTRFS_IOC_TREE_SEARCH_V2:
5495 		return btrfs_ioctl_tree_search_v2(file, argp);
5496 	case BTRFS_IOC_INO_LOOKUP:
5497 		return btrfs_ioctl_ino_lookup(file, argp);
5498 	case BTRFS_IOC_INO_PATHS:
5499 		return btrfs_ioctl_ino_to_path(root, argp);
5500 	case BTRFS_IOC_LOGICAL_INO:
5501 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5502 	case BTRFS_IOC_LOGICAL_INO_V2:
5503 		return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
5504 	case BTRFS_IOC_SPACE_INFO:
5505 		return btrfs_ioctl_space_info(fs_info, argp);
5506 	case BTRFS_IOC_SYNC: {
5507 		int ret;
5508 
5509 		ret = btrfs_start_delalloc_roots(fs_info, -1);
5510 		if (ret)
5511 			return ret;
5512 		ret = btrfs_sync_fs(inode->i_sb, 1);
5513 		/*
5514 		 * The transaction thread may want to do more work,
5515 		 * namely it pokes the cleaner kthread that will start
5516 		 * processing uncleaned subvols.
5517 		 */
5518 		wake_up_process(fs_info->transaction_kthread);
5519 		return ret;
5520 	}
5521 	case BTRFS_IOC_START_SYNC:
5522 		return btrfs_ioctl_start_sync(root, argp);
5523 	case BTRFS_IOC_WAIT_SYNC:
5524 		return btrfs_ioctl_wait_sync(fs_info, argp);
5525 	case BTRFS_IOC_SCRUB:
5526 		return btrfs_ioctl_scrub(file, argp);
5527 	case BTRFS_IOC_SCRUB_CANCEL:
5528 		return btrfs_ioctl_scrub_cancel(fs_info);
5529 	case BTRFS_IOC_SCRUB_PROGRESS:
5530 		return btrfs_ioctl_scrub_progress(fs_info, argp);
5531 	case BTRFS_IOC_BALANCE_V2:
5532 		return btrfs_ioctl_balance(file, argp);
5533 	case BTRFS_IOC_BALANCE_CTL:
5534 		return btrfs_ioctl_balance_ctl(fs_info, arg);
5535 	case BTRFS_IOC_BALANCE_PROGRESS:
5536 		return btrfs_ioctl_balance_progress(fs_info, argp);
5537 	case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5538 		return btrfs_ioctl_set_received_subvol(file, argp);
5539 #ifdef CONFIG_64BIT
5540 	case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5541 		return btrfs_ioctl_set_received_subvol_32(file, argp);
5542 #endif
5543 	case BTRFS_IOC_SEND:
5544 		return _btrfs_ioctl_send(file, argp, false);
5545 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5546 	case BTRFS_IOC_SEND_32:
5547 		return _btrfs_ioctl_send(file, argp, true);
5548 #endif
5549 	case BTRFS_IOC_GET_DEV_STATS:
5550 		return btrfs_ioctl_get_dev_stats(fs_info, argp);
5551 	case BTRFS_IOC_QUOTA_CTL:
5552 		return btrfs_ioctl_quota_ctl(file, argp);
5553 	case BTRFS_IOC_QGROUP_ASSIGN:
5554 		return btrfs_ioctl_qgroup_assign(file, argp);
5555 	case BTRFS_IOC_QGROUP_CREATE:
5556 		return btrfs_ioctl_qgroup_create(file, argp);
5557 	case BTRFS_IOC_QGROUP_LIMIT:
5558 		return btrfs_ioctl_qgroup_limit(file, argp);
5559 	case BTRFS_IOC_QUOTA_RESCAN:
5560 		return btrfs_ioctl_quota_rescan(file, argp);
5561 	case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5562 		return btrfs_ioctl_quota_rescan_status(fs_info, argp);
5563 	case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5564 		return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
5565 	case BTRFS_IOC_DEV_REPLACE:
5566 		return btrfs_ioctl_dev_replace(fs_info, argp);
5567 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5568 		return btrfs_ioctl_get_supported_features(argp);
5569 	case BTRFS_IOC_GET_FEATURES:
5570 		return btrfs_ioctl_get_features(fs_info, argp);
5571 	case BTRFS_IOC_SET_FEATURES:
5572 		return btrfs_ioctl_set_features(file, argp);
5573 	case FS_IOC_FSGETXATTR:
5574 		return btrfs_ioctl_fsgetxattr(file, argp);
5575 	case FS_IOC_FSSETXATTR:
5576 		return btrfs_ioctl_fssetxattr(file, argp);
5577 	case BTRFS_IOC_GET_SUBVOL_INFO:
5578 		return btrfs_ioctl_get_subvol_info(file, argp);
5579 	case BTRFS_IOC_GET_SUBVOL_ROOTREF:
5580 		return btrfs_ioctl_get_subvol_rootref(file, argp);
5581 	case BTRFS_IOC_INO_LOOKUP_USER:
5582 		return btrfs_ioctl_ino_lookup_user(file, argp);
5583 	}
5584 
5585 	return -ENOTTY;
5586 }
5587 
5588 #ifdef CONFIG_COMPAT
5589 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5590 {
5591 	/*
5592 	 * These all access 32-bit values anyway so no further
5593 	 * handling is necessary.
5594 	 */
5595 	switch (cmd) {
5596 	case FS_IOC32_GETFLAGS:
5597 		cmd = FS_IOC_GETFLAGS;
5598 		break;
5599 	case FS_IOC32_SETFLAGS:
5600 		cmd = FS_IOC_SETFLAGS;
5601 		break;
5602 	case FS_IOC32_GETVERSION:
5603 		cmd = FS_IOC_GETVERSION;
5604 		break;
5605 	}
5606 
5607 	return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
5608 }
5609 #endif
5610