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