1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/file.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>
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>
31 #include "transaction.h"
32 #include "btrfs_inode.h"
33 #include "print-tree.h"
36 #include "inode-map.h"
38 #include "rcu-string.h"
40 #include "dev-replace.h"
45 #include "compression.h"
48 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
49 * structures are incorrect, as the timespec structure from userspace
50 * is 4 bytes too small. We define these alternatives here to teach
51 * the kernel about the 32-bit struct packing.
53 struct btrfs_ioctl_timespec_32 {
56 } __attribute__ ((__packed__));
58 struct btrfs_ioctl_received_subvol_args_32 {
59 char uuid[BTRFS_UUID_SIZE]; /* in */
60 __u64 stransid; /* in */
61 __u64 rtransid; /* out */
62 struct btrfs_ioctl_timespec_32 stime; /* in */
63 struct btrfs_ioctl_timespec_32 rtime; /* out */
65 __u64 reserved[16]; /* in */
66 } __attribute__ ((__packed__));
68 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
69 struct btrfs_ioctl_received_subvol_args_32)
72 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
73 struct btrfs_ioctl_send_args_32 {
74 __s64 send_fd; /* in */
75 __u64 clone_sources_count; /* in */
76 compat_uptr_t clone_sources; /* in */
77 __u64 parent_root; /* in */
79 __u64 reserved[4]; /* in */
80 } __attribute__ ((__packed__));
82 #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
83 struct btrfs_ioctl_send_args_32)
86 static int btrfs_clone(struct inode *src, struct inode *inode,
87 u64 off, u64 olen, u64 olen_aligned, u64 destoff,
90 /* Mask out flags that are inappropriate for the given type of inode. */
91 static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
94 if (S_ISDIR(inode->i_mode))
96 else if (S_ISREG(inode->i_mode))
97 return flags & ~FS_DIRSYNC_FL;
99 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
103 * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
106 static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags)
108 unsigned int iflags = 0;
110 if (flags & BTRFS_INODE_SYNC)
111 iflags |= FS_SYNC_FL;
112 if (flags & BTRFS_INODE_IMMUTABLE)
113 iflags |= FS_IMMUTABLE_FL;
114 if (flags & BTRFS_INODE_APPEND)
115 iflags |= FS_APPEND_FL;
116 if (flags & BTRFS_INODE_NODUMP)
117 iflags |= FS_NODUMP_FL;
118 if (flags & BTRFS_INODE_NOATIME)
119 iflags |= FS_NOATIME_FL;
120 if (flags & BTRFS_INODE_DIRSYNC)
121 iflags |= FS_DIRSYNC_FL;
122 if (flags & BTRFS_INODE_NODATACOW)
123 iflags |= FS_NOCOW_FL;
125 if (flags & BTRFS_INODE_NOCOMPRESS)
126 iflags |= FS_NOCOMP_FL;
127 else if (flags & BTRFS_INODE_COMPRESS)
128 iflags |= FS_COMPR_FL;
134 * Update inode->i_flags based on the btrfs internal flags.
136 void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
138 struct btrfs_inode *binode = BTRFS_I(inode);
139 unsigned int new_fl = 0;
141 if (binode->flags & BTRFS_INODE_SYNC)
143 if (binode->flags & BTRFS_INODE_IMMUTABLE)
144 new_fl |= S_IMMUTABLE;
145 if (binode->flags & BTRFS_INODE_APPEND)
147 if (binode->flags & BTRFS_INODE_NOATIME)
149 if (binode->flags & BTRFS_INODE_DIRSYNC)
152 set_mask_bits(&inode->i_flags,
153 S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
157 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
159 struct btrfs_inode *binode = BTRFS_I(file_inode(file));
160 unsigned int flags = btrfs_inode_flags_to_fsflags(binode->flags);
162 if (copy_to_user(arg, &flags, sizeof(flags)))
167 /* Check if @flags are a supported and valid set of FS_*_FL flags */
168 static int check_fsflags(unsigned int flags)
170 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
171 FS_NOATIME_FL | FS_NODUMP_FL | \
172 FS_SYNC_FL | FS_DIRSYNC_FL | \
173 FS_NOCOMP_FL | FS_COMPR_FL |
177 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
183 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
185 struct inode *inode = file_inode(file);
186 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
187 struct btrfs_inode *binode = BTRFS_I(inode);
188 struct btrfs_root *root = binode->root;
189 struct btrfs_trans_handle *trans;
190 unsigned int fsflags, old_fsflags;
193 unsigned int old_i_flags;
196 if (!inode_owner_or_capable(inode))
199 if (btrfs_root_readonly(root))
202 if (copy_from_user(&fsflags, arg, sizeof(fsflags)))
205 ret = check_fsflags(fsflags);
209 ret = mnt_want_write_file(file);
215 old_flags = binode->flags;
216 old_i_flags = inode->i_flags;
217 mode = inode->i_mode;
219 fsflags = btrfs_mask_fsflags_for_type(inode, fsflags);
220 old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags);
221 if ((fsflags ^ old_fsflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
222 if (!capable(CAP_LINUX_IMMUTABLE)) {
228 if (fsflags & FS_SYNC_FL)
229 binode->flags |= BTRFS_INODE_SYNC;
231 binode->flags &= ~BTRFS_INODE_SYNC;
232 if (fsflags & FS_IMMUTABLE_FL)
233 binode->flags |= BTRFS_INODE_IMMUTABLE;
235 binode->flags &= ~BTRFS_INODE_IMMUTABLE;
236 if (fsflags & FS_APPEND_FL)
237 binode->flags |= BTRFS_INODE_APPEND;
239 binode->flags &= ~BTRFS_INODE_APPEND;
240 if (fsflags & FS_NODUMP_FL)
241 binode->flags |= BTRFS_INODE_NODUMP;
243 binode->flags &= ~BTRFS_INODE_NODUMP;
244 if (fsflags & FS_NOATIME_FL)
245 binode->flags |= BTRFS_INODE_NOATIME;
247 binode->flags &= ~BTRFS_INODE_NOATIME;
248 if (fsflags & FS_DIRSYNC_FL)
249 binode->flags |= BTRFS_INODE_DIRSYNC;
251 binode->flags &= ~BTRFS_INODE_DIRSYNC;
252 if (fsflags & FS_NOCOW_FL) {
255 * It's safe to turn csums off here, no extents exist.
256 * Otherwise we want the flag to reflect the real COW
257 * status of the file and will not set it.
259 if (inode->i_size == 0)
260 binode->flags |= BTRFS_INODE_NODATACOW
261 | BTRFS_INODE_NODATASUM;
263 binode->flags |= BTRFS_INODE_NODATACOW;
267 * Revert back under same assumptions as above
270 if (inode->i_size == 0)
271 binode->flags &= ~(BTRFS_INODE_NODATACOW
272 | BTRFS_INODE_NODATASUM);
274 binode->flags &= ~BTRFS_INODE_NODATACOW;
279 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
280 * flag may be changed automatically if compression code won't make
283 if (fsflags & FS_NOCOMP_FL) {
284 binode->flags &= ~BTRFS_INODE_COMPRESS;
285 binode->flags |= BTRFS_INODE_NOCOMPRESS;
287 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
288 if (ret && ret != -ENODATA)
290 } else if (fsflags & FS_COMPR_FL) {
293 if (IS_SWAPFILE(inode)) {
298 binode->flags |= BTRFS_INODE_COMPRESS;
299 binode->flags &= ~BTRFS_INODE_NOCOMPRESS;
301 comp = btrfs_compress_type2str(fs_info->compress_type);
302 if (!comp || comp[0] == 0)
303 comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
305 ret = btrfs_set_prop(inode, "btrfs.compression",
306 comp, strlen(comp), 0);
311 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
312 if (ret && ret != -ENODATA)
314 binode->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
317 trans = btrfs_start_transaction(root, 1);
319 ret = PTR_ERR(trans);
323 btrfs_sync_inode_flags_to_i_flags(inode);
324 inode_inc_iversion(inode);
325 inode->i_ctime = current_time(inode);
326 ret = btrfs_update_inode(trans, root, inode);
328 btrfs_end_transaction(trans);
331 binode->flags = old_flags;
332 inode->i_flags = old_i_flags;
337 mnt_drop_write_file(file);
342 * Translate btrfs internal inode flags to xflags as expected by the
343 * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are
346 static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags)
348 unsigned int xflags = 0;
350 if (flags & BTRFS_INODE_APPEND)
351 xflags |= FS_XFLAG_APPEND;
352 if (flags & BTRFS_INODE_IMMUTABLE)
353 xflags |= FS_XFLAG_IMMUTABLE;
354 if (flags & BTRFS_INODE_NOATIME)
355 xflags |= FS_XFLAG_NOATIME;
356 if (flags & BTRFS_INODE_NODUMP)
357 xflags |= FS_XFLAG_NODUMP;
358 if (flags & BTRFS_INODE_SYNC)
359 xflags |= FS_XFLAG_SYNC;
364 /* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */
365 static int check_xflags(unsigned int flags)
367 if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME |
368 FS_XFLAG_NODUMP | FS_XFLAG_SYNC))
374 * Set the xflags from the internal inode flags. The remaining items of fsxattr
377 static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg)
379 struct btrfs_inode *binode = BTRFS_I(file_inode(file));
382 memset(&fa, 0, sizeof(fa));
383 fa.fsx_xflags = btrfs_inode_flags_to_xflags(binode->flags);
385 if (copy_to_user(arg, &fa, sizeof(fa)))
391 static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg)
393 struct inode *inode = file_inode(file);
394 struct btrfs_inode *binode = BTRFS_I(inode);
395 struct btrfs_root *root = binode->root;
396 struct btrfs_trans_handle *trans;
399 unsigned old_i_flags;
402 if (!inode_owner_or_capable(inode))
405 if (btrfs_root_readonly(root))
408 memset(&fa, 0, sizeof(fa));
409 if (copy_from_user(&fa, arg, sizeof(fa)))
412 ret = check_xflags(fa.fsx_xflags);
416 if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0)
419 ret = mnt_want_write_file(file);
425 old_flags = binode->flags;
426 old_i_flags = inode->i_flags;
428 /* We need the capabilities to change append-only or immutable inode */
429 if (((old_flags & (BTRFS_INODE_APPEND | BTRFS_INODE_IMMUTABLE)) ||
430 (fa.fsx_xflags & (FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE))) &&
431 !capable(CAP_LINUX_IMMUTABLE)) {
436 if (fa.fsx_xflags & FS_XFLAG_SYNC)
437 binode->flags |= BTRFS_INODE_SYNC;
439 binode->flags &= ~BTRFS_INODE_SYNC;
440 if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE)
441 binode->flags |= BTRFS_INODE_IMMUTABLE;
443 binode->flags &= ~BTRFS_INODE_IMMUTABLE;
444 if (fa.fsx_xflags & FS_XFLAG_APPEND)
445 binode->flags |= BTRFS_INODE_APPEND;
447 binode->flags &= ~BTRFS_INODE_APPEND;
448 if (fa.fsx_xflags & FS_XFLAG_NODUMP)
449 binode->flags |= BTRFS_INODE_NODUMP;
451 binode->flags &= ~BTRFS_INODE_NODUMP;
452 if (fa.fsx_xflags & FS_XFLAG_NOATIME)
453 binode->flags |= BTRFS_INODE_NOATIME;
455 binode->flags &= ~BTRFS_INODE_NOATIME;
457 /* 1 item for the inode */
458 trans = btrfs_start_transaction(root, 1);
460 ret = PTR_ERR(trans);
464 btrfs_sync_inode_flags_to_i_flags(inode);
465 inode_inc_iversion(inode);
466 inode->i_ctime = current_time(inode);
467 ret = btrfs_update_inode(trans, root, inode);
469 btrfs_end_transaction(trans);
473 binode->flags = old_flags;
474 inode->i_flags = old_i_flags;
478 mnt_drop_write_file(file);
483 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
485 struct inode *inode = file_inode(file);
487 return put_user(inode->i_generation, arg);
490 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
492 struct inode *inode = file_inode(file);
493 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
494 struct btrfs_device *device;
495 struct request_queue *q;
496 struct fstrim_range range;
497 u64 minlen = ULLONG_MAX;
501 if (!capable(CAP_SYS_ADMIN))
505 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
509 q = bdev_get_queue(device->bdev);
510 if (blk_queue_discard(q)) {
512 minlen = min_t(u64, q->limits.discard_granularity,
520 if (copy_from_user(&range, arg, sizeof(range)))
524 * NOTE: Don't truncate the range using super->total_bytes. Bytenr of
525 * block group is in the logical address space, which can be any
526 * sectorsize aligned bytenr in the range [0, U64_MAX].
528 if (range.len < fs_info->sb->s_blocksize)
531 range.minlen = max(range.minlen, minlen);
532 ret = btrfs_trim_fs(fs_info, &range);
536 if (copy_to_user(arg, &range, sizeof(range)))
542 int btrfs_is_empty_uuid(u8 *uuid)
546 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
553 static noinline int create_subvol(struct inode *dir,
554 struct dentry *dentry,
555 const char *name, int namelen,
557 struct btrfs_qgroup_inherit *inherit)
559 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
560 struct btrfs_trans_handle *trans;
561 struct btrfs_key key;
562 struct btrfs_root_item *root_item;
563 struct btrfs_inode_item *inode_item;
564 struct extent_buffer *leaf;
565 struct btrfs_root *root = BTRFS_I(dir)->root;
566 struct btrfs_root *new_root;
567 struct btrfs_block_rsv block_rsv;
568 struct timespec64 cur_time = current_time(dir);
573 u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
577 root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
581 ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
586 * Don't create subvolume whose level is not zero. Or qgroup will be
587 * screwed up since it assumes subvolume qgroup's level to be 0.
589 if (btrfs_qgroup_level(objectid)) {
594 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
596 * The same as the snapshot creation, please see the comment
597 * of create_snapshot().
599 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
603 trans = btrfs_start_transaction(root, 0);
605 ret = PTR_ERR(trans);
606 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
609 trans->block_rsv = &block_rsv;
610 trans->bytes_reserved = block_rsv.size;
612 ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
616 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
622 btrfs_mark_buffer_dirty(leaf);
624 inode_item = &root_item->inode;
625 btrfs_set_stack_inode_generation(inode_item, 1);
626 btrfs_set_stack_inode_size(inode_item, 3);
627 btrfs_set_stack_inode_nlink(inode_item, 1);
628 btrfs_set_stack_inode_nbytes(inode_item,
630 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
632 btrfs_set_root_flags(root_item, 0);
633 btrfs_set_root_limit(root_item, 0);
634 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
636 btrfs_set_root_bytenr(root_item, leaf->start);
637 btrfs_set_root_generation(root_item, trans->transid);
638 btrfs_set_root_level(root_item, 0);
639 btrfs_set_root_refs(root_item, 1);
640 btrfs_set_root_used(root_item, leaf->len);
641 btrfs_set_root_last_snapshot(root_item, 0);
643 btrfs_set_root_generation_v2(root_item,
644 btrfs_root_generation(root_item));
645 uuid_le_gen(&new_uuid);
646 memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
647 btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
648 btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
649 root_item->ctime = root_item->otime;
650 btrfs_set_root_ctransid(root_item, trans->transid);
651 btrfs_set_root_otransid(root_item, trans->transid);
653 btrfs_tree_unlock(leaf);
654 free_extent_buffer(leaf);
657 btrfs_set_root_dirid(root_item, new_dirid);
659 key.objectid = objectid;
661 key.type = BTRFS_ROOT_ITEM_KEY;
662 ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
667 key.offset = (u64)-1;
668 new_root = btrfs_read_fs_root_no_name(fs_info, &key);
669 if (IS_ERR(new_root)) {
670 ret = PTR_ERR(new_root);
671 btrfs_abort_transaction(trans, ret);
675 btrfs_record_root_in_trans(trans, new_root);
677 ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
679 /* We potentially lose an unused inode item here */
680 btrfs_abort_transaction(trans, ret);
684 mutex_lock(&new_root->objectid_mutex);
685 new_root->highest_objectid = new_dirid;
686 mutex_unlock(&new_root->objectid_mutex);
689 * insert the directory item
691 ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
693 btrfs_abort_transaction(trans, ret);
697 ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
698 BTRFS_FT_DIR, index);
700 btrfs_abort_transaction(trans, ret);
704 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
705 ret = btrfs_update_inode(trans, root, dir);
708 ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
709 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
712 ret = btrfs_uuid_tree_add(trans, root_item->uuid,
713 BTRFS_UUID_KEY_SUBVOL, objectid);
715 btrfs_abort_transaction(trans, ret);
719 trans->block_rsv = NULL;
720 trans->bytes_reserved = 0;
721 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
724 *async_transid = trans->transid;
725 err = btrfs_commit_transaction_async(trans, 1);
727 err = btrfs_commit_transaction(trans);
729 err = btrfs_commit_transaction(trans);
735 inode = btrfs_lookup_dentry(dir, dentry);
737 return PTR_ERR(inode);
738 d_instantiate(dentry, inode);
747 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
748 struct dentry *dentry,
749 u64 *async_transid, bool readonly,
750 struct btrfs_qgroup_inherit *inherit)
752 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
754 struct btrfs_pending_snapshot *pending_snapshot;
755 struct btrfs_trans_handle *trans;
757 bool snapshot_force_cow = false;
759 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
762 if (atomic_read(&root->nr_swapfiles)) {
764 "cannot snapshot subvolume with active swapfile");
768 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
769 if (!pending_snapshot)
772 pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
774 pending_snapshot->path = btrfs_alloc_path();
775 if (!pending_snapshot->root_item || !pending_snapshot->path) {
781 * Force new buffered writes to reserve space even when NOCOW is
782 * possible. This is to avoid later writeback (running dealloc) to
783 * fallback to COW mode and unexpectedly fail with ENOSPC.
785 atomic_inc(&root->will_be_snapshotted);
786 smp_mb__after_atomic();
787 /* wait for no snapshot writes */
788 wait_event(root->subv_writers->wait,
789 percpu_counter_sum(&root->subv_writers->counter) == 0);
791 ret = btrfs_start_delalloc_snapshot(root);
796 * All previous writes have started writeback in NOCOW mode, so now
797 * we force future writes to fallback to COW mode during snapshot
800 atomic_inc(&root->snapshot_force_cow);
801 snapshot_force_cow = true;
803 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
805 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
806 BTRFS_BLOCK_RSV_TEMP);
808 * 1 - parent dir inode
811 * 2 - root ref/backref
812 * 1 - root of snapshot
815 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
816 &pending_snapshot->block_rsv, 8,
821 pending_snapshot->dentry = dentry;
822 pending_snapshot->root = root;
823 pending_snapshot->readonly = readonly;
824 pending_snapshot->dir = dir;
825 pending_snapshot->inherit = inherit;
827 trans = btrfs_start_transaction(root, 0);
829 ret = PTR_ERR(trans);
833 spin_lock(&fs_info->trans_lock);
834 list_add(&pending_snapshot->list,
835 &trans->transaction->pending_snapshots);
836 spin_unlock(&fs_info->trans_lock);
838 *async_transid = trans->transid;
839 ret = btrfs_commit_transaction_async(trans, 1);
841 ret = btrfs_commit_transaction(trans);
843 ret = btrfs_commit_transaction(trans);
848 ret = pending_snapshot->error;
852 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
856 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
858 ret = PTR_ERR(inode);
862 d_instantiate(dentry, inode);
865 btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
867 if (snapshot_force_cow)
868 atomic_dec(&root->snapshot_force_cow);
869 if (atomic_dec_and_test(&root->will_be_snapshotted))
870 wake_up_var(&root->will_be_snapshotted);
872 kfree(pending_snapshot->root_item);
873 btrfs_free_path(pending_snapshot->path);
874 kfree(pending_snapshot);
879 /* copy of may_delete in fs/namei.c()
880 * Check whether we can remove a link victim from directory dir, check
881 * whether the type of victim is right.
882 * 1. We can't do it if dir is read-only (done in permission())
883 * 2. We should have write and exec permissions on dir
884 * 3. We can't remove anything from append-only dir
885 * 4. We can't do anything with immutable dir (done in permission())
886 * 5. If the sticky bit on dir is set we should either
887 * a. be owner of dir, or
888 * b. be owner of victim, or
889 * c. have CAP_FOWNER capability
890 * 6. If the victim is append-only or immutable we can't do anything with
891 * links pointing to it.
892 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
893 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
894 * 9. We can't remove a root or mountpoint.
895 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
896 * nfs_async_unlink().
899 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
903 if (d_really_is_negative(victim))
906 BUG_ON(d_inode(victim->d_parent) != dir);
907 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
909 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
914 if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
915 IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
918 if (!d_is_dir(victim))
922 } else if (d_is_dir(victim))
926 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
931 /* copy of may_create in fs/namei.c() */
932 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
934 if (d_really_is_positive(child))
938 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
942 * Create a new subvolume below @parent. This is largely modeled after
943 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
944 * inside this filesystem so it's quite a bit simpler.
946 static noinline int btrfs_mksubvol(const struct path *parent,
947 const char *name, int namelen,
948 struct btrfs_root *snap_src,
949 u64 *async_transid, bool readonly,
950 struct btrfs_qgroup_inherit *inherit)
952 struct inode *dir = d_inode(parent->dentry);
953 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
954 struct dentry *dentry;
957 error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
961 dentry = lookup_one_len(name, parent->dentry, namelen);
962 error = PTR_ERR(dentry);
966 error = btrfs_may_create(dir, dentry);
971 * even if this name doesn't exist, we may get hash collisions.
972 * check for them now when we can safely fail
974 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
980 down_read(&fs_info->subvol_sem);
982 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
986 error = create_snapshot(snap_src, dir, dentry,
987 async_transid, readonly, inherit);
989 error = create_subvol(dir, dentry, name, namelen,
990 async_transid, inherit);
993 fsnotify_mkdir(dir, dentry);
995 up_read(&fs_info->subvol_sem);
1004 * When we're defragging a range, we don't want to kick it off again
1005 * if it is really just waiting for delalloc to send it down.
1006 * If we find a nice big extent or delalloc range for the bytes in the
1007 * file you want to defrag, we return 0 to let you know to skip this
1010 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
1012 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1013 struct extent_map *em = NULL;
1014 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1017 read_lock(&em_tree->lock);
1018 em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
1019 read_unlock(&em_tree->lock);
1022 end = extent_map_end(em);
1023 free_extent_map(em);
1024 if (end - offset > thresh)
1027 /* if we already have a nice delalloc here, just stop */
1029 end = count_range_bits(io_tree, &offset, offset + thresh,
1030 thresh, EXTENT_DELALLOC, 1);
1037 * helper function to walk through a file and find extents
1038 * newer than a specific transid, and smaller than thresh.
1040 * This is used by the defragging code to find new and small
1043 static int find_new_extents(struct btrfs_root *root,
1044 struct inode *inode, u64 newer_than,
1045 u64 *off, u32 thresh)
1047 struct btrfs_path *path;
1048 struct btrfs_key min_key;
1049 struct extent_buffer *leaf;
1050 struct btrfs_file_extent_item *extent;
1053 u64 ino = btrfs_ino(BTRFS_I(inode));
1055 path = btrfs_alloc_path();
1059 min_key.objectid = ino;
1060 min_key.type = BTRFS_EXTENT_DATA_KEY;
1061 min_key.offset = *off;
1064 ret = btrfs_search_forward(root, &min_key, path, newer_than);
1068 if (min_key.objectid != ino)
1070 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
1073 leaf = path->nodes[0];
1074 extent = btrfs_item_ptr(leaf, path->slots[0],
1075 struct btrfs_file_extent_item);
1077 type = btrfs_file_extent_type(leaf, extent);
1078 if (type == BTRFS_FILE_EXTENT_REG &&
1079 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
1080 check_defrag_in_cache(inode, min_key.offset, thresh)) {
1081 *off = min_key.offset;
1082 btrfs_free_path(path);
1087 if (path->slots[0] < btrfs_header_nritems(leaf)) {
1088 btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1092 if (min_key.offset == (u64)-1)
1096 btrfs_release_path(path);
1099 btrfs_free_path(path);
1103 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
1105 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1106 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1107 struct extent_map *em;
1108 u64 len = PAGE_SIZE;
1111 * hopefully we have this extent in the tree already, try without
1112 * the full extent lock
1114 read_lock(&em_tree->lock);
1115 em = lookup_extent_mapping(em_tree, start, len);
1116 read_unlock(&em_tree->lock);
1119 struct extent_state *cached = NULL;
1120 u64 end = start + len - 1;
1122 /* get the big lock and read metadata off disk */
1123 lock_extent_bits(io_tree, start, end, &cached);
1124 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1125 unlock_extent_cached(io_tree, start, end, &cached);
1134 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1136 struct extent_map *next;
1139 /* this is the last extent */
1140 if (em->start + em->len >= i_size_read(inode))
1143 next = defrag_lookup_extent(inode, em->start + em->len);
1144 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1146 else if ((em->block_start + em->block_len == next->block_start) &&
1147 (em->block_len > SZ_128K && next->block_len > SZ_128K))
1150 free_extent_map(next);
1154 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1155 u64 *last_len, u64 *skip, u64 *defrag_end,
1158 struct extent_map *em;
1160 bool next_mergeable = true;
1161 bool prev_mergeable = true;
1164 * make sure that once we start defragging an extent, we keep on
1167 if (start < *defrag_end)
1172 em = defrag_lookup_extent(inode, start);
1176 /* this will cover holes, and inline extents */
1177 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1183 prev_mergeable = false;
1185 next_mergeable = defrag_check_next_extent(inode, em);
1187 * we hit a real extent, if it is big or the next extent is not a
1188 * real extent, don't bother defragging it
1190 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1191 (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1195 * last_len ends up being a counter of how many bytes we've defragged.
1196 * every time we choose not to defrag an extent, we reset *last_len
1197 * so that the next tiny extent will force a defrag.
1199 * The end result of this is that tiny extents before a single big
1200 * extent will force at least part of that big extent to be defragged.
1203 *defrag_end = extent_map_end(em);
1206 *skip = extent_map_end(em);
1210 free_extent_map(em);
1215 * it doesn't do much good to defrag one or two pages
1216 * at a time. This pulls in a nice chunk of pages
1217 * to COW and defrag.
1219 * It also makes sure the delalloc code has enough
1220 * dirty data to avoid making new small extents as part
1223 * It's a good idea to start RA on this range
1224 * before calling this.
1226 static int cluster_pages_for_defrag(struct inode *inode,
1227 struct page **pages,
1228 unsigned long start_index,
1229 unsigned long num_pages)
1231 unsigned long file_end;
1232 u64 isize = i_size_read(inode);
1239 struct btrfs_ordered_extent *ordered;
1240 struct extent_state *cached_state = NULL;
1241 struct extent_io_tree *tree;
1242 struct extent_changeset *data_reserved = NULL;
1243 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1245 file_end = (isize - 1) >> PAGE_SHIFT;
1246 if (!isize || start_index > file_end)
1249 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1251 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
1252 start_index << PAGE_SHIFT,
1253 page_cnt << PAGE_SHIFT);
1257 tree = &BTRFS_I(inode)->io_tree;
1259 /* step one, lock all the pages */
1260 for (i = 0; i < page_cnt; i++) {
1263 page = find_or_create_page(inode->i_mapping,
1264 start_index + i, mask);
1268 page_start = page_offset(page);
1269 page_end = page_start + PAGE_SIZE - 1;
1271 lock_extent_bits(tree, page_start, page_end,
1273 ordered = btrfs_lookup_ordered_extent(inode,
1275 unlock_extent_cached(tree, page_start, page_end,
1281 btrfs_start_ordered_extent(inode, ordered, 1);
1282 btrfs_put_ordered_extent(ordered);
1285 * we unlocked the page above, so we need check if
1286 * it was released or not.
1288 if (page->mapping != inode->i_mapping) {
1295 if (!PageUptodate(page)) {
1296 btrfs_readpage(NULL, page);
1298 if (!PageUptodate(page)) {
1306 if (page->mapping != inode->i_mapping) {
1318 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1322 * so now we have a nice long stream of locked
1323 * and up to date pages, lets wait on them
1325 for (i = 0; i < i_done; i++)
1326 wait_on_page_writeback(pages[i]);
1328 page_start = page_offset(pages[0]);
1329 page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
1331 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1332 page_start, page_end - 1, &cached_state);
1333 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1334 page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1335 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1338 if (i_done != page_cnt) {
1339 spin_lock(&BTRFS_I(inode)->lock);
1340 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1341 spin_unlock(&BTRFS_I(inode)->lock);
1342 btrfs_delalloc_release_space(inode, data_reserved,
1343 start_index << PAGE_SHIFT,
1344 (page_cnt - i_done) << PAGE_SHIFT, true);
1348 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1351 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1352 page_start, page_end - 1, &cached_state);
1354 for (i = 0; i < i_done; i++) {
1355 clear_page_dirty_for_io(pages[i]);
1356 ClearPageChecked(pages[i]);
1357 set_page_extent_mapped(pages[i]);
1358 set_page_dirty(pages[i]);
1359 unlock_page(pages[i]);
1362 btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
1364 extent_changeset_free(data_reserved);
1367 for (i = 0; i < i_done; i++) {
1368 unlock_page(pages[i]);
1371 btrfs_delalloc_release_space(inode, data_reserved,
1372 start_index << PAGE_SHIFT,
1373 page_cnt << PAGE_SHIFT, true);
1374 btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
1376 extent_changeset_free(data_reserved);
1381 int btrfs_defrag_file(struct inode *inode, struct file *file,
1382 struct btrfs_ioctl_defrag_range_args *range,
1383 u64 newer_than, unsigned long max_to_defrag)
1385 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1386 struct btrfs_root *root = BTRFS_I(inode)->root;
1387 struct file_ra_state *ra = NULL;
1388 unsigned long last_index;
1389 u64 isize = i_size_read(inode);
1393 u64 newer_off = range->start;
1395 unsigned long ra_index = 0;
1397 int defrag_count = 0;
1398 int compress_type = BTRFS_COMPRESS_ZLIB;
1399 u32 extent_thresh = range->extent_thresh;
1400 unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1401 unsigned long cluster = max_cluster;
1402 u64 new_align = ~((u64)SZ_128K - 1);
1403 struct page **pages = NULL;
1404 bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1409 if (range->start >= isize)
1413 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1415 if (range->compress_type)
1416 compress_type = range->compress_type;
1419 if (extent_thresh == 0)
1420 extent_thresh = SZ_256K;
1423 * If we were not given a file, allocate a readahead context. As
1424 * readahead is just an optimization, defrag will work without it so
1425 * we don't error out.
1428 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1430 file_ra_state_init(ra, inode->i_mapping);
1435 pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
1441 /* find the last page to defrag */
1442 if (range->start + range->len > range->start) {
1443 last_index = min_t(u64, isize - 1,
1444 range->start + range->len - 1) >> PAGE_SHIFT;
1446 last_index = (isize - 1) >> PAGE_SHIFT;
1450 ret = find_new_extents(root, inode, newer_than,
1451 &newer_off, SZ_64K);
1453 range->start = newer_off;
1455 * we always align our defrag to help keep
1456 * the extents in the file evenly spaced
1458 i = (newer_off & new_align) >> PAGE_SHIFT;
1462 i = range->start >> PAGE_SHIFT;
1465 max_to_defrag = last_index - i + 1;
1468 * make writeback starts from i, so the defrag range can be
1469 * written sequentially.
1471 if (i < inode->i_mapping->writeback_index)
1472 inode->i_mapping->writeback_index = i;
1474 while (i <= last_index && defrag_count < max_to_defrag &&
1475 (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
1477 * make sure we stop running if someone unmounts
1480 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1483 if (btrfs_defrag_cancelled(fs_info)) {
1484 btrfs_debug(fs_info, "defrag_file cancelled");
1489 if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
1490 extent_thresh, &last_len, &skip,
1491 &defrag_end, do_compress)){
1494 * the should_defrag function tells us how much to skip
1495 * bump our counter by the suggested amount
1497 next = DIV_ROUND_UP(skip, PAGE_SIZE);
1498 i = max(i + 1, next);
1503 cluster = (PAGE_ALIGN(defrag_end) >>
1505 cluster = min(cluster, max_cluster);
1507 cluster = max_cluster;
1510 if (i + cluster > ra_index) {
1511 ra_index = max(i, ra_index);
1513 page_cache_sync_readahead(inode->i_mapping, ra,
1514 file, ra_index, cluster);
1515 ra_index += cluster;
1519 if (IS_SWAPFILE(inode)) {
1523 BTRFS_I(inode)->defrag_compress = compress_type;
1524 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1527 inode_unlock(inode);
1531 defrag_count += ret;
1532 balance_dirty_pages_ratelimited(inode->i_mapping);
1533 inode_unlock(inode);
1536 if (newer_off == (u64)-1)
1542 newer_off = max(newer_off + 1,
1543 (u64)i << PAGE_SHIFT);
1545 ret = find_new_extents(root, inode, newer_than,
1546 &newer_off, SZ_64K);
1548 range->start = newer_off;
1549 i = (newer_off & new_align) >> PAGE_SHIFT;
1556 last_len += ret << PAGE_SHIFT;
1564 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1565 filemap_flush(inode->i_mapping);
1566 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1567 &BTRFS_I(inode)->runtime_flags))
1568 filemap_flush(inode->i_mapping);
1571 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1572 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1573 } else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
1574 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1582 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1583 inode_unlock(inode);
1591 static noinline int btrfs_ioctl_resize(struct file *file,
1594 struct inode *inode = file_inode(file);
1595 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1599 struct btrfs_root *root = BTRFS_I(inode)->root;
1600 struct btrfs_ioctl_vol_args *vol_args;
1601 struct btrfs_trans_handle *trans;
1602 struct btrfs_device *device = NULL;
1605 char *devstr = NULL;
1609 if (!capable(CAP_SYS_ADMIN))
1612 ret = mnt_want_write_file(file);
1616 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
1617 mnt_drop_write_file(file);
1618 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1621 vol_args = memdup_user(arg, sizeof(*vol_args));
1622 if (IS_ERR(vol_args)) {
1623 ret = PTR_ERR(vol_args);
1627 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1629 sizestr = vol_args->name;
1630 devstr = strchr(sizestr, ':');
1632 sizestr = devstr + 1;
1634 devstr = vol_args->name;
1635 ret = kstrtoull(devstr, 10, &devid);
1642 btrfs_info(fs_info, "resizing devid %llu", devid);
1645 device = btrfs_find_device(fs_info, devid, NULL, NULL);
1647 btrfs_info(fs_info, "resizer unable to find device %llu",
1653 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1655 "resizer unable to apply on readonly device %llu",
1661 if (!strcmp(sizestr, "max"))
1662 new_size = device->bdev->bd_inode->i_size;
1664 if (sizestr[0] == '-') {
1667 } else if (sizestr[0] == '+') {
1671 new_size = memparse(sizestr, &retptr);
1672 if (*retptr != '\0' || new_size == 0) {
1678 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1683 old_size = btrfs_device_get_total_bytes(device);
1686 if (new_size > old_size) {
1690 new_size = old_size - new_size;
1691 } else if (mod > 0) {
1692 if (new_size > ULLONG_MAX - old_size) {
1696 new_size = old_size + new_size;
1699 if (new_size < SZ_256M) {
1703 if (new_size > device->bdev->bd_inode->i_size) {
1708 new_size = round_down(new_size, fs_info->sectorsize);
1710 btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1711 rcu_str_deref(device->name), new_size);
1713 if (new_size > old_size) {
1714 trans = btrfs_start_transaction(root, 0);
1715 if (IS_ERR(trans)) {
1716 ret = PTR_ERR(trans);
1719 ret = btrfs_grow_device(trans, device, new_size);
1720 btrfs_commit_transaction(trans);
1721 } else if (new_size < old_size) {
1722 ret = btrfs_shrink_device(device, new_size);
1723 } /* equal, nothing need to do */
1728 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
1729 mnt_drop_write_file(file);
1733 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1734 const char *name, unsigned long fd, int subvol,
1735 u64 *transid, bool readonly,
1736 struct btrfs_qgroup_inherit *inherit)
1741 if (!S_ISDIR(file_inode(file)->i_mode))
1744 ret = mnt_want_write_file(file);
1748 namelen = strlen(name);
1749 if (strchr(name, '/')) {
1751 goto out_drop_write;
1754 if (name[0] == '.' &&
1755 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1757 goto out_drop_write;
1761 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1762 NULL, transid, readonly, inherit);
1764 struct fd src = fdget(fd);
1765 struct inode *src_inode;
1768 goto out_drop_write;
1771 src_inode = file_inode(src.file);
1772 if (src_inode->i_sb != file_inode(file)->i_sb) {
1773 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1774 "Snapshot src from another FS");
1776 } else if (!inode_owner_or_capable(src_inode)) {
1778 * Subvolume creation is not restricted, but snapshots
1779 * are limited to own subvolumes only
1783 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1784 BTRFS_I(src_inode)->root,
1785 transid, readonly, inherit);
1790 mnt_drop_write_file(file);
1795 static noinline int btrfs_ioctl_snap_create(struct file *file,
1796 void __user *arg, int subvol)
1798 struct btrfs_ioctl_vol_args *vol_args;
1801 if (!S_ISDIR(file_inode(file)->i_mode))
1804 vol_args = memdup_user(arg, sizeof(*vol_args));
1805 if (IS_ERR(vol_args))
1806 return PTR_ERR(vol_args);
1807 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1809 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1810 vol_args->fd, subvol,
1817 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1818 void __user *arg, int subvol)
1820 struct btrfs_ioctl_vol_args_v2 *vol_args;
1824 bool readonly = false;
1825 struct btrfs_qgroup_inherit *inherit = NULL;
1827 if (!S_ISDIR(file_inode(file)->i_mode))
1830 vol_args = memdup_user(arg, sizeof(*vol_args));
1831 if (IS_ERR(vol_args))
1832 return PTR_ERR(vol_args);
1833 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1835 if (vol_args->flags &
1836 ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1837 BTRFS_SUBVOL_QGROUP_INHERIT)) {
1842 if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1844 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1846 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1847 if (vol_args->size > PAGE_SIZE) {
1851 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1852 if (IS_ERR(inherit)) {
1853 ret = PTR_ERR(inherit);
1858 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1859 vol_args->fd, subvol, ptr,
1864 if (ptr && copy_to_user(arg +
1865 offsetof(struct btrfs_ioctl_vol_args_v2,
1877 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1880 struct inode *inode = file_inode(file);
1881 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1882 struct btrfs_root *root = BTRFS_I(inode)->root;
1886 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1889 down_read(&fs_info->subvol_sem);
1890 if (btrfs_root_readonly(root))
1891 flags |= BTRFS_SUBVOL_RDONLY;
1892 up_read(&fs_info->subvol_sem);
1894 if (copy_to_user(arg, &flags, sizeof(flags)))
1900 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1903 struct inode *inode = file_inode(file);
1904 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1905 struct btrfs_root *root = BTRFS_I(inode)->root;
1906 struct btrfs_trans_handle *trans;
1911 if (!inode_owner_or_capable(inode))
1914 ret = mnt_want_write_file(file);
1918 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1920 goto out_drop_write;
1923 if (copy_from_user(&flags, arg, sizeof(flags))) {
1925 goto out_drop_write;
1928 if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1930 goto out_drop_write;
1933 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1935 goto out_drop_write;
1938 down_write(&fs_info->subvol_sem);
1941 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1944 root_flags = btrfs_root_flags(&root->root_item);
1945 if (flags & BTRFS_SUBVOL_RDONLY) {
1946 btrfs_set_root_flags(&root->root_item,
1947 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1950 * Block RO -> RW transition if this subvolume is involved in
1953 spin_lock(&root->root_item_lock);
1954 if (root->send_in_progress == 0) {
1955 btrfs_set_root_flags(&root->root_item,
1956 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1957 spin_unlock(&root->root_item_lock);
1959 spin_unlock(&root->root_item_lock);
1961 "Attempt to set subvolume %llu read-write during send",
1962 root->root_key.objectid);
1968 trans = btrfs_start_transaction(root, 1);
1969 if (IS_ERR(trans)) {
1970 ret = PTR_ERR(trans);
1974 ret = btrfs_update_root(trans, fs_info->tree_root,
1975 &root->root_key, &root->root_item);
1977 btrfs_end_transaction(trans);
1981 ret = btrfs_commit_transaction(trans);
1985 btrfs_set_root_flags(&root->root_item, root_flags);
1987 up_write(&fs_info->subvol_sem);
1989 mnt_drop_write_file(file);
1994 static noinline int key_in_sk(struct btrfs_key *key,
1995 struct btrfs_ioctl_search_key *sk)
1997 struct btrfs_key test;
2000 test.objectid = sk->min_objectid;
2001 test.type = sk->min_type;
2002 test.offset = sk->min_offset;
2004 ret = btrfs_comp_cpu_keys(key, &test);
2008 test.objectid = sk->max_objectid;
2009 test.type = sk->max_type;
2010 test.offset = sk->max_offset;
2012 ret = btrfs_comp_cpu_keys(key, &test);
2018 static noinline int copy_to_sk(struct btrfs_path *path,
2019 struct btrfs_key *key,
2020 struct btrfs_ioctl_search_key *sk,
2023 unsigned long *sk_offset,
2027 struct extent_buffer *leaf;
2028 struct btrfs_ioctl_search_header sh;
2029 struct btrfs_key test;
2030 unsigned long item_off;
2031 unsigned long item_len;
2037 leaf = path->nodes[0];
2038 slot = path->slots[0];
2039 nritems = btrfs_header_nritems(leaf);
2041 if (btrfs_header_generation(leaf) > sk->max_transid) {
2045 found_transid = btrfs_header_generation(leaf);
2047 for (i = slot; i < nritems; i++) {
2048 item_off = btrfs_item_ptr_offset(leaf, i);
2049 item_len = btrfs_item_size_nr(leaf, i);
2051 btrfs_item_key_to_cpu(leaf, key, i);
2052 if (!key_in_sk(key, sk))
2055 if (sizeof(sh) + item_len > *buf_size) {
2062 * return one empty item back for v1, which does not
2066 *buf_size = sizeof(sh) + item_len;
2071 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2076 sh.objectid = key->objectid;
2077 sh.offset = key->offset;
2078 sh.type = key->type;
2080 sh.transid = found_transid;
2082 /* copy search result header */
2083 if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2088 *sk_offset += sizeof(sh);
2091 char __user *up = ubuf + *sk_offset;
2093 if (read_extent_buffer_to_user(leaf, up,
2094 item_off, item_len)) {
2099 *sk_offset += item_len;
2103 if (ret) /* -EOVERFLOW from above */
2106 if (*num_found >= sk->nr_items) {
2113 test.objectid = sk->max_objectid;
2114 test.type = sk->max_type;
2115 test.offset = sk->max_offset;
2116 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2118 else if (key->offset < (u64)-1)
2120 else if (key->type < (u8)-1) {
2123 } else if (key->objectid < (u64)-1) {
2131 * 0: all items from this leaf copied, continue with next
2132 * 1: * more items can be copied, but unused buffer is too small
2133 * * all items were found
2134 * Either way, it will stops the loop which iterates to the next
2136 * -EOVERFLOW: item was to large for buffer
2137 * -EFAULT: could not copy extent buffer back to userspace
2142 static noinline int search_ioctl(struct inode *inode,
2143 struct btrfs_ioctl_search_key *sk,
2147 struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2148 struct btrfs_root *root;
2149 struct btrfs_key key;
2150 struct btrfs_path *path;
2153 unsigned long sk_offset = 0;
2155 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2156 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2160 path = btrfs_alloc_path();
2164 if (sk->tree_id == 0) {
2165 /* search the root of the inode that was passed */
2166 root = BTRFS_I(inode)->root;
2168 key.objectid = sk->tree_id;
2169 key.type = BTRFS_ROOT_ITEM_KEY;
2170 key.offset = (u64)-1;
2171 root = btrfs_read_fs_root_no_name(info, &key);
2173 btrfs_free_path(path);
2174 return PTR_ERR(root);
2178 key.objectid = sk->min_objectid;
2179 key.type = sk->min_type;
2180 key.offset = sk->min_offset;
2183 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2189 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2190 &sk_offset, &num_found);
2191 btrfs_release_path(path);
2199 sk->nr_items = num_found;
2200 btrfs_free_path(path);
2204 static noinline int btrfs_ioctl_tree_search(struct file *file,
2207 struct btrfs_ioctl_search_args __user *uargs;
2208 struct btrfs_ioctl_search_key sk;
2209 struct inode *inode;
2213 if (!capable(CAP_SYS_ADMIN))
2216 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2218 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2221 buf_size = sizeof(uargs->buf);
2223 inode = file_inode(file);
2224 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2227 * In the origin implementation an overflow is handled by returning a
2228 * search header with a len of zero, so reset ret.
2230 if (ret == -EOVERFLOW)
2233 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2238 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2241 struct btrfs_ioctl_search_args_v2 __user *uarg;
2242 struct btrfs_ioctl_search_args_v2 args;
2243 struct inode *inode;
2246 const size_t buf_limit = SZ_16M;
2248 if (!capable(CAP_SYS_ADMIN))
2251 /* copy search header and buffer size */
2252 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2253 if (copy_from_user(&args, uarg, sizeof(args)))
2256 buf_size = args.buf_size;
2258 /* limit result size to 16MB */
2259 if (buf_size > buf_limit)
2260 buf_size = buf_limit;
2262 inode = file_inode(file);
2263 ret = search_ioctl(inode, &args.key, &buf_size,
2264 (char __user *)(&uarg->buf[0]));
2265 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2267 else if (ret == -EOVERFLOW &&
2268 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2275 * Search INODE_REFs to identify path name of 'dirid' directory
2276 * in a 'tree_id' tree. and sets path name to 'name'.
2278 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2279 u64 tree_id, u64 dirid, char *name)
2281 struct btrfs_root *root;
2282 struct btrfs_key key;
2288 struct btrfs_inode_ref *iref;
2289 struct extent_buffer *l;
2290 struct btrfs_path *path;
2292 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2297 path = btrfs_alloc_path();
2301 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2303 key.objectid = tree_id;
2304 key.type = BTRFS_ROOT_ITEM_KEY;
2305 key.offset = (u64)-1;
2306 root = btrfs_read_fs_root_no_name(info, &key);
2308 ret = PTR_ERR(root);
2312 key.objectid = dirid;
2313 key.type = BTRFS_INODE_REF_KEY;
2314 key.offset = (u64)-1;
2317 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2321 ret = btrfs_previous_item(root, path, dirid,
2322 BTRFS_INODE_REF_KEY);
2332 slot = path->slots[0];
2333 btrfs_item_key_to_cpu(l, &key, slot);
2335 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2336 len = btrfs_inode_ref_name_len(l, iref);
2338 total_len += len + 1;
2340 ret = -ENAMETOOLONG;
2345 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2347 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2350 btrfs_release_path(path);
2351 key.objectid = key.offset;
2352 key.offset = (u64)-1;
2353 dirid = key.objectid;
2355 memmove(name, ptr, total_len);
2356 name[total_len] = '\0';
2359 btrfs_free_path(path);
2363 static int btrfs_search_path_in_tree_user(struct inode *inode,
2364 struct btrfs_ioctl_ino_lookup_user_args *args)
2366 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2367 struct super_block *sb = inode->i_sb;
2368 struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2369 u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2370 u64 dirid = args->dirid;
2371 unsigned long item_off;
2372 unsigned long item_len;
2373 struct btrfs_inode_ref *iref;
2374 struct btrfs_root_ref *rref;
2375 struct btrfs_root *root;
2376 struct btrfs_path *path;
2377 struct btrfs_key key, key2;
2378 struct extent_buffer *leaf;
2379 struct inode *temp_inode;
2386 path = btrfs_alloc_path();
2391 * If the bottom subvolume does not exist directly under upper_limit,
2392 * construct the path in from the bottom up.
2394 if (dirid != upper_limit.objectid) {
2395 ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2397 key.objectid = treeid;
2398 key.type = BTRFS_ROOT_ITEM_KEY;
2399 key.offset = (u64)-1;
2400 root = btrfs_read_fs_root_no_name(fs_info, &key);
2402 ret = PTR_ERR(root);
2406 key.objectid = dirid;
2407 key.type = BTRFS_INODE_REF_KEY;
2408 key.offset = (u64)-1;
2410 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2413 } else if (ret > 0) {
2414 ret = btrfs_previous_item(root, path, dirid,
2415 BTRFS_INODE_REF_KEY);
2418 } else if (ret > 0) {
2424 leaf = path->nodes[0];
2425 slot = path->slots[0];
2426 btrfs_item_key_to_cpu(leaf, &key, slot);
2428 iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2429 len = btrfs_inode_ref_name_len(leaf, iref);
2431 total_len += len + 1;
2432 if (ptr < args->path) {
2433 ret = -ENAMETOOLONG;
2438 read_extent_buffer(leaf, ptr,
2439 (unsigned long)(iref + 1), len);
2441 /* Check the read+exec permission of this directory */
2442 ret = btrfs_previous_item(root, path, dirid,
2443 BTRFS_INODE_ITEM_KEY);
2446 } else if (ret > 0) {
2451 leaf = path->nodes[0];
2452 slot = path->slots[0];
2453 btrfs_item_key_to_cpu(leaf, &key2, slot);
2454 if (key2.objectid != dirid) {
2459 temp_inode = btrfs_iget(sb, &key2, root, NULL);
2460 if (IS_ERR(temp_inode)) {
2461 ret = PTR_ERR(temp_inode);
2464 ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC);
2471 if (key.offset == upper_limit.objectid)
2473 if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2478 btrfs_release_path(path);
2479 key.objectid = key.offset;
2480 key.offset = (u64)-1;
2481 dirid = key.objectid;
2484 memmove(args->path, ptr, total_len);
2485 args->path[total_len] = '\0';
2486 btrfs_release_path(path);
2489 /* Get the bottom subvolume's name from ROOT_REF */
2490 root = fs_info->tree_root;
2491 key.objectid = treeid;
2492 key.type = BTRFS_ROOT_REF_KEY;
2493 key.offset = args->treeid;
2494 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2497 } else if (ret > 0) {
2502 leaf = path->nodes[0];
2503 slot = path->slots[0];
2504 btrfs_item_key_to_cpu(leaf, &key, slot);
2506 item_off = btrfs_item_ptr_offset(leaf, slot);
2507 item_len = btrfs_item_size_nr(leaf, slot);
2508 /* Check if dirid in ROOT_REF corresponds to passed dirid */
2509 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2510 if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2515 /* Copy subvolume's name */
2516 item_off += sizeof(struct btrfs_root_ref);
2517 item_len -= sizeof(struct btrfs_root_ref);
2518 read_extent_buffer(leaf, args->name, item_off, item_len);
2519 args->name[item_len] = 0;
2522 btrfs_free_path(path);
2526 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2529 struct btrfs_ioctl_ino_lookup_args *args;
2530 struct inode *inode;
2533 args = memdup_user(argp, sizeof(*args));
2535 return PTR_ERR(args);
2537 inode = file_inode(file);
2540 * Unprivileged query to obtain the containing subvolume root id. The
2541 * path is reset so it's consistent with btrfs_search_path_in_tree.
2543 if (args->treeid == 0)
2544 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2546 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2551 if (!capable(CAP_SYS_ADMIN)) {
2556 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2557 args->treeid, args->objectid,
2561 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2569 * Version of ino_lookup ioctl (unprivileged)
2571 * The main differences from ino_lookup ioctl are:
2573 * 1. Read + Exec permission will be checked using inode_permission() during
2574 * path construction. -EACCES will be returned in case of failure.
2575 * 2. Path construction will be stopped at the inode number which corresponds
2576 * to the fd with which this ioctl is called. If constructed path does not
2577 * exist under fd's inode, -EACCES will be returned.
2578 * 3. The name of bottom subvolume is also searched and filled.
2580 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2582 struct btrfs_ioctl_ino_lookup_user_args *args;
2583 struct inode *inode;
2586 args = memdup_user(argp, sizeof(*args));
2588 return PTR_ERR(args);
2590 inode = file_inode(file);
2592 if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2593 BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2595 * The subvolume does not exist under fd with which this is
2602 ret = btrfs_search_path_in_tree_user(inode, args);
2604 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2611 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2612 static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2614 struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2615 struct btrfs_fs_info *fs_info;
2616 struct btrfs_root *root;
2617 struct btrfs_path *path;
2618 struct btrfs_key key;
2619 struct btrfs_root_item *root_item;
2620 struct btrfs_root_ref *rref;
2621 struct extent_buffer *leaf;
2622 unsigned long item_off;
2623 unsigned long item_len;
2624 struct inode *inode;
2628 path = btrfs_alloc_path();
2632 subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2634 btrfs_free_path(path);
2638 inode = file_inode(file);
2639 fs_info = BTRFS_I(inode)->root->fs_info;
2641 /* Get root_item of inode's subvolume */
2642 key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2643 key.type = BTRFS_ROOT_ITEM_KEY;
2644 key.offset = (u64)-1;
2645 root = btrfs_read_fs_root_no_name(fs_info, &key);
2647 ret = PTR_ERR(root);
2650 root_item = &root->root_item;
2652 subvol_info->treeid = key.objectid;
2654 subvol_info->generation = btrfs_root_generation(root_item);
2655 subvol_info->flags = btrfs_root_flags(root_item);
2657 memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2658 memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2660 memcpy(subvol_info->received_uuid, root_item->received_uuid,
2663 subvol_info->ctransid = btrfs_root_ctransid(root_item);
2664 subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2665 subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2667 subvol_info->otransid = btrfs_root_otransid(root_item);
2668 subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2669 subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2671 subvol_info->stransid = btrfs_root_stransid(root_item);
2672 subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2673 subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2675 subvol_info->rtransid = btrfs_root_rtransid(root_item);
2676 subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2677 subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2679 if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2680 /* Search root tree for ROOT_BACKREF of this subvolume */
2681 root = fs_info->tree_root;
2683 key.type = BTRFS_ROOT_BACKREF_KEY;
2685 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2688 } else if (path->slots[0] >=
2689 btrfs_header_nritems(path->nodes[0])) {
2690 ret = btrfs_next_leaf(root, path);
2693 } else if (ret > 0) {
2699 leaf = path->nodes[0];
2700 slot = path->slots[0];
2701 btrfs_item_key_to_cpu(leaf, &key, slot);
2702 if (key.objectid == subvol_info->treeid &&
2703 key.type == BTRFS_ROOT_BACKREF_KEY) {
2704 subvol_info->parent_id = key.offset;
2706 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2707 subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2709 item_off = btrfs_item_ptr_offset(leaf, slot)
2710 + sizeof(struct btrfs_root_ref);
2711 item_len = btrfs_item_size_nr(leaf, slot)
2712 - sizeof(struct btrfs_root_ref);
2713 read_extent_buffer(leaf, subvol_info->name,
2714 item_off, item_len);
2721 if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2725 btrfs_free_path(path);
2726 kzfree(subvol_info);
2731 * Return ROOT_REF information of the subvolume containing this inode
2732 * except the subvolume name.
2734 static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
2736 struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
2737 struct btrfs_root_ref *rref;
2738 struct btrfs_root *root;
2739 struct btrfs_path *path;
2740 struct btrfs_key key;
2741 struct extent_buffer *leaf;
2742 struct inode *inode;
2748 path = btrfs_alloc_path();
2752 rootrefs = memdup_user(argp, sizeof(*rootrefs));
2753 if (IS_ERR(rootrefs)) {
2754 btrfs_free_path(path);
2755 return PTR_ERR(rootrefs);
2758 inode = file_inode(file);
2759 root = BTRFS_I(inode)->root->fs_info->tree_root;
2760 objectid = BTRFS_I(inode)->root->root_key.objectid;
2762 key.objectid = objectid;
2763 key.type = BTRFS_ROOT_REF_KEY;
2764 key.offset = rootrefs->min_treeid;
2767 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2770 } else if (path->slots[0] >=
2771 btrfs_header_nritems(path->nodes[0])) {
2772 ret = btrfs_next_leaf(root, path);
2775 } else if (ret > 0) {
2781 leaf = path->nodes[0];
2782 slot = path->slots[0];
2784 btrfs_item_key_to_cpu(leaf, &key, slot);
2785 if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
2790 if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
2795 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2796 rootrefs->rootref[found].treeid = key.offset;
2797 rootrefs->rootref[found].dirid =
2798 btrfs_root_ref_dirid(leaf, rref);
2801 ret = btrfs_next_item(root, path);
2804 } else if (ret > 0) {
2811 if (!ret || ret == -EOVERFLOW) {
2812 rootrefs->num_items = found;
2813 /* update min_treeid for next search */
2815 rootrefs->min_treeid =
2816 rootrefs->rootref[found - 1].treeid + 1;
2817 if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
2822 btrfs_free_path(path);
2827 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2830 struct dentry *parent = file->f_path.dentry;
2831 struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2832 struct dentry *dentry;
2833 struct inode *dir = d_inode(parent);
2834 struct inode *inode;
2835 struct btrfs_root *root = BTRFS_I(dir)->root;
2836 struct btrfs_root *dest = NULL;
2837 struct btrfs_ioctl_vol_args *vol_args;
2841 if (!S_ISDIR(dir->i_mode))
2844 vol_args = memdup_user(arg, sizeof(*vol_args));
2845 if (IS_ERR(vol_args))
2846 return PTR_ERR(vol_args);
2848 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2849 namelen = strlen(vol_args->name);
2850 if (strchr(vol_args->name, '/') ||
2851 strncmp(vol_args->name, "..", namelen) == 0) {
2856 err = mnt_want_write_file(file);
2861 err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
2863 goto out_drop_write;
2864 dentry = lookup_one_len(vol_args->name, parent, namelen);
2865 if (IS_ERR(dentry)) {
2866 err = PTR_ERR(dentry);
2867 goto out_unlock_dir;
2870 if (d_really_is_negative(dentry)) {
2875 inode = d_inode(dentry);
2876 dest = BTRFS_I(inode)->root;
2877 if (!capable(CAP_SYS_ADMIN)) {
2879 * Regular user. Only allow this with a special mount
2880 * option, when the user has write+exec access to the
2881 * subvol root, and when rmdir(2) would have been
2884 * Note that this is _not_ check that the subvol is
2885 * empty or doesn't contain data that we wouldn't
2886 * otherwise be able to delete.
2888 * Users who want to delete empty subvols should try
2892 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
2896 * Do not allow deletion if the parent dir is the same
2897 * as the dir to be deleted. That means the ioctl
2898 * must be called on the dentry referencing the root
2899 * of the subvol, not a random directory contained
2906 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2911 /* check if subvolume may be deleted by a user */
2912 err = btrfs_may_delete(dir, dentry, 1);
2916 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2922 err = btrfs_delete_subvolume(dir, dentry);
2923 inode_unlock(inode);
2932 mnt_drop_write_file(file);
2938 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2940 struct inode *inode = file_inode(file);
2941 struct btrfs_root *root = BTRFS_I(inode)->root;
2942 struct btrfs_ioctl_defrag_range_args *range;
2945 ret = mnt_want_write_file(file);
2949 if (btrfs_root_readonly(root)) {
2954 switch (inode->i_mode & S_IFMT) {
2956 if (!capable(CAP_SYS_ADMIN)) {
2960 ret = btrfs_defrag_root(root);
2964 * Note that this does not check the file descriptor for write
2965 * access. This prevents defragmenting executables that are
2966 * running and allows defrag on files open in read-only mode.
2968 if (!capable(CAP_SYS_ADMIN) &&
2969 inode_permission(inode, MAY_WRITE)) {
2974 range = kzalloc(sizeof(*range), GFP_KERNEL);
2981 if (copy_from_user(range, argp,
2987 /* compression requires us to start the IO */
2988 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2989 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2990 range->extent_thresh = (u32)-1;
2993 /* the rest are all set to zero by kzalloc */
2994 range->len = (u64)-1;
2996 ret = btrfs_defrag_file(file_inode(file), file,
2997 range, BTRFS_OLDEST_GENERATION, 0);
3006 mnt_drop_write_file(file);
3010 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3012 struct btrfs_ioctl_vol_args *vol_args;
3015 if (!capable(CAP_SYS_ADMIN))
3018 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
3019 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3021 vol_args = memdup_user(arg, sizeof(*vol_args));
3022 if (IS_ERR(vol_args)) {
3023 ret = PTR_ERR(vol_args);
3027 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3028 ret = btrfs_init_new_device(fs_info, vol_args->name);
3031 btrfs_info(fs_info, "disk added %s", vol_args->name);
3035 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3039 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3041 struct inode *inode = file_inode(file);
3042 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3043 struct btrfs_ioctl_vol_args_v2 *vol_args;
3046 if (!capable(CAP_SYS_ADMIN))
3049 ret = mnt_want_write_file(file);
3053 vol_args = memdup_user(arg, sizeof(*vol_args));
3054 if (IS_ERR(vol_args)) {
3055 ret = PTR_ERR(vol_args);
3059 /* Check for compatibility reject unknown flags */
3060 if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
3065 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3066 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3070 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3071 ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
3073 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3074 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3076 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3079 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3080 btrfs_info(fs_info, "device deleted: id %llu",
3083 btrfs_info(fs_info, "device deleted: %s",
3089 mnt_drop_write_file(file);
3093 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3095 struct inode *inode = file_inode(file);
3096 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3097 struct btrfs_ioctl_vol_args *vol_args;
3100 if (!capable(CAP_SYS_ADMIN))
3103 ret = mnt_want_write_file(file);
3107 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3108 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3109 goto out_drop_write;
3112 vol_args = memdup_user(arg, sizeof(*vol_args));
3113 if (IS_ERR(vol_args)) {
3114 ret = PTR_ERR(vol_args);
3118 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3119 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3122 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3125 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3127 mnt_drop_write_file(file);
3132 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3135 struct btrfs_ioctl_fs_info_args *fi_args;
3136 struct btrfs_device *device;
3137 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3140 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
3145 fi_args->num_devices = fs_devices->num_devices;
3147 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3148 if (device->devid > fi_args->max_id)
3149 fi_args->max_id = device->devid;
3153 memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
3154 fi_args->nodesize = fs_info->nodesize;
3155 fi_args->sectorsize = fs_info->sectorsize;
3156 fi_args->clone_alignment = fs_info->sectorsize;
3158 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3165 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3168 struct btrfs_ioctl_dev_info_args *di_args;
3169 struct btrfs_device *dev;
3171 char *s_uuid = NULL;
3173 di_args = memdup_user(arg, sizeof(*di_args));
3174 if (IS_ERR(di_args))
3175 return PTR_ERR(di_args);
3177 if (!btrfs_is_empty_uuid(di_args->uuid))
3178 s_uuid = di_args->uuid;
3181 dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
3188 di_args->devid = dev->devid;
3189 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3190 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3191 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3193 strncpy(di_args->path, rcu_str_deref(dev->name),
3194 sizeof(di_args->path) - 1);
3195 di_args->path[sizeof(di_args->path) - 1] = 0;
3197 di_args->path[0] = '\0';
3202 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3209 static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
3213 page = grab_cache_page(inode->i_mapping, index);
3215 return ERR_PTR(-ENOMEM);
3217 if (!PageUptodate(page)) {
3220 ret = btrfs_readpage(NULL, page);
3222 return ERR_PTR(ret);
3224 if (!PageUptodate(page)) {
3227 return ERR_PTR(-EIO);
3229 if (page->mapping != inode->i_mapping) {
3232 return ERR_PTR(-EAGAIN);
3239 static int gather_extent_pages(struct inode *inode, struct page **pages,
3240 int num_pages, u64 off)
3243 pgoff_t index = off >> PAGE_SHIFT;
3245 for (i = 0; i < num_pages; i++) {
3247 pages[i] = extent_same_get_page(inode, index + i);
3248 if (IS_ERR(pages[i])) {
3249 int err = PTR_ERR(pages[i]);
3260 static int lock_extent_range(struct inode *inode, u64 off, u64 len,
3261 bool retry_range_locking)
3264 * Do any pending delalloc/csum calculations on inode, one way or
3265 * another, and lock file content.
3266 * The locking order is:
3269 * 2) range in the inode's io tree
3272 struct btrfs_ordered_extent *ordered;
3273 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
3274 ordered = btrfs_lookup_first_ordered_extent(inode,
3277 ordered->file_offset + ordered->len <= off ||
3278 ordered->file_offset >= off + len) &&
3279 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
3280 off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
3282 btrfs_put_ordered_extent(ordered);
3285 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
3287 btrfs_put_ordered_extent(ordered);
3288 if (!retry_range_locking)
3290 btrfs_wait_ordered_range(inode, off, len);
3295 static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
3297 inode_unlock(inode1);
3298 inode_unlock(inode2);
3301 static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
3303 if (inode1 < inode2)
3304 swap(inode1, inode2);
3306 inode_lock_nested(inode1, I_MUTEX_PARENT);
3307 inode_lock_nested(inode2, I_MUTEX_CHILD);
3310 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
3311 struct inode *inode2, u64 loff2, u64 len)
3313 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3314 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3317 static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
3318 struct inode *inode2, u64 loff2, u64 len,
3319 bool retry_range_locking)
3323 if (inode1 < inode2) {
3324 swap(inode1, inode2);
3327 ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
3330 ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
3332 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
3339 struct page **src_pages;
3340 struct page **dst_pages;
3343 static void btrfs_cmp_data_free(struct cmp_pages *cmp)
3348 for (i = 0; i < cmp->num_pages; i++) {
3349 pg = cmp->src_pages[i];
3353 cmp->src_pages[i] = NULL;
3355 pg = cmp->dst_pages[i];
3359 cmp->dst_pages[i] = NULL;
3364 static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
3365 struct inode *dst, u64 dst_loff,
3366 u64 len, struct cmp_pages *cmp)
3369 int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
3371 cmp->num_pages = num_pages;
3373 ret = gather_extent_pages(src, cmp->src_pages, num_pages, loff);
3377 ret = gather_extent_pages(dst, cmp->dst_pages, num_pages, dst_loff);
3381 btrfs_cmp_data_free(cmp);
3385 static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
3389 struct page *src_page, *dst_page;
3390 unsigned int cmp_len = PAGE_SIZE;
3391 void *addr, *dst_addr;
3395 if (len < PAGE_SIZE)
3398 BUG_ON(i >= cmp->num_pages);
3400 src_page = cmp->src_pages[i];
3401 dst_page = cmp->dst_pages[i];
3402 ASSERT(PageLocked(src_page));
3403 ASSERT(PageLocked(dst_page));
3405 addr = kmap_atomic(src_page);
3406 dst_addr = kmap_atomic(dst_page);
3408 flush_dcache_page(src_page);
3409 flush_dcache_page(dst_page);
3411 if (memcmp(addr, dst_addr, cmp_len))
3414 kunmap_atomic(addr);
3415 kunmap_atomic(dst_addr);
3427 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3431 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3433 if (off + olen > inode->i_size || off + olen < off)
3436 /* if we extend to eof, continue to block boundary */
3437 if (off + len == inode->i_size)
3438 *plen = len = ALIGN(inode->i_size, bs) - off;
3440 /* Check that we are block aligned - btrfs_clone() requires this */
3441 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3447 static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 olen,
3448 struct inode *dst, u64 dst_loff,
3449 struct cmp_pages *cmp)
3453 bool same_inode = (src == dst);
3454 u64 same_lock_start = 0;
3455 u64 same_lock_len = 0;
3457 ret = extent_same_check_offsets(src, loff, &len, olen);
3461 ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3467 * Single inode case wants the same checks, except we
3468 * don't want our length pushed out past i_size as
3469 * comparing that data range makes no sense.
3471 * extent_same_check_offsets() will do this for an
3472 * unaligned length at i_size, so catch it here and
3473 * reject the request.
3475 * This effectively means we require aligned extents
3476 * for the single-inode case, whereas the other cases
3477 * allow an unaligned length so long as it ends at
3483 /* Check for overlapping ranges */
3484 if (dst_loff + len > loff && dst_loff < loff + len)
3487 same_lock_start = min_t(u64, loff, dst_loff);
3488 same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
3491 * If the source and destination inodes are different, the
3492 * source's range end offset matches the source's i_size, that
3493 * i_size is not a multiple of the sector size, and the
3494 * destination range does not go past the destination's i_size,
3495 * we must round down the length to the nearest sector size
3496 * multiple. If we don't do this adjustment we end replacing
3497 * with zeroes the bytes in the range that starts at the
3498 * deduplication range's end offset and ends at the next sector
3501 if (loff + olen == i_size_read(src) &&
3502 dst_loff + len < i_size_read(dst)) {
3503 const u64 sz = BTRFS_I(src)->root->fs_info->sectorsize;
3505 len = round_down(i_size_read(src), sz) - loff;
3513 ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, cmp);
3518 ret = lock_extent_range(src, same_lock_start, same_lock_len,
3521 ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3524 * If one of the inodes has dirty pages in the respective range or
3525 * ordered extents, we need to flush dellaloc and wait for all ordered
3526 * extents in the range. We must unlock the pages and the ranges in the
3527 * io trees to avoid deadlocks when flushing delalloc (requires locking
3528 * pages) and when waiting for ordered extents to complete (they require
3531 if (ret == -EAGAIN) {
3533 * Ranges in the io trees already unlocked. Now unlock all
3534 * pages before waiting for all IO to complete.
3536 btrfs_cmp_data_free(cmp);
3538 btrfs_wait_ordered_range(src, same_lock_start,
3541 btrfs_wait_ordered_range(src, loff, len);
3542 btrfs_wait_ordered_range(dst, dst_loff, len);
3548 /* ranges in the io trees already unlocked */
3549 btrfs_cmp_data_free(cmp);
3553 /* pass original length for comparison so we stay within i_size */
3554 ret = btrfs_cmp_data(olen, cmp);
3556 ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3559 unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
3560 same_lock_start + same_lock_len - 1);
3562 btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3564 btrfs_cmp_data_free(cmp);
3569 #define BTRFS_MAX_DEDUPE_LEN SZ_16M
3571 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3572 struct inode *dst, u64 dst_loff)
3575 struct cmp_pages cmp;
3576 int num_pages = PAGE_ALIGN(BTRFS_MAX_DEDUPE_LEN) >> PAGE_SHIFT;
3577 bool same_inode = (src == dst);
3578 u64 i, tail_len, chunk_count;
3586 btrfs_double_inode_lock(src, dst);
3588 /* don't make the dst file partly checksummed */
3589 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3590 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3595 if (IS_SWAPFILE(src) || IS_SWAPFILE(dst)) {
3600 tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3601 chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
3602 if (chunk_count == 0)
3603 num_pages = PAGE_ALIGN(tail_len) >> PAGE_SHIFT;
3606 * If deduping ranges in the same inode, locking rules make it
3607 * mandatory to always lock pages in ascending order to avoid deadlocks
3608 * with concurrent tasks (such as starting writeback/delalloc).
3610 if (same_inode && dst_loff < loff)
3611 swap(loff, dst_loff);
3614 * We must gather up all the pages before we initiate our extent
3615 * locking. We use an array for the page pointers. Size of the array is
3616 * bounded by len, which is in turn bounded by BTRFS_MAX_DEDUPE_LEN.
3618 cmp.src_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3619 GFP_KERNEL | __GFP_ZERO);
3620 cmp.dst_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3621 GFP_KERNEL | __GFP_ZERO);
3622 if (!cmp.src_pages || !cmp.dst_pages) {
3627 for (i = 0; i < chunk_count; i++) {
3628 ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
3629 dst, dst_loff, &cmp);
3633 loff += BTRFS_MAX_DEDUPE_LEN;
3634 dst_loff += BTRFS_MAX_DEDUPE_LEN;
3638 ret = btrfs_extent_same_range(src, loff, tail_len, dst,
3642 kvfree(cmp.src_pages);
3643 kvfree(cmp.dst_pages);
3649 btrfs_double_inode_unlock(src, dst);
3654 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3655 struct inode *inode,
3661 struct btrfs_root *root = BTRFS_I(inode)->root;
3664 inode_inc_iversion(inode);
3665 if (!no_time_update)
3666 inode->i_mtime = inode->i_ctime = current_time(inode);
3668 * We round up to the block size at eof when determining which
3669 * extents to clone above, but shouldn't round up the file size.
3671 if (endoff > destoff + olen)
3672 endoff = destoff + olen;
3673 if (endoff > inode->i_size)
3674 btrfs_i_size_write(BTRFS_I(inode), endoff);
3676 ret = btrfs_update_inode(trans, root, inode);
3678 btrfs_abort_transaction(trans, ret);
3679 btrfs_end_transaction(trans);
3682 ret = btrfs_end_transaction(trans);
3687 static void clone_update_extent_map(struct btrfs_inode *inode,
3688 const struct btrfs_trans_handle *trans,
3689 const struct btrfs_path *path,
3690 const u64 hole_offset,
3693 struct extent_map_tree *em_tree = &inode->extent_tree;
3694 struct extent_map *em;
3697 em = alloc_extent_map();
3699 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3704 struct btrfs_file_extent_item *fi;
3706 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
3707 struct btrfs_file_extent_item);
3708 btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
3709 em->generation = -1;
3710 if (btrfs_file_extent_type(path->nodes[0], fi) ==
3711 BTRFS_FILE_EXTENT_INLINE)
3712 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3713 &inode->runtime_flags);
3715 em->start = hole_offset;
3717 em->ram_bytes = em->len;
3718 em->orig_start = hole_offset;
3719 em->block_start = EXTENT_MAP_HOLE;
3721 em->orig_block_len = 0;
3722 em->compress_type = BTRFS_COMPRESS_NONE;
3723 em->generation = trans->transid;
3727 write_lock(&em_tree->lock);
3728 ret = add_extent_mapping(em_tree, em, 1);
3729 write_unlock(&em_tree->lock);
3730 if (ret != -EEXIST) {
3731 free_extent_map(em);
3734 btrfs_drop_extent_cache(inode, em->start,
3735 em->start + em->len - 1, 0);
3739 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3743 * Make sure we do not end up inserting an inline extent into a file that has
3744 * already other (non-inline) extents. If a file has an inline extent it can
3745 * not have any other extents and the (single) inline extent must start at the
3746 * file offset 0. Failing to respect these rules will lead to file corruption,
3747 * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
3749 * We can have extents that have been already written to disk or we can have
3750 * dirty ranges still in delalloc, in which case the extent maps and items are
3751 * created only when we run delalloc, and the delalloc ranges might fall outside
3752 * the range we are currently locking in the inode's io tree. So we check the
3753 * inode's i_size because of that (i_size updates are done while holding the
3754 * i_mutex, which we are holding here).
3755 * We also check to see if the inode has a size not greater than "datal" but has
3756 * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
3757 * protected against such concurrent fallocate calls by the i_mutex).
3759 * If the file has no extents but a size greater than datal, do not allow the
3760 * copy because we would need turn the inline extent into a non-inline one (even
3761 * with NO_HOLES enabled). If we find our destination inode only has one inline
3762 * extent, just overwrite it with the source inline extent if its size is less
3763 * than the source extent's size, or we could copy the source inline extent's
3764 * data into the destination inode's inline extent if the later is greater then
3767 static int clone_copy_inline_extent(struct inode *dst,
3768 struct btrfs_trans_handle *trans,
3769 struct btrfs_path *path,
3770 struct btrfs_key *new_key,
3771 const u64 drop_start,
3777 struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
3778 struct btrfs_root *root = BTRFS_I(dst)->root;
3779 const u64 aligned_end = ALIGN(new_key->offset + datal,
3780 fs_info->sectorsize);
3782 struct btrfs_key key;
3784 if (new_key->offset > 0)
3787 key.objectid = btrfs_ino(BTRFS_I(dst));
3788 key.type = BTRFS_EXTENT_DATA_KEY;
3790 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3793 } else if (ret > 0) {
3794 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3795 ret = btrfs_next_leaf(root, path);
3799 goto copy_inline_extent;
3801 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3802 if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3803 key.type == BTRFS_EXTENT_DATA_KEY) {
3804 ASSERT(key.offset > 0);
3807 } else if (i_size_read(dst) <= datal) {
3808 struct btrfs_file_extent_item *ei;
3812 * If the file size is <= datal, make sure there are no other
3813 * extents following (can happen do to an fallocate call with
3814 * the flag FALLOC_FL_KEEP_SIZE).
3816 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3817 struct btrfs_file_extent_item);
3819 * If it's an inline extent, it can not have other extents
3822 if (btrfs_file_extent_type(path->nodes[0], ei) ==
3823 BTRFS_FILE_EXTENT_INLINE)
3824 goto copy_inline_extent;
3826 ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3827 if (ext_len > aligned_end)
3830 ret = btrfs_next_item(root, path);
3833 } else if (ret == 0) {
3834 btrfs_item_key_to_cpu(path->nodes[0], &key,
3836 if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3837 key.type == BTRFS_EXTENT_DATA_KEY)
3844 * We have no extent items, or we have an extent at offset 0 which may
3845 * or may not be inlined. All these cases are dealt the same way.
3847 if (i_size_read(dst) > datal) {
3849 * If the destination inode has an inline extent...
3850 * This would require copying the data from the source inline
3851 * extent into the beginning of the destination's inline extent.
3852 * But this is really complex, both extents can be compressed
3853 * or just one of them, which would require decompressing and
3854 * re-compressing data (which could increase the new compressed
3855 * size, not allowing the compressed data to fit anymore in an
3857 * So just don't support this case for now (it should be rare,
3858 * we are not really saving space when cloning inline extents).
3863 btrfs_release_path(path);
3864 ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
3867 ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
3872 const u32 start = btrfs_file_extent_calc_inline_size(0);
3874 memmove(inline_data + start, inline_data + start + skip, datal);
3877 write_extent_buffer(path->nodes[0], inline_data,
3878 btrfs_item_ptr_offset(path->nodes[0],
3881 inode_add_bytes(dst, datal);
3887 * btrfs_clone() - clone a range from inode file to another
3889 * @src: Inode to clone from
3890 * @inode: Inode to clone to
3891 * @off: Offset within source to start clone from
3892 * @olen: Original length, passed by user, of range to clone
3893 * @olen_aligned: Block-aligned value of olen
3894 * @destoff: Offset within @inode to start clone
3895 * @no_time_update: Whether to update mtime/ctime on the target inode
3897 static int btrfs_clone(struct inode *src, struct inode *inode,
3898 const u64 off, const u64 olen, const u64 olen_aligned,
3899 const u64 destoff, int no_time_update)
3901 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3902 struct btrfs_root *root = BTRFS_I(inode)->root;
3903 struct btrfs_path *path = NULL;
3904 struct extent_buffer *leaf;
3905 struct btrfs_trans_handle *trans;
3907 struct btrfs_key key;
3911 const u64 len = olen_aligned;
3912 u64 last_dest_end = destoff;
3915 buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3919 path = btrfs_alloc_path();
3925 path->reada = READA_FORWARD;
3927 key.objectid = btrfs_ino(BTRFS_I(src));
3928 key.type = BTRFS_EXTENT_DATA_KEY;
3932 u64 next_key_min_offset = key.offset + 1;
3935 * note the key will change type as we walk through the
3938 path->leave_spinning = 1;
3939 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3944 * First search, if no extent item that starts at offset off was
3945 * found but the previous item is an extent item, it's possible
3946 * it might overlap our target range, therefore process it.
3948 if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3949 btrfs_item_key_to_cpu(path->nodes[0], &key,
3950 path->slots[0] - 1);
3951 if (key.type == BTRFS_EXTENT_DATA_KEY)
3955 nritems = btrfs_header_nritems(path->nodes[0]);
3957 if (path->slots[0] >= nritems) {
3958 ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3963 nritems = btrfs_header_nritems(path->nodes[0]);
3965 leaf = path->nodes[0];
3966 slot = path->slots[0];
3968 btrfs_item_key_to_cpu(leaf, &key, slot);
3969 if (key.type > BTRFS_EXTENT_DATA_KEY ||
3970 key.objectid != btrfs_ino(BTRFS_I(src)))
3973 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3974 struct btrfs_file_extent_item *extent;
3977 struct btrfs_key new_key;
3978 u64 disko = 0, diskl = 0;
3979 u64 datao = 0, datal = 0;
3983 extent = btrfs_item_ptr(leaf, slot,
3984 struct btrfs_file_extent_item);
3985 comp = btrfs_file_extent_compression(leaf, extent);
3986 type = btrfs_file_extent_type(leaf, extent);
3987 if (type == BTRFS_FILE_EXTENT_REG ||
3988 type == BTRFS_FILE_EXTENT_PREALLOC) {
3989 disko = btrfs_file_extent_disk_bytenr(leaf,
3991 diskl = btrfs_file_extent_disk_num_bytes(leaf,
3993 datao = btrfs_file_extent_offset(leaf, extent);
3994 datal = btrfs_file_extent_num_bytes(leaf,
3996 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3997 /* take upper bound, may be compressed */
3998 datal = btrfs_file_extent_ram_bytes(leaf,
4003 * The first search might have left us at an extent
4004 * item that ends before our target range's start, can
4005 * happen if we have holes and NO_HOLES feature enabled.
4007 if (key.offset + datal <= off) {
4010 } else if (key.offset >= off + len) {
4013 next_key_min_offset = key.offset + datal;
4014 size = btrfs_item_size_nr(leaf, slot);
4015 read_extent_buffer(leaf, buf,
4016 btrfs_item_ptr_offset(leaf, slot),
4019 btrfs_release_path(path);
4020 path->leave_spinning = 0;
4022 memcpy(&new_key, &key, sizeof(new_key));
4023 new_key.objectid = btrfs_ino(BTRFS_I(inode));
4024 if (off <= key.offset)
4025 new_key.offset = key.offset + destoff - off;
4027 new_key.offset = destoff;
4030 * Deal with a hole that doesn't have an extent item
4031 * that represents it (NO_HOLES feature enabled).
4032 * This hole is either in the middle of the cloning
4033 * range or at the beginning (fully overlaps it or
4034 * partially overlaps it).
4036 if (new_key.offset != last_dest_end)
4037 drop_start = last_dest_end;
4039 drop_start = new_key.offset;
4042 * 1 - adjusting old extent (we may have to split it)
4043 * 1 - add new extent
4046 trans = btrfs_start_transaction(root, 3);
4047 if (IS_ERR(trans)) {
4048 ret = PTR_ERR(trans);
4052 if (type == BTRFS_FILE_EXTENT_REG ||
4053 type == BTRFS_FILE_EXTENT_PREALLOC) {
4055 * a | --- range to clone ---| b
4056 * | ------------- extent ------------- |
4059 /* subtract range b */
4060 if (key.offset + datal > off + len)
4061 datal = off + len - key.offset;
4063 /* subtract range a */
4064 if (off > key.offset) {
4065 datao += off - key.offset;
4066 datal -= off - key.offset;
4069 ret = btrfs_drop_extents(trans, root, inode,
4071 new_key.offset + datal,
4074 if (ret != -EOPNOTSUPP)
4075 btrfs_abort_transaction(trans,
4077 btrfs_end_transaction(trans);
4081 ret = btrfs_insert_empty_item(trans, root, path,
4084 btrfs_abort_transaction(trans, ret);
4085 btrfs_end_transaction(trans);
4089 leaf = path->nodes[0];
4090 slot = path->slots[0];
4091 write_extent_buffer(leaf, buf,
4092 btrfs_item_ptr_offset(leaf, slot),
4095 extent = btrfs_item_ptr(leaf, slot,
4096 struct btrfs_file_extent_item);
4098 /* disko == 0 means it's a hole */
4102 btrfs_set_file_extent_offset(leaf, extent,
4104 btrfs_set_file_extent_num_bytes(leaf, extent,
4108 inode_add_bytes(inode, datal);
4109 ret = btrfs_inc_extent_ref(trans,
4112 root->root_key.objectid,
4113 btrfs_ino(BTRFS_I(inode)),
4114 new_key.offset - datao);
4116 btrfs_abort_transaction(trans,
4118 btrfs_end_transaction(trans);
4123 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
4127 if (off > key.offset) {
4128 skip = off - key.offset;
4129 new_key.offset += skip;
4132 if (key.offset + datal > off + len)
4133 trim = key.offset + datal - (off + len);
4135 if (comp && (skip || trim)) {
4137 btrfs_end_transaction(trans);
4140 size -= skip + trim;
4141 datal -= skip + trim;
4143 ret = clone_copy_inline_extent(inode,
4150 if (ret != -EOPNOTSUPP)
4151 btrfs_abort_transaction(trans,
4153 btrfs_end_transaction(trans);
4156 leaf = path->nodes[0];
4157 slot = path->slots[0];
4160 /* If we have an implicit hole (NO_HOLES feature). */
4161 if (drop_start < new_key.offset)
4162 clone_update_extent_map(BTRFS_I(inode), trans,
4164 new_key.offset - drop_start);
4166 clone_update_extent_map(BTRFS_I(inode), trans,
4169 btrfs_mark_buffer_dirty(leaf);
4170 btrfs_release_path(path);
4172 last_dest_end = ALIGN(new_key.offset + datal,
4173 fs_info->sectorsize);
4174 ret = clone_finish_inode_update(trans, inode,
4180 if (new_key.offset + datal >= destoff + len)
4183 btrfs_release_path(path);
4184 key.offset = next_key_min_offset;
4186 if (fatal_signal_pending(current)) {
4193 if (last_dest_end < destoff + len) {
4195 * We have an implicit hole (NO_HOLES feature is enabled) that
4196 * fully or partially overlaps our cloning range at its end.
4198 btrfs_release_path(path);
4201 * 1 - remove extent(s)
4204 trans = btrfs_start_transaction(root, 2);
4205 if (IS_ERR(trans)) {
4206 ret = PTR_ERR(trans);
4209 ret = btrfs_drop_extents(trans, root, inode,
4210 last_dest_end, destoff + len, 1);
4212 if (ret != -EOPNOTSUPP)
4213 btrfs_abort_transaction(trans, ret);
4214 btrfs_end_transaction(trans);
4217 clone_update_extent_map(BTRFS_I(inode), trans, NULL,
4219 destoff + len - last_dest_end);
4220 ret = clone_finish_inode_update(trans, inode, destoff + len,
4221 destoff, olen, no_time_update);
4225 btrfs_free_path(path);
4230 static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
4231 u64 off, u64 olen, u64 destoff)
4233 struct inode *inode = file_inode(file);
4234 struct inode *src = file_inode(file_src);
4235 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4236 struct btrfs_root *root = BTRFS_I(inode)->root;
4239 u64 bs = fs_info->sb->s_blocksize;
4240 int same_inode = src == inode;
4244 * - split compressed inline extents. annoying: we need to
4245 * decompress into destination's address_space (the file offset
4246 * may change, so source mapping won't do), then recompress (or
4247 * otherwise reinsert) a subrange.
4249 * - split destination inode's inline extents. The inline extents can
4250 * be either compressed or non-compressed.
4253 if (btrfs_root_readonly(root))
4256 if (file_src->f_path.mnt != file->f_path.mnt ||
4257 src->i_sb != inode->i_sb)
4260 if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
4264 btrfs_double_inode_lock(src, inode);
4269 /* don't make the dst file partly checksummed */
4270 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
4271 (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
4276 if (IS_SWAPFILE(src) || IS_SWAPFILE(inode)) {
4281 /* determine range to clone */
4283 if (off + len > src->i_size || off + len < off)
4286 olen = len = src->i_size - off;
4288 * If we extend to eof, continue to block boundary if and only if the
4289 * destination end offset matches the destination file's size, otherwise
4290 * we would be corrupting data by placing the eof block into the middle
4293 if (off + len == src->i_size) {
4294 if (!IS_ALIGNED(len, bs) && destoff + len < inode->i_size)
4296 len = ALIGN(src->i_size, bs) - off;
4304 /* verify the end result is block aligned */
4305 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
4306 !IS_ALIGNED(destoff, bs))
4309 /* verify if ranges are overlapped within the same file */
4311 if (destoff + len > off && destoff < off + len)
4315 if (destoff > inode->i_size) {
4316 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
4322 * Lock the target range too. Right after we replace the file extent
4323 * items in the fs tree (which now point to the cloned data), we might
4324 * have a worker replace them with extent items relative to a write
4325 * operation that was issued before this clone operation (i.e. confront
4326 * with inode.c:btrfs_finish_ordered_io).
4329 u64 lock_start = min_t(u64, off, destoff);
4330 u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
4332 ret = lock_extent_range(src, lock_start, lock_len, true);
4334 ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
4339 /* ranges in the io trees already unlocked */
4343 ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
4346 u64 lock_start = min_t(u64, off, destoff);
4347 u64 lock_end = max_t(u64, off, destoff) + len - 1;
4349 unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
4351 btrfs_double_extent_unlock(src, off, inode, destoff, len);
4354 * Truncate page cache pages so that future reads will see the cloned
4355 * data immediately and not the previous data.
4357 truncate_inode_pages_range(&inode->i_data,
4358 round_down(destoff, PAGE_SIZE),
4359 round_up(destoff + len, PAGE_SIZE) - 1);
4362 btrfs_double_inode_unlock(src, inode);
4368 loff_t btrfs_remap_file_range(struct file *src_file, loff_t off,
4369 struct file *dst_file, loff_t destoff, loff_t len,
4370 unsigned int remap_flags)
4374 if (remap_flags & ~(REMAP_FILE_DEDUP | REMAP_FILE_ADVISORY))
4377 if (remap_flags & REMAP_FILE_DEDUP) {
4378 struct inode *src = file_inode(src_file);
4379 struct inode *dst = file_inode(dst_file);
4380 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
4382 if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
4384 * Btrfs does not support blocksize < page_size. As a
4385 * result, btrfs_cmp_data() won't correctly handle
4386 * this situation without an update.
4391 ret = btrfs_extent_same(src, off, len, dst, destoff);
4393 ret = btrfs_clone_files(dst_file, src_file, off, len, destoff);
4395 return ret < 0 ? ret : len;
4398 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
4400 struct inode *inode = file_inode(file);
4401 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4402 struct btrfs_root *root = BTRFS_I(inode)->root;
4403 struct btrfs_root *new_root;
4404 struct btrfs_dir_item *di;
4405 struct btrfs_trans_handle *trans;
4406 struct btrfs_path *path;
4407 struct btrfs_key location;
4408 struct btrfs_disk_key disk_key;
4413 if (!capable(CAP_SYS_ADMIN))
4416 ret = mnt_want_write_file(file);
4420 if (copy_from_user(&objectid, argp, sizeof(objectid))) {
4426 objectid = BTRFS_FS_TREE_OBJECTID;
4428 location.objectid = objectid;
4429 location.type = BTRFS_ROOT_ITEM_KEY;
4430 location.offset = (u64)-1;
4432 new_root = btrfs_read_fs_root_no_name(fs_info, &location);
4433 if (IS_ERR(new_root)) {
4434 ret = PTR_ERR(new_root);
4437 if (!is_fstree(new_root->root_key.objectid)) {
4442 path = btrfs_alloc_path();
4447 path->leave_spinning = 1;
4449 trans = btrfs_start_transaction(root, 1);
4450 if (IS_ERR(trans)) {
4451 btrfs_free_path(path);
4452 ret = PTR_ERR(trans);
4456 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4457 di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
4458 dir_id, "default", 7, 1);
4459 if (IS_ERR_OR_NULL(di)) {
4460 btrfs_free_path(path);
4461 btrfs_end_transaction(trans);
4463 "Umm, you don't have the default diritem, this isn't going to work");
4468 btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
4469 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
4470 btrfs_mark_buffer_dirty(path->nodes[0]);
4471 btrfs_free_path(path);
4473 btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
4474 btrfs_end_transaction(trans);
4476 mnt_drop_write_file(file);
4480 static void get_block_group_info(struct list_head *groups_list,
4481 struct btrfs_ioctl_space_info *space)
4483 struct btrfs_block_group_cache *block_group;
4485 space->total_bytes = 0;
4486 space->used_bytes = 0;
4488 list_for_each_entry(block_group, groups_list, list) {
4489 space->flags = block_group->flags;
4490 space->total_bytes += block_group->key.offset;
4491 space->used_bytes +=
4492 btrfs_block_group_used(&block_group->item);
4496 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
4499 struct btrfs_ioctl_space_args space_args;
4500 struct btrfs_ioctl_space_info space;
4501 struct btrfs_ioctl_space_info *dest;
4502 struct btrfs_ioctl_space_info *dest_orig;
4503 struct btrfs_ioctl_space_info __user *user_dest;
4504 struct btrfs_space_info *info;
4505 static const u64 types[] = {
4506 BTRFS_BLOCK_GROUP_DATA,
4507 BTRFS_BLOCK_GROUP_SYSTEM,
4508 BTRFS_BLOCK_GROUP_METADATA,
4509 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4517 if (copy_from_user(&space_args,
4518 (struct btrfs_ioctl_space_args __user *)arg,
4519 sizeof(space_args)))
4522 for (i = 0; i < num_types; i++) {
4523 struct btrfs_space_info *tmp;
4527 list_for_each_entry_rcu(tmp, &fs_info->space_info,
4529 if (tmp->flags == types[i]) {
4539 down_read(&info->groups_sem);
4540 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4541 if (!list_empty(&info->block_groups[c]))
4544 up_read(&info->groups_sem);
4548 * Global block reserve, exported as a space_info
4552 /* space_slots == 0 means they are asking for a count */
4553 if (space_args.space_slots == 0) {
4554 space_args.total_spaces = slot_count;
4558 slot_count = min_t(u64, space_args.space_slots, slot_count);
4560 alloc_size = sizeof(*dest) * slot_count;
4562 /* we generally have at most 6 or so space infos, one for each raid
4563 * level. So, a whole page should be more than enough for everyone
4565 if (alloc_size > PAGE_SIZE)
4568 space_args.total_spaces = 0;
4569 dest = kmalloc(alloc_size, GFP_KERNEL);
4574 /* now we have a buffer to copy into */
4575 for (i = 0; i < num_types; i++) {
4576 struct btrfs_space_info *tmp;
4583 list_for_each_entry_rcu(tmp, &fs_info->space_info,
4585 if (tmp->flags == types[i]) {
4594 down_read(&info->groups_sem);
4595 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4596 if (!list_empty(&info->block_groups[c])) {
4597 get_block_group_info(&info->block_groups[c],
4599 memcpy(dest, &space, sizeof(space));
4601 space_args.total_spaces++;
4607 up_read(&info->groups_sem);
4611 * Add global block reserve
4614 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4616 spin_lock(&block_rsv->lock);
4617 space.total_bytes = block_rsv->size;
4618 space.used_bytes = block_rsv->size - block_rsv->reserved;
4619 spin_unlock(&block_rsv->lock);
4620 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
4621 memcpy(dest, &space, sizeof(space));
4622 space_args.total_spaces++;
4625 user_dest = (struct btrfs_ioctl_space_info __user *)
4626 (arg + sizeof(struct btrfs_ioctl_space_args));
4628 if (copy_to_user(user_dest, dest_orig, alloc_size))
4633 if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
4639 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
4642 struct btrfs_trans_handle *trans;
4646 trans = btrfs_attach_transaction_barrier(root);
4647 if (IS_ERR(trans)) {
4648 if (PTR_ERR(trans) != -ENOENT)
4649 return PTR_ERR(trans);
4651 /* No running transaction, don't bother */
4652 transid = root->fs_info->last_trans_committed;
4655 transid = trans->transid;
4656 ret = btrfs_commit_transaction_async(trans, 0);
4658 btrfs_end_transaction(trans);
4663 if (copy_to_user(argp, &transid, sizeof(transid)))
4668 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
4674 if (copy_from_user(&transid, argp, sizeof(transid)))
4677 transid = 0; /* current trans */
4679 return btrfs_wait_for_commit(fs_info, transid);
4682 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4684 struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4685 struct btrfs_ioctl_scrub_args *sa;
4688 if (!capable(CAP_SYS_ADMIN))
4691 sa = memdup_user(arg, sizeof(*sa));
4695 if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4696 ret = mnt_want_write_file(file);
4701 ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
4702 &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4705 if (copy_to_user(arg, sa, sizeof(*sa)))
4708 if (!(sa->flags & BTRFS_SCRUB_READONLY))
4709 mnt_drop_write_file(file);
4715 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4717 if (!capable(CAP_SYS_ADMIN))
4720 return btrfs_scrub_cancel(fs_info);
4723 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4726 struct btrfs_ioctl_scrub_args *sa;
4729 if (!capable(CAP_SYS_ADMIN))
4732 sa = memdup_user(arg, sizeof(*sa));
4736 ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4738 if (copy_to_user(arg, sa, sizeof(*sa)))
4745 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4748 struct btrfs_ioctl_get_dev_stats *sa;
4751 sa = memdup_user(arg, sizeof(*sa));
4755 if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4760 ret = btrfs_get_dev_stats(fs_info, sa);
4762 if (copy_to_user(arg, sa, sizeof(*sa)))
4769 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
4772 struct btrfs_ioctl_dev_replace_args *p;
4775 if (!capable(CAP_SYS_ADMIN))
4778 p = memdup_user(arg, sizeof(*p));
4783 case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4784 if (sb_rdonly(fs_info->sb)) {
4788 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4789 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4791 ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4792 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4795 case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4796 btrfs_dev_replace_status(fs_info, p);
4799 case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4800 p->result = btrfs_dev_replace_cancel(fs_info);
4808 if (copy_to_user(arg, p, sizeof(*p)))
4815 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4821 struct btrfs_ioctl_ino_path_args *ipa = NULL;
4822 struct inode_fs_paths *ipath = NULL;
4823 struct btrfs_path *path;
4825 if (!capable(CAP_DAC_READ_SEARCH))
4828 path = btrfs_alloc_path();
4834 ipa = memdup_user(arg, sizeof(*ipa));
4841 size = min_t(u32, ipa->size, 4096);
4842 ipath = init_ipath(size, root, path);
4843 if (IS_ERR(ipath)) {
4844 ret = PTR_ERR(ipath);
4849 ret = paths_from_inode(ipa->inum, ipath);
4853 for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4854 rel_ptr = ipath->fspath->val[i] -
4855 (u64)(unsigned long)ipath->fspath->val;
4856 ipath->fspath->val[i] = rel_ptr;
4859 ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4860 ipath->fspath, size);
4867 btrfs_free_path(path);
4874 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4876 struct btrfs_data_container *inodes = ctx;
4877 const size_t c = 3 * sizeof(u64);
4879 if (inodes->bytes_left >= c) {
4880 inodes->bytes_left -= c;
4881 inodes->val[inodes->elem_cnt] = inum;
4882 inodes->val[inodes->elem_cnt + 1] = offset;
4883 inodes->val[inodes->elem_cnt + 2] = root;
4884 inodes->elem_cnt += 3;
4886 inodes->bytes_missing += c - inodes->bytes_left;
4887 inodes->bytes_left = 0;
4888 inodes->elem_missed += 3;
4894 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4895 void __user *arg, int version)
4899 struct btrfs_ioctl_logical_ino_args *loi;
4900 struct btrfs_data_container *inodes = NULL;
4901 struct btrfs_path *path = NULL;
4904 if (!capable(CAP_SYS_ADMIN))
4907 loi = memdup_user(arg, sizeof(*loi));
4909 return PTR_ERR(loi);
4912 ignore_offset = false;
4913 size = min_t(u32, loi->size, SZ_64K);
4915 /* All reserved bits must be 0 for now */
4916 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4920 /* Only accept flags we have defined so far */
4921 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4925 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4926 size = min_t(u32, loi->size, SZ_16M);
4929 path = btrfs_alloc_path();
4935 inodes = init_data_container(size);
4936 if (IS_ERR(inodes)) {
4937 ret = PTR_ERR(inodes);
4942 ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4943 build_ino_list, inodes, ignore_offset);
4949 ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4955 btrfs_free_path(path);
4963 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4964 struct btrfs_ioctl_balance_args *bargs)
4966 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4968 bargs->flags = bctl->flags;
4970 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4971 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4972 if (atomic_read(&fs_info->balance_pause_req))
4973 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4974 if (atomic_read(&fs_info->balance_cancel_req))
4975 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4977 memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4978 memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4979 memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4981 spin_lock(&fs_info->balance_lock);
4982 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4983 spin_unlock(&fs_info->balance_lock);
4986 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4988 struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4989 struct btrfs_fs_info *fs_info = root->fs_info;
4990 struct btrfs_ioctl_balance_args *bargs;
4991 struct btrfs_balance_control *bctl;
4992 bool need_unlock; /* for mut. excl. ops lock */
4995 if (!capable(CAP_SYS_ADMIN))
4998 ret = mnt_want_write_file(file);
5003 if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
5004 mutex_lock(&fs_info->balance_mutex);
5010 * mut. excl. ops lock is locked. Three possibilities:
5011 * (1) some other op is running
5012 * (2) balance is running
5013 * (3) balance is paused -- special case (think resume)
5015 mutex_lock(&fs_info->balance_mutex);
5016 if (fs_info->balance_ctl) {
5017 /* this is either (2) or (3) */
5018 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
5019 mutex_unlock(&fs_info->balance_mutex);
5021 * Lock released to allow other waiters to continue,
5022 * we'll reexamine the status again.
5024 mutex_lock(&fs_info->balance_mutex);
5026 if (fs_info->balance_ctl &&
5027 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
5029 need_unlock = false;
5033 mutex_unlock(&fs_info->balance_mutex);
5037 mutex_unlock(&fs_info->balance_mutex);
5043 mutex_unlock(&fs_info->balance_mutex);
5044 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
5049 BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
5052 bargs = memdup_user(arg, sizeof(*bargs));
5053 if (IS_ERR(bargs)) {
5054 ret = PTR_ERR(bargs);
5058 if (bargs->flags & BTRFS_BALANCE_RESUME) {
5059 if (!fs_info->balance_ctl) {
5064 bctl = fs_info->balance_ctl;
5065 spin_lock(&fs_info->balance_lock);
5066 bctl->flags |= BTRFS_BALANCE_RESUME;
5067 spin_unlock(&fs_info->balance_lock);
5075 if (fs_info->balance_ctl) {
5080 bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
5087 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
5088 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
5089 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
5091 bctl->flags = bargs->flags;
5093 /* balance everything - no filters */
5094 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
5097 if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
5104 * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
5105 * btrfs_balance. bctl is freed in reset_balance_state, or, if
5106 * restriper was paused all the way until unmount, in free_fs_info.
5107 * The flag should be cleared after reset_balance_state.
5109 need_unlock = false;
5111 ret = btrfs_balance(fs_info, bctl, bargs);
5115 if (copy_to_user(arg, bargs, sizeof(*bargs)))
5124 mutex_unlock(&fs_info->balance_mutex);
5126 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
5128 mnt_drop_write_file(file);
5132 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
5134 if (!capable(CAP_SYS_ADMIN))
5138 case BTRFS_BALANCE_CTL_PAUSE:
5139 return btrfs_pause_balance(fs_info);
5140 case BTRFS_BALANCE_CTL_CANCEL:
5141 return btrfs_cancel_balance(fs_info);
5147 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
5150 struct btrfs_ioctl_balance_args *bargs;
5153 if (!capable(CAP_SYS_ADMIN))
5156 mutex_lock(&fs_info->balance_mutex);
5157 if (!fs_info->balance_ctl) {
5162 bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
5168 btrfs_update_ioctl_balance_args(fs_info, bargs);
5170 if (copy_to_user(arg, bargs, sizeof(*bargs)))
5175 mutex_unlock(&fs_info->balance_mutex);
5179 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
5181 struct inode *inode = file_inode(file);
5182 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5183 struct btrfs_ioctl_quota_ctl_args *sa;
5186 if (!capable(CAP_SYS_ADMIN))
5189 ret = mnt_want_write_file(file);
5193 sa = memdup_user(arg, sizeof(*sa));
5199 down_write(&fs_info->subvol_sem);
5202 case BTRFS_QUOTA_CTL_ENABLE:
5203 ret = btrfs_quota_enable(fs_info);
5205 case BTRFS_QUOTA_CTL_DISABLE:
5206 ret = btrfs_quota_disable(fs_info);
5214 up_write(&fs_info->subvol_sem);
5216 mnt_drop_write_file(file);
5220 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
5222 struct inode *inode = file_inode(file);
5223 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5224 struct btrfs_root *root = BTRFS_I(inode)->root;
5225 struct btrfs_ioctl_qgroup_assign_args *sa;
5226 struct btrfs_trans_handle *trans;
5230 if (!capable(CAP_SYS_ADMIN))
5233 ret = mnt_want_write_file(file);
5237 sa = memdup_user(arg, sizeof(*sa));
5243 trans = btrfs_join_transaction(root);
5244 if (IS_ERR(trans)) {
5245 ret = PTR_ERR(trans);
5250 ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
5252 ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
5255 /* update qgroup status and info */
5256 err = btrfs_run_qgroups(trans);
5258 btrfs_handle_fs_error(fs_info, err,
5259 "failed to update qgroup status and info");
5260 err = btrfs_end_transaction(trans);
5267 mnt_drop_write_file(file);
5271 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
5273 struct inode *inode = file_inode(file);
5274 struct btrfs_root *root = BTRFS_I(inode)->root;
5275 struct btrfs_ioctl_qgroup_create_args *sa;
5276 struct btrfs_trans_handle *trans;
5280 if (!capable(CAP_SYS_ADMIN))
5283 ret = mnt_want_write_file(file);
5287 sa = memdup_user(arg, sizeof(*sa));
5293 if (!sa->qgroupid) {
5298 trans = btrfs_join_transaction(root);
5299 if (IS_ERR(trans)) {
5300 ret = PTR_ERR(trans);
5305 ret = btrfs_create_qgroup(trans, sa->qgroupid);
5307 ret = btrfs_remove_qgroup(trans, sa->qgroupid);
5310 err = btrfs_end_transaction(trans);
5317 mnt_drop_write_file(file);
5321 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
5323 struct inode *inode = file_inode(file);
5324 struct btrfs_root *root = BTRFS_I(inode)->root;
5325 struct btrfs_ioctl_qgroup_limit_args *sa;
5326 struct btrfs_trans_handle *trans;
5331 if (!capable(CAP_SYS_ADMIN))
5334 ret = mnt_want_write_file(file);
5338 sa = memdup_user(arg, sizeof(*sa));
5344 trans = btrfs_join_transaction(root);
5345 if (IS_ERR(trans)) {
5346 ret = PTR_ERR(trans);
5350 qgroupid = sa->qgroupid;
5352 /* take the current subvol as qgroup */
5353 qgroupid = root->root_key.objectid;
5356 ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
5358 err = btrfs_end_transaction(trans);
5365 mnt_drop_write_file(file);
5369 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
5371 struct inode *inode = file_inode(file);
5372 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5373 struct btrfs_ioctl_quota_rescan_args *qsa;
5376 if (!capable(CAP_SYS_ADMIN))
5379 ret = mnt_want_write_file(file);
5383 qsa = memdup_user(arg, sizeof(*qsa));
5394 ret = btrfs_qgroup_rescan(fs_info);
5399 mnt_drop_write_file(file);
5403 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
5405 struct inode *inode = file_inode(file);
5406 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5407 struct btrfs_ioctl_quota_rescan_args *qsa;
5410 if (!capable(CAP_SYS_ADMIN))
5413 qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
5417 if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
5419 qsa->progress = fs_info->qgroup_rescan_progress.objectid;
5422 if (copy_to_user(arg, qsa, sizeof(*qsa)))
5429 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
5431 struct inode *inode = file_inode(file);
5432 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5434 if (!capable(CAP_SYS_ADMIN))
5437 return btrfs_qgroup_wait_for_completion(fs_info, true);
5440 static long _btrfs_ioctl_set_received_subvol(struct file *file,
5441 struct btrfs_ioctl_received_subvol_args *sa)
5443 struct inode *inode = file_inode(file);
5444 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5445 struct btrfs_root *root = BTRFS_I(inode)->root;
5446 struct btrfs_root_item *root_item = &root->root_item;
5447 struct btrfs_trans_handle *trans;
5448 struct timespec64 ct = current_time(inode);
5450 int received_uuid_changed;
5452 if (!inode_owner_or_capable(inode))
5455 ret = mnt_want_write_file(file);
5459 down_write(&fs_info->subvol_sem);
5461 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
5466 if (btrfs_root_readonly(root)) {
5473 * 2 - uuid items (received uuid + subvol uuid)
5475 trans = btrfs_start_transaction(root, 3);
5476 if (IS_ERR(trans)) {
5477 ret = PTR_ERR(trans);
5482 sa->rtransid = trans->transid;
5483 sa->rtime.sec = ct.tv_sec;
5484 sa->rtime.nsec = ct.tv_nsec;
5486 received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5488 if (received_uuid_changed &&
5489 !btrfs_is_empty_uuid(root_item->received_uuid)) {
5490 ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
5491 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5492 root->root_key.objectid);
5493 if (ret && ret != -ENOENT) {
5494 btrfs_abort_transaction(trans, ret);
5495 btrfs_end_transaction(trans);
5499 memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
5500 btrfs_set_root_stransid(root_item, sa->stransid);
5501 btrfs_set_root_rtransid(root_item, sa->rtransid);
5502 btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
5503 btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
5504 btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
5505 btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
5507 ret = btrfs_update_root(trans, fs_info->tree_root,
5508 &root->root_key, &root->root_item);
5510 btrfs_end_transaction(trans);
5513 if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5514 ret = btrfs_uuid_tree_add(trans, sa->uuid,
5515 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5516 root->root_key.objectid);
5517 if (ret < 0 && ret != -EEXIST) {
5518 btrfs_abort_transaction(trans, ret);
5519 btrfs_end_transaction(trans);
5523 ret = btrfs_commit_transaction(trans);
5525 up_write(&fs_info->subvol_sem);
5526 mnt_drop_write_file(file);
5531 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5534 struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5535 struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5538 args32 = memdup_user(arg, sizeof(*args32));
5540 return PTR_ERR(args32);
5542 args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
5548 memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5549 args64->stransid = args32->stransid;
5550 args64->rtransid = args32->rtransid;
5551 args64->stime.sec = args32->stime.sec;
5552 args64->stime.nsec = args32->stime.nsec;
5553 args64->rtime.sec = args32->rtime.sec;
5554 args64->rtime.nsec = args32->rtime.nsec;
5555 args64->flags = args32->flags;
5557 ret = _btrfs_ioctl_set_received_subvol(file, args64);
5561 memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5562 args32->stransid = args64->stransid;
5563 args32->rtransid = args64->rtransid;
5564 args32->stime.sec = args64->stime.sec;
5565 args32->stime.nsec = args64->stime.nsec;
5566 args32->rtime.sec = args64->rtime.sec;
5567 args32->rtime.nsec = args64->rtime.nsec;
5568 args32->flags = args64->flags;
5570 ret = copy_to_user(arg, args32, sizeof(*args32));
5581 static long btrfs_ioctl_set_received_subvol(struct file *file,
5584 struct btrfs_ioctl_received_subvol_args *sa = NULL;
5587 sa = memdup_user(arg, sizeof(*sa));
5591 ret = _btrfs_ioctl_set_received_subvol(file, sa);
5596 ret = copy_to_user(arg, sa, sizeof(*sa));
5605 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5607 struct inode *inode = file_inode(file);
5608 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5611 char label[BTRFS_LABEL_SIZE];
5613 spin_lock(&fs_info->super_lock);
5614 memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5615 spin_unlock(&fs_info->super_lock);
5617 len = strnlen(label, BTRFS_LABEL_SIZE);
5619 if (len == BTRFS_LABEL_SIZE) {
5621 "label is too long, return the first %zu bytes",
5625 ret = copy_to_user(arg, label, len);
5627 return ret ? -EFAULT : 0;
5630 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5632 struct inode *inode = file_inode(file);
5633 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5634 struct btrfs_root *root = BTRFS_I(inode)->root;
5635 struct btrfs_super_block *super_block = fs_info->super_copy;
5636 struct btrfs_trans_handle *trans;
5637 char label[BTRFS_LABEL_SIZE];
5640 if (!capable(CAP_SYS_ADMIN))
5643 if (copy_from_user(label, arg, sizeof(label)))
5646 if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
5648 "unable to set label with more than %d bytes",
5649 BTRFS_LABEL_SIZE - 1);
5653 ret = mnt_want_write_file(file);
5657 trans = btrfs_start_transaction(root, 0);
5658 if (IS_ERR(trans)) {
5659 ret = PTR_ERR(trans);
5663 spin_lock(&fs_info->super_lock);
5664 strcpy(super_block->label, label);
5665 spin_unlock(&fs_info->super_lock);
5666 ret = btrfs_commit_transaction(trans);
5669 mnt_drop_write_file(file);
5673 #define INIT_FEATURE_FLAGS(suffix) \
5674 { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5675 .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5676 .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5678 int btrfs_ioctl_get_supported_features(void __user *arg)
5680 static const struct btrfs_ioctl_feature_flags features[3] = {
5681 INIT_FEATURE_FLAGS(SUPP),
5682 INIT_FEATURE_FLAGS(SAFE_SET),
5683 INIT_FEATURE_FLAGS(SAFE_CLEAR)
5686 if (copy_to_user(arg, &features, sizeof(features)))
5692 static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
5694 struct inode *inode = file_inode(file);
5695 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5696 struct btrfs_super_block *super_block = fs_info->super_copy;
5697 struct btrfs_ioctl_feature_flags features;
5699 features.compat_flags = btrfs_super_compat_flags(super_block);
5700 features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5701 features.incompat_flags = btrfs_super_incompat_flags(super_block);
5703 if (copy_to_user(arg, &features, sizeof(features)))
5709 static int check_feature_bits(struct btrfs_fs_info *fs_info,
5710 enum btrfs_feature_set set,
5711 u64 change_mask, u64 flags, u64 supported_flags,
5712 u64 safe_set, u64 safe_clear)
5714 const char *type = btrfs_feature_set_names[set];
5716 u64 disallowed, unsupported;
5717 u64 set_mask = flags & change_mask;
5718 u64 clear_mask = ~flags & change_mask;
5720 unsupported = set_mask & ~supported_flags;
5722 names = btrfs_printable_features(set, unsupported);
5725 "this kernel does not support the %s feature bit%s",
5726 names, strchr(names, ',') ? "s" : "");
5730 "this kernel does not support %s bits 0x%llx",
5735 disallowed = set_mask & ~safe_set;
5737 names = btrfs_printable_features(set, disallowed);
5740 "can't set the %s feature bit%s while mounted",
5741 names, strchr(names, ',') ? "s" : "");
5745 "can't set %s bits 0x%llx while mounted",
5750 disallowed = clear_mask & ~safe_clear;
5752 names = btrfs_printable_features(set, disallowed);
5755 "can't clear the %s feature bit%s while mounted",
5756 names, strchr(names, ',') ? "s" : "");
5760 "can't clear %s bits 0x%llx while mounted",
5768 #define check_feature(fs_info, change_mask, flags, mask_base) \
5769 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \
5770 BTRFS_FEATURE_ ## mask_base ## _SUPP, \
5771 BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \
5772 BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5774 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5776 struct inode *inode = file_inode(file);
5777 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5778 struct btrfs_root *root = BTRFS_I(inode)->root;
5779 struct btrfs_super_block *super_block = fs_info->super_copy;
5780 struct btrfs_ioctl_feature_flags flags[2];
5781 struct btrfs_trans_handle *trans;
5785 if (!capable(CAP_SYS_ADMIN))
5788 if (copy_from_user(flags, arg, sizeof(flags)))
5792 if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5793 !flags[0].incompat_flags)
5796 ret = check_feature(fs_info, flags[0].compat_flags,
5797 flags[1].compat_flags, COMPAT);
5801 ret = check_feature(fs_info, flags[0].compat_ro_flags,
5802 flags[1].compat_ro_flags, COMPAT_RO);
5806 ret = check_feature(fs_info, flags[0].incompat_flags,
5807 flags[1].incompat_flags, INCOMPAT);
5811 ret = mnt_want_write_file(file);
5815 trans = btrfs_start_transaction(root, 0);
5816 if (IS_ERR(trans)) {
5817 ret = PTR_ERR(trans);
5818 goto out_drop_write;
5821 spin_lock(&fs_info->super_lock);
5822 newflags = btrfs_super_compat_flags(super_block);
5823 newflags |= flags[0].compat_flags & flags[1].compat_flags;
5824 newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5825 btrfs_set_super_compat_flags(super_block, newflags);
5827 newflags = btrfs_super_compat_ro_flags(super_block);
5828 newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5829 newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5830 btrfs_set_super_compat_ro_flags(super_block, newflags);
5832 newflags = btrfs_super_incompat_flags(super_block);
5833 newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5834 newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5835 btrfs_set_super_incompat_flags(super_block, newflags);
5836 spin_unlock(&fs_info->super_lock);
5838 ret = btrfs_commit_transaction(trans);
5840 mnt_drop_write_file(file);
5845 static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
5847 struct btrfs_ioctl_send_args *arg;
5851 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5852 struct btrfs_ioctl_send_args_32 args32;
5854 ret = copy_from_user(&args32, argp, sizeof(args32));
5857 arg = kzalloc(sizeof(*arg), GFP_KERNEL);
5860 arg->send_fd = args32.send_fd;
5861 arg->clone_sources_count = args32.clone_sources_count;
5862 arg->clone_sources = compat_ptr(args32.clone_sources);
5863 arg->parent_root = args32.parent_root;
5864 arg->flags = args32.flags;
5865 memcpy(arg->reserved, args32.reserved,
5866 sizeof(args32.reserved));
5871 arg = memdup_user(argp, sizeof(*arg));
5873 return PTR_ERR(arg);
5875 ret = btrfs_ioctl_send(file, arg);
5880 long btrfs_ioctl(struct file *file, unsigned int
5881 cmd, unsigned long arg)
5883 struct inode *inode = file_inode(file);
5884 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5885 struct btrfs_root *root = BTRFS_I(inode)->root;
5886 void __user *argp = (void __user *)arg;
5889 case FS_IOC_GETFLAGS:
5890 return btrfs_ioctl_getflags(file, argp);
5891 case FS_IOC_SETFLAGS:
5892 return btrfs_ioctl_setflags(file, argp);
5893 case FS_IOC_GETVERSION:
5894 return btrfs_ioctl_getversion(file, argp);
5896 return btrfs_ioctl_fitrim(file, argp);
5897 case BTRFS_IOC_SNAP_CREATE:
5898 return btrfs_ioctl_snap_create(file, argp, 0);
5899 case BTRFS_IOC_SNAP_CREATE_V2:
5900 return btrfs_ioctl_snap_create_v2(file, argp, 0);
5901 case BTRFS_IOC_SUBVOL_CREATE:
5902 return btrfs_ioctl_snap_create(file, argp, 1);
5903 case BTRFS_IOC_SUBVOL_CREATE_V2:
5904 return btrfs_ioctl_snap_create_v2(file, argp, 1);
5905 case BTRFS_IOC_SNAP_DESTROY:
5906 return btrfs_ioctl_snap_destroy(file, argp);
5907 case BTRFS_IOC_SUBVOL_GETFLAGS:
5908 return btrfs_ioctl_subvol_getflags(file, argp);
5909 case BTRFS_IOC_SUBVOL_SETFLAGS:
5910 return btrfs_ioctl_subvol_setflags(file, argp);
5911 case BTRFS_IOC_DEFAULT_SUBVOL:
5912 return btrfs_ioctl_default_subvol(file, argp);
5913 case BTRFS_IOC_DEFRAG:
5914 return btrfs_ioctl_defrag(file, NULL);
5915 case BTRFS_IOC_DEFRAG_RANGE:
5916 return btrfs_ioctl_defrag(file, argp);
5917 case BTRFS_IOC_RESIZE:
5918 return btrfs_ioctl_resize(file, argp);
5919 case BTRFS_IOC_ADD_DEV:
5920 return btrfs_ioctl_add_dev(fs_info, argp);
5921 case BTRFS_IOC_RM_DEV:
5922 return btrfs_ioctl_rm_dev(file, argp);
5923 case BTRFS_IOC_RM_DEV_V2:
5924 return btrfs_ioctl_rm_dev_v2(file, argp);
5925 case BTRFS_IOC_FS_INFO:
5926 return btrfs_ioctl_fs_info(fs_info, argp);
5927 case BTRFS_IOC_DEV_INFO:
5928 return btrfs_ioctl_dev_info(fs_info, argp);
5929 case BTRFS_IOC_BALANCE:
5930 return btrfs_ioctl_balance(file, NULL);
5931 case BTRFS_IOC_TREE_SEARCH:
5932 return btrfs_ioctl_tree_search(file, argp);
5933 case BTRFS_IOC_TREE_SEARCH_V2:
5934 return btrfs_ioctl_tree_search_v2(file, argp);
5935 case BTRFS_IOC_INO_LOOKUP:
5936 return btrfs_ioctl_ino_lookup(file, argp);
5937 case BTRFS_IOC_INO_PATHS:
5938 return btrfs_ioctl_ino_to_path(root, argp);
5939 case BTRFS_IOC_LOGICAL_INO:
5940 return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5941 case BTRFS_IOC_LOGICAL_INO_V2:
5942 return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
5943 case BTRFS_IOC_SPACE_INFO:
5944 return btrfs_ioctl_space_info(fs_info, argp);
5945 case BTRFS_IOC_SYNC: {
5948 ret = btrfs_start_delalloc_roots(fs_info, -1);
5951 ret = btrfs_sync_fs(inode->i_sb, 1);
5953 * The transaction thread may want to do more work,
5954 * namely it pokes the cleaner kthread that will start
5955 * processing uncleaned subvols.
5957 wake_up_process(fs_info->transaction_kthread);
5960 case BTRFS_IOC_START_SYNC:
5961 return btrfs_ioctl_start_sync(root, argp);
5962 case BTRFS_IOC_WAIT_SYNC:
5963 return btrfs_ioctl_wait_sync(fs_info, argp);
5964 case BTRFS_IOC_SCRUB:
5965 return btrfs_ioctl_scrub(file, argp);
5966 case BTRFS_IOC_SCRUB_CANCEL:
5967 return btrfs_ioctl_scrub_cancel(fs_info);
5968 case BTRFS_IOC_SCRUB_PROGRESS:
5969 return btrfs_ioctl_scrub_progress(fs_info, argp);
5970 case BTRFS_IOC_BALANCE_V2:
5971 return btrfs_ioctl_balance(file, argp);
5972 case BTRFS_IOC_BALANCE_CTL:
5973 return btrfs_ioctl_balance_ctl(fs_info, arg);
5974 case BTRFS_IOC_BALANCE_PROGRESS:
5975 return btrfs_ioctl_balance_progress(fs_info, argp);
5976 case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5977 return btrfs_ioctl_set_received_subvol(file, argp);
5979 case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5980 return btrfs_ioctl_set_received_subvol_32(file, argp);
5982 case BTRFS_IOC_SEND:
5983 return _btrfs_ioctl_send(file, argp, false);
5984 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5985 case BTRFS_IOC_SEND_32:
5986 return _btrfs_ioctl_send(file, argp, true);
5988 case BTRFS_IOC_GET_DEV_STATS:
5989 return btrfs_ioctl_get_dev_stats(fs_info, argp);
5990 case BTRFS_IOC_QUOTA_CTL:
5991 return btrfs_ioctl_quota_ctl(file, argp);
5992 case BTRFS_IOC_QGROUP_ASSIGN:
5993 return btrfs_ioctl_qgroup_assign(file, argp);
5994 case BTRFS_IOC_QGROUP_CREATE:
5995 return btrfs_ioctl_qgroup_create(file, argp);
5996 case BTRFS_IOC_QGROUP_LIMIT:
5997 return btrfs_ioctl_qgroup_limit(file, argp);
5998 case BTRFS_IOC_QUOTA_RESCAN:
5999 return btrfs_ioctl_quota_rescan(file, argp);
6000 case BTRFS_IOC_QUOTA_RESCAN_STATUS:
6001 return btrfs_ioctl_quota_rescan_status(file, argp);
6002 case BTRFS_IOC_QUOTA_RESCAN_WAIT:
6003 return btrfs_ioctl_quota_rescan_wait(file, argp);
6004 case BTRFS_IOC_DEV_REPLACE:
6005 return btrfs_ioctl_dev_replace(fs_info, argp);
6006 case BTRFS_IOC_GET_FSLABEL:
6007 return btrfs_ioctl_get_fslabel(file, argp);
6008 case BTRFS_IOC_SET_FSLABEL:
6009 return btrfs_ioctl_set_fslabel(file, argp);
6010 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
6011 return btrfs_ioctl_get_supported_features(argp);
6012 case BTRFS_IOC_GET_FEATURES:
6013 return btrfs_ioctl_get_features(file, argp);
6014 case BTRFS_IOC_SET_FEATURES:
6015 return btrfs_ioctl_set_features(file, argp);
6016 case FS_IOC_FSGETXATTR:
6017 return btrfs_ioctl_fsgetxattr(file, argp);
6018 case FS_IOC_FSSETXATTR:
6019 return btrfs_ioctl_fssetxattr(file, argp);
6020 case BTRFS_IOC_GET_SUBVOL_INFO:
6021 return btrfs_ioctl_get_subvol_info(file, argp);
6022 case BTRFS_IOC_GET_SUBVOL_ROOTREF:
6023 return btrfs_ioctl_get_subvol_rootref(file, argp);
6024 case BTRFS_IOC_INO_LOOKUP_USER:
6025 return btrfs_ioctl_ino_lookup_user(file, argp);
6031 #ifdef CONFIG_COMPAT
6032 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6035 * These all access 32-bit values anyway so no further
6036 * handling is necessary.
6039 case FS_IOC32_GETFLAGS:
6040 cmd = FS_IOC_GETFLAGS;
6042 case FS_IOC32_SETFLAGS:
6043 cmd = FS_IOC_SETFLAGS;
6045 case FS_IOC32_GETVERSION:
6046 cmd = FS_IOC_GETVERSION;
6050 return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));