Btrfs: fix clone vs chattr NODATASUM race
[linux-2.6-block.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 */
735654ea
DS
2616 if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED)
2617 return -EOPNOTSUPP;
f46b5a66 2618
171938e5 2619 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
183860f6
AJ
2620 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2621 goto out;
2622 }
2623
735654ea 2624 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
2ff7e61e 2625 ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
6b526ed7
AJ
2626 } else {
2627 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
2ff7e61e 2628 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
6b526ed7 2629 }
171938e5 2630 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
183860f6 2631
6b526ed7 2632 if (!ret) {
735654ea 2633 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
0b246afa 2634 btrfs_info(fs_info, "device deleted: id %llu",
6b526ed7
AJ
2635 vol_args->devid);
2636 else
0b246afa 2637 btrfs_info(fs_info, "device deleted: %s",
6b526ed7
AJ
2638 vol_args->name);
2639 }
183860f6
AJ
2640out:
2641 kfree(vol_args);
c47ca32d 2642err_drop:
4ac20c70 2643 mnt_drop_write_file(file);
f46b5a66
CH
2644 return ret;
2645}
2646
da24927b 2647static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
f46b5a66 2648{
0b246afa
JM
2649 struct inode *inode = file_inode(file);
2650 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
f46b5a66
CH
2651 struct btrfs_ioctl_vol_args *vol_args;
2652 int ret;
2653
e441d54d
CM
2654 if (!capable(CAP_SYS_ADMIN))
2655 return -EPERM;
2656
da24927b
MX
2657 ret = mnt_want_write_file(file);
2658 if (ret)
2659 return ret;
c146afad 2660
171938e5 2661 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
183860f6 2662 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
58d7bbf8
DS
2663 goto out_drop_write;
2664 }
2665
2666 vol_args = memdup_user(arg, sizeof(*vol_args));
2667 if (IS_ERR(vol_args)) {
2668 ret = PTR_ERR(vol_args);
183860f6
AJ
2669 goto out;
2670 }
2671
58d7bbf8 2672 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2ff7e61e 2673 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
183860f6 2674
ec95d491 2675 if (!ret)
0b246afa 2676 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
183860f6 2677 kfree(vol_args);
58d7bbf8 2678out:
171938e5 2679 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
58d7bbf8 2680out_drop_write:
4ac20c70 2681 mnt_drop_write_file(file);
58d7bbf8 2682
f46b5a66
CH
2683 return ret;
2684}
2685
2ff7e61e
JM
2686static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
2687 void __user *arg)
475f6387 2688{
027ed2f0 2689 struct btrfs_ioctl_fs_info_args *fi_args;
475f6387 2690 struct btrfs_device *device;
0b246afa 2691 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
027ed2f0 2692 int ret = 0;
475f6387 2693
027ed2f0
LZ
2694 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2695 if (!fi_args)
2696 return -ENOMEM;
2697
d03262c7 2698 rcu_read_lock();
027ed2f0 2699 fi_args->num_devices = fs_devices->num_devices;
475f6387 2700
d03262c7 2701 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
027ed2f0
LZ
2702 if (device->devid > fi_args->max_id)
2703 fi_args->max_id = device->devid;
475f6387 2704 }
d03262c7 2705 rcu_read_unlock();
475f6387 2706
d03262c7 2707 memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
bea7eafd
OS
2708 fi_args->nodesize = fs_info->nodesize;
2709 fi_args->sectorsize = fs_info->sectorsize;
2710 fi_args->clone_alignment = fs_info->sectorsize;
80a773fb 2711
027ed2f0
LZ
2712 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2713 ret = -EFAULT;
475f6387 2714
027ed2f0
LZ
2715 kfree(fi_args);
2716 return ret;
475f6387
JS
2717}
2718
2ff7e61e
JM
2719static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
2720 void __user *arg)
475f6387
JS
2721{
2722 struct btrfs_ioctl_dev_info_args *di_args;
2723 struct btrfs_device *dev;
475f6387
JS
2724 int ret = 0;
2725 char *s_uuid = NULL;
475f6387 2726
475f6387
JS
2727 di_args = memdup_user(arg, sizeof(*di_args));
2728 if (IS_ERR(di_args))
2729 return PTR_ERR(di_args);
2730
dd5f9615 2731 if (!btrfs_is_empty_uuid(di_args->uuid))
475f6387
JS
2732 s_uuid = di_args->uuid;
2733
c5593ca3 2734 rcu_read_lock();
0b246afa 2735 dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
475f6387
JS
2736
2737 if (!dev) {
2738 ret = -ENODEV;
2739 goto out;
2740 }
2741
2742 di_args->devid = dev->devid;
7cc8e58d
MX
2743 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
2744 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
475f6387 2745 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
a27202fb 2746 if (dev->name) {
606686ee
JB
2747 struct rcu_string *name;
2748
606686ee 2749 name = rcu_dereference(dev->name);
6670d4c2 2750 strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
a27202fb
JM
2751 di_args->path[sizeof(di_args->path) - 1] = 0;
2752 } else {
99ba55ad 2753 di_args->path[0] = '\0';
a27202fb 2754 }
475f6387
JS
2755
2756out:
c5593ca3 2757 rcu_read_unlock();
475f6387
JS
2758 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2759 ret = -EFAULT;
2760
2761 kfree(di_args);
2762 return ret;
2763}
2764
f4414602 2765static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
416161db
MF
2766{
2767 struct page *page;
416161db 2768
416161db
MF
2769 page = grab_cache_page(inode->i_mapping, index);
2770 if (!page)
31314002 2771 return ERR_PTR(-ENOMEM);
416161db
MF
2772
2773 if (!PageUptodate(page)) {
31314002
FM
2774 int ret;
2775
2776 ret = btrfs_readpage(NULL, page);
2777 if (ret)
2778 return ERR_PTR(ret);
416161db
MF
2779 lock_page(page);
2780 if (!PageUptodate(page)) {
2781 unlock_page(page);
09cbfeaf 2782 put_page(page);
31314002
FM
2783 return ERR_PTR(-EIO);
2784 }
2785 if (page->mapping != inode->i_mapping) {
2786 unlock_page(page);
09cbfeaf 2787 put_page(page);
31314002 2788 return ERR_PTR(-EAGAIN);
416161db
MF
2789 }
2790 }
416161db
MF
2791
2792 return page;
2793}
2794
f4414602
MF
2795static int gather_extent_pages(struct inode *inode, struct page **pages,
2796 int num_pages, u64 off)
2797{
2798 int i;
09cbfeaf 2799 pgoff_t index = off >> PAGE_SHIFT;
f4414602
MF
2800
2801 for (i = 0; i < num_pages; i++) {
31314002 2802again:
f4414602 2803 pages[i] = extent_same_get_page(inode, index + i);
31314002
FM
2804 if (IS_ERR(pages[i])) {
2805 int err = PTR_ERR(pages[i]);
2806
2807 if (err == -EAGAIN)
2808 goto again;
2809 pages[i] = NULL;
2810 return err;
2811 }
f4414602
MF
2812 }
2813 return 0;
2814}
2815
e0bd70c6
FM
2816static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2817 bool retry_range_locking)
77fe20dc 2818{
e0bd70c6
FM
2819 /*
2820 * Do any pending delalloc/csum calculations on inode, one way or
2821 * another, and lock file content.
2822 * The locking order is:
2823 *
2824 * 1) pages
2825 * 2) range in the inode's io tree
2826 */
77fe20dc
MF
2827 while (1) {
2828 struct btrfs_ordered_extent *ordered;
2829 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2830 ordered = btrfs_lookup_first_ordered_extent(inode,
2831 off + len - 1);
ff5df9b8
FM
2832 if ((!ordered ||
2833 ordered->file_offset + ordered->len <= off ||
2834 ordered->file_offset >= off + len) &&
77fe20dc 2835 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
ff5df9b8
FM
2836 off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2837 if (ordered)
2838 btrfs_put_ordered_extent(ordered);
77fe20dc 2839 break;
ff5df9b8 2840 }
77fe20dc
MF
2841 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2842 if (ordered)
2843 btrfs_put_ordered_extent(ordered);
e0bd70c6
FM
2844 if (!retry_range_locking)
2845 return -EAGAIN;
77fe20dc
MF
2846 btrfs_wait_ordered_range(inode, off, len);
2847 }
e0bd70c6 2848 return 0;
77fe20dc
MF
2849}
2850
f4414602 2851static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
416161db 2852{
5955102c
AV
2853 inode_unlock(inode1);
2854 inode_unlock(inode2);
416161db
MF
2855}
2856
f4414602
MF
2857static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2858{
2859 if (inode1 < inode2)
2860 swap(inode1, inode2);
2861
5955102c
AV
2862 inode_lock_nested(inode1, I_MUTEX_PARENT);
2863 inode_lock_nested(inode2, I_MUTEX_CHILD);
f4414602
MF
2864}
2865
2866static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2867 struct inode *inode2, u64 loff2, u64 len)
2868{
2869 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2870 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2871}
2872
e0bd70c6
FM
2873static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2874 struct inode *inode2, u64 loff2, u64 len,
2875 bool retry_range_locking)
416161db 2876{
e0bd70c6
FM
2877 int ret;
2878
416161db
MF
2879 if (inode1 < inode2) {
2880 swap(inode1, inode2);
2881 swap(loff1, loff2);
2882 }
e0bd70c6
FM
2883 ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2884 if (ret)
2885 return ret;
2886 ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2887 if (ret)
2888 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2889 loff1 + len - 1);
2890 return ret;
f4414602
MF
2891}
2892
2893struct cmp_pages {
2894 int num_pages;
2895 struct page **src_pages;
2896 struct page **dst_pages;
2897};
2898
2899static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2900{
2901 int i;
2902 struct page *pg;
2903
2904 for (i = 0; i < cmp->num_pages; i++) {
2905 pg = cmp->src_pages[i];
e0bd70c6
FM
2906 if (pg) {
2907 unlock_page(pg);
09cbfeaf 2908 put_page(pg);
e0bd70c6 2909 }
f4414602 2910 pg = cmp->dst_pages[i];
e0bd70c6
FM
2911 if (pg) {
2912 unlock_page(pg);
09cbfeaf 2913 put_page(pg);
e0bd70c6 2914 }
f4414602 2915 }
f4414602
MF
2916}
2917
2918static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2919 struct inode *dst, u64 dst_loff,
2920 u64 len, struct cmp_pages *cmp)
2921{
2922 int ret;
09cbfeaf 2923 int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
f4414602 2924
f4414602 2925 cmp->num_pages = num_pages;
b1517622 2926
67b07bd4 2927 ret = gather_extent_pages(src, cmp->src_pages, num_pages, loff);
f4414602
MF
2928 if (ret)
2929 goto out;
2930
67b07bd4 2931 ret = gather_extent_pages(dst, cmp->dst_pages, num_pages, dst_loff);
f4414602
MF
2932
2933out:
2934 if (ret)
2935 btrfs_cmp_data_free(cmp);
78ad4ce0 2936 return ret;
416161db
MF
2937}
2938
1a287cfe 2939static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
416161db
MF
2940{
2941 int ret = 0;
f4414602 2942 int i;
416161db 2943 struct page *src_page, *dst_page;
09cbfeaf 2944 unsigned int cmp_len = PAGE_SIZE;
416161db
MF
2945 void *addr, *dst_addr;
2946
f4414602 2947 i = 0;
416161db 2948 while (len) {
09cbfeaf 2949 if (len < PAGE_SIZE)
416161db
MF
2950 cmp_len = len;
2951
f4414602
MF
2952 BUG_ON(i >= cmp->num_pages);
2953
2954 src_page = cmp->src_pages[i];
2955 dst_page = cmp->dst_pages[i];
e0bd70c6
FM
2956 ASSERT(PageLocked(src_page));
2957 ASSERT(PageLocked(dst_page));
f4414602 2958
416161db
MF
2959 addr = kmap_atomic(src_page);
2960 dst_addr = kmap_atomic(dst_page);
2961
2962 flush_dcache_page(src_page);
2963 flush_dcache_page(dst_page);
2964
2965 if (memcmp(addr, dst_addr, cmp_len))
2b3909f8 2966 ret = -EBADE;
416161db
MF
2967
2968 kunmap_atomic(addr);
2969 kunmap_atomic(dst_addr);
416161db
MF
2970
2971 if (ret)
2972 break;
2973
416161db 2974 len -= cmp_len;
f4414602 2975 i++;
416161db
MF
2976 }
2977
2978 return ret;
2979}
2980
e1d227a4
MF
2981static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
2982 u64 olen)
416161db 2983{
e1d227a4 2984 u64 len = *plen;
416161db
MF
2985 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2986
e1d227a4 2987 if (off + olen > inode->i_size || off + olen < off)
416161db 2988 return -EINVAL;
e1d227a4
MF
2989
2990 /* if we extend to eof, continue to block boundary */
2991 if (off + len == inode->i_size)
2992 *plen = len = ALIGN(inode->i_size, bs) - off;
2993
416161db
MF
2994 /* Check that we are block aligned - btrfs_clone() requires this */
2995 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2996 return -EINVAL;
2997
2998 return 0;
2999}
3000
3973909d 3001static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 olen,
67b07bd4
TT
3002 struct inode *dst, u64 dst_loff,
3003 struct cmp_pages *cmp)
416161db
MF
3004{
3005 int ret;
e1d227a4 3006 u64 len = olen;
fc4badd9 3007 bool same_inode = (src == dst);
0efa9f48
MF
3008 u64 same_lock_start = 0;
3009 u64 same_lock_len = 0;
416161db 3010
fc4badd9
OS
3011 ret = extent_same_check_offsets(src, loff, &len, olen);
3012 if (ret)
3973909d 3013 return ret;
416161db 3014
fc4badd9
OS
3015 ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3016 if (ret)
3973909d 3017 return ret;
fc4badd9
OS
3018
3019 if (same_inode) {
0efa9f48
MF
3020 /*
3021 * Single inode case wants the same checks, except we
3022 * don't want our length pushed out past i_size as
3023 * comparing that data range makes no sense.
3024 *
3025 * extent_same_check_offsets() will do this for an
3026 * unaligned length at i_size, so catch it here and
3027 * reject the request.
3028 *
3029 * This effectively means we require aligned extents
3030 * for the single-inode case, whereas the other cases
3031 * allow an unaligned length so long as it ends at
3032 * i_size.
3033 */
3973909d
TT
3034 if (len != olen)
3035 return -EINVAL;
0efa9f48
MF
3036
3037 /* Check for overlapping ranges */
3973909d
TT
3038 if (dst_loff + len > loff && dst_loff < loff + len)
3039 return -EINVAL;
0efa9f48
MF
3040
3041 same_lock_start = min_t(u64, loff, dst_loff);
3042 same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
0efa9f48 3043 }
416161db 3044
e0bd70c6 3045again:
67b07bd4 3046 ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, cmp);
f4414602 3047 if (ret)
3973909d 3048 return ret;
f4414602 3049
0efa9f48 3050 if (same_inode)
e0bd70c6
FM
3051 ret = lock_extent_range(src, same_lock_start, same_lock_len,
3052 false);
0efa9f48 3053 else
e0bd70c6
FM
3054 ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3055 false);
3056 /*
3057 * If one of the inodes has dirty pages in the respective range or
3058 * ordered extents, we need to flush dellaloc and wait for all ordered
3059 * extents in the range. We must unlock the pages and the ranges in the
3060 * io trees to avoid deadlocks when flushing delalloc (requires locking
3061 * pages) and when waiting for ordered extents to complete (they require
3062 * range locking).
3063 */
3064 if (ret == -EAGAIN) {
3065 /*
3066 * Ranges in the io trees already unlocked. Now unlock all
3067 * pages before waiting for all IO to complete.
3068 */
67b07bd4 3069 btrfs_cmp_data_free(cmp);
e0bd70c6
FM
3070 if (same_inode) {
3071 btrfs_wait_ordered_range(src, same_lock_start,
3072 same_lock_len);
3073 } else {
3074 btrfs_wait_ordered_range(src, loff, len);
3075 btrfs_wait_ordered_range(dst, dst_loff, len);
3076 }
3077 goto again;
3078 }
3079 ASSERT(ret == 0);
3080 if (WARN_ON(ret)) {
3081 /* ranges in the io trees already unlocked */
67b07bd4 3082 btrfs_cmp_data_free(cmp);
e0bd70c6
FM
3083 return ret;
3084 }
f4414602 3085
207910dd 3086 /* pass original length for comparison so we stay within i_size */
67b07bd4 3087 ret = btrfs_cmp_data(olen, cmp);
416161db 3088 if (ret == 0)
1c919a5e 3089 ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
416161db 3090
0efa9f48
MF
3091 if (same_inode)
3092 unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
3093 same_lock_start + same_lock_len - 1);
3094 else
3095 btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
f4414602 3096
67b07bd4 3097 btrfs_cmp_data_free(cmp);
3973909d
TT
3098
3099 return ret;
3100}
3101
b6728768
TT
3102#define BTRFS_MAX_DEDUPE_LEN SZ_16M
3103
3973909d
TT
3104static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3105 struct inode *dst, u64 dst_loff)
3106{
3107 int ret;
67b07bd4
TT
3108 struct cmp_pages cmp;
3109 int num_pages = PAGE_ALIGN(BTRFS_MAX_DEDUPE_LEN) >> PAGE_SHIFT;
3973909d 3110 bool same_inode = (src == dst);
b6728768 3111 u64 i, tail_len, chunk_count;
3973909d
TT
3112
3113 if (olen == 0)
3114 return 0;
3115
3116 if (same_inode)
3117 inode_lock(src);
3118 else
3119 btrfs_double_inode_lock(src, dst);
3120
3121 /* don't make the dst file partly checksummed */
3122 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3123 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3124 ret = -EINVAL;
3125 goto out_unlock;
3126 }
3127
b6728768
TT
3128 tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3129 chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
67b07bd4
TT
3130 if (chunk_count == 0)
3131 num_pages = PAGE_ALIGN(tail_len) >> PAGE_SHIFT;
3132
3133 /*
3134 * If deduping ranges in the same inode, locking rules make it
3135 * mandatory to always lock pages in ascending order to avoid deadlocks
3136 * with concurrent tasks (such as starting writeback/delalloc).
3137 */
3138 if (same_inode && dst_loff < loff)
3139 swap(loff, dst_loff);
3140
3141 /*
3142 * We must gather up all the pages before we initiate our extent
3143 * locking. We use an array for the page pointers. Size of the array is
3144 * bounded by len, which is in turn bounded by BTRFS_MAX_DEDUPE_LEN.
3145 */
bf5091c8
DS
3146 cmp.src_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3147 GFP_KERNEL | __GFP_ZERO);
3148 cmp.dst_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3149 GFP_KERNEL | __GFP_ZERO);
67b07bd4 3150 if (!cmp.src_pages || !cmp.dst_pages) {
bf5091c8
DS
3151 ret = -ENOMEM;
3152 goto out_free;
67b07bd4 3153 }
b6728768
TT
3154
3155 for (i = 0; i < chunk_count; i++) {
3156 ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
67b07bd4 3157 dst, dst_loff, &cmp);
b6728768
TT
3158 if (ret)
3159 goto out_unlock;
3160
3161 loff += BTRFS_MAX_DEDUPE_LEN;
3162 dst_loff += BTRFS_MAX_DEDUPE_LEN;
3163 }
3164
3165 if (tail_len > 0)
67b07bd4
TT
3166 ret = btrfs_extent_same_range(src, loff, tail_len, dst,
3167 dst_loff, &cmp);
3973909d 3168
416161db 3169out_unlock:
0efa9f48 3170 if (same_inode)
5955102c 3171 inode_unlock(src);
0efa9f48
MF
3172 else
3173 btrfs_double_inode_unlock(src, dst);
416161db 3174
bf5091c8
DS
3175out_free:
3176 kvfree(cmp.src_pages);
3177 kvfree(cmp.dst_pages);
67b07bd4 3178
416161db
MF
3179 return ret;
3180}
3181
2b3909f8
DW
3182ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
3183 struct file *dst_file, u64 dst_loff)
416161db 3184{
2b3909f8
DW
3185 struct inode *src = file_inode(src_file);
3186 struct inode *dst = file_inode(dst_file);
416161db 3187 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
2b3909f8 3188 ssize_t res;
416161db 3189
09cbfeaf 3190 if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
416161db
MF
3191 /*
3192 * Btrfs does not support blocksize < page_size. As a
3193 * result, btrfs_cmp_data() won't correctly handle
3194 * this situation without an update.
3195 */
2b3909f8 3196 return -EINVAL;
416161db
MF
3197 }
3198
2b3909f8
DW
3199 res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
3200 if (res)
3201 return res;
3202 return olen;
416161db
MF
3203}
3204
f82a9901
FM
3205static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3206 struct inode *inode,
3207 u64 endoff,
3208 const u64 destoff,
1c919a5e
MF
3209 const u64 olen,
3210 int no_time_update)
f82a9901
FM
3211{
3212 struct btrfs_root *root = BTRFS_I(inode)->root;
3213 int ret;
3214
3215 inode_inc_iversion(inode);
1c919a5e 3216 if (!no_time_update)
c2050a45 3217 inode->i_mtime = inode->i_ctime = current_time(inode);
f82a9901
FM
3218 /*
3219 * We round up to the block size at eof when determining which
3220 * extents to clone above, but shouldn't round up the file size.
3221 */
3222 if (endoff > destoff + olen)
3223 endoff = destoff + olen;
3224 if (endoff > inode->i_size)
6ef06d27 3225 btrfs_i_size_write(BTRFS_I(inode), endoff);
f82a9901
FM
3226
3227 ret = btrfs_update_inode(trans, root, inode);
3228 if (ret) {
66642832 3229 btrfs_abort_transaction(trans, ret);
3a45bb20 3230 btrfs_end_transaction(trans);
f82a9901
FM
3231 goto out;
3232 }
3a45bb20 3233 ret = btrfs_end_transaction(trans);
f82a9901
FM
3234out:
3235 return ret;
3236}
3237
a2f392e4 3238static void clone_update_extent_map(struct btrfs_inode *inode,
7ffbb598
FM
3239 const struct btrfs_trans_handle *trans,
3240 const struct btrfs_path *path,
7ffbb598
FM
3241 const u64 hole_offset,
3242 const u64 hole_len)
3243{
a2f392e4 3244 struct extent_map_tree *em_tree = &inode->extent_tree;
7ffbb598
FM
3245 struct extent_map *em;
3246 int ret;
3247
3248 em = alloc_extent_map();
3249 if (!em) {
a2f392e4 3250 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
7ffbb598
FM
3251 return;
3252 }
3253
14f59796
FM
3254 if (path) {
3255 struct btrfs_file_extent_item *fi;
3256
3257 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
3258 struct btrfs_file_extent_item);
a2f392e4 3259 btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
7ffbb598
FM
3260 em->generation = -1;
3261 if (btrfs_file_extent_type(path->nodes[0], fi) ==
3262 BTRFS_FILE_EXTENT_INLINE)
3263 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
a2f392e4 3264 &inode->runtime_flags);
7ffbb598
FM
3265 } else {
3266 em->start = hole_offset;
3267 em->len = hole_len;
3268 em->ram_bytes = em->len;
3269 em->orig_start = hole_offset;
3270 em->block_start = EXTENT_MAP_HOLE;
3271 em->block_len = 0;
3272 em->orig_block_len = 0;
3273 em->compress_type = BTRFS_COMPRESS_NONE;
3274 em->generation = trans->transid;
3275 }
3276
3277 while (1) {
3278 write_lock(&em_tree->lock);
3279 ret = add_extent_mapping(em_tree, em, 1);
3280 write_unlock(&em_tree->lock);
3281 if (ret != -EEXIST) {
3282 free_extent_map(em);
3283 break;
3284 }
a2f392e4 3285 btrfs_drop_extent_cache(inode, em->start,
7ffbb598
FM
3286 em->start + em->len - 1, 0);
3287 }
3288
ee39b432 3289 if (ret)
a2f392e4 3290 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
7ffbb598
FM
3291}
3292
8039d87d
FM
3293/*
3294 * Make sure we do not end up inserting an inline extent into a file that has
3295 * already other (non-inline) extents. If a file has an inline extent it can
3296 * not have any other extents and the (single) inline extent must start at the
3297 * file offset 0. Failing to respect these rules will lead to file corruption,
3298 * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
3299 *
3300 * We can have extents that have been already written to disk or we can have
3301 * dirty ranges still in delalloc, in which case the extent maps and items are
3302 * created only when we run delalloc, and the delalloc ranges might fall outside
3303 * the range we are currently locking in the inode's io tree. So we check the
3304 * inode's i_size because of that (i_size updates are done while holding the
3305 * i_mutex, which we are holding here).
3306 * We also check to see if the inode has a size not greater than "datal" but has
3307 * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
3308 * protected against such concurrent fallocate calls by the i_mutex).
3309 *
3310 * If the file has no extents but a size greater than datal, do not allow the
3311 * copy because we would need turn the inline extent into a non-inline one (even
3312 * with NO_HOLES enabled). If we find our destination inode only has one inline
3313 * extent, just overwrite it with the source inline extent if its size is less
3314 * than the source extent's size, or we could copy the source inline extent's
3315 * data into the destination inode's inline extent if the later is greater then
3316 * the former.
3317 */
4a0ab9d7 3318static int clone_copy_inline_extent(struct inode *dst,
8039d87d
FM
3319 struct btrfs_trans_handle *trans,
3320 struct btrfs_path *path,
3321 struct btrfs_key *new_key,
3322 const u64 drop_start,
3323 const u64 datal,
3324 const u64 skip,
3325 const u64 size,
3326 char *inline_data)
3327{
0b246afa 3328 struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
8039d87d
FM
3329 struct btrfs_root *root = BTRFS_I(dst)->root;
3330 const u64 aligned_end = ALIGN(new_key->offset + datal,
0b246afa 3331 fs_info->sectorsize);
8039d87d
FM
3332 int ret;
3333 struct btrfs_key key;
3334
3335 if (new_key->offset > 0)
3336 return -EOPNOTSUPP;
3337
4a0cc7ca 3338 key.objectid = btrfs_ino(BTRFS_I(dst));
8039d87d
FM
3339 key.type = BTRFS_EXTENT_DATA_KEY;
3340 key.offset = 0;
3341 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3342 if (ret < 0) {
3343 return ret;
3344 } else if (ret > 0) {
3345 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3346 ret = btrfs_next_leaf(root, path);
3347 if (ret < 0)
3348 return ret;
3349 else if (ret > 0)
3350 goto copy_inline_extent;
3351 }
3352 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4a0cc7ca 3353 if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
8039d87d
FM
3354 key.type == BTRFS_EXTENT_DATA_KEY) {
3355 ASSERT(key.offset > 0);
3356 return -EOPNOTSUPP;
3357 }
3358 } else if (i_size_read(dst) <= datal) {
3359 struct btrfs_file_extent_item *ei;
3360 u64 ext_len;
3361
3362 /*
3363 * If the file size is <= datal, make sure there are no other
3364 * extents following (can happen do to an fallocate call with
3365 * the flag FALLOC_FL_KEEP_SIZE).
3366 */
3367 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3368 struct btrfs_file_extent_item);
3369 /*
3370 * If it's an inline extent, it can not have other extents
3371 * following it.
3372 */
3373 if (btrfs_file_extent_type(path->nodes[0], ei) ==
3374 BTRFS_FILE_EXTENT_INLINE)
3375 goto copy_inline_extent;
3376
3377 ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3378 if (ext_len > aligned_end)
3379 return -EOPNOTSUPP;
3380
3381 ret = btrfs_next_item(root, path);
3382 if (ret < 0) {
3383 return ret;
3384 } else if (ret == 0) {
3385 btrfs_item_key_to_cpu(path->nodes[0], &key,
3386 path->slots[0]);
4a0cc7ca 3387 if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
8039d87d
FM
3388 key.type == BTRFS_EXTENT_DATA_KEY)
3389 return -EOPNOTSUPP;
3390 }
3391 }
3392
3393copy_inline_extent:
3394 /*
3395 * We have no extent items, or we have an extent at offset 0 which may
3396 * or may not be inlined. All these cases are dealt the same way.
3397 */
3398 if (i_size_read(dst) > datal) {
3399 /*
3400 * If the destination inode has an inline extent...
3401 * This would require copying the data from the source inline
3402 * extent into the beginning of the destination's inline extent.
3403 * But this is really complex, both extents can be compressed
3404 * or just one of them, which would require decompressing and
3405 * re-compressing data (which could increase the new compressed
3406 * size, not allowing the compressed data to fit anymore in an
3407 * inline extent).
3408 * So just don't support this case for now (it should be rare,
3409 * we are not really saving space when cloning inline extents).
3410 */
3411 return -EOPNOTSUPP;
3412 }
3413
3414 btrfs_release_path(path);
3415 ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
3416 if (ret)
3417 return ret;
3418 ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
3419 if (ret)
3420 return ret;
3421
3422 if (skip) {
3423 const u32 start = btrfs_file_extent_calc_inline_size(0);
3424
3425 memmove(inline_data + start, inline_data + start + skip, datal);
3426 }
3427
3428 write_extent_buffer(path->nodes[0], inline_data,
3429 btrfs_item_ptr_offset(path->nodes[0],
3430 path->slots[0]),
3431 size);
3432 inode_add_bytes(dst, datal);
3433
3434 return 0;
3435}
3436
32b7c687
MF
3437/**
3438 * btrfs_clone() - clone a range from inode file to another
3439 *
3440 * @src: Inode to clone from
3441 * @inode: Inode to clone to
3442 * @off: Offset within source to start clone from
3443 * @olen: Original length, passed by user, of range to clone
1c919a5e 3444 * @olen_aligned: Block-aligned value of olen
32b7c687 3445 * @destoff: Offset within @inode to start clone
1c919a5e 3446 * @no_time_update: Whether to update mtime/ctime on the target inode
32b7c687
MF
3447 */
3448static int btrfs_clone(struct inode *src, struct inode *inode,
f82a9901 3449 const u64 off, const u64 olen, const u64 olen_aligned,
1c919a5e 3450 const u64 destoff, int no_time_update)
f46b5a66 3451{
0b246afa 3452 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
f46b5a66 3453 struct btrfs_root *root = BTRFS_I(inode)->root;
32b7c687 3454 struct btrfs_path *path = NULL;
f46b5a66 3455 struct extent_buffer *leaf;
32b7c687
MF
3456 struct btrfs_trans_handle *trans;
3457 char *buf = NULL;
ae01a0ab 3458 struct btrfs_key key;
f46b5a66
CH
3459 u32 nritems;
3460 int slot;
ae01a0ab 3461 int ret;
f82a9901 3462 const u64 len = olen_aligned;
f82a9901 3463 u64 last_dest_end = destoff;
ae01a0ab
YZ
3464
3465 ret = -ENOMEM;
752ade68
MH
3466 buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3467 if (!buf)
3468 return ret;
ae01a0ab
YZ
3469
3470 path = btrfs_alloc_path();
3471 if (!path) {
15351955 3472 kvfree(buf);
32b7c687 3473 return ret;
d525e8ab
LZ
3474 }
3475
e4058b54 3476 path->reada = READA_FORWARD;
c5c9cd4d 3477 /* clone data */
4a0cc7ca 3478 key.objectid = btrfs_ino(BTRFS_I(src));
ae01a0ab 3479 key.type = BTRFS_EXTENT_DATA_KEY;
2c463823 3480 key.offset = off;
f46b5a66
CH
3481
3482 while (1) {
de249e66 3483 u64 next_key_min_offset = key.offset + 1;
df858e76 3484
f46b5a66
CH
3485 /*
3486 * note the key will change type as we walk through the
3487 * tree.
3488 */
e4355f34 3489 path->leave_spinning = 1;
362a20c5
DS
3490 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3491 0, 0);
f46b5a66
CH
3492 if (ret < 0)
3493 goto out;
2c463823
FM
3494 /*
3495 * First search, if no extent item that starts at offset off was
3496 * found but the previous item is an extent item, it's possible
3497 * it might overlap our target range, therefore process it.
3498 */
3499 if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3500 btrfs_item_key_to_cpu(path->nodes[0], &key,
3501 path->slots[0] - 1);
3502 if (key.type == BTRFS_EXTENT_DATA_KEY)
3503 path->slots[0]--;
3504 }
f46b5a66 3505
ae01a0ab 3506 nritems = btrfs_header_nritems(path->nodes[0]);
e4355f34 3507process_slot:
ae01a0ab 3508 if (path->slots[0] >= nritems) {
362a20c5 3509 ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
f46b5a66
CH
3510 if (ret < 0)
3511 goto out;
3512 if (ret > 0)
3513 break;
ae01a0ab 3514 nritems = btrfs_header_nritems(path->nodes[0]);
f46b5a66
CH
3515 }
3516 leaf = path->nodes[0];
3517 slot = path->slots[0];
f46b5a66 3518
ae01a0ab 3519 btrfs_item_key_to_cpu(leaf, &key, slot);
962a298f 3520 if (key.type > BTRFS_EXTENT_DATA_KEY ||
4a0cc7ca 3521 key.objectid != btrfs_ino(BTRFS_I(src)))
f46b5a66
CH
3522 break;
3523
962a298f 3524 if (key.type == BTRFS_EXTENT_DATA_KEY) {
c5c9cd4d
SW
3525 struct btrfs_file_extent_item *extent;
3526 int type;
31840ae1
ZY
3527 u32 size;
3528 struct btrfs_key new_key;
c5c9cd4d
SW
3529 u64 disko = 0, diskl = 0;
3530 u64 datao = 0, datal = 0;
3531 u8 comp;
f82a9901 3532 u64 drop_start;
31840ae1 3533
c5c9cd4d
SW
3534 extent = btrfs_item_ptr(leaf, slot,
3535 struct btrfs_file_extent_item);
3536 comp = btrfs_file_extent_compression(leaf, extent);
3537 type = btrfs_file_extent_type(leaf, extent);
c8a894d7
CM
3538 if (type == BTRFS_FILE_EXTENT_REG ||
3539 type == BTRFS_FILE_EXTENT_PREALLOC) {
d397712b
CM
3540 disko = btrfs_file_extent_disk_bytenr(leaf,
3541 extent);
3542 diskl = btrfs_file_extent_disk_num_bytes(leaf,
3543 extent);
c5c9cd4d 3544 datao = btrfs_file_extent_offset(leaf, extent);
d397712b
CM
3545 datal = btrfs_file_extent_num_bytes(leaf,
3546 extent);
c5c9cd4d
SW
3547 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3548 /* take upper bound, may be compressed */
3549 datal = btrfs_file_extent_ram_bytes(leaf,
3550 extent);
3551 }
31840ae1 3552
2c463823
FM
3553 /*
3554 * The first search might have left us at an extent
3555 * item that ends before our target range's start, can
3556 * happen if we have holes and NO_HOLES feature enabled.
3557 */
3558 if (key.offset + datal <= off) {
e4355f34
FDBM
3559 path->slots[0]++;
3560 goto process_slot;
2c463823
FM
3561 } else if (key.offset >= off + len) {
3562 break;
e4355f34 3563 }
df858e76 3564 next_key_min_offset = key.offset + datal;
e4355f34
FDBM
3565 size = btrfs_item_size_nr(leaf, slot);
3566 read_extent_buffer(leaf, buf,
3567 btrfs_item_ptr_offset(leaf, slot),
3568 size);
3569
3570 btrfs_release_path(path);
3571 path->leave_spinning = 0;
c5c9cd4d 3572
31840ae1 3573 memcpy(&new_key, &key, sizeof(new_key));
4a0cc7ca 3574 new_key.objectid = btrfs_ino(BTRFS_I(inode));
4d728ec7
LZ
3575 if (off <= key.offset)
3576 new_key.offset = key.offset + destoff - off;
3577 else
3578 new_key.offset = destoff;
31840ae1 3579
f82a9901
FM
3580 /*
3581 * Deal with a hole that doesn't have an extent item
3582 * that represents it (NO_HOLES feature enabled).
3583 * This hole is either in the middle of the cloning
3584 * range or at the beginning (fully overlaps it or
3585 * partially overlaps it).
3586 */
3587 if (new_key.offset != last_dest_end)
3588 drop_start = last_dest_end;
3589 else
3590 drop_start = new_key.offset;
3591
b6f3409b
SW
3592 /*
3593 * 1 - adjusting old extent (we may have to split it)
3594 * 1 - add new extent
3595 * 1 - inode update
3596 */
3597 trans = btrfs_start_transaction(root, 3);
a22285a6
YZ
3598 if (IS_ERR(trans)) {
3599 ret = PTR_ERR(trans);
3600 goto out;
3601 }
3602
c8a894d7
CM
3603 if (type == BTRFS_FILE_EXTENT_REG ||
3604 type == BTRFS_FILE_EXTENT_PREALLOC) {
d72c0842
LZ
3605 /*
3606 * a | --- range to clone ---| b
3607 * | ------------- extent ------------- |
3608 */
3609
93915584 3610 /* subtract range b */
d72c0842
LZ
3611 if (key.offset + datal > off + len)
3612 datal = off + len - key.offset;
3613
93915584 3614 /* subtract range a */
a22285a6
YZ
3615 if (off > key.offset) {
3616 datao += off - key.offset;
3617 datal -= off - key.offset;
3618 }
3619
5dc562c5 3620 ret = btrfs_drop_extents(trans, root, inode,
f82a9901 3621 drop_start,
a22285a6 3622 new_key.offset + datal,
2671485d 3623 1);
79787eaa 3624 if (ret) {
3f9e3df8 3625 if (ret != -EOPNOTSUPP)
00fdf13a 3626 btrfs_abort_transaction(trans,
66642832 3627 ret);
3a45bb20 3628 btrfs_end_transaction(trans);
79787eaa
JM
3629 goto out;
3630 }
a22285a6 3631
c5c9cd4d
SW
3632 ret = btrfs_insert_empty_item(trans, root, path,
3633 &new_key, size);
79787eaa 3634 if (ret) {
66642832 3635 btrfs_abort_transaction(trans, ret);
3a45bb20 3636 btrfs_end_transaction(trans);
79787eaa
JM
3637 goto out;
3638 }
c5c9cd4d
SW
3639
3640 leaf = path->nodes[0];
3641 slot = path->slots[0];
3642 write_extent_buffer(leaf, buf,
31840ae1
ZY
3643 btrfs_item_ptr_offset(leaf, slot),
3644 size);
ae01a0ab 3645
c5c9cd4d 3646 extent = btrfs_item_ptr(leaf, slot,
f46b5a66 3647 struct btrfs_file_extent_item);
c5c9cd4d 3648
c5c9cd4d
SW
3649 /* disko == 0 means it's a hole */
3650 if (!disko)
3651 datao = 0;
c5c9cd4d
SW
3652
3653 btrfs_set_file_extent_offset(leaf, extent,
3654 datao);
3655 btrfs_set_file_extent_num_bytes(leaf, extent,
3656 datal);
fcebe456 3657
c5c9cd4d
SW
3658 if (disko) {
3659 inode_add_bytes(inode, datal);
2ff7e61e 3660 ret = btrfs_inc_extent_ref(trans,
84f7d8e6 3661 root,
5d4f98a2
YZ
3662 disko, diskl, 0,
3663 root->root_key.objectid,
4a0cc7ca 3664 btrfs_ino(BTRFS_I(inode)),
b06c4bf5 3665 new_key.offset - datao);
79787eaa
JM
3666 if (ret) {
3667 btrfs_abort_transaction(trans,
79787eaa 3668 ret);
3a45bb20 3669 btrfs_end_transaction(trans);
79787eaa
JM
3670 goto out;
3671
3672 }
f46b5a66 3673 }
c5c9cd4d
SW
3674 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3675 u64 skip = 0;
3676 u64 trim = 0;
ed958762 3677
c5c9cd4d
SW
3678 if (off > key.offset) {
3679 skip = off - key.offset;
3680 new_key.offset += skip;
3681 }
d397712b 3682
aa42ffd9
LB
3683 if (key.offset + datal > off + len)
3684 trim = key.offset + datal - (off + len);
d397712b 3685
c5c9cd4d 3686 if (comp && (skip || trim)) {
c5c9cd4d 3687 ret = -EINVAL;
3a45bb20 3688 btrfs_end_transaction(trans);
c5c9cd4d
SW
3689 goto out;
3690 }
3691 size -= skip + trim;
3692 datal -= skip + trim;
a22285a6 3693
4a0ab9d7 3694 ret = clone_copy_inline_extent(inode,
8039d87d
FM
3695 trans, path,
3696 &new_key,
3697 drop_start,
3698 datal,
3699 skip, size, buf);
79787eaa 3700 if (ret) {
3f9e3df8 3701 if (ret != -EOPNOTSUPP)
3a29bc09 3702 btrfs_abort_transaction(trans,
8039d87d 3703 ret);
3a45bb20 3704 btrfs_end_transaction(trans);
79787eaa
JM
3705 goto out;
3706 }
c5c9cd4d
SW
3707 leaf = path->nodes[0];
3708 slot = path->slots[0];
f46b5a66 3709 }
c5c9cd4d 3710
7ffbb598
FM
3711 /* If we have an implicit hole (NO_HOLES feature). */
3712 if (drop_start < new_key.offset)
a2f392e4 3713 clone_update_extent_map(BTRFS_I(inode), trans,
14f59796 3714 NULL, drop_start,
7ffbb598
FM
3715 new_key.offset - drop_start);
3716
a2f392e4
NB
3717 clone_update_extent_map(BTRFS_I(inode), trans,
3718 path, 0, 0);
7ffbb598 3719
c5c9cd4d 3720 btrfs_mark_buffer_dirty(leaf);
b3b4aa74 3721 btrfs_release_path(path);
c5c9cd4d 3722
62e2390e 3723 last_dest_end = ALIGN(new_key.offset + datal,
0b246afa 3724 fs_info->sectorsize);
f82a9901
FM
3725 ret = clone_finish_inode_update(trans, inode,
3726 last_dest_end,
1c919a5e
MF
3727 destoff, olen,
3728 no_time_update);
f82a9901 3729 if (ret)
79787eaa 3730 goto out;
2c463823
FM
3731 if (new_key.offset + datal >= destoff + len)
3732 break;
a22285a6 3733 }
b3b4aa74 3734 btrfs_release_path(path);
df858e76 3735 key.offset = next_key_min_offset;
69ae5e44
WX
3736
3737 if (fatal_signal_pending(current)) {
3738 ret = -EINTR;
3739 goto out;
3740 }
f46b5a66 3741 }
f46b5a66 3742 ret = 0;
32b7c687 3743
f82a9901
FM
3744 if (last_dest_end < destoff + len) {
3745 /*
3746 * We have an implicit hole (NO_HOLES feature is enabled) that
3747 * fully or partially overlaps our cloning range at its end.
3748 */
3749 btrfs_release_path(path);
3750
3751 /*
3752 * 1 - remove extent(s)
3753 * 1 - inode update
3754 */
3755 trans = btrfs_start_transaction(root, 2);
3756 if (IS_ERR(trans)) {
3757 ret = PTR_ERR(trans);
3758 goto out;
3759 }
3760 ret = btrfs_drop_extents(trans, root, inode,
3761 last_dest_end, destoff + len, 1);
3762 if (ret) {
3763 if (ret != -EOPNOTSUPP)
66642832 3764 btrfs_abort_transaction(trans, ret);
3a45bb20 3765 btrfs_end_transaction(trans);
f82a9901
FM
3766 goto out;
3767 }
a2f392e4
NB
3768 clone_update_extent_map(BTRFS_I(inode), trans, NULL,
3769 last_dest_end,
3770 destoff + len - last_dest_end);
f82a9901 3771 ret = clone_finish_inode_update(trans, inode, destoff + len,
1c919a5e 3772 destoff, olen, no_time_update);
f82a9901
FM
3773 }
3774
f46b5a66 3775out:
32b7c687 3776 btrfs_free_path(path);
15351955 3777 kvfree(buf);
32b7c687
MF
3778 return ret;
3779}
3780
3db11b2e
ZB
3781static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
3782 u64 off, u64 olen, u64 destoff)
32b7c687 3783{
54563d41 3784 struct inode *inode = file_inode(file);
3db11b2e 3785 struct inode *src = file_inode(file_src);
0b246afa 3786 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
32b7c687 3787 struct btrfs_root *root = BTRFS_I(inode)->root;
32b7c687
MF
3788 int ret;
3789 u64 len = olen;
0b246afa 3790 u64 bs = fs_info->sb->s_blocksize;
3db11b2e 3791 int same_inode = src == inode;
32b7c687
MF
3792
3793 /*
3794 * TODO:
3795 * - split compressed inline extents. annoying: we need to
3796 * decompress into destination's address_space (the file offset
3797 * may change, so source mapping won't do), then recompress (or
3798 * otherwise reinsert) a subrange.
00fdf13a
LB
3799 *
3800 * - split destination inode's inline extents. The inline extents can
3801 * be either compressed or non-compressed.
32b7c687
MF
3802 */
3803
32b7c687
MF
3804 if (btrfs_root_readonly(root))
3805 return -EROFS;
3806
3db11b2e
ZB
3807 if (file_src->f_path.mnt != file->f_path.mnt ||
3808 src->i_sb != inode->i_sb)
3809 return -EXDEV;
32b7c687 3810
32b7c687 3811 if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3db11b2e 3812 return -EISDIR;
32b7c687
MF
3813
3814 if (!same_inode) {
293a8489 3815 btrfs_double_inode_lock(src, inode);
32b7c687 3816 } else {
5955102c 3817 inode_lock(src);
32b7c687
MF
3818 }
3819
b5c40d59
OS
3820 /* don't make the dst file partly checksummed */
3821 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3822 (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
3823 ret = -EINVAL;
3824 goto out_unlock;
3825 }
3826
32b7c687
MF
3827 /* determine range to clone */
3828 ret = -EINVAL;
3829 if (off + len > src->i_size || off + len < off)
3830 goto out_unlock;
3831 if (len == 0)
3832 olen = len = src->i_size - off;
3833 /* if we extend to eof, continue to block boundary */
3834 if (off + len == src->i_size)
3835 len = ALIGN(src->i_size, bs) - off;
3836
ccccf3d6
FM
3837 if (len == 0) {
3838 ret = 0;
3839 goto out_unlock;
3840 }
3841
32b7c687
MF
3842 /* verify the end result is block aligned */
3843 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3844 !IS_ALIGNED(destoff, bs))
3845 goto out_unlock;
3846
3847 /* verify if ranges are overlapped within the same file */
3848 if (same_inode) {
3849 if (destoff + len > off && destoff < off + len)
3850 goto out_unlock;
3851 }
3852
3853 if (destoff > inode->i_size) {
3854 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3855 if (ret)
3856 goto out_unlock;
3857 }
3858
c125b8bf
FM
3859 /*
3860 * Lock the target range too. Right after we replace the file extent
3861 * items in the fs tree (which now point to the cloned data), we might
3862 * have a worker replace them with extent items relative to a write
3863 * operation that was issued before this clone operation (i.e. confront
3864 * with inode.c:btrfs_finish_ordered_io).
3865 */
3866 if (same_inode) {
3867 u64 lock_start = min_t(u64, off, destoff);
3868 u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
32b7c687 3869
e0bd70c6 3870 ret = lock_extent_range(src, lock_start, lock_len, true);
c125b8bf 3871 } else {
e0bd70c6
FM
3872 ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
3873 true);
3874 }
3875 ASSERT(ret == 0);
3876 if (WARN_ON(ret)) {
3877 /* ranges in the io trees already unlocked */
3878 goto out_unlock;
c125b8bf 3879 }
32b7c687 3880
1c919a5e 3881 ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
32b7c687 3882
c125b8bf
FM
3883 if (same_inode) {
3884 u64 lock_start = min_t(u64, off, destoff);
3885 u64 lock_end = max_t(u64, off, destoff) + len - 1;
3886
3887 unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
3888 } else {
293a8489 3889 btrfs_double_extent_unlock(src, off, inode, destoff, len);
c125b8bf
FM
3890 }
3891 /*
3892 * Truncate page cache pages so that future reads will see the cloned
3893 * data immediately and not the previous data.
3894 */
65bfa658 3895 truncate_inode_pages_range(&inode->i_data,
09cbfeaf
KS
3896 round_down(destoff, PAGE_SIZE),
3897 round_up(destoff + len, PAGE_SIZE) - 1);
f46b5a66 3898out_unlock:
293a8489
MF
3899 if (!same_inode)
3900 btrfs_double_inode_unlock(src, inode);
3901 else
5955102c 3902 inode_unlock(src);
3db11b2e
ZB
3903 return ret;
3904}
3905
04b38d60
CH
3906int btrfs_clone_file_range(struct file *src_file, loff_t off,
3907 struct file *dst_file, loff_t destoff, u64 len)
3db11b2e 3908{
04b38d60 3909 return btrfs_clone_files(dst_file, src_file, off, len, destoff);
c5c9cd4d
SW
3910}
3911
6ef5ed0d
JB
3912static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3913{
496ad9aa 3914 struct inode *inode = file_inode(file);
0b246afa 3915 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6ef5ed0d
JB
3916 struct btrfs_root *root = BTRFS_I(inode)->root;
3917 struct btrfs_root *new_root;
3918 struct btrfs_dir_item *di;
3919 struct btrfs_trans_handle *trans;
3920 struct btrfs_path *path;
3921 struct btrfs_key location;
3922 struct btrfs_disk_key disk_key;
6ef5ed0d
JB
3923 u64 objectid = 0;
3924 u64 dir_id;
3c04ce01 3925 int ret;
6ef5ed0d
JB
3926
3927 if (!capable(CAP_SYS_ADMIN))
3928 return -EPERM;
3929
3c04ce01
MX
3930 ret = mnt_want_write_file(file);
3931 if (ret)
3932 return ret;
3933
3934 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3935 ret = -EFAULT;
3936 goto out;
3937 }
6ef5ed0d
JB
3938
3939 if (!objectid)
1cecf579 3940 objectid = BTRFS_FS_TREE_OBJECTID;
6ef5ed0d
JB
3941
3942 location.objectid = objectid;
3943 location.type = BTRFS_ROOT_ITEM_KEY;
3944 location.offset = (u64)-1;
3945
0b246afa 3946 new_root = btrfs_read_fs_root_no_name(fs_info, &location);
3c04ce01
MX
3947 if (IS_ERR(new_root)) {
3948 ret = PTR_ERR(new_root);
3949 goto out;
3950 }
6d6d2829 3951 if (!is_fstree(new_root->objectid)) {
3952 ret = -ENOENT;
3953 goto out;
3954 }
6ef5ed0d 3955
6ef5ed0d 3956 path = btrfs_alloc_path();
3c04ce01
MX
3957 if (!path) {
3958 ret = -ENOMEM;
3959 goto out;
3960 }
6ef5ed0d
JB
3961 path->leave_spinning = 1;
3962
3963 trans = btrfs_start_transaction(root, 1);
98d5dc13 3964 if (IS_ERR(trans)) {
6ef5ed0d 3965 btrfs_free_path(path);
3c04ce01
MX
3966 ret = PTR_ERR(trans);
3967 goto out;
6ef5ed0d
JB
3968 }
3969
0b246afa
JM
3970 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3971 di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
6ef5ed0d 3972 dir_id, "default", 7, 1);
cf1e99a4 3973 if (IS_ERR_OR_NULL(di)) {
6ef5ed0d 3974 btrfs_free_path(path);
3a45bb20 3975 btrfs_end_transaction(trans);
0b246afa 3976 btrfs_err(fs_info,
5d163e0e 3977 "Umm, you don't have the default diritem, this isn't going to work");
3c04ce01
MX
3978 ret = -ENOENT;
3979 goto out;
6ef5ed0d
JB
3980 }
3981
3982 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3983 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3984 btrfs_mark_buffer_dirty(path->nodes[0]);
3985 btrfs_free_path(path);
3986
0b246afa 3987 btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
3a45bb20 3988 btrfs_end_transaction(trans);
3c04ce01
MX
3989out:
3990 mnt_drop_write_file(file);
3991 return ret;
6ef5ed0d
JB
3992}
3993
c065f5b1
SY
3994static void get_block_group_info(struct list_head *groups_list,
3995 struct btrfs_ioctl_space_info *space)
bf5fc093
JB
3996{
3997 struct btrfs_block_group_cache *block_group;
3998
3999 space->total_bytes = 0;
4000 space->used_bytes = 0;
4001 space->flags = 0;
4002 list_for_each_entry(block_group, groups_list, list) {
4003 space->flags = block_group->flags;
4004 space->total_bytes += block_group->key.offset;
4005 space->used_bytes +=
4006 btrfs_block_group_used(&block_group->item);
4007 }
4008}
4009
2ff7e61e
JM
4010static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
4011 void __user *arg)
1406e432
JB
4012{
4013 struct btrfs_ioctl_space_args space_args;
4014 struct btrfs_ioctl_space_info space;
4015 struct btrfs_ioctl_space_info *dest;
7fde62bf 4016 struct btrfs_ioctl_space_info *dest_orig;
13f2696f 4017 struct btrfs_ioctl_space_info __user *user_dest;
1406e432 4018 struct btrfs_space_info *info;
315d8e98
CIK
4019 static const u64 types[] = {
4020 BTRFS_BLOCK_GROUP_DATA,
4021 BTRFS_BLOCK_GROUP_SYSTEM,
4022 BTRFS_BLOCK_GROUP_METADATA,
4023 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4024 };
bf5fc093 4025 int num_types = 4;
7fde62bf 4026 int alloc_size;
1406e432 4027 int ret = 0;
51788b1b 4028 u64 slot_count = 0;
bf5fc093 4029 int i, c;
1406e432
JB
4030
4031 if (copy_from_user(&space_args,
4032 (struct btrfs_ioctl_space_args __user *)arg,
4033 sizeof(space_args)))
4034 return -EFAULT;
4035
bf5fc093
JB
4036 for (i = 0; i < num_types; i++) {
4037 struct btrfs_space_info *tmp;
4038
4039 info = NULL;
4040 rcu_read_lock();
0b246afa 4041 list_for_each_entry_rcu(tmp, &fs_info->space_info,
bf5fc093
JB
4042 list) {
4043 if (tmp->flags == types[i]) {
4044 info = tmp;
4045 break;
4046 }
4047 }
4048 rcu_read_unlock();
4049
4050 if (!info)
4051 continue;
4052
4053 down_read(&info->groups_sem);
4054 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4055 if (!list_empty(&info->block_groups[c]))
4056 slot_count++;
4057 }
4058 up_read(&info->groups_sem);
4059 }
7fde62bf 4060
36523e95
DS
4061 /*
4062 * Global block reserve, exported as a space_info
4063 */
4064 slot_count++;
4065
7fde62bf
CM
4066 /* space_slots == 0 means they are asking for a count */
4067 if (space_args.space_slots == 0) {
4068 space_args.total_spaces = slot_count;
4069 goto out;
4070 }
bf5fc093 4071
51788b1b 4072 slot_count = min_t(u64, space_args.space_slots, slot_count);
bf5fc093 4073
7fde62bf 4074 alloc_size = sizeof(*dest) * slot_count;
bf5fc093 4075
7fde62bf
CM
4076 /* we generally have at most 6 or so space infos, one for each raid
4077 * level. So, a whole page should be more than enough for everyone
4078 */
09cbfeaf 4079 if (alloc_size > PAGE_SIZE)
7fde62bf
CM
4080 return -ENOMEM;
4081
1406e432 4082 space_args.total_spaces = 0;
8d2db785 4083 dest = kmalloc(alloc_size, GFP_KERNEL);
7fde62bf
CM
4084 if (!dest)
4085 return -ENOMEM;
4086 dest_orig = dest;
1406e432 4087
7fde62bf 4088 /* now we have a buffer to copy into */
bf5fc093
JB
4089 for (i = 0; i < num_types; i++) {
4090 struct btrfs_space_info *tmp;
4091
51788b1b
DR
4092 if (!slot_count)
4093 break;
4094
bf5fc093
JB
4095 info = NULL;
4096 rcu_read_lock();
0b246afa 4097 list_for_each_entry_rcu(tmp, &fs_info->space_info,
bf5fc093
JB
4098 list) {
4099 if (tmp->flags == types[i]) {
4100 info = tmp;
4101 break;
4102 }
4103 }
4104 rcu_read_unlock();
7fde62bf 4105
bf5fc093
JB
4106 if (!info)
4107 continue;
4108 down_read(&info->groups_sem);
4109 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4110 if (!list_empty(&info->block_groups[c])) {
c065f5b1
SY
4111 get_block_group_info(&info->block_groups[c],
4112 &space);
bf5fc093
JB
4113 memcpy(dest, &space, sizeof(space));
4114 dest++;
4115 space_args.total_spaces++;
51788b1b 4116 slot_count--;
bf5fc093 4117 }
51788b1b
DR
4118 if (!slot_count)
4119 break;
bf5fc093
JB
4120 }
4121 up_read(&info->groups_sem);
1406e432 4122 }
1406e432 4123
36523e95
DS
4124 /*
4125 * Add global block reserve
4126 */
4127 if (slot_count) {
0b246afa 4128 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
36523e95
DS
4129
4130 spin_lock(&block_rsv->lock);
4131 space.total_bytes = block_rsv->size;
4132 space.used_bytes = block_rsv->size - block_rsv->reserved;
4133 spin_unlock(&block_rsv->lock);
4134 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
4135 memcpy(dest, &space, sizeof(space));
4136 space_args.total_spaces++;
4137 }
4138
2eec6c81 4139 user_dest = (struct btrfs_ioctl_space_info __user *)
7fde62bf
CM
4140 (arg + sizeof(struct btrfs_ioctl_space_args));
4141
4142 if (copy_to_user(user_dest, dest_orig, alloc_size))
4143 ret = -EFAULT;
4144
4145 kfree(dest_orig);
4146out:
4147 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
1406e432
JB
4148 ret = -EFAULT;
4149
4150 return ret;
4151}
4152
9a8c28be
MX
4153static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
4154 void __user *argp)
46204592 4155{
46204592
SW
4156 struct btrfs_trans_handle *trans;
4157 u64 transid;
db5b493a 4158 int ret;
46204592 4159
d4edf39b 4160 trans = btrfs_attach_transaction_barrier(root);
ff7c1d33
MX
4161 if (IS_ERR(trans)) {
4162 if (PTR_ERR(trans) != -ENOENT)
4163 return PTR_ERR(trans);
4164
4165 /* No running transaction, don't bother */
4166 transid = root->fs_info->last_trans_committed;
4167 goto out;
4168 }
46204592 4169 transid = trans->transid;
3a45bb20 4170 ret = btrfs_commit_transaction_async(trans, 0);
8b2b2d3c 4171 if (ret) {
3a45bb20 4172 btrfs_end_transaction(trans);
db5b493a 4173 return ret;
8b2b2d3c 4174 }
ff7c1d33 4175out:
46204592
SW
4176 if (argp)
4177 if (copy_to_user(argp, &transid, sizeof(transid)))
4178 return -EFAULT;
4179 return 0;
4180}
4181
2ff7e61e 4182static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
9a8c28be 4183 void __user *argp)
46204592 4184{
46204592
SW
4185 u64 transid;
4186
4187 if (argp) {
4188 if (copy_from_user(&transid, argp, sizeof(transid)))
4189 return -EFAULT;
4190 } else {
4191 transid = 0; /* current trans */
4192 }
2ff7e61e 4193 return btrfs_wait_for_commit(fs_info, transid);
46204592
SW
4194}
4195
b8e95489 4196static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
475f6387 4197{
0b246afa 4198 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
475f6387 4199 struct btrfs_ioctl_scrub_args *sa;
b8e95489 4200 int ret;
475f6387
JS
4201
4202 if (!capable(CAP_SYS_ADMIN))
4203 return -EPERM;
4204
4205 sa = memdup_user(arg, sizeof(*sa));
4206 if (IS_ERR(sa))
4207 return PTR_ERR(sa);
4208
b8e95489
MX
4209 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4210 ret = mnt_want_write_file(file);
4211 if (ret)
4212 goto out;
4213 }
4214
0b246afa 4215 ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
63a212ab
SB
4216 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4217 0);
475f6387
JS
4218
4219 if (copy_to_user(arg, sa, sizeof(*sa)))
4220 ret = -EFAULT;
4221
b8e95489
MX
4222 if (!(sa->flags & BTRFS_SCRUB_READONLY))
4223 mnt_drop_write_file(file);
4224out:
475f6387
JS
4225 kfree(sa);
4226 return ret;
4227}
4228
2ff7e61e 4229static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
475f6387
JS
4230{
4231 if (!capable(CAP_SYS_ADMIN))
4232 return -EPERM;
4233
2ff7e61e 4234 return btrfs_scrub_cancel(fs_info);
475f6387
JS
4235}
4236
2ff7e61e 4237static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
475f6387
JS
4238 void __user *arg)
4239{
4240 struct btrfs_ioctl_scrub_args *sa;
4241 int ret;
4242
4243 if (!capable(CAP_SYS_ADMIN))
4244 return -EPERM;
4245
4246 sa = memdup_user(arg, sizeof(*sa));
4247 if (IS_ERR(sa))
4248 return PTR_ERR(sa);
4249
2ff7e61e 4250 ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
475f6387
JS
4251
4252 if (copy_to_user(arg, sa, sizeof(*sa)))
4253 ret = -EFAULT;
4254
4255 kfree(sa);
4256 return ret;
4257}
4258
2ff7e61e 4259static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
b27f7c0c 4260 void __user *arg)
c11d2c23
SB
4261{
4262 struct btrfs_ioctl_get_dev_stats *sa;
4263 int ret;
4264
c11d2c23
SB
4265 sa = memdup_user(arg, sizeof(*sa));
4266 if (IS_ERR(sa))
4267 return PTR_ERR(sa);
4268
b27f7c0c
DS
4269 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4270 kfree(sa);
4271 return -EPERM;
4272 }
4273
2ff7e61e 4274 ret = btrfs_get_dev_stats(fs_info, sa);
c11d2c23
SB
4275
4276 if (copy_to_user(arg, sa, sizeof(*sa)))
4277 ret = -EFAULT;
4278
4279 kfree(sa);
4280 return ret;
4281}
4282
2ff7e61e
JM
4283static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
4284 void __user *arg)
3f6bcfbd
SB
4285{
4286 struct btrfs_ioctl_dev_replace_args *p;
4287 int ret;
4288
4289 if (!capable(CAP_SYS_ADMIN))
4290 return -EPERM;
4291
4292 p = memdup_user(arg, sizeof(*p));
4293 if (IS_ERR(p))
4294 return PTR_ERR(p);
4295
4296 switch (p->cmd) {
4297 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
bc98a42c 4298 if (sb_rdonly(fs_info->sb)) {
adfa97cb
ID
4299 ret = -EROFS;
4300 goto out;
4301 }
171938e5 4302 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
e57138b3 4303 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3f6bcfbd 4304 } else {
2ff7e61e 4305 ret = btrfs_dev_replace_by_ioctl(fs_info, p);
171938e5 4306 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3f6bcfbd
SB
4307 }
4308 break;
4309 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
0b246afa 4310 btrfs_dev_replace_status(fs_info, p);
3f6bcfbd
SB
4311 ret = 0;
4312 break;
4313 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
17d202b9 4314 p->result = btrfs_dev_replace_cancel(fs_info);
97282031 4315 ret = 0;
3f6bcfbd
SB
4316 break;
4317 default:
4318 ret = -EINVAL;
4319 break;
4320 }
4321
4322 if (copy_to_user(arg, p, sizeof(*p)))
4323 ret = -EFAULT;
adfa97cb 4324out:
3f6bcfbd
SB
4325 kfree(p);
4326 return ret;
4327}
4328
d7728c96
JS
4329static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4330{
4331 int ret = 0;
4332 int i;
740c3d22 4333 u64 rel_ptr;
d7728c96 4334 int size;
806468f8 4335 struct btrfs_ioctl_ino_path_args *ipa = NULL;
d7728c96
JS
4336 struct inode_fs_paths *ipath = NULL;
4337 struct btrfs_path *path;
4338
82b22ac8 4339 if (!capable(CAP_DAC_READ_SEARCH))
d7728c96
JS
4340 return -EPERM;
4341
4342 path = btrfs_alloc_path();
4343 if (!path) {
4344 ret = -ENOMEM;
4345 goto out;
4346 }
4347
4348 ipa = memdup_user(arg, sizeof(*ipa));
4349 if (IS_ERR(ipa)) {
4350 ret = PTR_ERR(ipa);
4351 ipa = NULL;
4352 goto out;
4353 }
4354
4355 size = min_t(u32, ipa->size, 4096);
4356 ipath = init_ipath(size, root, path);
4357 if (IS_ERR(ipath)) {
4358 ret = PTR_ERR(ipath);
4359 ipath = NULL;
4360 goto out;
4361 }
4362
4363 ret = paths_from_inode(ipa->inum, ipath);
4364 if (ret < 0)
4365 goto out;
4366
4367 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
745c4d8e
JM
4368 rel_ptr = ipath->fspath->val[i] -
4369 (u64)(unsigned long)ipath->fspath->val;
740c3d22 4370 ipath->fspath->val[i] = rel_ptr;
d7728c96
JS
4371 }
4372
718dc5fa
OS
4373 ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4374 ipath->fspath, size);
d7728c96
JS
4375 if (ret) {
4376 ret = -EFAULT;
4377 goto out;
4378 }
4379
4380out:
4381 btrfs_free_path(path);
4382 free_ipath(ipath);
4383 kfree(ipa);
4384
4385 return ret;
4386}
4387
4388static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4389{
4390 struct btrfs_data_container *inodes = ctx;
4391 const size_t c = 3 * sizeof(u64);
4392
4393 if (inodes->bytes_left >= c) {
4394 inodes->bytes_left -= c;
4395 inodes->val[inodes->elem_cnt] = inum;
4396 inodes->val[inodes->elem_cnt + 1] = offset;
4397 inodes->val[inodes->elem_cnt + 2] = root;
4398 inodes->elem_cnt += 3;
4399 } else {
4400 inodes->bytes_missing += c - inodes->bytes_left;
4401 inodes->bytes_left = 0;
4402 inodes->elem_missed += 3;
4403 }
4404
4405 return 0;
4406}
4407
2ff7e61e 4408static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
d24a67b2 4409 void __user *arg, int version)
d7728c96
JS
4410{
4411 int ret = 0;
4412 int size;
d7728c96
JS
4413 struct btrfs_ioctl_logical_ino_args *loi;
4414 struct btrfs_data_container *inodes = NULL;
4415 struct btrfs_path *path = NULL;
d24a67b2 4416 bool ignore_offset;
d7728c96
JS
4417
4418 if (!capable(CAP_SYS_ADMIN))
4419 return -EPERM;
4420
4421 loi = memdup_user(arg, sizeof(*loi));
7b9ea627
SV
4422 if (IS_ERR(loi))
4423 return PTR_ERR(loi);
d7728c96 4424
d24a67b2
ZB
4425 if (version == 1) {
4426 ignore_offset = false;
b115e3bc 4427 size = min_t(u32, loi->size, SZ_64K);
d24a67b2
ZB
4428 } else {
4429 /* All reserved bits must be 0 for now */
4430 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4431 ret = -EINVAL;
4432 goto out_loi;
4433 }
4434 /* Only accept flags we have defined so far */
4435 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4436 ret = -EINVAL;
4437 goto out_loi;
4438 }
4439 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
b115e3bc 4440 size = min_t(u32, loi->size, SZ_16M);
d24a67b2
ZB
4441 }
4442
d7728c96
JS
4443 path = btrfs_alloc_path();
4444 if (!path) {
4445 ret = -ENOMEM;
4446 goto out;
4447 }
4448
d7728c96
JS
4449 inodes = init_data_container(size);
4450 if (IS_ERR(inodes)) {
4451 ret = PTR_ERR(inodes);
4452 inodes = NULL;
4453 goto out;
4454 }
4455
2ff7e61e 4456 ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
d24a67b2 4457 build_ino_list, inodes, ignore_offset);
df031f07 4458 if (ret == -EINVAL)
d7728c96
JS
4459 ret = -ENOENT;
4460 if (ret < 0)
4461 goto out;
4462
718dc5fa
OS
4463 ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4464 size);
d7728c96
JS
4465 if (ret)
4466 ret = -EFAULT;
4467
4468out:
4469 btrfs_free_path(path);
f54de068 4470 kvfree(inodes);
d24a67b2 4471out_loi:
d7728c96
JS
4472 kfree(loi);
4473
4474 return ret;
4475}
4476
008ef096 4477void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
c9e9f97b
ID
4478 struct btrfs_ioctl_balance_args *bargs)
4479{
4480 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4481
4482 bargs->flags = bctl->flags;
4483
3009a62f 4484 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
837d5b6e
ID
4485 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4486 if (atomic_read(&fs_info->balance_pause_req))
4487 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
a7e99c69
ID
4488 if (atomic_read(&fs_info->balance_cancel_req))
4489 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
837d5b6e 4490
c9e9f97b
ID
4491 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4492 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4493 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
19a39dce 4494
008ef096
DS
4495 spin_lock(&fs_info->balance_lock);
4496 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4497 spin_unlock(&fs_info->balance_lock);
c9e9f97b
ID
4498}
4499
9ba1f6e4 4500static long btrfs_ioctl_balance(struct file *file, void __user *arg)
c9e9f97b 4501{
496ad9aa 4502 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
c9e9f97b
ID
4503 struct btrfs_fs_info *fs_info = root->fs_info;
4504 struct btrfs_ioctl_balance_args *bargs;
4505 struct btrfs_balance_control *bctl;
ed0fb78f 4506 bool need_unlock; /* for mut. excl. ops lock */
c9e9f97b
ID
4507 int ret;
4508
4509 if (!capable(CAP_SYS_ADMIN))
4510 return -EPERM;
4511
e54bfa31 4512 ret = mnt_want_write_file(file);
9ba1f6e4
LB
4513 if (ret)
4514 return ret;
4515
ed0fb78f 4516again:
171938e5 4517 if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
ed0fb78f
ID
4518 mutex_lock(&fs_info->balance_mutex);
4519 need_unlock = true;
4520 goto locked;
4521 }
4522
4523 /*
01327610 4524 * mut. excl. ops lock is locked. Three possibilities:
ed0fb78f
ID
4525 * (1) some other op is running
4526 * (2) balance is running
4527 * (3) balance is paused -- special case (think resume)
4528 */
c9e9f97b 4529 mutex_lock(&fs_info->balance_mutex);
ed0fb78f
ID
4530 if (fs_info->balance_ctl) {
4531 /* this is either (2) or (3) */
3009a62f 4532 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
ed0fb78f 4533 mutex_unlock(&fs_info->balance_mutex);
dccdb07b
DS
4534 /*
4535 * Lock released to allow other waiters to continue,
4536 * we'll reexamine the status again.
4537 */
ed0fb78f
ID
4538 mutex_lock(&fs_info->balance_mutex);
4539
4540 if (fs_info->balance_ctl &&
3009a62f 4541 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
ed0fb78f
ID
4542 /* this is (3) */
4543 need_unlock = false;
4544 goto locked;
4545 }
4546
4547 mutex_unlock(&fs_info->balance_mutex);
ed0fb78f
ID
4548 goto again;
4549 } else {
4550 /* this is (2) */
4551 mutex_unlock(&fs_info->balance_mutex);
4552 ret = -EINPROGRESS;
4553 goto out;
4554 }
4555 } else {
4556 /* this is (1) */
4557 mutex_unlock(&fs_info->balance_mutex);
e57138b3 4558 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
ed0fb78f
ID
4559 goto out;
4560 }
4561
4562locked:
171938e5 4563 BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
c9e9f97b
ID
4564
4565 if (arg) {
4566 bargs = memdup_user(arg, sizeof(*bargs));
4567 if (IS_ERR(bargs)) {
4568 ret = PTR_ERR(bargs);
ed0fb78f 4569 goto out_unlock;
c9e9f97b 4570 }
de322263
ID
4571
4572 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4573 if (!fs_info->balance_ctl) {
4574 ret = -ENOTCONN;
4575 goto out_bargs;
4576 }
4577
4578 bctl = fs_info->balance_ctl;
4579 spin_lock(&fs_info->balance_lock);
4580 bctl->flags |= BTRFS_BALANCE_RESUME;
4581 spin_unlock(&fs_info->balance_lock);
4582
4583 goto do_balance;
4584 }
c9e9f97b
ID
4585 } else {
4586 bargs = NULL;
4587 }
4588
ed0fb78f 4589 if (fs_info->balance_ctl) {
837d5b6e
ID
4590 ret = -EINPROGRESS;
4591 goto out_bargs;
4592 }
4593
8d2db785 4594 bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
c9e9f97b
ID
4595 if (!bctl) {
4596 ret = -ENOMEM;
4597 goto out_bargs;
4598 }
4599
c9e9f97b
ID
4600 if (arg) {
4601 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4602 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4603 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4604
4605 bctl->flags = bargs->flags;
f43ffb60
ID
4606 } else {
4607 /* balance everything - no filters */
4608 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
c9e9f97b
ID
4609 }
4610
8eb93459
DS
4611 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4612 ret = -EINVAL;
0f89abf5 4613 goto out_bctl;
8eb93459
DS
4614 }
4615
de322263 4616do_balance:
c9e9f97b 4617 /*
149196a2
DS
4618 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
4619 * btrfs_balance. bctl is freed in reset_balance_state, or, if
4620 * restriper was paused all the way until unmount, in free_fs_info.
4621 * The flag should be cleared after reset_balance_state.
c9e9f97b 4622 */
ed0fb78f
ID
4623 need_unlock = false;
4624
6fcf6e2b 4625 ret = btrfs_balance(fs_info, bctl, bargs);
0f89abf5 4626 bctl = NULL;
ed0fb78f 4627
c9e9f97b
ID
4628 if (arg) {
4629 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4630 ret = -EFAULT;
4631 }
4632
0f89abf5
CE
4633out_bctl:
4634 kfree(bctl);
c9e9f97b
ID
4635out_bargs:
4636 kfree(bargs);
ed0fb78f 4637out_unlock:
c9e9f97b 4638 mutex_unlock(&fs_info->balance_mutex);
ed0fb78f 4639 if (need_unlock)
171938e5 4640 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
ed0fb78f 4641out:
e54bfa31 4642 mnt_drop_write_file(file);
c9e9f97b
ID
4643 return ret;
4644}
4645
2ff7e61e 4646static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
837d5b6e
ID
4647{
4648 if (!capable(CAP_SYS_ADMIN))
4649 return -EPERM;
4650
4651 switch (cmd) {
4652 case BTRFS_BALANCE_CTL_PAUSE:
0b246afa 4653 return btrfs_pause_balance(fs_info);
a7e99c69 4654 case BTRFS_BALANCE_CTL_CANCEL:
0b246afa 4655 return btrfs_cancel_balance(fs_info);
837d5b6e
ID
4656 }
4657
4658 return -EINVAL;
4659}
4660
2ff7e61e 4661static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
19a39dce
ID
4662 void __user *arg)
4663{
19a39dce
ID
4664 struct btrfs_ioctl_balance_args *bargs;
4665 int ret = 0;
4666
4667 if (!capable(CAP_SYS_ADMIN))
4668 return -EPERM;
4669
4670 mutex_lock(&fs_info->balance_mutex);
4671 if (!fs_info->balance_ctl) {
4672 ret = -ENOTCONN;
4673 goto out;
4674 }
4675
8d2db785 4676 bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
19a39dce
ID
4677 if (!bargs) {
4678 ret = -ENOMEM;
4679 goto out;
4680 }
4681
008ef096 4682 btrfs_update_ioctl_balance_args(fs_info, bargs);
19a39dce
ID
4683
4684 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4685 ret = -EFAULT;
4686
4687 kfree(bargs);
4688out:
4689 mutex_unlock(&fs_info->balance_mutex);
4690 return ret;
4691}
4692
905b0dda 4693static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
5d13a37b 4694{
0b246afa
JM
4695 struct inode *inode = file_inode(file);
4696 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5d13a37b
AJ
4697 struct btrfs_ioctl_quota_ctl_args *sa;
4698 struct btrfs_trans_handle *trans = NULL;
4699 int ret;
4700 int err;
4701
4702 if (!capable(CAP_SYS_ADMIN))
4703 return -EPERM;
4704
905b0dda
MX
4705 ret = mnt_want_write_file(file);
4706 if (ret)
4707 return ret;
5d13a37b
AJ
4708
4709 sa = memdup_user(arg, sizeof(*sa));
905b0dda
MX
4710 if (IS_ERR(sa)) {
4711 ret = PTR_ERR(sa);
4712 goto drop_write;
4713 }
5d13a37b 4714
0b246afa
JM
4715 down_write(&fs_info->subvol_sem);
4716 trans = btrfs_start_transaction(fs_info->tree_root, 2);
2f232036
JS
4717 if (IS_ERR(trans)) {
4718 ret = PTR_ERR(trans);
4719 goto out;
5d13a37b
AJ
4720 }
4721
4722 switch (sa->cmd) {
4723 case BTRFS_QUOTA_CTL_ENABLE:
0b246afa 4724 ret = btrfs_quota_enable(trans, fs_info);
5d13a37b
AJ
4725 break;
4726 case BTRFS_QUOTA_CTL_DISABLE:
0b246afa 4727 ret = btrfs_quota_disable(trans, fs_info);
5d13a37b 4728 break;
5d13a37b
AJ
4729 default:
4730 ret = -EINVAL;
4731 break;
4732 }
4733
3a45bb20 4734 err = btrfs_commit_transaction(trans);
2f232036
JS
4735 if (err && !ret)
4736 ret = err;
5d13a37b
AJ
4737out:
4738 kfree(sa);
0b246afa 4739 up_write(&fs_info->subvol_sem);
905b0dda
MX
4740drop_write:
4741 mnt_drop_write_file(file);
5d13a37b
AJ
4742 return ret;
4743}
4744
905b0dda 4745static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
5d13a37b 4746{
0b246afa
JM
4747 struct inode *inode = file_inode(file);
4748 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4749 struct btrfs_root *root = BTRFS_I(inode)->root;
5d13a37b
AJ
4750 struct btrfs_ioctl_qgroup_assign_args *sa;
4751 struct btrfs_trans_handle *trans;
4752 int ret;
4753 int err;
4754
4755 if (!capable(CAP_SYS_ADMIN))
4756 return -EPERM;
4757
905b0dda
MX
4758 ret = mnt_want_write_file(file);
4759 if (ret)
4760 return ret;
5d13a37b
AJ
4761
4762 sa = memdup_user(arg, sizeof(*sa));
905b0dda
MX
4763 if (IS_ERR(sa)) {
4764 ret = PTR_ERR(sa);
4765 goto drop_write;
4766 }
5d13a37b
AJ
4767
4768 trans = btrfs_join_transaction(root);
4769 if (IS_ERR(trans)) {
4770 ret = PTR_ERR(trans);
4771 goto out;
4772 }
4773
5d13a37b 4774 if (sa->assign) {
0b246afa 4775 ret = btrfs_add_qgroup_relation(trans, fs_info,
5d13a37b
AJ
4776 sa->src, sa->dst);
4777 } else {
0b246afa 4778 ret = btrfs_del_qgroup_relation(trans, fs_info,
5d13a37b
AJ
4779 sa->src, sa->dst);
4780 }
4781
e082f563 4782 /* update qgroup status and info */
0b246afa 4783 err = btrfs_run_qgroups(trans, fs_info);
e082f563 4784 if (err < 0)
0b246afa
JM
4785 btrfs_handle_fs_error(fs_info, err,
4786 "failed to update qgroup status and info");
3a45bb20 4787 err = btrfs_end_transaction(trans);
5d13a37b
AJ
4788 if (err && !ret)
4789 ret = err;
4790
4791out:
4792 kfree(sa);
905b0dda
MX
4793drop_write:
4794 mnt_drop_write_file(file);
5d13a37b
AJ
4795 return ret;
4796}
4797
905b0dda 4798static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
5d13a37b 4799{
0b246afa
JM
4800 struct inode *inode = file_inode(file);
4801 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4802 struct btrfs_root *root = BTRFS_I(inode)->root;
5d13a37b
AJ
4803 struct btrfs_ioctl_qgroup_create_args *sa;
4804 struct btrfs_trans_handle *trans;
4805 int ret;
4806 int err;
4807
4808 if (!capable(CAP_SYS_ADMIN))
4809 return -EPERM;
4810
905b0dda
MX
4811 ret = mnt_want_write_file(file);
4812 if (ret)
4813 return ret;
5d13a37b
AJ
4814
4815 sa = memdup_user(arg, sizeof(*sa));
905b0dda
MX
4816 if (IS_ERR(sa)) {
4817 ret = PTR_ERR(sa);
4818 goto drop_write;
4819 }
5d13a37b 4820
d86e56cf
MX
4821 if (!sa->qgroupid) {
4822 ret = -EINVAL;
4823 goto out;
4824 }
4825
5d13a37b
AJ
4826 trans = btrfs_join_transaction(root);
4827 if (IS_ERR(trans)) {
4828 ret = PTR_ERR(trans);
4829 goto out;
4830 }
4831
5d13a37b 4832 if (sa->create) {
0b246afa 4833 ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
5d13a37b 4834 } else {
0b246afa 4835 ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
5d13a37b
AJ
4836 }
4837
3a45bb20 4838 err = btrfs_end_transaction(trans);
5d13a37b
AJ
4839 if (err && !ret)
4840 ret = err;
4841
4842out:
4843 kfree(sa);
905b0dda
MX
4844drop_write:
4845 mnt_drop_write_file(file);
5d13a37b
AJ
4846 return ret;
4847}
4848
905b0dda 4849static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
5d13a37b 4850{
0b246afa
JM
4851 struct inode *inode = file_inode(file);
4852 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4853 struct btrfs_root *root = BTRFS_I(inode)->root;
5d13a37b
AJ
4854 struct btrfs_ioctl_qgroup_limit_args *sa;
4855 struct btrfs_trans_handle *trans;
4856 int ret;
4857 int err;
4858 u64 qgroupid;
4859
4860 if (!capable(CAP_SYS_ADMIN))
4861 return -EPERM;
4862
905b0dda
MX
4863 ret = mnt_want_write_file(file);
4864 if (ret)
4865 return ret;
5d13a37b
AJ
4866
4867 sa = memdup_user(arg, sizeof(*sa));
905b0dda
MX
4868 if (IS_ERR(sa)) {
4869 ret = PTR_ERR(sa);
4870 goto drop_write;
4871 }
5d13a37b
AJ
4872
4873 trans = btrfs_join_transaction(root);
4874 if (IS_ERR(trans)) {
4875 ret = PTR_ERR(trans);
4876 goto out;
4877 }
4878
4879 qgroupid = sa->qgroupid;
4880 if (!qgroupid) {
4881 /* take the current subvol as qgroup */
4882 qgroupid = root->root_key.objectid;
4883 }
4884
0b246afa 4885 ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
5d13a37b 4886
3a45bb20 4887 err = btrfs_end_transaction(trans);
5d13a37b
AJ
4888 if (err && !ret)
4889 ret = err;
4890
4891out:
4892 kfree(sa);
905b0dda
MX
4893drop_write:
4894 mnt_drop_write_file(file);
5d13a37b
AJ
4895 return ret;
4896}
4897
2f232036
JS
4898static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4899{
0b246afa
JM
4900 struct inode *inode = file_inode(file);
4901 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2f232036
JS
4902 struct btrfs_ioctl_quota_rescan_args *qsa;
4903 int ret;
4904
4905 if (!capable(CAP_SYS_ADMIN))
4906 return -EPERM;
4907
4908 ret = mnt_want_write_file(file);
4909 if (ret)
4910 return ret;
4911
4912 qsa = memdup_user(arg, sizeof(*qsa));
4913 if (IS_ERR(qsa)) {
4914 ret = PTR_ERR(qsa);
4915 goto drop_write;
4916 }
4917
4918 if (qsa->flags) {
4919 ret = -EINVAL;
4920 goto out;
4921 }
4922
0b246afa 4923 ret = btrfs_qgroup_rescan(fs_info);
2f232036
JS
4924
4925out:
4926 kfree(qsa);
4927drop_write:
4928 mnt_drop_write_file(file);
4929 return ret;
4930}
4931
4932static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
4933{
0b246afa
JM
4934 struct inode *inode = file_inode(file);
4935 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2f232036
JS
4936 struct btrfs_ioctl_quota_rescan_args *qsa;
4937 int ret = 0;
4938
4939 if (!capable(CAP_SYS_ADMIN))
4940 return -EPERM;
4941
8d2db785 4942 qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
2f232036
JS
4943 if (!qsa)
4944 return -ENOMEM;
4945
0b246afa 4946 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
2f232036 4947 qsa->flags = 1;
0b246afa 4948 qsa->progress = fs_info->qgroup_rescan_progress.objectid;
2f232036
JS
4949 }
4950
4951 if (copy_to_user(arg, qsa, sizeof(*qsa)))
4952 ret = -EFAULT;
4953
4954 kfree(qsa);
4955 return ret;
4956}
4957
57254b6e
JS
4958static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
4959{
0b246afa
JM
4960 struct inode *inode = file_inode(file);
4961 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
57254b6e
JS
4962
4963 if (!capable(CAP_SYS_ADMIN))
4964 return -EPERM;
4965
0b246afa 4966 return btrfs_qgroup_wait_for_completion(fs_info, true);
57254b6e
JS
4967}
4968
abccd00f
HM
4969static long _btrfs_ioctl_set_received_subvol(struct file *file,
4970 struct btrfs_ioctl_received_subvol_args *sa)
8ea05e3a 4971{
496ad9aa 4972 struct inode *inode = file_inode(file);
0b246afa 4973 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8ea05e3a
AB
4974 struct btrfs_root *root = BTRFS_I(inode)->root;
4975 struct btrfs_root_item *root_item = &root->root_item;
4976 struct btrfs_trans_handle *trans;
c2050a45 4977 struct timespec ct = current_time(inode);
8ea05e3a 4978 int ret = 0;
dd5f9615 4979 int received_uuid_changed;
8ea05e3a 4980
bd60ea0f
DS
4981 if (!inode_owner_or_capable(inode))
4982 return -EPERM;
4983
8ea05e3a
AB
4984 ret = mnt_want_write_file(file);
4985 if (ret < 0)
4986 return ret;
4987
0b246afa 4988 down_write(&fs_info->subvol_sem);
8ea05e3a 4989
4a0cc7ca 4990 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
8ea05e3a
AB
4991 ret = -EINVAL;
4992 goto out;
4993 }
4994
4995 if (btrfs_root_readonly(root)) {
4996 ret = -EROFS;
4997 goto out;
4998 }
4999
dd5f9615
SB
5000 /*
5001 * 1 - root item
5002 * 2 - uuid items (received uuid + subvol uuid)
5003 */
5004 trans = btrfs_start_transaction(root, 3);
8ea05e3a
AB
5005 if (IS_ERR(trans)) {
5006 ret = PTR_ERR(trans);
5007 trans = NULL;
5008 goto out;
5009 }
5010
5011 sa->rtransid = trans->transid;
5012 sa->rtime.sec = ct.tv_sec;
5013 sa->rtime.nsec = ct.tv_nsec;
5014
dd5f9615
SB
5015 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5016 BTRFS_UUID_SIZE);
5017 if (received_uuid_changed &&
d87ff758
NB
5018 !btrfs_is_empty_uuid(root_item->received_uuid)) {
5019 ret = btrfs_uuid_tree_rem(trans, fs_info,
5020 root_item->received_uuid,
5021 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5022 root->root_key.objectid);
5023 if (ret && ret != -ENOENT) {
5024 btrfs_abort_transaction(trans, ret);
5025 btrfs_end_transaction(trans);
5026 goto out;
5027 }
5028 }
8ea05e3a
AB
5029 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
5030 btrfs_set_root_stransid(root_item, sa->stransid);
5031 btrfs_set_root_rtransid(root_item, sa->rtransid);
3cae210f
QW
5032 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
5033 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
5034 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
5035 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
8ea05e3a 5036
0b246afa 5037 ret = btrfs_update_root(trans, fs_info->tree_root,
8ea05e3a
AB
5038 &root->root_key, &root->root_item);
5039 if (ret < 0) {
3a45bb20 5040 btrfs_end_transaction(trans);
8ea05e3a 5041 goto out;
dd5f9615
SB
5042 }
5043 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
0b246afa 5044 ret = btrfs_uuid_tree_add(trans, fs_info, sa->uuid,
dd5f9615
SB
5045 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5046 root->root_key.objectid);
5047 if (ret < 0 && ret != -EEXIST) {
66642832 5048 btrfs_abort_transaction(trans, ret);
efd38150 5049 btrfs_end_transaction(trans);
8ea05e3a 5050 goto out;
dd5f9615
SB
5051 }
5052 }
3a45bb20 5053 ret = btrfs_commit_transaction(trans);
abccd00f 5054out:
0b246afa 5055 up_write(&fs_info->subvol_sem);
abccd00f
HM
5056 mnt_drop_write_file(file);
5057 return ret;
5058}
5059
5060#ifdef CONFIG_64BIT
5061static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5062 void __user *arg)
5063{
5064 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5065 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5066 int ret = 0;
5067
5068 args32 = memdup_user(arg, sizeof(*args32));
7b9ea627
SV
5069 if (IS_ERR(args32))
5070 return PTR_ERR(args32);
abccd00f 5071
8d2db785 5072 args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
84dbeb87
DC
5073 if (!args64) {
5074 ret = -ENOMEM;
abccd00f
HM
5075 goto out;
5076 }
5077
5078 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5079 args64->stransid = args32->stransid;
5080 args64->rtransid = args32->rtransid;
5081 args64->stime.sec = args32->stime.sec;
5082 args64->stime.nsec = args32->stime.nsec;
5083 args64->rtime.sec = args32->rtime.sec;
5084 args64->rtime.nsec = args32->rtime.nsec;
5085 args64->flags = args32->flags;
5086
5087 ret = _btrfs_ioctl_set_received_subvol(file, args64);
5088 if (ret)
5089 goto out;
5090
5091 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5092 args32->stransid = args64->stransid;
5093 args32->rtransid = args64->rtransid;
5094 args32->stime.sec = args64->stime.sec;
5095 args32->stime.nsec = args64->stime.nsec;
5096 args32->rtime.sec = args64->rtime.sec;
5097 args32->rtime.nsec = args64->rtime.nsec;
5098 args32->flags = args64->flags;
5099
5100 ret = copy_to_user(arg, args32, sizeof(*args32));
5101 if (ret)
5102 ret = -EFAULT;
5103
5104out:
5105 kfree(args32);
5106 kfree(args64);
5107 return ret;
5108}
5109#endif
5110
5111static long btrfs_ioctl_set_received_subvol(struct file *file,
5112 void __user *arg)
5113{
5114 struct btrfs_ioctl_received_subvol_args *sa = NULL;
5115 int ret = 0;
5116
5117 sa = memdup_user(arg, sizeof(*sa));
7b9ea627
SV
5118 if (IS_ERR(sa))
5119 return PTR_ERR(sa);
abccd00f
HM
5120
5121 ret = _btrfs_ioctl_set_received_subvol(file, sa);
5122
5123 if (ret)
5124 goto out;
5125
8ea05e3a
AB
5126 ret = copy_to_user(arg, sa, sizeof(*sa));
5127 if (ret)
5128 ret = -EFAULT;
5129
5130out:
5131 kfree(sa);
8ea05e3a
AB
5132 return ret;
5133}
5134
867ab667 5135static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5136{
0b246afa
JM
5137 struct inode *inode = file_inode(file);
5138 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
a1b83ac5 5139 size_t len;
867ab667 5140 int ret;
a1b83ac5
AJ
5141 char label[BTRFS_LABEL_SIZE];
5142
0b246afa
JM
5143 spin_lock(&fs_info->super_lock);
5144 memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5145 spin_unlock(&fs_info->super_lock);
a1b83ac5
AJ
5146
5147 len = strnlen(label, BTRFS_LABEL_SIZE);
867ab667 5148
5149 if (len == BTRFS_LABEL_SIZE) {
0b246afa
JM
5150 btrfs_warn(fs_info,
5151 "label is too long, return the first %zu bytes",
5152 --len);
867ab667 5153 }
5154
867ab667 5155 ret = copy_to_user(arg, label, len);
867ab667 5156
5157 return ret ? -EFAULT : 0;
5158}
5159
a8bfd4ab 5160static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5161{
0b246afa
JM
5162 struct inode *inode = file_inode(file);
5163 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5164 struct btrfs_root *root = BTRFS_I(inode)->root;
5165 struct btrfs_super_block *super_block = fs_info->super_copy;
a8bfd4ab 5166 struct btrfs_trans_handle *trans;
5167 char label[BTRFS_LABEL_SIZE];
5168 int ret;
5169
5170 if (!capable(CAP_SYS_ADMIN))
5171 return -EPERM;
5172
5173 if (copy_from_user(label, arg, sizeof(label)))
5174 return -EFAULT;
5175
5176 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
0b246afa 5177 btrfs_err(fs_info,
5d163e0e
JM
5178 "unable to set label with more than %d bytes",
5179 BTRFS_LABEL_SIZE - 1);
a8bfd4ab 5180 return -EINVAL;
5181 }
5182
5183 ret = mnt_want_write_file(file);
5184 if (ret)
5185 return ret;
5186
a8bfd4ab 5187 trans = btrfs_start_transaction(root, 0);
5188 if (IS_ERR(trans)) {
5189 ret = PTR_ERR(trans);
5190 goto out_unlock;
5191 }
5192
0b246afa 5193 spin_lock(&fs_info->super_lock);
a8bfd4ab 5194 strcpy(super_block->label, label);
0b246afa 5195 spin_unlock(&fs_info->super_lock);
3a45bb20 5196 ret = btrfs_commit_transaction(trans);
a8bfd4ab 5197
5198out_unlock:
a8bfd4ab 5199 mnt_drop_write_file(file);
5200 return ret;
5201}
5202
2eaa055f
JM
5203#define INIT_FEATURE_FLAGS(suffix) \
5204 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5205 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5206 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5207
d5131b65 5208int btrfs_ioctl_get_supported_features(void __user *arg)
2eaa055f 5209{
4d4ab6d6 5210 static const struct btrfs_ioctl_feature_flags features[3] = {
2eaa055f
JM
5211 INIT_FEATURE_FLAGS(SUPP),
5212 INIT_FEATURE_FLAGS(SAFE_SET),
5213 INIT_FEATURE_FLAGS(SAFE_CLEAR)
5214 };
5215
5216 if (copy_to_user(arg, &features, sizeof(features)))
5217 return -EFAULT;
5218
5219 return 0;
5220}
5221
5222static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
5223{
0b246afa
JM
5224 struct inode *inode = file_inode(file);
5225 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5226 struct btrfs_super_block *super_block = fs_info->super_copy;
2eaa055f
JM
5227 struct btrfs_ioctl_feature_flags features;
5228
5229 features.compat_flags = btrfs_super_compat_flags(super_block);
5230 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5231 features.incompat_flags = btrfs_super_incompat_flags(super_block);
5232
5233 if (copy_to_user(arg, &features, sizeof(features)))
5234 return -EFAULT;
5235
5236 return 0;
5237}
5238
2ff7e61e 5239static int check_feature_bits(struct btrfs_fs_info *fs_info,
3b02a68a 5240 enum btrfs_feature_set set,
2eaa055f
JM
5241 u64 change_mask, u64 flags, u64 supported_flags,
5242 u64 safe_set, u64 safe_clear)
5243{
3b02a68a
JM
5244 const char *type = btrfs_feature_set_names[set];
5245 char *names;
2eaa055f
JM
5246 u64 disallowed, unsupported;
5247 u64 set_mask = flags & change_mask;
5248 u64 clear_mask = ~flags & change_mask;
5249
5250 unsupported = set_mask & ~supported_flags;
5251 if (unsupported) {
3b02a68a
JM
5252 names = btrfs_printable_features(set, unsupported);
5253 if (names) {
0b246afa
JM
5254 btrfs_warn(fs_info,
5255 "this kernel does not support the %s feature bit%s",
5256 names, strchr(names, ',') ? "s" : "");
3b02a68a
JM
5257 kfree(names);
5258 } else
0b246afa
JM
5259 btrfs_warn(fs_info,
5260 "this kernel does not support %s bits 0x%llx",
5261 type, unsupported);
2eaa055f
JM
5262 return -EOPNOTSUPP;
5263 }
5264
5265 disallowed = set_mask & ~safe_set;
5266 if (disallowed) {
3b02a68a
JM
5267 names = btrfs_printable_features(set, disallowed);
5268 if (names) {
0b246afa
JM
5269 btrfs_warn(fs_info,
5270 "can't set the %s feature bit%s while mounted",
5271 names, strchr(names, ',') ? "s" : "");
3b02a68a
JM
5272 kfree(names);
5273 } else
0b246afa
JM
5274 btrfs_warn(fs_info,
5275 "can't set %s bits 0x%llx while mounted",
5276 type, disallowed);
2eaa055f
JM
5277 return -EPERM;
5278 }
5279
5280 disallowed = clear_mask & ~safe_clear;
5281 if (disallowed) {
3b02a68a
JM
5282 names = btrfs_printable_features(set, disallowed);
5283 if (names) {
0b246afa
JM
5284 btrfs_warn(fs_info,
5285 "can't clear the %s feature bit%s while mounted",
5286 names, strchr(names, ',') ? "s" : "");
3b02a68a
JM
5287 kfree(names);
5288 } else
0b246afa
JM
5289 btrfs_warn(fs_info,
5290 "can't clear %s bits 0x%llx while mounted",
5291 type, disallowed);
2eaa055f
JM
5292 return -EPERM;
5293 }
5294
5295 return 0;
5296}
5297
2ff7e61e
JM
5298#define check_feature(fs_info, change_mask, flags, mask_base) \
5299check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \
2eaa055f
JM
5300 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
5301 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
5302 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5303
5304static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5305{
0b246afa
JM
5306 struct inode *inode = file_inode(file);
5307 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5308 struct btrfs_root *root = BTRFS_I(inode)->root;
5309 struct btrfs_super_block *super_block = fs_info->super_copy;
2eaa055f
JM
5310 struct btrfs_ioctl_feature_flags flags[2];
5311 struct btrfs_trans_handle *trans;
5312 u64 newflags;
5313 int ret;
5314
5315 if (!capable(CAP_SYS_ADMIN))
5316 return -EPERM;
5317
5318 if (copy_from_user(flags, arg, sizeof(flags)))
5319 return -EFAULT;
5320
5321 /* Nothing to do */
5322 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5323 !flags[0].incompat_flags)
5324 return 0;
5325
2ff7e61e 5326 ret = check_feature(fs_info, flags[0].compat_flags,
2eaa055f
JM
5327 flags[1].compat_flags, COMPAT);
5328 if (ret)
5329 return ret;
5330
2ff7e61e 5331 ret = check_feature(fs_info, flags[0].compat_ro_flags,
2eaa055f
JM
5332 flags[1].compat_ro_flags, COMPAT_RO);
5333 if (ret)
5334 return ret;
5335
2ff7e61e 5336 ret = check_feature(fs_info, flags[0].incompat_flags,
2eaa055f
JM
5337 flags[1].incompat_flags, INCOMPAT);
5338 if (ret)
5339 return ret;
5340
7ab19625
DS
5341 ret = mnt_want_write_file(file);
5342 if (ret)
5343 return ret;
5344
8051aa1a 5345 trans = btrfs_start_transaction(root, 0);
7ab19625
DS
5346 if (IS_ERR(trans)) {
5347 ret = PTR_ERR(trans);
5348 goto out_drop_write;
5349 }
2eaa055f 5350
0b246afa 5351 spin_lock(&fs_info->super_lock);
2eaa055f
JM
5352 newflags = btrfs_super_compat_flags(super_block);
5353 newflags |= flags[0].compat_flags & flags[1].compat_flags;
5354 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5355 btrfs_set_super_compat_flags(super_block, newflags);
5356
5357 newflags = btrfs_super_compat_ro_flags(super_block);
5358 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5359 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5360 btrfs_set_super_compat_ro_flags(super_block, newflags);
5361
5362 newflags = btrfs_super_incompat_flags(super_block);
5363 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5364 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5365 btrfs_set_super_incompat_flags(super_block, newflags);
0b246afa 5366 spin_unlock(&fs_info->super_lock);
2eaa055f 5367
3a45bb20 5368 ret = btrfs_commit_transaction(trans);
7ab19625
DS
5369out_drop_write:
5370 mnt_drop_write_file(file);
5371
5372 return ret;
2eaa055f
JM
5373}
5374
2351f431
JB
5375static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
5376{
5377 struct btrfs_ioctl_send_args *arg;
5378 int ret;
5379
5380 if (compat) {
5381#if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5382 struct btrfs_ioctl_send_args_32 args32;
5383
5384 ret = copy_from_user(&args32, argp, sizeof(args32));
5385 if (ret)
5386 return -EFAULT;
5387 arg = kzalloc(sizeof(*arg), GFP_KERNEL);
5388 if (!arg)
5389 return -ENOMEM;
5390 arg->send_fd = args32.send_fd;
5391 arg->clone_sources_count = args32.clone_sources_count;
5392 arg->clone_sources = compat_ptr(args32.clone_sources);
5393 arg->parent_root = args32.parent_root;
5394 arg->flags = args32.flags;
5395 memcpy(arg->reserved, args32.reserved,
5396 sizeof(args32.reserved));
5397#else
5398 return -ENOTTY;
5399#endif
5400 } else {
5401 arg = memdup_user(argp, sizeof(*arg));
5402 if (IS_ERR(arg))
5403 return PTR_ERR(arg);
5404 }
5405 ret = btrfs_ioctl_send(file, arg);
5406 kfree(arg);
5407 return ret;
5408}
5409
f46b5a66
CH
5410long btrfs_ioctl(struct file *file, unsigned int
5411 cmd, unsigned long arg)
5412{
0b246afa
JM
5413 struct inode *inode = file_inode(file);
5414 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5415 struct btrfs_root *root = BTRFS_I(inode)->root;
4bcabaa3 5416 void __user *argp = (void __user *)arg;
f46b5a66
CH
5417
5418 switch (cmd) {
6cbff00f
CH
5419 case FS_IOC_GETFLAGS:
5420 return btrfs_ioctl_getflags(file, argp);
5421 case FS_IOC_SETFLAGS:
5422 return btrfs_ioctl_setflags(file, argp);
5423 case FS_IOC_GETVERSION:
5424 return btrfs_ioctl_getversion(file, argp);
f7039b1d
LD
5425 case FITRIM:
5426 return btrfs_ioctl_fitrim(file, argp);
f46b5a66 5427 case BTRFS_IOC_SNAP_CREATE:
fa0d2b9b 5428 return btrfs_ioctl_snap_create(file, argp, 0);
fdfb1e4f 5429 case BTRFS_IOC_SNAP_CREATE_V2:
fa0d2b9b 5430 return btrfs_ioctl_snap_create_v2(file, argp, 0);
3de4586c 5431 case BTRFS_IOC_SUBVOL_CREATE:
fa0d2b9b 5432 return btrfs_ioctl_snap_create(file, argp, 1);
6f72c7e2
AJ
5433 case BTRFS_IOC_SUBVOL_CREATE_V2:
5434 return btrfs_ioctl_snap_create_v2(file, argp, 1);
76dda93c
YZ
5435 case BTRFS_IOC_SNAP_DESTROY:
5436 return btrfs_ioctl_snap_destroy(file, argp);
0caa102d
LZ
5437 case BTRFS_IOC_SUBVOL_GETFLAGS:
5438 return btrfs_ioctl_subvol_getflags(file, argp);
5439 case BTRFS_IOC_SUBVOL_SETFLAGS:
5440 return btrfs_ioctl_subvol_setflags(file, argp);
6ef5ed0d
JB
5441 case BTRFS_IOC_DEFAULT_SUBVOL:
5442 return btrfs_ioctl_default_subvol(file, argp);
f46b5a66 5443 case BTRFS_IOC_DEFRAG:
1e701a32
CM
5444 return btrfs_ioctl_defrag(file, NULL);
5445 case BTRFS_IOC_DEFRAG_RANGE:
5446 return btrfs_ioctl_defrag(file, argp);
f46b5a66 5447 case BTRFS_IOC_RESIZE:
198605a8 5448 return btrfs_ioctl_resize(file, argp);
f46b5a66 5449 case BTRFS_IOC_ADD_DEV:
2ff7e61e 5450 return btrfs_ioctl_add_dev(fs_info, argp);
f46b5a66 5451 case BTRFS_IOC_RM_DEV:
da24927b 5452 return btrfs_ioctl_rm_dev(file, argp);
6b526ed7
AJ
5453 case BTRFS_IOC_RM_DEV_V2:
5454 return btrfs_ioctl_rm_dev_v2(file, argp);
475f6387 5455 case BTRFS_IOC_FS_INFO:
2ff7e61e 5456 return btrfs_ioctl_fs_info(fs_info, argp);
475f6387 5457 case BTRFS_IOC_DEV_INFO:
2ff7e61e 5458 return btrfs_ioctl_dev_info(fs_info, argp);
f46b5a66 5459 case BTRFS_IOC_BALANCE:
9ba1f6e4 5460 return btrfs_ioctl_balance(file, NULL);
ac8e9819
CM
5461 case BTRFS_IOC_TREE_SEARCH:
5462 return btrfs_ioctl_tree_search(file, argp);
cc68a8a5
GH
5463 case BTRFS_IOC_TREE_SEARCH_V2:
5464 return btrfs_ioctl_tree_search_v2(file, argp);
ac8e9819
CM
5465 case BTRFS_IOC_INO_LOOKUP:
5466 return btrfs_ioctl_ino_lookup(file, argp);
d7728c96
JS
5467 case BTRFS_IOC_INO_PATHS:
5468 return btrfs_ioctl_ino_to_path(root, argp);
5469 case BTRFS_IOC_LOGICAL_INO:
d24a67b2
ZB
5470 return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5471 case BTRFS_IOC_LOGICAL_INO_V2:
5472 return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
1406e432 5473 case BTRFS_IOC_SPACE_INFO:
2ff7e61e 5474 return btrfs_ioctl_space_info(fs_info, argp);
9b199859
FDBM
5475 case BTRFS_IOC_SYNC: {
5476 int ret;
5477
82b3e53b 5478 ret = btrfs_start_delalloc_roots(fs_info, -1);
9b199859
FDBM
5479 if (ret)
5480 return ret;
0b246afa 5481 ret = btrfs_sync_fs(inode->i_sb, 1);
2fad4e83
DS
5482 /*
5483 * The transaction thread may want to do more work,
01327610 5484 * namely it pokes the cleaner kthread that will start
2fad4e83
DS
5485 * processing uncleaned subvols.
5486 */
0b246afa 5487 wake_up_process(fs_info->transaction_kthread);
9b199859
FDBM
5488 return ret;
5489 }
46204592 5490 case BTRFS_IOC_START_SYNC:
9a8c28be 5491 return btrfs_ioctl_start_sync(root, argp);
46204592 5492 case BTRFS_IOC_WAIT_SYNC:
2ff7e61e 5493 return btrfs_ioctl_wait_sync(fs_info, argp);
475f6387 5494 case BTRFS_IOC_SCRUB:
b8e95489 5495 return btrfs_ioctl_scrub(file, argp);
475f6387 5496 case BTRFS_IOC_SCRUB_CANCEL:
2ff7e61e 5497 return btrfs_ioctl_scrub_cancel(fs_info);
475f6387 5498 case BTRFS_IOC_SCRUB_PROGRESS:
2ff7e61e 5499 return btrfs_ioctl_scrub_progress(fs_info, argp);
c9e9f97b 5500 case BTRFS_IOC_BALANCE_V2:
9ba1f6e4 5501 return btrfs_ioctl_balance(file, argp);
837d5b6e 5502 case BTRFS_IOC_BALANCE_CTL:
2ff7e61e 5503 return btrfs_ioctl_balance_ctl(fs_info, arg);
19a39dce 5504 case BTRFS_IOC_BALANCE_PROGRESS:
2ff7e61e 5505 return btrfs_ioctl_balance_progress(fs_info, argp);
8ea05e3a
AB
5506 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5507 return btrfs_ioctl_set_received_subvol(file, argp);
abccd00f
HM
5508#ifdef CONFIG_64BIT
5509 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5510 return btrfs_ioctl_set_received_subvol_32(file, argp);
5511#endif
31db9f7c 5512 case BTRFS_IOC_SEND:
2351f431
JB
5513 return _btrfs_ioctl_send(file, argp, false);
5514#if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5515 case BTRFS_IOC_SEND_32:
5516 return _btrfs_ioctl_send(file, argp, true);
5517#endif
c11d2c23 5518 case BTRFS_IOC_GET_DEV_STATS:
2ff7e61e 5519 return btrfs_ioctl_get_dev_stats(fs_info, argp);
5d13a37b 5520 case BTRFS_IOC_QUOTA_CTL:
905b0dda 5521 return btrfs_ioctl_quota_ctl(file, argp);
5d13a37b 5522 case BTRFS_IOC_QGROUP_ASSIGN:
905b0dda 5523 return btrfs_ioctl_qgroup_assign(file, argp);
5d13a37b 5524 case BTRFS_IOC_QGROUP_CREATE:
905b0dda 5525 return btrfs_ioctl_qgroup_create(file, argp);
5d13a37b 5526 case BTRFS_IOC_QGROUP_LIMIT:
905b0dda 5527 return btrfs_ioctl_qgroup_limit(file, argp);
2f232036
JS
5528 case BTRFS_IOC_QUOTA_RESCAN:
5529 return btrfs_ioctl_quota_rescan(file, argp);
5530 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5531 return btrfs_ioctl_quota_rescan_status(file, argp);
57254b6e
JS
5532 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5533 return btrfs_ioctl_quota_rescan_wait(file, argp);
3f6bcfbd 5534 case BTRFS_IOC_DEV_REPLACE:
2ff7e61e 5535 return btrfs_ioctl_dev_replace(fs_info, argp);
867ab667 5536 case BTRFS_IOC_GET_FSLABEL:
5537 return btrfs_ioctl_get_fslabel(file, argp);
a8bfd4ab 5538 case BTRFS_IOC_SET_FSLABEL:
5539 return btrfs_ioctl_set_fslabel(file, argp);
2eaa055f 5540 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
d5131b65 5541 return btrfs_ioctl_get_supported_features(argp);
2eaa055f
JM
5542 case BTRFS_IOC_GET_FEATURES:
5543 return btrfs_ioctl_get_features(file, argp);
5544 case BTRFS_IOC_SET_FEATURES:
5545 return btrfs_ioctl_set_features(file, argp);
e4202ac9
DS
5546 case FS_IOC_FSGETXATTR:
5547 return btrfs_ioctl_fsgetxattr(file, argp);
025f2121
DS
5548 case FS_IOC_FSSETXATTR:
5549 return btrfs_ioctl_fssetxattr(file, argp);
f46b5a66
CH
5550 }
5551
5552 return -ENOTTY;
5553}
4c63c245
LD
5554
5555#ifdef CONFIG_COMPAT
5556long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5557{
2a362249
JM
5558 /*
5559 * These all access 32-bit values anyway so no further
5560 * handling is necessary.
5561 */
4c63c245
LD
5562 switch (cmd) {
5563 case FS_IOC32_GETFLAGS:
5564 cmd = FS_IOC_GETFLAGS;
5565 break;
5566 case FS_IOC32_SETFLAGS:
5567 cmd = FS_IOC_SETFLAGS;
5568 break;
5569 case FS_IOC32_GETVERSION:
5570 cmd = FS_IOC_GETVERSION;
5571 break;
4c63c245
LD
5572 }
5573
5574 return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
5575}
5576#endif