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