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