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