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