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