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