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