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