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