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