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