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