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