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