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