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