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