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