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