]> git.ipfire.org Git - people/ms/linux.git/blame - fs/btrfs/ioctl.c
btrfs: sysfs: convert scnprintf and snprintf to sysfs_emit
[people/ms/linux.git] / fs / btrfs / ioctl.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
f46b5a66
CH
2/*
3 * Copyright (C) 2007 Oracle. All rights reserved.
f46b5a66
CH
4 */
5
6#include <linux/kernel.h>
7#include <linux/bio.h>
f46b5a66
CH
8#include <linux/file.h>
9#include <linux/fs.h>
cb8e7090 10#include <linux/fsnotify.h>
f46b5a66
CH
11#include <linux/pagemap.h>
12#include <linux/highmem.h>
13#include <linux/time.h>
f46b5a66 14#include <linux/string.h>
f46b5a66 15#include <linux/backing-dev.h>
cb8e7090 16#include <linux/mount.h>
cb8e7090 17#include <linux/namei.h>
f46b5a66 18#include <linux/writeback.h>
f46b5a66 19#include <linux/compat.h>
cb8e7090 20#include <linux/security.h>
f46b5a66 21#include <linux/xattr.h>
f54de068 22#include <linux/mm.h>
5a0e3ad6 23#include <linux/slab.h>
f7039b1d 24#include <linux/blkdev.h>
8ea05e3a 25#include <linux/uuid.h>
55e301fd 26#include <linux/btrfs.h>
416161db 27#include <linux/uaccess.h>
ae5e165d 28#include <linux/iversion.h>
97fc2977 29#include <linux/fileattr.h>
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{
1a15eb72 3163 BTRFS_DEV_LOOKUP_ARGS(args);
0b246afa
JM
3164 struct inode *inode = file_inode(file);
3165 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6b526ed7 3166 struct btrfs_ioctl_vol_args_v2 *vol_args;
3fa421de
JB
3167 struct block_device *bdev = NULL;
3168 fmode_t mode;
f46b5a66 3169 int ret;
67ae34b6 3170 bool cancel = false;
f46b5a66 3171
e441d54d
CM
3172 if (!capable(CAP_SYS_ADMIN))
3173 return -EPERM;
3174
dae7b665 3175 vol_args = memdup_user(arg, sizeof(*vol_args));
c9e9f97b
ID
3176 if (IS_ERR(vol_args)) {
3177 ret = PTR_ERR(vol_args);
1a15eb72 3178 goto out;
c9e9f97b 3179 }
f46b5a66 3180
748449cd 3181 if (vol_args->flags & ~BTRFS_DEVICE_REMOVE_ARGS_MASK) {
fd4e994b
OS
3182 ret = -EOPNOTSUPP;
3183 goto out;
3184 }
1a15eb72 3185
67ae34b6 3186 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1a15eb72
JB
3187 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3188 args.devid = vol_args->devid;
3189 } else if (!strcmp("cancel", vol_args->name)) {
67ae34b6 3190 cancel = true;
1a15eb72
JB
3191 } else {
3192 ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3193 if (ret)
3194 goto out;
3195 }
3196
3197 ret = mnt_want_write_file(file);
3198 if (ret)
3199 goto out;
f46b5a66 3200
67ae34b6
DS
3201 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3202 cancel);
3203 if (ret)
1a15eb72 3204 goto err_drop;
183860f6 3205
1a15eb72
JB
3206 /* Exclusive operation is now claimed */
3207 ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
67ae34b6 3208
c3e1f96c 3209 btrfs_exclop_finish(fs_info);
183860f6 3210
6b526ed7 3211 if (!ret) {
735654ea 3212 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
0b246afa 3213 btrfs_info(fs_info, "device deleted: id %llu",
6b526ed7
AJ
3214 vol_args->devid);
3215 else
0b246afa 3216 btrfs_info(fs_info, "device deleted: %s",
6b526ed7
AJ
3217 vol_args->name);
3218 }
c47ca32d 3219err_drop:
4ac20c70 3220 mnt_drop_write_file(file);
3fa421de
JB
3221 if (bdev)
3222 blkdev_put(bdev, mode);
1a15eb72
JB
3223out:
3224 btrfs_put_dev_args_from_path(&args);
3225 kfree(vol_args);
f46b5a66
CH
3226 return ret;
3227}
3228
da24927b 3229static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
f46b5a66 3230{
1a15eb72 3231 BTRFS_DEV_LOOKUP_ARGS(args);
0b246afa
JM
3232 struct inode *inode = file_inode(file);
3233 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
f46b5a66 3234 struct btrfs_ioctl_vol_args *vol_args;
3fa421de
JB
3235 struct block_device *bdev = NULL;
3236 fmode_t mode;
f46b5a66 3237 int ret;
67ae34b6 3238 bool cancel;
f46b5a66 3239
e441d54d
CM
3240 if (!capable(CAP_SYS_ADMIN))
3241 return -EPERM;
3242
58d7bbf8 3243 vol_args = memdup_user(arg, sizeof(*vol_args));
1a15eb72
JB
3244 if (IS_ERR(vol_args))
3245 return PTR_ERR(vol_args);
3246
58d7bbf8 3247 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1a15eb72
JB
3248 if (!strcmp("cancel", vol_args->name)) {
3249 cancel = true;
3250 } else {
3251 ret = btrfs_get_dev_args_from_path(fs_info, &args, vol_args->name);
3252 if (ret)
3253 goto out;
3254 }
3255
3256 ret = mnt_want_write_file(file);
3257 if (ret)
3258 goto out;
67ae34b6
DS
3259
3260 ret = exclop_start_or_cancel_reloc(fs_info, BTRFS_EXCLOP_DEV_REMOVE,
3261 cancel);
3262 if (ret == 0) {
1a15eb72 3263 ret = btrfs_rm_device(fs_info, &args, &bdev, &mode);
67ae34b6
DS
3264 if (!ret)
3265 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3266 btrfs_exclop_finish(fs_info);
3267 }
183860f6 3268
4ac20c70 3269 mnt_drop_write_file(file);
3fa421de
JB
3270 if (bdev)
3271 blkdev_put(bdev, mode);
1a15eb72
JB
3272out:
3273 btrfs_put_dev_args_from_path(&args);
3274 kfree(vol_args);
f46b5a66
CH
3275 return ret;
3276}
3277
2ff7e61e
JM
3278static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3279 void __user *arg)
475f6387 3280{
027ed2f0 3281 struct btrfs_ioctl_fs_info_args *fi_args;
475f6387 3282 struct btrfs_device *device;
0b246afa 3283 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
137c5418 3284 u64 flags_in;
027ed2f0 3285 int ret = 0;
475f6387 3286
137c5418
JT
3287 fi_args = memdup_user(arg, sizeof(*fi_args));
3288 if (IS_ERR(fi_args))
3289 return PTR_ERR(fi_args);
3290
3291 flags_in = fi_args->flags;
3292 memset(fi_args, 0, sizeof(*fi_args));
027ed2f0 3293
d03262c7 3294 rcu_read_lock();
027ed2f0 3295 fi_args->num_devices = fs_devices->num_devices;
475f6387 3296
d03262c7 3297 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
027ed2f0
LZ
3298 if (device->devid > fi_args->max_id)
3299 fi_args->max_id = device->devid;
475f6387 3300 }
d03262c7 3301 rcu_read_unlock();
475f6387 3302
de37aa51 3303 memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
bea7eafd
OS
3304 fi_args->nodesize = fs_info->nodesize;
3305 fi_args->sectorsize = fs_info->sectorsize;
3306 fi_args->clone_alignment = fs_info->sectorsize;
80a773fb 3307
137c5418
JT
3308 if (flags_in & BTRFS_FS_INFO_FLAG_CSUM_INFO) {
3309 fi_args->csum_type = btrfs_super_csum_type(fs_info->super_copy);
3310 fi_args->csum_size = btrfs_super_csum_size(fs_info->super_copy);
3311 fi_args->flags |= BTRFS_FS_INFO_FLAG_CSUM_INFO;
3312 }
3313
0fb408a5
JT
3314 if (flags_in & BTRFS_FS_INFO_FLAG_GENERATION) {
3315 fi_args->generation = fs_info->generation;
3316 fi_args->flags |= BTRFS_FS_INFO_FLAG_GENERATION;
3317 }
3318
49bac897
JT
3319 if (flags_in & BTRFS_FS_INFO_FLAG_METADATA_UUID) {
3320 memcpy(&fi_args->metadata_uuid, fs_devices->metadata_uuid,
3321 sizeof(fi_args->metadata_uuid));
3322 fi_args->flags |= BTRFS_FS_INFO_FLAG_METADATA_UUID;
3323 }
3324
027ed2f0
LZ
3325 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3326 ret = -EFAULT;
475f6387 3327
027ed2f0
LZ
3328 kfree(fi_args);
3329 return ret;
475f6387
JS
3330}
3331
2ff7e61e
JM
3332static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3333 void __user *arg)
475f6387 3334{
562d7b15 3335 BTRFS_DEV_LOOKUP_ARGS(args);
475f6387
JS
3336 struct btrfs_ioctl_dev_info_args *di_args;
3337 struct btrfs_device *dev;
475f6387 3338 int ret = 0;
475f6387 3339
475f6387
JS
3340 di_args = memdup_user(arg, sizeof(*di_args));
3341 if (IS_ERR(di_args))
3342 return PTR_ERR(di_args);
3343
562d7b15 3344 args.devid = di_args->devid;
dd5f9615 3345 if (!btrfs_is_empty_uuid(di_args->uuid))
562d7b15 3346 args.uuid = di_args->uuid;
475f6387 3347
c5593ca3 3348 rcu_read_lock();
562d7b15 3349 dev = btrfs_find_device(fs_info->fs_devices, &args);
475f6387
JS
3350 if (!dev) {
3351 ret = -ENODEV;
3352 goto out;
3353 }
3354
3355 di_args->devid = dev->devid;
7cc8e58d
MX
3356 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3357 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
475f6387 3358 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
a27202fb 3359 if (dev->name) {
672d5990
MT
3360 strncpy(di_args->path, rcu_str_deref(dev->name),
3361 sizeof(di_args->path) - 1);
a27202fb
JM
3362 di_args->path[sizeof(di_args->path) - 1] = 0;
3363 } else {
99ba55ad 3364 di_args->path[0] = '\0';
a27202fb 3365 }
475f6387
JS
3366
3367out:
c5593ca3 3368 rcu_read_unlock();
475f6387
JS
3369 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3370 ret = -EFAULT;
3371
3372 kfree(di_args);
3373 return ret;
3374}
3375
6ef5ed0d
JB
3376static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3377{
496ad9aa 3378 struct inode *inode = file_inode(file);
0b246afa 3379 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6ef5ed0d
JB
3380 struct btrfs_root *root = BTRFS_I(inode)->root;
3381 struct btrfs_root *new_root;
3382 struct btrfs_dir_item *di;
3383 struct btrfs_trans_handle *trans;
2a2b5d62 3384 struct btrfs_path *path = NULL;
6ef5ed0d 3385 struct btrfs_disk_key disk_key;
6ef5ed0d
JB
3386 u64 objectid = 0;
3387 u64 dir_id;
3c04ce01 3388 int ret;
6ef5ed0d
JB
3389
3390 if (!capable(CAP_SYS_ADMIN))
3391 return -EPERM;
3392
3c04ce01
MX
3393 ret = mnt_want_write_file(file);
3394 if (ret)
3395 return ret;
3396
3397 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3398 ret = -EFAULT;
3399 goto out;
3400 }
6ef5ed0d
JB
3401
3402 if (!objectid)
1cecf579 3403 objectid = BTRFS_FS_TREE_OBJECTID;
6ef5ed0d 3404
56e9357a 3405 new_root = btrfs_get_fs_root(fs_info, objectid, true);
3c04ce01
MX
3406 if (IS_ERR(new_root)) {
3407 ret = PTR_ERR(new_root);
3408 goto out;
3409 }
2a2b5d62
JB
3410 if (!is_fstree(new_root->root_key.objectid)) {
3411 ret = -ENOENT;
3412 goto out_free;
3413 }
6ef5ed0d 3414
6ef5ed0d 3415 path = btrfs_alloc_path();
3c04ce01
MX
3416 if (!path) {
3417 ret = -ENOMEM;
2a2b5d62 3418 goto out_free;
3c04ce01 3419 }
6ef5ed0d
JB
3420
3421 trans = btrfs_start_transaction(root, 1);
98d5dc13 3422 if (IS_ERR(trans)) {
3c04ce01 3423 ret = PTR_ERR(trans);
2a2b5d62 3424 goto out_free;
6ef5ed0d
JB
3425 }
3426
0b246afa
JM
3427 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3428 di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
6ef5ed0d 3429 dir_id, "default", 7, 1);
cf1e99a4 3430 if (IS_ERR_OR_NULL(di)) {
2a2b5d62 3431 btrfs_release_path(path);
3a45bb20 3432 btrfs_end_transaction(trans);
0b246afa 3433 btrfs_err(fs_info,
5d163e0e 3434 "Umm, you don't have the default diritem, this isn't going to work");
3c04ce01 3435 ret = -ENOENT;
2a2b5d62 3436 goto out_free;
6ef5ed0d
JB
3437 }
3438
3439 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3440 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3441 btrfs_mark_buffer_dirty(path->nodes[0]);
2a2b5d62 3442 btrfs_release_path(path);
6ef5ed0d 3443
0b246afa 3444 btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
3a45bb20 3445 btrfs_end_transaction(trans);
2a2b5d62 3446out_free:
00246528 3447 btrfs_put_root(new_root);
2a2b5d62 3448 btrfs_free_path(path);
3c04ce01
MX
3449out:
3450 mnt_drop_write_file(file);
3451 return ret;
6ef5ed0d
JB
3452}
3453
c065f5b1
SY
3454static void get_block_group_info(struct list_head *groups_list,
3455 struct btrfs_ioctl_space_info *space)
bf5fc093 3456{
32da5386 3457 struct btrfs_block_group *block_group;
bf5fc093
JB
3458
3459 space->total_bytes = 0;
3460 space->used_bytes = 0;
3461 space->flags = 0;
3462 list_for_each_entry(block_group, groups_list, list) {
3463 space->flags = block_group->flags;
b3470b5d 3464 space->total_bytes += block_group->length;
bf38be65 3465 space->used_bytes += block_group->used;
bf5fc093
JB
3466 }
3467}
3468
2ff7e61e
JM
3469static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
3470 void __user *arg)
1406e432
JB
3471{
3472 struct btrfs_ioctl_space_args space_args;
3473 struct btrfs_ioctl_space_info space;
3474 struct btrfs_ioctl_space_info *dest;
7fde62bf 3475 struct btrfs_ioctl_space_info *dest_orig;
13f2696f 3476 struct btrfs_ioctl_space_info __user *user_dest;
1406e432 3477 struct btrfs_space_info *info;
315d8e98
CIK
3478 static const u64 types[] = {
3479 BTRFS_BLOCK_GROUP_DATA,
3480 BTRFS_BLOCK_GROUP_SYSTEM,
3481 BTRFS_BLOCK_GROUP_METADATA,
3482 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
3483 };
bf5fc093 3484 int num_types = 4;
7fde62bf 3485 int alloc_size;
1406e432 3486 int ret = 0;
51788b1b 3487 u64 slot_count = 0;
bf5fc093 3488 int i, c;
1406e432
JB
3489
3490 if (copy_from_user(&space_args,
3491 (struct btrfs_ioctl_space_args __user *)arg,
3492 sizeof(space_args)))
3493 return -EFAULT;
3494
bf5fc093
JB
3495 for (i = 0; i < num_types; i++) {
3496 struct btrfs_space_info *tmp;
3497
3498 info = NULL;
72804905 3499 list_for_each_entry(tmp, &fs_info->space_info, list) {
bf5fc093
JB
3500 if (tmp->flags == types[i]) {
3501 info = tmp;
3502 break;
3503 }
3504 }
bf5fc093
JB
3505
3506 if (!info)
3507 continue;
3508
3509 down_read(&info->groups_sem);
3510 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3511 if (!list_empty(&info->block_groups[c]))
3512 slot_count++;
3513 }
3514 up_read(&info->groups_sem);
3515 }
7fde62bf 3516
36523e95
DS
3517 /*
3518 * Global block reserve, exported as a space_info
3519 */
3520 slot_count++;
3521
7fde62bf
CM
3522 /* space_slots == 0 means they are asking for a count */
3523 if (space_args.space_slots == 0) {
3524 space_args.total_spaces = slot_count;
3525 goto out;
3526 }
bf5fc093 3527
51788b1b 3528 slot_count = min_t(u64, space_args.space_slots, slot_count);
bf5fc093 3529
7fde62bf 3530 alloc_size = sizeof(*dest) * slot_count;
bf5fc093 3531
7fde62bf
CM
3532 /* we generally have at most 6 or so space infos, one for each raid
3533 * level. So, a whole page should be more than enough for everyone
3534 */
09cbfeaf 3535 if (alloc_size > PAGE_SIZE)
7fde62bf
CM
3536 return -ENOMEM;
3537
1406e432 3538 space_args.total_spaces = 0;
8d2db785 3539 dest = kmalloc(alloc_size, GFP_KERNEL);
7fde62bf
CM
3540 if (!dest)
3541 return -ENOMEM;
3542 dest_orig = dest;
1406e432 3543
7fde62bf 3544 /* now we have a buffer to copy into */
bf5fc093
JB
3545 for (i = 0; i < num_types; i++) {
3546 struct btrfs_space_info *tmp;
3547
51788b1b
DR
3548 if (!slot_count)
3549 break;
3550
bf5fc093 3551 info = NULL;
72804905 3552 list_for_each_entry(tmp, &fs_info->space_info, list) {
bf5fc093
JB
3553 if (tmp->flags == types[i]) {
3554 info = tmp;
3555 break;
3556 }
3557 }
7fde62bf 3558
bf5fc093
JB
3559 if (!info)
3560 continue;
3561 down_read(&info->groups_sem);
3562 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3563 if (!list_empty(&info->block_groups[c])) {
c065f5b1
SY
3564 get_block_group_info(&info->block_groups[c],
3565 &space);
bf5fc093
JB
3566 memcpy(dest, &space, sizeof(space));
3567 dest++;
3568 space_args.total_spaces++;
51788b1b 3569 slot_count--;
bf5fc093 3570 }
51788b1b
DR
3571 if (!slot_count)
3572 break;
bf5fc093
JB
3573 }
3574 up_read(&info->groups_sem);
1406e432 3575 }
1406e432 3576
36523e95
DS
3577 /*
3578 * Add global block reserve
3579 */
3580 if (slot_count) {
0b246afa 3581 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
36523e95
DS
3582
3583 spin_lock(&block_rsv->lock);
3584 space.total_bytes = block_rsv->size;
3585 space.used_bytes = block_rsv->size - block_rsv->reserved;
3586 spin_unlock(&block_rsv->lock);
3587 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
3588 memcpy(dest, &space, sizeof(space));
3589 space_args.total_spaces++;
3590 }
3591
2eec6c81 3592 user_dest = (struct btrfs_ioctl_space_info __user *)
7fde62bf
CM
3593 (arg + sizeof(struct btrfs_ioctl_space_args));
3594
3595 if (copy_to_user(user_dest, dest_orig, alloc_size))
3596 ret = -EFAULT;
3597
3598 kfree(dest_orig);
3599out:
3600 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
1406e432
JB
3601 ret = -EFAULT;
3602
3603 return ret;
3604}
3605
9a8c28be
MX
3606static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3607 void __user *argp)
46204592 3608{
46204592
SW
3609 struct btrfs_trans_handle *trans;
3610 u64 transid;
db5b493a 3611 int ret;
46204592 3612
d4edf39b 3613 trans = btrfs_attach_transaction_barrier(root);
ff7c1d33
MX
3614 if (IS_ERR(trans)) {
3615 if (PTR_ERR(trans) != -ENOENT)
3616 return PTR_ERR(trans);
3617
3618 /* No running transaction, don't bother */
3619 transid = root->fs_info->last_trans_committed;
3620 goto out;
3621 }
46204592 3622 transid = trans->transid;
32cc4f87 3623 ret = btrfs_commit_transaction_async(trans);
8b2b2d3c 3624 if (ret) {
3a45bb20 3625 btrfs_end_transaction(trans);
db5b493a 3626 return ret;
8b2b2d3c 3627 }
ff7c1d33 3628out:
46204592
SW
3629 if (argp)
3630 if (copy_to_user(argp, &transid, sizeof(transid)))
3631 return -EFAULT;
3632 return 0;
3633}
3634
2ff7e61e 3635static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
9a8c28be 3636 void __user *argp)
46204592 3637{
46204592
SW
3638 u64 transid;
3639
3640 if (argp) {
3641 if (copy_from_user(&transid, argp, sizeof(transid)))
3642 return -EFAULT;
3643 } else {
3644 transid = 0; /* current trans */
3645 }
2ff7e61e 3646 return btrfs_wait_for_commit(fs_info, transid);
46204592
SW
3647}
3648
b8e95489 3649static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
475f6387 3650{
0b246afa 3651 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
475f6387 3652 struct btrfs_ioctl_scrub_args *sa;
b8e95489 3653 int ret;
475f6387
JS
3654
3655 if (!capable(CAP_SYS_ADMIN))
3656 return -EPERM;
3657
3658 sa = memdup_user(arg, sizeof(*sa));
3659 if (IS_ERR(sa))
3660 return PTR_ERR(sa);
3661
b8e95489
MX
3662 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3663 ret = mnt_want_write_file(file);
3664 if (ret)
3665 goto out;
3666 }
3667
0b246afa 3668 ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
63a212ab
SB
3669 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3670 0);
475f6387 3671
5afe6ce7
FM
3672 /*
3673 * Copy scrub args to user space even if btrfs_scrub_dev() returned an
3674 * error. This is important as it allows user space to know how much
3675 * progress scrub has done. For example, if scrub is canceled we get
3676 * -ECANCELED from btrfs_scrub_dev() and return that error back to user
3677 * space. Later user space can inspect the progress from the structure
3678 * btrfs_ioctl_scrub_args and resume scrub from where it left off
3679 * previously (btrfs-progs does this).
3680 * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
3681 * then return -EFAULT to signal the structure was not copied or it may
3682 * be corrupt and unreliable due to a partial copy.
3683 */
3684 if (copy_to_user(arg, sa, sizeof(*sa)))
475f6387
JS
3685 ret = -EFAULT;
3686
b8e95489
MX
3687 if (!(sa->flags & BTRFS_SCRUB_READONLY))
3688 mnt_drop_write_file(file);
3689out:
475f6387
JS
3690 kfree(sa);
3691 return ret;
3692}
3693
2ff7e61e 3694static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
475f6387
JS
3695{
3696 if (!capable(CAP_SYS_ADMIN))
3697 return -EPERM;
3698
2ff7e61e 3699 return btrfs_scrub_cancel(fs_info);
475f6387
JS
3700}
3701
2ff7e61e 3702static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
475f6387
JS
3703 void __user *arg)
3704{
3705 struct btrfs_ioctl_scrub_args *sa;
3706 int ret;
3707
3708 if (!capable(CAP_SYS_ADMIN))
3709 return -EPERM;
3710
3711 sa = memdup_user(arg, sizeof(*sa));
3712 if (IS_ERR(sa))
3713 return PTR_ERR(sa);
3714
2ff7e61e 3715 ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
475f6387 3716
4fa99b00 3717 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
475f6387
JS
3718 ret = -EFAULT;
3719
3720 kfree(sa);
3721 return ret;
3722}
3723
2ff7e61e 3724static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
b27f7c0c 3725 void __user *arg)
c11d2c23
SB
3726{
3727 struct btrfs_ioctl_get_dev_stats *sa;
3728 int ret;
3729
c11d2c23
SB
3730 sa = memdup_user(arg, sizeof(*sa));
3731 if (IS_ERR(sa))
3732 return PTR_ERR(sa);
3733
b27f7c0c
DS
3734 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3735 kfree(sa);
3736 return -EPERM;
3737 }
3738
2ff7e61e 3739 ret = btrfs_get_dev_stats(fs_info, sa);
c11d2c23 3740
eee99577 3741 if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
c11d2c23
SB
3742 ret = -EFAULT;
3743
3744 kfree(sa);
3745 return ret;
3746}
3747
2ff7e61e
JM
3748static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
3749 void __user *arg)
3f6bcfbd
SB
3750{
3751 struct btrfs_ioctl_dev_replace_args *p;
3752 int ret;
3753
3754 if (!capable(CAP_SYS_ADMIN))
3755 return -EPERM;
3756
3757 p = memdup_user(arg, sizeof(*p));
3758 if (IS_ERR(p))
3759 return PTR_ERR(p);
3760
3761 switch (p->cmd) {
3762 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
bc98a42c 3763 if (sb_rdonly(fs_info->sb)) {
adfa97cb
ID
3764 ret = -EROFS;
3765 goto out;
3766 }
c3e1f96c 3767 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
e57138b3 3768 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3f6bcfbd 3769 } else {
2ff7e61e 3770 ret = btrfs_dev_replace_by_ioctl(fs_info, p);
c3e1f96c 3771 btrfs_exclop_finish(fs_info);
3f6bcfbd
SB
3772 }
3773 break;
3774 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
0b246afa 3775 btrfs_dev_replace_status(fs_info, p);
3f6bcfbd
SB
3776 ret = 0;
3777 break;
3778 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
17d202b9 3779 p->result = btrfs_dev_replace_cancel(fs_info);
97282031 3780 ret = 0;
3f6bcfbd
SB
3781 break;
3782 default:
3783 ret = -EINVAL;
3784 break;
3785 }
3786
d3a53286 3787 if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
3f6bcfbd 3788 ret = -EFAULT;
adfa97cb 3789out:
3f6bcfbd
SB
3790 kfree(p);
3791 return ret;
3792}
3793
d7728c96
JS
3794static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3795{
3796 int ret = 0;
3797 int i;
740c3d22 3798 u64 rel_ptr;
d7728c96 3799 int size;
806468f8 3800 struct btrfs_ioctl_ino_path_args *ipa = NULL;
d7728c96
JS
3801 struct inode_fs_paths *ipath = NULL;
3802 struct btrfs_path *path;
3803
82b22ac8 3804 if (!capable(CAP_DAC_READ_SEARCH))
d7728c96
JS
3805 return -EPERM;
3806
3807 path = btrfs_alloc_path();
3808 if (!path) {
3809 ret = -ENOMEM;
3810 goto out;
3811 }
3812
3813 ipa = memdup_user(arg, sizeof(*ipa));
3814 if (IS_ERR(ipa)) {
3815 ret = PTR_ERR(ipa);
3816 ipa = NULL;
3817 goto out;
3818 }
3819
3820 size = min_t(u32, ipa->size, 4096);
3821 ipath = init_ipath(size, root, path);
3822 if (IS_ERR(ipath)) {
3823 ret = PTR_ERR(ipath);
3824 ipath = NULL;
3825 goto out;
3826 }
3827
3828 ret = paths_from_inode(ipa->inum, ipath);
3829 if (ret < 0)
3830 goto out;
3831
3832 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
745c4d8e
JM
3833 rel_ptr = ipath->fspath->val[i] -
3834 (u64)(unsigned long)ipath->fspath->val;
740c3d22 3835 ipath->fspath->val[i] = rel_ptr;
d7728c96
JS
3836 }
3837
718dc5fa
OS
3838 ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
3839 ipath->fspath, size);
d7728c96
JS
3840 if (ret) {
3841 ret = -EFAULT;
3842 goto out;
3843 }
3844
3845out:
3846 btrfs_free_path(path);
3847 free_ipath(ipath);
3848 kfree(ipa);
3849
3850 return ret;
3851}
3852
3853static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3854{
3855 struct btrfs_data_container *inodes = ctx;
3856 const size_t c = 3 * sizeof(u64);
3857
3858 if (inodes->bytes_left >= c) {
3859 inodes->bytes_left -= c;
3860 inodes->val[inodes->elem_cnt] = inum;
3861 inodes->val[inodes->elem_cnt + 1] = offset;
3862 inodes->val[inodes->elem_cnt + 2] = root;
3863 inodes->elem_cnt += 3;
3864 } else {
3865 inodes->bytes_missing += c - inodes->bytes_left;
3866 inodes->bytes_left = 0;
3867 inodes->elem_missed += 3;
3868 }
3869
3870 return 0;
3871}
3872
2ff7e61e 3873static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
d24a67b2 3874 void __user *arg, int version)
d7728c96
JS
3875{
3876 int ret = 0;
3877 int size;
d7728c96
JS
3878 struct btrfs_ioctl_logical_ino_args *loi;
3879 struct btrfs_data_container *inodes = NULL;
3880 struct btrfs_path *path = NULL;
d24a67b2 3881 bool ignore_offset;
d7728c96
JS
3882
3883 if (!capable(CAP_SYS_ADMIN))
3884 return -EPERM;
3885
3886 loi = memdup_user(arg, sizeof(*loi));
7b9ea627
SV
3887 if (IS_ERR(loi))
3888 return PTR_ERR(loi);
d7728c96 3889
d24a67b2
ZB
3890 if (version == 1) {
3891 ignore_offset = false;
b115e3bc 3892 size = min_t(u32, loi->size, SZ_64K);
d24a67b2
ZB
3893 } else {
3894 /* All reserved bits must be 0 for now */
3895 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
3896 ret = -EINVAL;
3897 goto out_loi;
3898 }
3899 /* Only accept flags we have defined so far */
3900 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
3901 ret = -EINVAL;
3902 goto out_loi;
3903 }
3904 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
b115e3bc 3905 size = min_t(u32, loi->size, SZ_16M);
d24a67b2
ZB
3906 }
3907
d7728c96
JS
3908 path = btrfs_alloc_path();
3909 if (!path) {
3910 ret = -ENOMEM;
3911 goto out;
3912 }
3913
d7728c96
JS
3914 inodes = init_data_container(size);
3915 if (IS_ERR(inodes)) {
3916 ret = PTR_ERR(inodes);
3917 inodes = NULL;
3918 goto out;
3919 }
3920
2ff7e61e 3921 ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
d24a67b2 3922 build_ino_list, inodes, ignore_offset);
df031f07 3923 if (ret == -EINVAL)
d7728c96
JS
3924 ret = -ENOENT;
3925 if (ret < 0)
3926 goto out;
3927
718dc5fa
OS
3928 ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
3929 size);
d7728c96
JS
3930 if (ret)
3931 ret = -EFAULT;
3932
3933out:
3934 btrfs_free_path(path);
f54de068 3935 kvfree(inodes);
d24a67b2 3936out_loi:
d7728c96
JS
3937 kfree(loi);
3938
3939 return ret;
3940}
3941
008ef096 3942void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
c9e9f97b
ID
3943 struct btrfs_ioctl_balance_args *bargs)
3944{
3945 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3946
3947 bargs->flags = bctl->flags;
3948
3009a62f 3949 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
837d5b6e
ID
3950 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3951 if (atomic_read(&fs_info->balance_pause_req))
3952 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
a7e99c69
ID
3953 if (atomic_read(&fs_info->balance_cancel_req))
3954 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
837d5b6e 3955
c9e9f97b
ID
3956 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3957 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3958 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
19a39dce 3959
008ef096
DS
3960 spin_lock(&fs_info->balance_lock);
3961 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3962 spin_unlock(&fs_info->balance_lock);
c9e9f97b
ID
3963}
3964
9ba1f6e4 3965static long btrfs_ioctl_balance(struct file *file, void __user *arg)
c9e9f97b 3966{
496ad9aa 3967 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
c9e9f97b
ID
3968 struct btrfs_fs_info *fs_info = root->fs_info;
3969 struct btrfs_ioctl_balance_args *bargs;
3970 struct btrfs_balance_control *bctl;
ed0fb78f 3971 bool need_unlock; /* for mut. excl. ops lock */
c9e9f97b
ID
3972 int ret;
3973
3974 if (!capable(CAP_SYS_ADMIN))
3975 return -EPERM;
3976
e54bfa31 3977 ret = mnt_want_write_file(file);
9ba1f6e4
LB
3978 if (ret)
3979 return ret;
3980
ed0fb78f 3981again:
c3e1f96c 3982 if (btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
ed0fb78f
ID
3983 mutex_lock(&fs_info->balance_mutex);
3984 need_unlock = true;
3985 goto locked;
3986 }
3987
3988 /*
01327610 3989 * mut. excl. ops lock is locked. Three possibilities:
ed0fb78f
ID
3990 * (1) some other op is running
3991 * (2) balance is running
3992 * (3) balance is paused -- special case (think resume)
3993 */
c9e9f97b 3994 mutex_lock(&fs_info->balance_mutex);
ed0fb78f
ID
3995 if (fs_info->balance_ctl) {
3996 /* this is either (2) or (3) */
3009a62f 3997 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
ed0fb78f 3998 mutex_unlock(&fs_info->balance_mutex);
dccdb07b
DS
3999 /*
4000 * Lock released to allow other waiters to continue,
4001 * we'll reexamine the status again.
4002 */
ed0fb78f
ID
4003 mutex_lock(&fs_info->balance_mutex);
4004
4005 if (fs_info->balance_ctl &&
3009a62f 4006 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
ed0fb78f
ID
4007 /* this is (3) */
4008 need_unlock = false;
4009 goto locked;
4010 }
4011
4012 mutex_unlock(&fs_info->balance_mutex);
ed0fb78f
ID
4013 goto again;
4014 } else {
4015 /* this is (2) */
4016 mutex_unlock(&fs_info->balance_mutex);
4017 ret = -EINPROGRESS;
4018 goto out;
4019 }
4020 } else {
4021 /* this is (1) */
4022 mutex_unlock(&fs_info->balance_mutex);
e57138b3 4023 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
ed0fb78f
ID
4024 goto out;
4025 }
4026
4027locked:
c9e9f97b
ID
4028
4029 if (arg) {
4030 bargs = memdup_user(arg, sizeof(*bargs));
4031 if (IS_ERR(bargs)) {
4032 ret = PTR_ERR(bargs);
ed0fb78f 4033 goto out_unlock;
c9e9f97b 4034 }
de322263
ID
4035
4036 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4037 if (!fs_info->balance_ctl) {
4038 ret = -ENOTCONN;
4039 goto out_bargs;
4040 }
4041
4042 bctl = fs_info->balance_ctl;
4043 spin_lock(&fs_info->balance_lock);
4044 bctl->flags |= BTRFS_BALANCE_RESUME;
4045 spin_unlock(&fs_info->balance_lock);
4046
4047 goto do_balance;
4048 }
c9e9f97b
ID
4049 } else {
4050 bargs = NULL;
4051 }
4052
ed0fb78f 4053 if (fs_info->balance_ctl) {
837d5b6e
ID
4054 ret = -EINPROGRESS;
4055 goto out_bargs;
4056 }
4057
8d2db785 4058 bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
c9e9f97b
ID
4059 if (!bctl) {
4060 ret = -ENOMEM;
4061 goto out_bargs;
4062 }
4063
c9e9f97b
ID
4064 if (arg) {
4065 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4066 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4067 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4068
4069 bctl->flags = bargs->flags;
f43ffb60
ID
4070 } else {
4071 /* balance everything - no filters */
4072 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
c9e9f97b
ID
4073 }
4074
8eb93459
DS
4075 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4076 ret = -EINVAL;
0f89abf5 4077 goto out_bctl;
8eb93459
DS
4078 }
4079
de322263 4080do_balance:
c9e9f97b 4081 /*
c3e1f96c
GR
4082 * Ownership of bctl and exclusive operation goes to btrfs_balance.
4083 * bctl is freed in reset_balance_state, or, if restriper was paused
4084 * all the way until unmount, in free_fs_info. The flag should be
4085 * cleared after reset_balance_state.
c9e9f97b 4086 */
ed0fb78f
ID
4087 need_unlock = false;
4088
6fcf6e2b 4089 ret = btrfs_balance(fs_info, bctl, bargs);
0f89abf5 4090 bctl = NULL;
ed0fb78f 4091
d00c2d9c 4092 if ((ret == 0 || ret == -ECANCELED) && arg) {
c9e9f97b
ID
4093 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4094 ret = -EFAULT;
4095 }
4096
0f89abf5
CE
4097out_bctl:
4098 kfree(bctl);
c9e9f97b
ID
4099out_bargs:
4100 kfree(bargs);
ed0fb78f 4101out_unlock:
c9e9f97b 4102 mutex_unlock(&fs_info->balance_mutex);
ed0fb78f 4103 if (need_unlock)
c3e1f96c 4104 btrfs_exclop_finish(fs_info);
ed0fb78f 4105out:
e54bfa31 4106 mnt_drop_write_file(file);
c9e9f97b
ID
4107 return ret;
4108}
4109
2ff7e61e 4110static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
837d5b6e
ID
4111{
4112 if (!capable(CAP_SYS_ADMIN))
4113 return -EPERM;
4114
4115 switch (cmd) {
4116 case BTRFS_BALANCE_CTL_PAUSE:
0b246afa 4117 return btrfs_pause_balance(fs_info);
a7e99c69 4118 case BTRFS_BALANCE_CTL_CANCEL:
0b246afa 4119 return btrfs_cancel_balance(fs_info);
837d5b6e
ID
4120 }
4121
4122 return -EINVAL;
4123}
4124
2ff7e61e 4125static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
19a39dce
ID
4126 void __user *arg)
4127{
19a39dce
ID
4128 struct btrfs_ioctl_balance_args *bargs;
4129 int ret = 0;
4130
4131 if (!capable(CAP_SYS_ADMIN))
4132 return -EPERM;
4133
4134 mutex_lock(&fs_info->balance_mutex);
4135 if (!fs_info->balance_ctl) {
4136 ret = -ENOTCONN;
4137 goto out;
4138 }
4139
8d2db785 4140 bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
19a39dce
ID
4141 if (!bargs) {
4142 ret = -ENOMEM;
4143 goto out;
4144 }
4145
008ef096 4146 btrfs_update_ioctl_balance_args(fs_info, bargs);
19a39dce
ID
4147
4148 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4149 ret = -EFAULT;
4150
4151 kfree(bargs);
4152out:
4153 mutex_unlock(&fs_info->balance_mutex);
4154 return ret;
4155}
4156
905b0dda 4157static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
5d13a37b 4158{
0b246afa
JM
4159 struct inode *inode = file_inode(file);
4160 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5d13a37b 4161 struct btrfs_ioctl_quota_ctl_args *sa;
5d13a37b 4162 int ret;
5d13a37b
AJ
4163
4164 if (!capable(CAP_SYS_ADMIN))
4165 return -EPERM;
4166
905b0dda
MX
4167 ret = mnt_want_write_file(file);
4168 if (ret)
4169 return ret;
5d13a37b
AJ
4170
4171 sa = memdup_user(arg, sizeof(*sa));
905b0dda
MX
4172 if (IS_ERR(sa)) {
4173 ret = PTR_ERR(sa);
4174 goto drop_write;
4175 }
5d13a37b 4176
0b246afa 4177 down_write(&fs_info->subvol_sem);
5d13a37b
AJ
4178
4179 switch (sa->cmd) {
4180 case BTRFS_QUOTA_CTL_ENABLE:
340f1aa2 4181 ret = btrfs_quota_enable(fs_info);
5d13a37b
AJ
4182 break;
4183 case BTRFS_QUOTA_CTL_DISABLE:
340f1aa2 4184 ret = btrfs_quota_disable(fs_info);
5d13a37b 4185 break;
5d13a37b
AJ
4186 default:
4187 ret = -EINVAL;
4188 break;
4189 }
4190
5d13a37b 4191 kfree(sa);
0b246afa 4192 up_write(&fs_info->subvol_sem);
905b0dda
MX
4193drop_write:
4194 mnt_drop_write_file(file);
5d13a37b
AJ
4195 return ret;
4196}
4197
905b0dda 4198static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
5d13a37b 4199{
0b246afa
JM
4200 struct inode *inode = file_inode(file);
4201 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4202 struct btrfs_root *root = BTRFS_I(inode)->root;
5d13a37b
AJ
4203 struct btrfs_ioctl_qgroup_assign_args *sa;
4204 struct btrfs_trans_handle *trans;
4205 int ret;
4206 int err;
4207
4208 if (!capable(CAP_SYS_ADMIN))
4209 return -EPERM;
4210
905b0dda
MX
4211 ret = mnt_want_write_file(file);
4212 if (ret)
4213 return ret;
5d13a37b
AJ
4214
4215 sa = memdup_user(arg, sizeof(*sa));
905b0dda
MX
4216 if (IS_ERR(sa)) {
4217 ret = PTR_ERR(sa);
4218 goto drop_write;
4219 }
5d13a37b
AJ
4220
4221 trans = btrfs_join_transaction(root);
4222 if (IS_ERR(trans)) {
4223 ret = PTR_ERR(trans);
4224 goto out;
4225 }
4226
5d13a37b 4227 if (sa->assign) {
9f8a6ce6 4228 ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
5d13a37b 4229 } else {
39616c27 4230 ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
5d13a37b
AJ
4231 }
4232
e082f563 4233 /* update qgroup status and info */
280f8bd2 4234 err = btrfs_run_qgroups(trans);
e082f563 4235 if (err < 0)
0b246afa
JM
4236 btrfs_handle_fs_error(fs_info, err,
4237 "failed to update qgroup status and info");
3a45bb20 4238 err = btrfs_end_transaction(trans);
5d13a37b
AJ
4239 if (err && !ret)
4240 ret = err;
4241
4242out:
4243 kfree(sa);
905b0dda
MX
4244drop_write:
4245 mnt_drop_write_file(file);
5d13a37b
AJ
4246 return ret;
4247}
4248
905b0dda 4249static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
5d13a37b 4250{
0b246afa 4251 struct inode *inode = file_inode(file);
0b246afa 4252 struct btrfs_root *root = BTRFS_I(inode)->root;
5d13a37b
AJ
4253 struct btrfs_ioctl_qgroup_create_args *sa;
4254 struct btrfs_trans_handle *trans;
4255 int ret;
4256 int err;
4257
4258 if (!capable(CAP_SYS_ADMIN))
4259 return -EPERM;
4260
905b0dda
MX
4261 ret = mnt_want_write_file(file);
4262 if (ret)
4263 return ret;
5d13a37b
AJ
4264
4265 sa = memdup_user(arg, sizeof(*sa));
905b0dda
MX
4266 if (IS_ERR(sa)) {
4267 ret = PTR_ERR(sa);
4268 goto drop_write;
4269 }
5d13a37b 4270
d86e56cf
MX
4271 if (!sa->qgroupid) {
4272 ret = -EINVAL;
4273 goto out;
4274 }
4275
5d13a37b
AJ
4276 trans = btrfs_join_transaction(root);
4277 if (IS_ERR(trans)) {
4278 ret = PTR_ERR(trans);
4279 goto out;
4280 }
4281
5d13a37b 4282 if (sa->create) {
49a05ecd 4283 ret = btrfs_create_qgroup(trans, sa->qgroupid);
5d13a37b 4284 } else {
3efbee1d 4285 ret = btrfs_remove_qgroup(trans, sa->qgroupid);
5d13a37b
AJ
4286 }
4287
3a45bb20 4288 err = btrfs_end_transaction(trans);
5d13a37b
AJ
4289 if (err && !ret)
4290 ret = err;
4291
4292out:
4293 kfree(sa);
905b0dda
MX
4294drop_write:
4295 mnt_drop_write_file(file);
5d13a37b
AJ
4296 return ret;
4297}
4298
905b0dda 4299static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
5d13a37b 4300{
0b246afa 4301 struct inode *inode = file_inode(file);
0b246afa 4302 struct btrfs_root *root = BTRFS_I(inode)->root;
5d13a37b
AJ
4303 struct btrfs_ioctl_qgroup_limit_args *sa;
4304 struct btrfs_trans_handle *trans;
4305 int ret;
4306 int err;
4307 u64 qgroupid;
4308
4309 if (!capable(CAP_SYS_ADMIN))
4310 return -EPERM;
4311
905b0dda
MX
4312 ret = mnt_want_write_file(file);
4313 if (ret)
4314 return ret;
5d13a37b
AJ
4315
4316 sa = memdup_user(arg, sizeof(*sa));
905b0dda
MX
4317 if (IS_ERR(sa)) {
4318 ret = PTR_ERR(sa);
4319 goto drop_write;
4320 }
5d13a37b
AJ
4321
4322 trans = btrfs_join_transaction(root);
4323 if (IS_ERR(trans)) {
4324 ret = PTR_ERR(trans);
4325 goto out;
4326 }
4327
4328 qgroupid = sa->qgroupid;
4329 if (!qgroupid) {
4330 /* take the current subvol as qgroup */
4331 qgroupid = root->root_key.objectid;
4332 }
4333
f0042d5e 4334 ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
5d13a37b 4335
3a45bb20 4336 err = btrfs_end_transaction(trans);
5d13a37b
AJ
4337 if (err && !ret)
4338 ret = err;
4339
4340out:
4341 kfree(sa);
905b0dda
MX
4342drop_write:
4343 mnt_drop_write_file(file);
5d13a37b
AJ
4344 return ret;
4345}
4346
2f232036
JS
4347static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4348{
0b246afa
JM
4349 struct inode *inode = file_inode(file);
4350 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2f232036
JS
4351 struct btrfs_ioctl_quota_rescan_args *qsa;
4352 int ret;
4353
4354 if (!capable(CAP_SYS_ADMIN))
4355 return -EPERM;
4356
4357 ret = mnt_want_write_file(file);
4358 if (ret)
4359 return ret;
4360
4361 qsa = memdup_user(arg, sizeof(*qsa));
4362 if (IS_ERR(qsa)) {
4363 ret = PTR_ERR(qsa);
4364 goto drop_write;
4365 }
4366
4367 if (qsa->flags) {
4368 ret = -EINVAL;
4369 goto out;
4370 }
4371
0b246afa 4372 ret = btrfs_qgroup_rescan(fs_info);
2f232036
JS
4373
4374out:
4375 kfree(qsa);
4376drop_write:
4377 mnt_drop_write_file(file);
4378 return ret;
4379}
4380
b929c1d8
MPS
4381static long btrfs_ioctl_quota_rescan_status(struct btrfs_fs_info *fs_info,
4382 void __user *arg)
2f232036 4383{
0afb603a 4384 struct btrfs_ioctl_quota_rescan_args qsa = {0};
2f232036
JS
4385
4386 if (!capable(CAP_SYS_ADMIN))
4387 return -EPERM;
4388
0b246afa 4389 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
0afb603a
GR
4390 qsa.flags = 1;
4391 qsa.progress = fs_info->qgroup_rescan_progress.objectid;
2f232036
JS
4392 }
4393
0afb603a 4394 if (copy_to_user(arg, &qsa, sizeof(qsa)))
991a3dae 4395 return -EFAULT;
2f232036 4396
991a3dae 4397 return 0;
2f232036
JS
4398}
4399
b929c1d8
MPS
4400static long btrfs_ioctl_quota_rescan_wait(struct btrfs_fs_info *fs_info,
4401 void __user *arg)
57254b6e 4402{
57254b6e
JS
4403 if (!capable(CAP_SYS_ADMIN))
4404 return -EPERM;
4405
0b246afa 4406 return btrfs_qgroup_wait_for_completion(fs_info, true);
57254b6e
JS
4407}
4408
abccd00f 4409static long _btrfs_ioctl_set_received_subvol(struct file *file,
e4fed17a 4410 struct user_namespace *mnt_userns,
abccd00f 4411 struct btrfs_ioctl_received_subvol_args *sa)
8ea05e3a 4412{
496ad9aa 4413 struct inode *inode = file_inode(file);
0b246afa 4414 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8ea05e3a
AB
4415 struct btrfs_root *root = BTRFS_I(inode)->root;
4416 struct btrfs_root_item *root_item = &root->root_item;
4417 struct btrfs_trans_handle *trans;
95582b00 4418 struct timespec64 ct = current_time(inode);
8ea05e3a 4419 int ret = 0;
dd5f9615 4420 int received_uuid_changed;
8ea05e3a 4421
e4fed17a 4422 if (!inode_owner_or_capable(mnt_userns, inode))
bd60ea0f
DS
4423 return -EPERM;
4424
8ea05e3a
AB
4425 ret = mnt_want_write_file(file);
4426 if (ret < 0)
4427 return ret;
4428
0b246afa 4429 down_write(&fs_info->subvol_sem);
8ea05e3a 4430
4a0cc7ca 4431 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
8ea05e3a
AB
4432 ret = -EINVAL;
4433 goto out;
4434 }
4435
4436 if (btrfs_root_readonly(root)) {
4437 ret = -EROFS;
4438 goto out;
4439 }
4440
dd5f9615
SB
4441 /*
4442 * 1 - root item
4443 * 2 - uuid items (received uuid + subvol uuid)
4444 */
4445 trans = btrfs_start_transaction(root, 3);
8ea05e3a
AB
4446 if (IS_ERR(trans)) {
4447 ret = PTR_ERR(trans);
4448 trans = NULL;
4449 goto out;
4450 }
4451
4452 sa->rtransid = trans->transid;
4453 sa->rtime.sec = ct.tv_sec;
4454 sa->rtime.nsec = ct.tv_nsec;
4455
dd5f9615
SB
4456 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4457 BTRFS_UUID_SIZE);
4458 if (received_uuid_changed &&
d87ff758 4459 !btrfs_is_empty_uuid(root_item->received_uuid)) {
d1957791 4460 ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
d87ff758
NB
4461 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4462 root->root_key.objectid);
4463 if (ret && ret != -ENOENT) {
4464 btrfs_abort_transaction(trans, ret);
4465 btrfs_end_transaction(trans);
4466 goto out;
4467 }
4468 }
8ea05e3a
AB
4469 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4470 btrfs_set_root_stransid(root_item, sa->stransid);
4471 btrfs_set_root_rtransid(root_item, sa->rtransid);
3cae210f
QW
4472 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4473 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4474 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4475 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
8ea05e3a 4476
0b246afa 4477 ret = btrfs_update_root(trans, fs_info->tree_root,
8ea05e3a
AB
4478 &root->root_key, &root->root_item);
4479 if (ret < 0) {
3a45bb20 4480 btrfs_end_transaction(trans);
8ea05e3a 4481 goto out;
dd5f9615
SB
4482 }
4483 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
cdb345a8 4484 ret = btrfs_uuid_tree_add(trans, sa->uuid,
dd5f9615
SB
4485 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4486 root->root_key.objectid);
4487 if (ret < 0 && ret != -EEXIST) {
66642832 4488 btrfs_abort_transaction(trans, ret);
efd38150 4489 btrfs_end_transaction(trans);
8ea05e3a 4490 goto out;
dd5f9615
SB
4491 }
4492 }
3a45bb20 4493 ret = btrfs_commit_transaction(trans);
abccd00f 4494out:
0b246afa 4495 up_write(&fs_info->subvol_sem);
abccd00f
HM
4496 mnt_drop_write_file(file);
4497 return ret;
4498}
4499
4500#ifdef CONFIG_64BIT
4501static long btrfs_ioctl_set_received_subvol_32(struct file *file,
4502 void __user *arg)
4503{
4504 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
4505 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
4506 int ret = 0;
4507
4508 args32 = memdup_user(arg, sizeof(*args32));
7b9ea627
SV
4509 if (IS_ERR(args32))
4510 return PTR_ERR(args32);
abccd00f 4511
8d2db785 4512 args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
84dbeb87
DC
4513 if (!args64) {
4514 ret = -ENOMEM;
abccd00f
HM
4515 goto out;
4516 }
4517
4518 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
4519 args64->stransid = args32->stransid;
4520 args64->rtransid = args32->rtransid;
4521 args64->stime.sec = args32->stime.sec;
4522 args64->stime.nsec = args32->stime.nsec;
4523 args64->rtime.sec = args32->rtime.sec;
4524 args64->rtime.nsec = args32->rtime.nsec;
4525 args64->flags = args32->flags;
4526
e4fed17a 4527 ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), args64);
abccd00f
HM
4528 if (ret)
4529 goto out;
4530
4531 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
4532 args32->stransid = args64->stransid;
4533 args32->rtransid = args64->rtransid;
4534 args32->stime.sec = args64->stime.sec;
4535 args32->stime.nsec = args64->stime.nsec;
4536 args32->rtime.sec = args64->rtime.sec;
4537 args32->rtime.nsec = args64->rtime.nsec;
4538 args32->flags = args64->flags;
4539
4540 ret = copy_to_user(arg, args32, sizeof(*args32));
4541 if (ret)
4542 ret = -EFAULT;
4543
4544out:
4545 kfree(args32);
4546 kfree(args64);
4547 return ret;
4548}
4549#endif
4550
4551static long btrfs_ioctl_set_received_subvol(struct file *file,
4552 void __user *arg)
4553{
4554 struct btrfs_ioctl_received_subvol_args *sa = NULL;
4555 int ret = 0;
4556
4557 sa = memdup_user(arg, sizeof(*sa));
7b9ea627
SV
4558 if (IS_ERR(sa))
4559 return PTR_ERR(sa);
abccd00f 4560
e4fed17a 4561 ret = _btrfs_ioctl_set_received_subvol(file, file_mnt_user_ns(file), sa);
abccd00f
HM
4562
4563 if (ret)
4564 goto out;
4565
8ea05e3a
AB
4566 ret = copy_to_user(arg, sa, sizeof(*sa));
4567 if (ret)
4568 ret = -EFAULT;
4569
4570out:
4571 kfree(sa);
8ea05e3a
AB
4572 return ret;
4573}
4574
b929c1d8
MPS
4575static int btrfs_ioctl_get_fslabel(struct btrfs_fs_info *fs_info,
4576 void __user *arg)
867ab667 4577{
a1b83ac5 4578 size_t len;
867ab667 4579 int ret;
a1b83ac5
AJ
4580 char label[BTRFS_LABEL_SIZE];
4581
0b246afa
JM
4582 spin_lock(&fs_info->super_lock);
4583 memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4584 spin_unlock(&fs_info->super_lock);
a1b83ac5
AJ
4585
4586 len = strnlen(label, BTRFS_LABEL_SIZE);
867ab667 4587
4588 if (len == BTRFS_LABEL_SIZE) {
0b246afa
JM
4589 btrfs_warn(fs_info,
4590 "label is too long, return the first %zu bytes",
4591 --len);
867ab667 4592 }
4593
867ab667 4594 ret = copy_to_user(arg, label, len);
867ab667 4595
4596 return ret ? -EFAULT : 0;
4597}
4598
a8bfd4ab 4599static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4600{
0b246afa
JM
4601 struct inode *inode = file_inode(file);
4602 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4603 struct btrfs_root *root = BTRFS_I(inode)->root;
4604 struct btrfs_super_block *super_block = fs_info->super_copy;
a8bfd4ab 4605 struct btrfs_trans_handle *trans;
4606 char label[BTRFS_LABEL_SIZE];
4607 int ret;
4608
4609 if (!capable(CAP_SYS_ADMIN))
4610 return -EPERM;
4611
4612 if (copy_from_user(label, arg, sizeof(label)))
4613 return -EFAULT;
4614
4615 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
0b246afa 4616 btrfs_err(fs_info,
5d163e0e
JM
4617 "unable to set label with more than %d bytes",
4618 BTRFS_LABEL_SIZE - 1);
a8bfd4ab 4619 return -EINVAL;
4620 }
4621
4622 ret = mnt_want_write_file(file);
4623 if (ret)
4624 return ret;
4625
a8bfd4ab 4626 trans = btrfs_start_transaction(root, 0);
4627 if (IS_ERR(trans)) {
4628 ret = PTR_ERR(trans);
4629 goto out_unlock;
4630 }
4631
0b246afa 4632 spin_lock(&fs_info->super_lock);
a8bfd4ab 4633 strcpy(super_block->label, label);
0b246afa 4634 spin_unlock(&fs_info->super_lock);
3a45bb20 4635 ret = btrfs_commit_transaction(trans);
a8bfd4ab 4636
4637out_unlock:
a8bfd4ab 4638 mnt_drop_write_file(file);
4639 return ret;
4640}
4641
2eaa055f
JM
4642#define INIT_FEATURE_FLAGS(suffix) \
4643 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
4644 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
4645 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
4646
d5131b65 4647int btrfs_ioctl_get_supported_features(void __user *arg)
2eaa055f 4648{
4d4ab6d6 4649 static const struct btrfs_ioctl_feature_flags features[3] = {
2eaa055f
JM
4650 INIT_FEATURE_FLAGS(SUPP),
4651 INIT_FEATURE_FLAGS(SAFE_SET),
4652 INIT_FEATURE_FLAGS(SAFE_CLEAR)
4653 };
4654
4655 if (copy_to_user(arg, &features, sizeof(features)))
4656 return -EFAULT;
4657
4658 return 0;
4659}
4660
b929c1d8
MPS
4661static int btrfs_ioctl_get_features(struct btrfs_fs_info *fs_info,
4662 void __user *arg)
2eaa055f 4663{
0b246afa 4664 struct btrfs_super_block *super_block = fs_info->super_copy;
2eaa055f
JM
4665 struct btrfs_ioctl_feature_flags features;
4666
4667 features.compat_flags = btrfs_super_compat_flags(super_block);
4668 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
4669 features.incompat_flags = btrfs_super_incompat_flags(super_block);
4670
4671 if (copy_to_user(arg, &features, sizeof(features)))
4672 return -EFAULT;
4673
4674 return 0;
4675}
4676
2ff7e61e 4677static int check_feature_bits(struct btrfs_fs_info *fs_info,
3b02a68a 4678 enum btrfs_feature_set set,
2eaa055f
JM
4679 u64 change_mask, u64 flags, u64 supported_flags,
4680 u64 safe_set, u64 safe_clear)
4681{
f10152bc 4682 const char *type = btrfs_feature_set_name(set);
3b02a68a 4683 char *names;
2eaa055f
JM
4684 u64 disallowed, unsupported;
4685 u64 set_mask = flags & change_mask;
4686 u64 clear_mask = ~flags & change_mask;
4687
4688 unsupported = set_mask & ~supported_flags;
4689 if (unsupported) {
3b02a68a
JM
4690 names = btrfs_printable_features(set, unsupported);
4691 if (names) {
0b246afa
JM
4692 btrfs_warn(fs_info,
4693 "this kernel does not support the %s feature bit%s",
4694 names, strchr(names, ',') ? "s" : "");
3b02a68a
JM
4695 kfree(names);
4696 } else
0b246afa
JM
4697 btrfs_warn(fs_info,
4698 "this kernel does not support %s bits 0x%llx",
4699 type, unsupported);
2eaa055f
JM
4700 return -EOPNOTSUPP;
4701 }
4702
4703 disallowed = set_mask & ~safe_set;
4704 if (disallowed) {
3b02a68a
JM
4705 names = btrfs_printable_features(set, disallowed);
4706 if (names) {
0b246afa
JM
4707 btrfs_warn(fs_info,
4708 "can't set the %s feature bit%s while mounted",
4709 names, strchr(names, ',') ? "s" : "");
3b02a68a
JM
4710 kfree(names);
4711 } else
0b246afa
JM
4712 btrfs_warn(fs_info,
4713 "can't set %s bits 0x%llx while mounted",
4714 type, disallowed);
2eaa055f
JM
4715 return -EPERM;
4716 }
4717
4718 disallowed = clear_mask & ~safe_clear;
4719 if (disallowed) {
3b02a68a
JM
4720 names = btrfs_printable_features(set, disallowed);
4721 if (names) {
0b246afa
JM
4722 btrfs_warn(fs_info,
4723 "can't clear the %s feature bit%s while mounted",
4724 names, strchr(names, ',') ? "s" : "");
3b02a68a
JM
4725 kfree(names);
4726 } else
0b246afa
JM
4727 btrfs_warn(fs_info,
4728 "can't clear %s bits 0x%llx while mounted",
4729 type, disallowed);
2eaa055f
JM
4730 return -EPERM;
4731 }
4732
4733 return 0;
4734}
4735
2ff7e61e
JM
4736#define check_feature(fs_info, change_mask, flags, mask_base) \
4737check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \
2eaa055f
JM
4738 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
4739 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
4740 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
4741
4742static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
4743{
0b246afa
JM
4744 struct inode *inode = file_inode(file);
4745 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4746 struct btrfs_root *root = BTRFS_I(inode)->root;
4747 struct btrfs_super_block *super_block = fs_info->super_copy;
2eaa055f
JM
4748 struct btrfs_ioctl_feature_flags flags[2];
4749 struct btrfs_trans_handle *trans;
4750 u64 newflags;
4751 int ret;
4752
4753 if (!capable(CAP_SYS_ADMIN))
4754 return -EPERM;
4755
4756 if (copy_from_user(flags, arg, sizeof(flags)))
4757 return -EFAULT;
4758
4759 /* Nothing to do */
4760 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
4761 !flags[0].incompat_flags)
4762 return 0;
4763
2ff7e61e 4764 ret = check_feature(fs_info, flags[0].compat_flags,
2eaa055f
JM
4765 flags[1].compat_flags, COMPAT);
4766 if (ret)
4767 return ret;
4768
2ff7e61e 4769 ret = check_feature(fs_info, flags[0].compat_ro_flags,
2eaa055f
JM
4770 flags[1].compat_ro_flags, COMPAT_RO);
4771 if (ret)
4772 return ret;
4773
2ff7e61e 4774 ret = check_feature(fs_info, flags[0].incompat_flags,
2eaa055f
JM
4775 flags[1].incompat_flags, INCOMPAT);
4776 if (ret)
4777 return ret;
4778
7ab19625
DS
4779 ret = mnt_want_write_file(file);
4780 if (ret)
4781 return ret;
4782
8051aa1a 4783 trans = btrfs_start_transaction(root, 0);
7ab19625
DS
4784 if (IS_ERR(trans)) {
4785 ret = PTR_ERR(trans);
4786 goto out_drop_write;
4787 }
2eaa055f 4788
0b246afa 4789 spin_lock(&fs_info->super_lock);
2eaa055f
JM
4790 newflags = btrfs_super_compat_flags(super_block);
4791 newflags |= flags[0].compat_flags & flags[1].compat_flags;
4792 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
4793 btrfs_set_super_compat_flags(super_block, newflags);
4794
4795 newflags = btrfs_super_compat_ro_flags(super_block);
4796 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
4797 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
4798 btrfs_set_super_compat_ro_flags(super_block, newflags);
4799
4800 newflags = btrfs_super_incompat_flags(super_block);
4801 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
4802 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
4803 btrfs_set_super_incompat_flags(super_block, newflags);
0b246afa 4804 spin_unlock(&fs_info->super_lock);
2eaa055f 4805
3a45bb20 4806 ret = btrfs_commit_transaction(trans);
7ab19625
DS
4807out_drop_write:
4808 mnt_drop_write_file(file);
4809
4810 return ret;
2eaa055f
JM
4811}
4812
2351f431
JB
4813static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
4814{
4815 struct btrfs_ioctl_send_args *arg;
4816 int ret;
4817
4818 if (compat) {
4819#if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
4820 struct btrfs_ioctl_send_args_32 args32;
4821
4822 ret = copy_from_user(&args32, argp, sizeof(args32));
4823 if (ret)
4824 return -EFAULT;
4825 arg = kzalloc(sizeof(*arg), GFP_KERNEL);
4826 if (!arg)
4827 return -ENOMEM;
4828 arg->send_fd = args32.send_fd;
4829 arg->clone_sources_count = args32.clone_sources_count;
4830 arg->clone_sources = compat_ptr(args32.clone_sources);
4831 arg->parent_root = args32.parent_root;
4832 arg->flags = args32.flags;
4833 memcpy(arg->reserved, args32.reserved,
4834 sizeof(args32.reserved));
4835#else
4836 return -ENOTTY;
4837#endif
4838 } else {
4839 arg = memdup_user(argp, sizeof(*arg));
4840 if (IS_ERR(arg))
4841 return PTR_ERR(arg);
4842 }
4843 ret = btrfs_ioctl_send(file, arg);
4844 kfree(arg);
4845 return ret;
4846}
4847
f46b5a66
CH
4848long btrfs_ioctl(struct file *file, unsigned int
4849 cmd, unsigned long arg)
4850{
0b246afa
JM
4851 struct inode *inode = file_inode(file);
4852 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4853 struct btrfs_root *root = BTRFS_I(inode)->root;
4bcabaa3 4854 void __user *argp = (void __user *)arg;
f46b5a66
CH
4855
4856 switch (cmd) {
6cbff00f
CH
4857 case FS_IOC_GETVERSION:
4858 return btrfs_ioctl_getversion(file, argp);
40cf931f 4859 case FS_IOC_GETFSLABEL:
b929c1d8 4860 return btrfs_ioctl_get_fslabel(fs_info, argp);
40cf931f
ES
4861 case FS_IOC_SETFSLABEL:
4862 return btrfs_ioctl_set_fslabel(file, argp);
f7039b1d 4863 case FITRIM:
b929c1d8 4864 return btrfs_ioctl_fitrim(fs_info, argp);
f46b5a66 4865 case BTRFS_IOC_SNAP_CREATE:
fa0d2b9b 4866 return btrfs_ioctl_snap_create(file, argp, 0);
fdfb1e4f 4867 case BTRFS_IOC_SNAP_CREATE_V2:
fa0d2b9b 4868 return btrfs_ioctl_snap_create_v2(file, argp, 0);
3de4586c 4869 case BTRFS_IOC_SUBVOL_CREATE:
fa0d2b9b 4870 return btrfs_ioctl_snap_create(file, argp, 1);
6f72c7e2
AJ
4871 case BTRFS_IOC_SUBVOL_CREATE_V2:
4872 return btrfs_ioctl_snap_create_v2(file, argp, 1);
76dda93c 4873 case BTRFS_IOC_SNAP_DESTROY:
949964c9
MPS
4874 return btrfs_ioctl_snap_destroy(file, argp, false);
4875 case BTRFS_IOC_SNAP_DESTROY_V2:
4876 return btrfs_ioctl_snap_destroy(file, argp, true);
0caa102d
LZ
4877 case BTRFS_IOC_SUBVOL_GETFLAGS:
4878 return btrfs_ioctl_subvol_getflags(file, argp);
4879 case BTRFS_IOC_SUBVOL_SETFLAGS:
4880 return btrfs_ioctl_subvol_setflags(file, argp);
6ef5ed0d
JB
4881 case BTRFS_IOC_DEFAULT_SUBVOL:
4882 return btrfs_ioctl_default_subvol(file, argp);
f46b5a66 4883 case BTRFS_IOC_DEFRAG:
1e701a32
CM
4884 return btrfs_ioctl_defrag(file, NULL);
4885 case BTRFS_IOC_DEFRAG_RANGE:
4886 return btrfs_ioctl_defrag(file, argp);
f46b5a66 4887 case BTRFS_IOC_RESIZE:
198605a8 4888 return btrfs_ioctl_resize(file, argp);
f46b5a66 4889 case BTRFS_IOC_ADD_DEV:
2ff7e61e 4890 return btrfs_ioctl_add_dev(fs_info, argp);
f46b5a66 4891 case BTRFS_IOC_RM_DEV:
da24927b 4892 return btrfs_ioctl_rm_dev(file, argp);
6b526ed7
AJ
4893 case BTRFS_IOC_RM_DEV_V2:
4894 return btrfs_ioctl_rm_dev_v2(file, argp);
475f6387 4895 case BTRFS_IOC_FS_INFO:
2ff7e61e 4896 return btrfs_ioctl_fs_info(fs_info, argp);
475f6387 4897 case BTRFS_IOC_DEV_INFO:
2ff7e61e 4898 return btrfs_ioctl_dev_info(fs_info, argp);
f46b5a66 4899 case BTRFS_IOC_BALANCE:
9ba1f6e4 4900 return btrfs_ioctl_balance(file, NULL);
ac8e9819
CM
4901 case BTRFS_IOC_TREE_SEARCH:
4902 return btrfs_ioctl_tree_search(file, argp);
cc68a8a5
GH
4903 case BTRFS_IOC_TREE_SEARCH_V2:
4904 return btrfs_ioctl_tree_search_v2(file, argp);
ac8e9819
CM
4905 case BTRFS_IOC_INO_LOOKUP:
4906 return btrfs_ioctl_ino_lookup(file, argp);
d7728c96
JS
4907 case BTRFS_IOC_INO_PATHS:
4908 return btrfs_ioctl_ino_to_path(root, argp);
4909 case BTRFS_IOC_LOGICAL_INO:
d24a67b2
ZB
4910 return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
4911 case BTRFS_IOC_LOGICAL_INO_V2:
4912 return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
1406e432 4913 case BTRFS_IOC_SPACE_INFO:
2ff7e61e 4914 return btrfs_ioctl_space_info(fs_info, argp);
9b199859
FDBM
4915 case BTRFS_IOC_SYNC: {
4916 int ret;
4917
9db4dc24 4918 ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
9b199859
FDBM
4919 if (ret)
4920 return ret;
0b246afa 4921 ret = btrfs_sync_fs(inode->i_sb, 1);
2fad4e83
DS
4922 /*
4923 * The transaction thread may want to do more work,
01327610 4924 * namely it pokes the cleaner kthread that will start
2fad4e83
DS
4925 * processing uncleaned subvols.
4926 */
0b246afa 4927 wake_up_process(fs_info->transaction_kthread);
9b199859
FDBM
4928 return ret;
4929 }
46204592 4930 case BTRFS_IOC_START_SYNC:
9a8c28be 4931 return btrfs_ioctl_start_sync(root, argp);
46204592 4932 case BTRFS_IOC_WAIT_SYNC:
2ff7e61e 4933 return btrfs_ioctl_wait_sync(fs_info, argp);
475f6387 4934 case BTRFS_IOC_SCRUB:
b8e95489 4935 return btrfs_ioctl_scrub(file, argp);
475f6387 4936 case BTRFS_IOC_SCRUB_CANCEL:
2ff7e61e 4937 return btrfs_ioctl_scrub_cancel(fs_info);
475f6387 4938 case BTRFS_IOC_SCRUB_PROGRESS:
2ff7e61e 4939 return btrfs_ioctl_scrub_progress(fs_info, argp);
c9e9f97b 4940 case BTRFS_IOC_BALANCE_V2:
9ba1f6e4 4941 return btrfs_ioctl_balance(file, argp);
837d5b6e 4942 case BTRFS_IOC_BALANCE_CTL:
2ff7e61e 4943 return btrfs_ioctl_balance_ctl(fs_info, arg);
19a39dce 4944 case BTRFS_IOC_BALANCE_PROGRESS:
2ff7e61e 4945 return btrfs_ioctl_balance_progress(fs_info, argp);
8ea05e3a
AB
4946 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
4947 return btrfs_ioctl_set_received_subvol(file, argp);
abccd00f
HM
4948#ifdef CONFIG_64BIT
4949 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
4950 return btrfs_ioctl_set_received_subvol_32(file, argp);
4951#endif
31db9f7c 4952 case BTRFS_IOC_SEND:
2351f431
JB
4953 return _btrfs_ioctl_send(file, argp, false);
4954#if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
4955 case BTRFS_IOC_SEND_32:
4956 return _btrfs_ioctl_send(file, argp, true);
4957#endif
c11d2c23 4958 case BTRFS_IOC_GET_DEV_STATS:
2ff7e61e 4959 return btrfs_ioctl_get_dev_stats(fs_info, argp);
5d13a37b 4960 case BTRFS_IOC_QUOTA_CTL:
905b0dda 4961 return btrfs_ioctl_quota_ctl(file, argp);
5d13a37b 4962 case BTRFS_IOC_QGROUP_ASSIGN:
905b0dda 4963 return btrfs_ioctl_qgroup_assign(file, argp);
5d13a37b 4964 case BTRFS_IOC_QGROUP_CREATE:
905b0dda 4965 return btrfs_ioctl_qgroup_create(file, argp);
5d13a37b 4966 case BTRFS_IOC_QGROUP_LIMIT:
905b0dda 4967 return btrfs_ioctl_qgroup_limit(file, argp);
2f232036
JS
4968 case BTRFS_IOC_QUOTA_RESCAN:
4969 return btrfs_ioctl_quota_rescan(file, argp);
4970 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
b929c1d8 4971 return btrfs_ioctl_quota_rescan_status(fs_info, argp);
57254b6e 4972 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
b929c1d8 4973 return btrfs_ioctl_quota_rescan_wait(fs_info, argp);
3f6bcfbd 4974 case BTRFS_IOC_DEV_REPLACE:
2ff7e61e 4975 return btrfs_ioctl_dev_replace(fs_info, argp);
2eaa055f 4976 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
d5131b65 4977 return btrfs_ioctl_get_supported_features(argp);
2eaa055f 4978 case BTRFS_IOC_GET_FEATURES:
b929c1d8 4979 return btrfs_ioctl_get_features(fs_info, argp);
2eaa055f
JM
4980 case BTRFS_IOC_SET_FEATURES:
4981 return btrfs_ioctl_set_features(file, argp);
b64ec075
TM
4982 case BTRFS_IOC_GET_SUBVOL_INFO:
4983 return btrfs_ioctl_get_subvol_info(file, argp);
42e4b520
TM
4984 case BTRFS_IOC_GET_SUBVOL_ROOTREF:
4985 return btrfs_ioctl_get_subvol_rootref(file, argp);
23d0b79d
TM
4986 case BTRFS_IOC_INO_LOOKUP_USER:
4987 return btrfs_ioctl_ino_lookup_user(file, argp);
14605409
BB
4988 case FS_IOC_ENABLE_VERITY:
4989 return fsverity_ioctl_enable(file, (const void __user *)argp);
4990 case FS_IOC_MEASURE_VERITY:
4991 return fsverity_ioctl_measure(file, argp);
f46b5a66
CH
4992 }
4993
4994 return -ENOTTY;
4995}
4c63c245
LD
4996
4997#ifdef CONFIG_COMPAT
4998long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4999{
2a362249
JM
5000 /*
5001 * These all access 32-bit values anyway so no further
5002 * handling is necessary.
5003 */
4c63c245 5004 switch (cmd) {
4c63c245
LD
5005 case FS_IOC32_GETVERSION:
5006 cmd = FS_IOC_GETVERSION;
5007 break;
4c63c245
LD
5008 }
5009
5010 return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
5011}
5012#endif