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