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