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