1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
11 #include <linux/fsnotify.h>
12 #include <linux/pagemap.h>
13 #include <linux/highmem.h>
14 #include <linux/time.h>
15 #include <linux/init.h>
16 #include <linux/string.h>
17 #include <linux/backing-dev.h>
18 #include <linux/mount.h>
19 #include <linux/mpage.h>
20 #include <linux/namei.h>
21 #include <linux/swap.h>
22 #include <linux/writeback.h>
23 #include <linux/compat.h>
24 #include <linux/bit_spinlock.h>
25 #include <linux/security.h>
26 #include <linux/xattr.h>
28 #include <linux/slab.h>
29 #include <linux/blkdev.h>
30 #include <linux/uuid.h>
31 #include <linux/btrfs.h>
32 #include <linux/uaccess.h>
33 #include <linux/iversion.h>
36 #include "transaction.h"
37 #include "btrfs_inode.h"
38 #include "print-tree.h"
41 #include "inode-map.h"
43 #include "rcu-string.h"
45 #include "dev-replace.h"
50 #include "compression.h"
53 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
54 * structures are incorrect, as the timespec structure from userspace
55 * is 4 bytes too small. We define these alternatives here to teach
56 * the kernel about the 32-bit struct packing.
58 struct btrfs_ioctl_timespec_32 {
61 } __attribute__ ((__packed__));
63 struct btrfs_ioctl_received_subvol_args_32 {
64 char uuid[BTRFS_UUID_SIZE]; /* in */
65 __u64 stransid; /* in */
66 __u64 rtransid; /* out */
67 struct btrfs_ioctl_timespec_32 stime; /* in */
68 struct btrfs_ioctl_timespec_32 rtime; /* out */
70 __u64 reserved[16]; /* in */
71 } __attribute__ ((__packed__));
73 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
74 struct btrfs_ioctl_received_subvol_args_32)
77 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
78 struct btrfs_ioctl_send_args_32 {
79 __s64 send_fd; /* in */
80 __u64 clone_sources_count; /* in */
81 compat_uptr_t clone_sources; /* in */
82 __u64 parent_root; /* in */
84 __u64 reserved[4]; /* in */
85 } __attribute__ ((__packed__));
87 #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
88 struct btrfs_ioctl_send_args_32)
91 static int btrfs_clone(struct inode *src, struct inode *inode,
92 u64 off, u64 olen, u64 olen_aligned, u64 destoff,
95 /* Mask out flags that are inappropriate for the given type of inode. */
96 static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
99 if (S_ISDIR(inode->i_mode))
101 else if (S_ISREG(inode->i_mode))
102 return flags & ~FS_DIRSYNC_FL;
104 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
108 * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
111 static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags)
113 unsigned int iflags = 0;
115 if (flags & BTRFS_INODE_SYNC)
116 iflags |= FS_SYNC_FL;
117 if (flags & BTRFS_INODE_IMMUTABLE)
118 iflags |= FS_IMMUTABLE_FL;
119 if (flags & BTRFS_INODE_APPEND)
120 iflags |= FS_APPEND_FL;
121 if (flags & BTRFS_INODE_NODUMP)
122 iflags |= FS_NODUMP_FL;
123 if (flags & BTRFS_INODE_NOATIME)
124 iflags |= FS_NOATIME_FL;
125 if (flags & BTRFS_INODE_DIRSYNC)
126 iflags |= FS_DIRSYNC_FL;
127 if (flags & BTRFS_INODE_NODATACOW)
128 iflags |= FS_NOCOW_FL;
130 if (flags & BTRFS_INODE_NOCOMPRESS)
131 iflags |= FS_NOCOMP_FL;
132 else if (flags & BTRFS_INODE_COMPRESS)
133 iflags |= FS_COMPR_FL;
139 * Update inode->i_flags based on the btrfs internal flags.
141 void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
143 struct btrfs_inode *ip = BTRFS_I(inode);
144 unsigned int new_fl = 0;
146 if (ip->flags & BTRFS_INODE_SYNC)
148 if (ip->flags & BTRFS_INODE_IMMUTABLE)
149 new_fl |= S_IMMUTABLE;
150 if (ip->flags & BTRFS_INODE_APPEND)
152 if (ip->flags & BTRFS_INODE_NOATIME)
154 if (ip->flags & BTRFS_INODE_DIRSYNC)
157 set_mask_bits(&inode->i_flags,
158 S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
162 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
164 struct btrfs_inode *ip = BTRFS_I(file_inode(file));
165 unsigned int flags = btrfs_inode_flags_to_fsflags(ip->flags);
167 if (copy_to_user(arg, &flags, sizeof(flags)))
172 /* Check if @flags are a supported and valid set of FS_*_FL flags */
173 static int check_fsflags(unsigned int flags)
175 if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
176 FS_NOATIME_FL | FS_NODUMP_FL | \
177 FS_SYNC_FL | FS_DIRSYNC_FL | \
178 FS_NOCOMP_FL | FS_COMPR_FL |
182 if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
188 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
190 struct inode *inode = file_inode(file);
191 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
192 struct btrfs_inode *ip = BTRFS_I(inode);
193 struct btrfs_root *root = ip->root;
194 struct btrfs_trans_handle *trans;
195 unsigned int flags, oldflags;
198 unsigned int i_oldflags;
201 if (!inode_owner_or_capable(inode))
204 if (btrfs_root_readonly(root))
207 if (copy_from_user(&flags, arg, sizeof(flags)))
210 ret = check_fsflags(flags);
214 ret = mnt_want_write_file(file);
220 ip_oldflags = ip->flags;
221 i_oldflags = inode->i_flags;
222 mode = inode->i_mode;
224 flags = btrfs_mask_fsflags_for_type(inode, flags);
225 oldflags = btrfs_inode_flags_to_fsflags(ip->flags);
226 if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
227 if (!capable(CAP_LINUX_IMMUTABLE)) {
233 if (flags & FS_SYNC_FL)
234 ip->flags |= BTRFS_INODE_SYNC;
236 ip->flags &= ~BTRFS_INODE_SYNC;
237 if (flags & FS_IMMUTABLE_FL)
238 ip->flags |= BTRFS_INODE_IMMUTABLE;
240 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
241 if (flags & FS_APPEND_FL)
242 ip->flags |= BTRFS_INODE_APPEND;
244 ip->flags &= ~BTRFS_INODE_APPEND;
245 if (flags & FS_NODUMP_FL)
246 ip->flags |= BTRFS_INODE_NODUMP;
248 ip->flags &= ~BTRFS_INODE_NODUMP;
249 if (flags & FS_NOATIME_FL)
250 ip->flags |= BTRFS_INODE_NOATIME;
252 ip->flags &= ~BTRFS_INODE_NOATIME;
253 if (flags & FS_DIRSYNC_FL)
254 ip->flags |= BTRFS_INODE_DIRSYNC;
256 ip->flags &= ~BTRFS_INODE_DIRSYNC;
257 if (flags & FS_NOCOW_FL) {
260 * It's safe to turn csums off here, no extents exist.
261 * Otherwise we want the flag to reflect the real COW
262 * status of the file and will not set it.
264 if (inode->i_size == 0)
265 ip->flags |= BTRFS_INODE_NODATACOW
266 | BTRFS_INODE_NODATASUM;
268 ip->flags |= BTRFS_INODE_NODATACOW;
272 * Revert back under same assumptions as above
275 if (inode->i_size == 0)
276 ip->flags &= ~(BTRFS_INODE_NODATACOW
277 | BTRFS_INODE_NODATASUM);
279 ip->flags &= ~BTRFS_INODE_NODATACOW;
284 * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
285 * flag may be changed automatically if compression code won't make
288 if (flags & FS_NOCOMP_FL) {
289 ip->flags &= ~BTRFS_INODE_COMPRESS;
290 ip->flags |= BTRFS_INODE_NOCOMPRESS;
292 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
293 if (ret && ret != -ENODATA)
295 } else if (flags & FS_COMPR_FL) {
298 ip->flags |= BTRFS_INODE_COMPRESS;
299 ip->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 ip->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 ip->flags = ip_oldflags;
332 inode->i_flags = i_oldflags;
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;
499 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
502 if (!capable(CAP_SYS_ADMIN))
506 list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
510 q = bdev_get_queue(device->bdev);
511 if (blk_queue_discard(q)) {
513 minlen = min_t(u64, q->limits.discard_granularity,
521 if (copy_from_user(&range, arg, sizeof(range)))
523 if (range.start > total_bytes ||
524 range.len < fs_info->sb->s_blocksize)
527 range.len = min(range.len, total_bytes - range.start);
528 range.minlen = max(range.minlen, minlen);
529 ret = btrfs_trim_fs(fs_info, &range);
533 if (copy_to_user(arg, &range, sizeof(range)))
539 int btrfs_is_empty_uuid(u8 *uuid)
543 for (i = 0; i < BTRFS_UUID_SIZE; i++) {
550 static noinline int create_subvol(struct inode *dir,
551 struct dentry *dentry,
552 const char *name, int namelen,
554 struct btrfs_qgroup_inherit *inherit)
556 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
557 struct btrfs_trans_handle *trans;
558 struct btrfs_key key;
559 struct btrfs_root_item *root_item;
560 struct btrfs_inode_item *inode_item;
561 struct extent_buffer *leaf;
562 struct btrfs_root *root = BTRFS_I(dir)->root;
563 struct btrfs_root *new_root;
564 struct btrfs_block_rsv block_rsv;
565 struct timespec cur_time = current_time(dir);
570 u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
575 root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
579 ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
584 * Don't create subvolume whose level is not zero. Or qgroup will be
585 * screwed up since it assumes subvolume qgroup's level to be 0.
587 if (btrfs_qgroup_level(objectid)) {
592 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
594 * The same as the snapshot creation, please see the comment
595 * of create_snapshot().
597 ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
598 8, &qgroup_reserved, false);
602 trans = btrfs_start_transaction(root, 0);
604 ret = PTR_ERR(trans);
605 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
608 trans->block_rsv = &block_rsv;
609 trans->bytes_reserved = block_rsv.size;
611 ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
615 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
621 memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
622 btrfs_set_header_bytenr(leaf, leaf->start);
623 btrfs_set_header_generation(leaf, trans->transid);
624 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
625 btrfs_set_header_owner(leaf, objectid);
627 write_extent_buffer_fsid(leaf, fs_info->fsid);
628 write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
629 btrfs_mark_buffer_dirty(leaf);
631 inode_item = &root_item->inode;
632 btrfs_set_stack_inode_generation(inode_item, 1);
633 btrfs_set_stack_inode_size(inode_item, 3);
634 btrfs_set_stack_inode_nlink(inode_item, 1);
635 btrfs_set_stack_inode_nbytes(inode_item,
637 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
639 btrfs_set_root_flags(root_item, 0);
640 btrfs_set_root_limit(root_item, 0);
641 btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
643 btrfs_set_root_bytenr(root_item, leaf->start);
644 btrfs_set_root_generation(root_item, trans->transid);
645 btrfs_set_root_level(root_item, 0);
646 btrfs_set_root_refs(root_item, 1);
647 btrfs_set_root_used(root_item, leaf->len);
648 btrfs_set_root_last_snapshot(root_item, 0);
650 btrfs_set_root_generation_v2(root_item,
651 btrfs_root_generation(root_item));
652 uuid_le_gen(&new_uuid);
653 memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
654 btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
655 btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
656 root_item->ctime = root_item->otime;
657 btrfs_set_root_ctransid(root_item, trans->transid);
658 btrfs_set_root_otransid(root_item, trans->transid);
660 btrfs_tree_unlock(leaf);
661 free_extent_buffer(leaf);
664 btrfs_set_root_dirid(root_item, new_dirid);
666 key.objectid = objectid;
668 key.type = BTRFS_ROOT_ITEM_KEY;
669 ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
674 key.offset = (u64)-1;
675 new_root = btrfs_read_fs_root_no_name(fs_info, &key);
676 if (IS_ERR(new_root)) {
677 ret = PTR_ERR(new_root);
678 btrfs_abort_transaction(trans, ret);
682 btrfs_record_root_in_trans(trans, new_root);
684 ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
686 /* We potentially lose an unused inode item here */
687 btrfs_abort_transaction(trans, ret);
691 mutex_lock(&new_root->objectid_mutex);
692 new_root->highest_objectid = new_dirid;
693 mutex_unlock(&new_root->objectid_mutex);
696 * insert the directory item
698 ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
700 btrfs_abort_transaction(trans, ret);
704 ret = btrfs_insert_dir_item(trans, root,
705 name, namelen, BTRFS_I(dir), &key,
706 BTRFS_FT_DIR, index);
708 btrfs_abort_transaction(trans, ret);
712 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
713 ret = btrfs_update_inode(trans, root, dir);
716 ret = btrfs_add_root_ref(trans, fs_info,
717 objectid, root->root_key.objectid,
718 btrfs_ino(BTRFS_I(dir)), index, name, namelen);
721 ret = btrfs_uuid_tree_add(trans, fs_info, root_item->uuid,
722 BTRFS_UUID_KEY_SUBVOL, objectid);
724 btrfs_abort_transaction(trans, ret);
728 trans->block_rsv = NULL;
729 trans->bytes_reserved = 0;
730 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
733 *async_transid = trans->transid;
734 err = btrfs_commit_transaction_async(trans, 1);
736 err = btrfs_commit_transaction(trans);
738 err = btrfs_commit_transaction(trans);
744 inode = btrfs_lookup_dentry(dir, dentry);
746 return PTR_ERR(inode);
747 d_instantiate(dentry, inode);
756 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
757 struct dentry *dentry,
758 u64 *async_transid, bool readonly,
759 struct btrfs_qgroup_inherit *inherit)
761 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
763 struct btrfs_pending_snapshot *pending_snapshot;
764 struct btrfs_trans_handle *trans;
767 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
770 pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
771 if (!pending_snapshot)
774 pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
776 pending_snapshot->path = btrfs_alloc_path();
777 if (!pending_snapshot->root_item || !pending_snapshot->path) {
782 atomic_inc(&root->will_be_snapshotted);
783 smp_mb__after_atomic();
784 /* wait for no snapshot writes */
785 wait_event(root->subv_writers->wait,
786 percpu_counter_sum(&root->subv_writers->counter) == 0);
788 ret = btrfs_start_delalloc_inodes(root);
792 btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
794 btrfs_init_block_rsv(&pending_snapshot->block_rsv,
795 BTRFS_BLOCK_RSV_TEMP);
797 * 1 - parent dir inode
800 * 2 - root ref/backref
801 * 1 - root of snapshot
804 ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
805 &pending_snapshot->block_rsv, 8,
806 &pending_snapshot->qgroup_reserved,
811 pending_snapshot->dentry = dentry;
812 pending_snapshot->root = root;
813 pending_snapshot->readonly = readonly;
814 pending_snapshot->dir = dir;
815 pending_snapshot->inherit = inherit;
817 trans = btrfs_start_transaction(root, 0);
819 ret = PTR_ERR(trans);
823 spin_lock(&fs_info->trans_lock);
824 list_add(&pending_snapshot->list,
825 &trans->transaction->pending_snapshots);
826 spin_unlock(&fs_info->trans_lock);
828 *async_transid = trans->transid;
829 ret = btrfs_commit_transaction_async(trans, 1);
831 ret = btrfs_commit_transaction(trans);
833 ret = btrfs_commit_transaction(trans);
838 ret = pending_snapshot->error;
842 ret = btrfs_orphan_cleanup(pending_snapshot->snap);
846 inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
848 ret = PTR_ERR(inode);
852 d_instantiate(dentry, inode);
855 btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
857 if (atomic_dec_and_test(&root->will_be_snapshotted))
858 wake_up_var(&root->will_be_snapshotted);
860 kfree(pending_snapshot->root_item);
861 btrfs_free_path(pending_snapshot->path);
862 kfree(pending_snapshot);
867 /* copy of may_delete in fs/namei.c()
868 * Check whether we can remove a link victim from directory dir, check
869 * whether the type of victim is right.
870 * 1. We can't do it if dir is read-only (done in permission())
871 * 2. We should have write and exec permissions on dir
872 * 3. We can't remove anything from append-only dir
873 * 4. We can't do anything with immutable dir (done in permission())
874 * 5. If the sticky bit on dir is set we should either
875 * a. be owner of dir, or
876 * b. be owner of victim, or
877 * c. have CAP_FOWNER capability
878 * 6. If the victim is append-only or immutable we can't do anything with
879 * links pointing to it.
880 * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
881 * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
882 * 9. We can't remove a root or mountpoint.
883 * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
884 * nfs_async_unlink().
887 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
891 if (d_really_is_negative(victim))
894 BUG_ON(d_inode(victim->d_parent) != dir);
895 audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
897 error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
902 if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
903 IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
906 if (!d_is_dir(victim))
910 } else if (d_is_dir(victim))
914 if (victim->d_flags & DCACHE_NFSFS_RENAMED)
919 /* copy of may_create in fs/namei.c() */
920 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
922 if (d_really_is_positive(child))
926 return inode_permission(dir, MAY_WRITE | MAY_EXEC);
930 * Create a new subvolume below @parent. This is largely modeled after
931 * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
932 * inside this filesystem so it's quite a bit simpler.
934 static noinline int btrfs_mksubvol(const struct path *parent,
935 const char *name, int namelen,
936 struct btrfs_root *snap_src,
937 u64 *async_transid, bool readonly,
938 struct btrfs_qgroup_inherit *inherit)
940 struct inode *dir = d_inode(parent->dentry);
941 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
942 struct dentry *dentry;
945 error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
949 dentry = lookup_one_len(name, parent->dentry, namelen);
950 error = PTR_ERR(dentry);
954 error = btrfs_may_create(dir, dentry);
959 * even if this name doesn't exist, we may get hash collisions.
960 * check for them now when we can safely fail
962 error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
968 down_read(&fs_info->subvol_sem);
970 if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
974 error = create_snapshot(snap_src, dir, dentry,
975 async_transid, readonly, inherit);
977 error = create_subvol(dir, dentry, name, namelen,
978 async_transid, inherit);
981 fsnotify_mkdir(dir, dentry);
983 up_read(&fs_info->subvol_sem);
992 * When we're defragging a range, we don't want to kick it off again
993 * if it is really just waiting for delalloc to send it down.
994 * If we find a nice big extent or delalloc range for the bytes in the
995 * file you want to defrag, we return 0 to let you know to skip this
998 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
1000 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1001 struct extent_map *em = NULL;
1002 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1005 read_lock(&em_tree->lock);
1006 em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
1007 read_unlock(&em_tree->lock);
1010 end = extent_map_end(em);
1011 free_extent_map(em);
1012 if (end - offset > thresh)
1015 /* if we already have a nice delalloc here, just stop */
1017 end = count_range_bits(io_tree, &offset, offset + thresh,
1018 thresh, EXTENT_DELALLOC, 1);
1025 * helper function to walk through a file and find extents
1026 * newer than a specific transid, and smaller than thresh.
1028 * This is used by the defragging code to find new and small
1031 static int find_new_extents(struct btrfs_root *root,
1032 struct inode *inode, u64 newer_than,
1033 u64 *off, u32 thresh)
1035 struct btrfs_path *path;
1036 struct btrfs_key min_key;
1037 struct extent_buffer *leaf;
1038 struct btrfs_file_extent_item *extent;
1041 u64 ino = btrfs_ino(BTRFS_I(inode));
1043 path = btrfs_alloc_path();
1047 min_key.objectid = ino;
1048 min_key.type = BTRFS_EXTENT_DATA_KEY;
1049 min_key.offset = *off;
1052 ret = btrfs_search_forward(root, &min_key, path, newer_than);
1056 if (min_key.objectid != ino)
1058 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
1061 leaf = path->nodes[0];
1062 extent = btrfs_item_ptr(leaf, path->slots[0],
1063 struct btrfs_file_extent_item);
1065 type = btrfs_file_extent_type(leaf, extent);
1066 if (type == BTRFS_FILE_EXTENT_REG &&
1067 btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
1068 check_defrag_in_cache(inode, min_key.offset, thresh)) {
1069 *off = min_key.offset;
1070 btrfs_free_path(path);
1075 if (path->slots[0] < btrfs_header_nritems(leaf)) {
1076 btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1080 if (min_key.offset == (u64)-1)
1084 btrfs_release_path(path);
1087 btrfs_free_path(path);
1091 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
1093 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1094 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1095 struct extent_map *em;
1096 u64 len = PAGE_SIZE;
1099 * hopefully we have this extent in the tree already, try without
1100 * the full extent lock
1102 read_lock(&em_tree->lock);
1103 em = lookup_extent_mapping(em_tree, start, len);
1104 read_unlock(&em_tree->lock);
1107 struct extent_state *cached = NULL;
1108 u64 end = start + len - 1;
1110 /* get the big lock and read metadata off disk */
1111 lock_extent_bits(io_tree, start, end, &cached);
1112 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1113 unlock_extent_cached(io_tree, start, end, &cached);
1122 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1124 struct extent_map *next;
1127 /* this is the last extent */
1128 if (em->start + em->len >= i_size_read(inode))
1131 next = defrag_lookup_extent(inode, em->start + em->len);
1132 if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1134 else if ((em->block_start + em->block_len == next->block_start) &&
1135 (em->block_len > SZ_128K && next->block_len > SZ_128K))
1138 free_extent_map(next);
1142 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1143 u64 *last_len, u64 *skip, u64 *defrag_end,
1146 struct extent_map *em;
1148 bool next_mergeable = true;
1149 bool prev_mergeable = true;
1152 * make sure that once we start defragging an extent, we keep on
1155 if (start < *defrag_end)
1160 em = defrag_lookup_extent(inode, start);
1164 /* this will cover holes, and inline extents */
1165 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1171 prev_mergeable = false;
1173 next_mergeable = defrag_check_next_extent(inode, em);
1175 * we hit a real extent, if it is big or the next extent is not a
1176 * real extent, don't bother defragging it
1178 if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1179 (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1183 * last_len ends up being a counter of how many bytes we've defragged.
1184 * every time we choose not to defrag an extent, we reset *last_len
1185 * so that the next tiny extent will force a defrag.
1187 * The end result of this is that tiny extents before a single big
1188 * extent will force at least part of that big extent to be defragged.
1191 *defrag_end = extent_map_end(em);
1194 *skip = extent_map_end(em);
1198 free_extent_map(em);
1203 * it doesn't do much good to defrag one or two pages
1204 * at a time. This pulls in a nice chunk of pages
1205 * to COW and defrag.
1207 * It also makes sure the delalloc code has enough
1208 * dirty data to avoid making new small extents as part
1211 * It's a good idea to start RA on this range
1212 * before calling this.
1214 static int cluster_pages_for_defrag(struct inode *inode,
1215 struct page **pages,
1216 unsigned long start_index,
1217 unsigned long num_pages)
1219 unsigned long file_end;
1220 u64 isize = i_size_read(inode);
1227 struct btrfs_ordered_extent *ordered;
1228 struct extent_state *cached_state = NULL;
1229 struct extent_io_tree *tree;
1230 struct extent_changeset *data_reserved = NULL;
1231 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1233 file_end = (isize - 1) >> PAGE_SHIFT;
1234 if (!isize || start_index > file_end)
1237 page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1239 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
1240 start_index << PAGE_SHIFT,
1241 page_cnt << PAGE_SHIFT);
1245 tree = &BTRFS_I(inode)->io_tree;
1247 /* step one, lock all the pages */
1248 for (i = 0; i < page_cnt; i++) {
1251 page = find_or_create_page(inode->i_mapping,
1252 start_index + i, mask);
1256 page_start = page_offset(page);
1257 page_end = page_start + PAGE_SIZE - 1;
1259 lock_extent_bits(tree, page_start, page_end,
1261 ordered = btrfs_lookup_ordered_extent(inode,
1263 unlock_extent_cached(tree, page_start, page_end,
1269 btrfs_start_ordered_extent(inode, ordered, 1);
1270 btrfs_put_ordered_extent(ordered);
1273 * we unlocked the page above, so we need check if
1274 * it was released or not.
1276 if (page->mapping != inode->i_mapping) {
1283 if (!PageUptodate(page)) {
1284 btrfs_readpage(NULL, page);
1286 if (!PageUptodate(page)) {
1294 if (page->mapping != inode->i_mapping) {
1306 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1310 * so now we have a nice long stream of locked
1311 * and up to date pages, lets wait on them
1313 for (i = 0; i < i_done; i++)
1314 wait_on_page_writeback(pages[i]);
1316 page_start = page_offset(pages[0]);
1317 page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
1319 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1320 page_start, page_end - 1, &cached_state);
1321 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1322 page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1323 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1326 if (i_done != page_cnt) {
1327 spin_lock(&BTRFS_I(inode)->lock);
1328 BTRFS_I(inode)->outstanding_extents++;
1329 spin_unlock(&BTRFS_I(inode)->lock);
1330 btrfs_delalloc_release_space(inode, data_reserved,
1331 start_index << PAGE_SHIFT,
1332 (page_cnt - i_done) << PAGE_SHIFT, true);
1336 set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1339 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1340 page_start, page_end - 1, &cached_state);
1342 for (i = 0; i < i_done; i++) {
1343 clear_page_dirty_for_io(pages[i]);
1344 ClearPageChecked(pages[i]);
1345 set_page_extent_mapped(pages[i]);
1346 set_page_dirty(pages[i]);
1347 unlock_page(pages[i]);
1350 btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
1352 extent_changeset_free(data_reserved);
1355 for (i = 0; i < i_done; i++) {
1356 unlock_page(pages[i]);
1359 btrfs_delalloc_release_space(inode, data_reserved,
1360 start_index << PAGE_SHIFT,
1361 page_cnt << PAGE_SHIFT, true);
1362 btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
1364 extent_changeset_free(data_reserved);
1369 int btrfs_defrag_file(struct inode *inode, struct file *file,
1370 struct btrfs_ioctl_defrag_range_args *range,
1371 u64 newer_than, unsigned long max_to_defrag)
1373 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1374 struct btrfs_root *root = BTRFS_I(inode)->root;
1375 struct file_ra_state *ra = NULL;
1376 unsigned long last_index;
1377 u64 isize = i_size_read(inode);
1381 u64 newer_off = range->start;
1383 unsigned long ra_index = 0;
1385 int defrag_count = 0;
1386 int compress_type = BTRFS_COMPRESS_ZLIB;
1387 u32 extent_thresh = range->extent_thresh;
1388 unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1389 unsigned long cluster = max_cluster;
1390 u64 new_align = ~((u64)SZ_128K - 1);
1391 struct page **pages = NULL;
1392 bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1397 if (range->start >= isize)
1401 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1403 if (range->compress_type)
1404 compress_type = range->compress_type;
1407 if (extent_thresh == 0)
1408 extent_thresh = SZ_256K;
1411 * If we were not given a file, allocate a readahead context. As
1412 * readahead is just an optimization, defrag will work without it so
1413 * we don't error out.
1416 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1418 file_ra_state_init(ra, inode->i_mapping);
1423 pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
1429 /* find the last page to defrag */
1430 if (range->start + range->len > range->start) {
1431 last_index = min_t(u64, isize - 1,
1432 range->start + range->len - 1) >> PAGE_SHIFT;
1434 last_index = (isize - 1) >> PAGE_SHIFT;
1438 ret = find_new_extents(root, inode, newer_than,
1439 &newer_off, SZ_64K);
1441 range->start = newer_off;
1443 * we always align our defrag to help keep
1444 * the extents in the file evenly spaced
1446 i = (newer_off & new_align) >> PAGE_SHIFT;
1450 i = range->start >> PAGE_SHIFT;
1453 max_to_defrag = last_index - i + 1;
1456 * make writeback starts from i, so the defrag range can be
1457 * written sequentially.
1459 if (i < inode->i_mapping->writeback_index)
1460 inode->i_mapping->writeback_index = i;
1462 while (i <= last_index && defrag_count < max_to_defrag &&
1463 (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
1465 * make sure we stop running if someone unmounts
1468 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1471 if (btrfs_defrag_cancelled(fs_info)) {
1472 btrfs_debug(fs_info, "defrag_file cancelled");
1477 if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
1478 extent_thresh, &last_len, &skip,
1479 &defrag_end, do_compress)){
1482 * the should_defrag function tells us how much to skip
1483 * bump our counter by the suggested amount
1485 next = DIV_ROUND_UP(skip, PAGE_SIZE);
1486 i = max(i + 1, next);
1491 cluster = (PAGE_ALIGN(defrag_end) >>
1493 cluster = min(cluster, max_cluster);
1495 cluster = max_cluster;
1498 if (i + cluster > ra_index) {
1499 ra_index = max(i, ra_index);
1501 page_cache_sync_readahead(inode->i_mapping, ra,
1502 file, ra_index, cluster);
1503 ra_index += cluster;
1508 BTRFS_I(inode)->defrag_compress = compress_type;
1509 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1511 inode_unlock(inode);
1515 defrag_count += ret;
1516 balance_dirty_pages_ratelimited(inode->i_mapping);
1517 inode_unlock(inode);
1520 if (newer_off == (u64)-1)
1526 newer_off = max(newer_off + 1,
1527 (u64)i << PAGE_SHIFT);
1529 ret = find_new_extents(root, inode, newer_than,
1530 &newer_off, SZ_64K);
1532 range->start = newer_off;
1533 i = (newer_off & new_align) >> PAGE_SHIFT;
1540 last_len += ret << PAGE_SHIFT;
1548 if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1549 filemap_flush(inode->i_mapping);
1550 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1551 &BTRFS_I(inode)->runtime_flags))
1552 filemap_flush(inode->i_mapping);
1555 if (range->compress_type == BTRFS_COMPRESS_LZO) {
1556 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1557 } else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
1558 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1566 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1567 inode_unlock(inode);
1575 static noinline int btrfs_ioctl_resize(struct file *file,
1578 struct inode *inode = file_inode(file);
1579 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1583 struct btrfs_root *root = BTRFS_I(inode)->root;
1584 struct btrfs_ioctl_vol_args *vol_args;
1585 struct btrfs_trans_handle *trans;
1586 struct btrfs_device *device = NULL;
1589 char *devstr = NULL;
1593 if (!capable(CAP_SYS_ADMIN))
1596 ret = mnt_want_write_file(file);
1600 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
1601 mnt_drop_write_file(file);
1602 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1605 vol_args = memdup_user(arg, sizeof(*vol_args));
1606 if (IS_ERR(vol_args)) {
1607 ret = PTR_ERR(vol_args);
1611 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1613 sizestr = vol_args->name;
1614 devstr = strchr(sizestr, ':');
1616 sizestr = devstr + 1;
1618 devstr = vol_args->name;
1619 ret = kstrtoull(devstr, 10, &devid);
1626 btrfs_info(fs_info, "resizing devid %llu", devid);
1629 device = btrfs_find_device(fs_info, devid, NULL, NULL);
1631 btrfs_info(fs_info, "resizer unable to find device %llu",
1637 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1639 "resizer unable to apply on readonly device %llu",
1645 if (!strcmp(sizestr, "max"))
1646 new_size = device->bdev->bd_inode->i_size;
1648 if (sizestr[0] == '-') {
1651 } else if (sizestr[0] == '+') {
1655 new_size = memparse(sizestr, &retptr);
1656 if (*retptr != '\0' || new_size == 0) {
1662 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1667 old_size = btrfs_device_get_total_bytes(device);
1670 if (new_size > old_size) {
1674 new_size = old_size - new_size;
1675 } else if (mod > 0) {
1676 if (new_size > ULLONG_MAX - old_size) {
1680 new_size = old_size + new_size;
1683 if (new_size < SZ_256M) {
1687 if (new_size > device->bdev->bd_inode->i_size) {
1692 new_size = round_down(new_size, fs_info->sectorsize);
1694 btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1695 rcu_str_deref(device->name), new_size);
1697 if (new_size > old_size) {
1698 trans = btrfs_start_transaction(root, 0);
1699 if (IS_ERR(trans)) {
1700 ret = PTR_ERR(trans);
1703 ret = btrfs_grow_device(trans, device, new_size);
1704 btrfs_commit_transaction(trans);
1705 } else if (new_size < old_size) {
1706 ret = btrfs_shrink_device(device, new_size);
1707 } /* equal, nothing need to do */
1712 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
1713 mnt_drop_write_file(file);
1717 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1718 const char *name, unsigned long fd, int subvol,
1719 u64 *transid, bool readonly,
1720 struct btrfs_qgroup_inherit *inherit)
1725 if (!S_ISDIR(file_inode(file)->i_mode))
1728 ret = mnt_want_write_file(file);
1732 namelen = strlen(name);
1733 if (strchr(name, '/')) {
1735 goto out_drop_write;
1738 if (name[0] == '.' &&
1739 (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1741 goto out_drop_write;
1745 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1746 NULL, transid, readonly, inherit);
1748 struct fd src = fdget(fd);
1749 struct inode *src_inode;
1752 goto out_drop_write;
1755 src_inode = file_inode(src.file);
1756 if (src_inode->i_sb != file_inode(file)->i_sb) {
1757 btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1758 "Snapshot src from another FS");
1760 } else if (!inode_owner_or_capable(src_inode)) {
1762 * Subvolume creation is not restricted, but snapshots
1763 * are limited to own subvolumes only
1767 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1768 BTRFS_I(src_inode)->root,
1769 transid, readonly, inherit);
1774 mnt_drop_write_file(file);
1779 static noinline int btrfs_ioctl_snap_create(struct file *file,
1780 void __user *arg, int subvol)
1782 struct btrfs_ioctl_vol_args *vol_args;
1785 if (!S_ISDIR(file_inode(file)->i_mode))
1788 vol_args = memdup_user(arg, sizeof(*vol_args));
1789 if (IS_ERR(vol_args))
1790 return PTR_ERR(vol_args);
1791 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1793 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1794 vol_args->fd, subvol,
1801 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1802 void __user *arg, int subvol)
1804 struct btrfs_ioctl_vol_args_v2 *vol_args;
1808 bool readonly = false;
1809 struct btrfs_qgroup_inherit *inherit = NULL;
1811 if (!S_ISDIR(file_inode(file)->i_mode))
1814 vol_args = memdup_user(arg, sizeof(*vol_args));
1815 if (IS_ERR(vol_args))
1816 return PTR_ERR(vol_args);
1817 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1819 if (vol_args->flags &
1820 ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1821 BTRFS_SUBVOL_QGROUP_INHERIT)) {
1826 if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1828 if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1830 if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1831 if (vol_args->size > PAGE_SIZE) {
1835 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1836 if (IS_ERR(inherit)) {
1837 ret = PTR_ERR(inherit);
1842 ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1843 vol_args->fd, subvol, ptr,
1848 if (ptr && copy_to_user(arg +
1849 offsetof(struct btrfs_ioctl_vol_args_v2,
1861 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1864 struct inode *inode = file_inode(file);
1865 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1866 struct btrfs_root *root = BTRFS_I(inode)->root;
1870 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1873 down_read(&fs_info->subvol_sem);
1874 if (btrfs_root_readonly(root))
1875 flags |= BTRFS_SUBVOL_RDONLY;
1876 up_read(&fs_info->subvol_sem);
1878 if (copy_to_user(arg, &flags, sizeof(flags)))
1884 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1887 struct inode *inode = file_inode(file);
1888 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1889 struct btrfs_root *root = BTRFS_I(inode)->root;
1890 struct btrfs_trans_handle *trans;
1895 if (!inode_owner_or_capable(inode))
1898 ret = mnt_want_write_file(file);
1902 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1904 goto out_drop_write;
1907 if (copy_from_user(&flags, arg, sizeof(flags))) {
1909 goto out_drop_write;
1912 if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1914 goto out_drop_write;
1917 if (flags & ~BTRFS_SUBVOL_RDONLY) {
1919 goto out_drop_write;
1922 down_write(&fs_info->subvol_sem);
1925 if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1928 root_flags = btrfs_root_flags(&root->root_item);
1929 if (flags & BTRFS_SUBVOL_RDONLY) {
1930 btrfs_set_root_flags(&root->root_item,
1931 root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1934 * Block RO -> RW transition if this subvolume is involved in
1937 spin_lock(&root->root_item_lock);
1938 if (root->send_in_progress == 0) {
1939 btrfs_set_root_flags(&root->root_item,
1940 root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1941 spin_unlock(&root->root_item_lock);
1943 spin_unlock(&root->root_item_lock);
1945 "Attempt to set subvolume %llu read-write during send",
1946 root->root_key.objectid);
1952 trans = btrfs_start_transaction(root, 1);
1953 if (IS_ERR(trans)) {
1954 ret = PTR_ERR(trans);
1958 ret = btrfs_update_root(trans, fs_info->tree_root,
1959 &root->root_key, &root->root_item);
1961 btrfs_end_transaction(trans);
1965 ret = btrfs_commit_transaction(trans);
1969 btrfs_set_root_flags(&root->root_item, root_flags);
1971 up_write(&fs_info->subvol_sem);
1973 mnt_drop_write_file(file);
1978 static noinline int key_in_sk(struct btrfs_key *key,
1979 struct btrfs_ioctl_search_key *sk)
1981 struct btrfs_key test;
1984 test.objectid = sk->min_objectid;
1985 test.type = sk->min_type;
1986 test.offset = sk->min_offset;
1988 ret = btrfs_comp_cpu_keys(key, &test);
1992 test.objectid = sk->max_objectid;
1993 test.type = sk->max_type;
1994 test.offset = sk->max_offset;
1996 ret = btrfs_comp_cpu_keys(key, &test);
2002 static noinline int copy_to_sk(struct btrfs_path *path,
2003 struct btrfs_key *key,
2004 struct btrfs_ioctl_search_key *sk,
2007 unsigned long *sk_offset,
2011 struct extent_buffer *leaf;
2012 struct btrfs_ioctl_search_header sh;
2013 struct btrfs_key test;
2014 unsigned long item_off;
2015 unsigned long item_len;
2021 leaf = path->nodes[0];
2022 slot = path->slots[0];
2023 nritems = btrfs_header_nritems(leaf);
2025 if (btrfs_header_generation(leaf) > sk->max_transid) {
2029 found_transid = btrfs_header_generation(leaf);
2031 for (i = slot; i < nritems; i++) {
2032 item_off = btrfs_item_ptr_offset(leaf, i);
2033 item_len = btrfs_item_size_nr(leaf, i);
2035 btrfs_item_key_to_cpu(leaf, key, i);
2036 if (!key_in_sk(key, sk))
2039 if (sizeof(sh) + item_len > *buf_size) {
2046 * return one empty item back for v1, which does not
2050 *buf_size = sizeof(sh) + item_len;
2055 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2060 sh.objectid = key->objectid;
2061 sh.offset = key->offset;
2062 sh.type = key->type;
2064 sh.transid = found_transid;
2066 /* copy search result header */
2067 if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2072 *sk_offset += sizeof(sh);
2075 char __user *up = ubuf + *sk_offset;
2077 if (read_extent_buffer_to_user(leaf, up,
2078 item_off, item_len)) {
2083 *sk_offset += item_len;
2087 if (ret) /* -EOVERFLOW from above */
2090 if (*num_found >= sk->nr_items) {
2097 test.objectid = sk->max_objectid;
2098 test.type = sk->max_type;
2099 test.offset = sk->max_offset;
2100 if (btrfs_comp_cpu_keys(key, &test) >= 0)
2102 else if (key->offset < (u64)-1)
2104 else if (key->type < (u8)-1) {
2107 } else if (key->objectid < (u64)-1) {
2115 * 0: all items from this leaf copied, continue with next
2116 * 1: * more items can be copied, but unused buffer is too small
2117 * * all items were found
2118 * Either way, it will stops the loop which iterates to the next
2120 * -EOVERFLOW: item was to large for buffer
2121 * -EFAULT: could not copy extent buffer back to userspace
2126 static noinline int search_ioctl(struct inode *inode,
2127 struct btrfs_ioctl_search_key *sk,
2131 struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2132 struct btrfs_root *root;
2133 struct btrfs_key key;
2134 struct btrfs_path *path;
2137 unsigned long sk_offset = 0;
2139 if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2140 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2144 path = btrfs_alloc_path();
2148 if (sk->tree_id == 0) {
2149 /* search the root of the inode that was passed */
2150 root = BTRFS_I(inode)->root;
2152 key.objectid = sk->tree_id;
2153 key.type = BTRFS_ROOT_ITEM_KEY;
2154 key.offset = (u64)-1;
2155 root = btrfs_read_fs_root_no_name(info, &key);
2157 btrfs_free_path(path);
2162 key.objectid = sk->min_objectid;
2163 key.type = sk->min_type;
2164 key.offset = sk->min_offset;
2167 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2173 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2174 &sk_offset, &num_found);
2175 btrfs_release_path(path);
2183 sk->nr_items = num_found;
2184 btrfs_free_path(path);
2188 static noinline int btrfs_ioctl_tree_search(struct file *file,
2191 struct btrfs_ioctl_search_args __user *uargs;
2192 struct btrfs_ioctl_search_key sk;
2193 struct inode *inode;
2197 if (!capable(CAP_SYS_ADMIN))
2200 uargs = (struct btrfs_ioctl_search_args __user *)argp;
2202 if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2205 buf_size = sizeof(uargs->buf);
2207 inode = file_inode(file);
2208 ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2211 * In the origin implementation an overflow is handled by returning a
2212 * search header with a len of zero, so reset ret.
2214 if (ret == -EOVERFLOW)
2217 if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2222 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2225 struct btrfs_ioctl_search_args_v2 __user *uarg;
2226 struct btrfs_ioctl_search_args_v2 args;
2227 struct inode *inode;
2230 const size_t buf_limit = SZ_16M;
2232 if (!capable(CAP_SYS_ADMIN))
2235 /* copy search header and buffer size */
2236 uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2237 if (copy_from_user(&args, uarg, sizeof(args)))
2240 buf_size = args.buf_size;
2242 /* limit result size to 16MB */
2243 if (buf_size > buf_limit)
2244 buf_size = buf_limit;
2246 inode = file_inode(file);
2247 ret = search_ioctl(inode, &args.key, &buf_size,
2248 (char __user *)(&uarg->buf[0]));
2249 if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2251 else if (ret == -EOVERFLOW &&
2252 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2259 * Search INODE_REFs to identify path name of 'dirid' directory
2260 * in a 'tree_id' tree. and sets path name to 'name'.
2262 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2263 u64 tree_id, u64 dirid, char *name)
2265 struct btrfs_root *root;
2266 struct btrfs_key key;
2272 struct btrfs_inode_ref *iref;
2273 struct extent_buffer *l;
2274 struct btrfs_path *path;
2276 if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2281 path = btrfs_alloc_path();
2285 ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2287 key.objectid = tree_id;
2288 key.type = BTRFS_ROOT_ITEM_KEY;
2289 key.offset = (u64)-1;
2290 root = btrfs_read_fs_root_no_name(info, &key);
2292 btrfs_err(info, "could not find root %llu", tree_id);
2297 key.objectid = dirid;
2298 key.type = BTRFS_INODE_REF_KEY;
2299 key.offset = (u64)-1;
2302 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2306 ret = btrfs_previous_item(root, path, dirid,
2307 BTRFS_INODE_REF_KEY);
2317 slot = path->slots[0];
2318 btrfs_item_key_to_cpu(l, &key, slot);
2320 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2321 len = btrfs_inode_ref_name_len(l, iref);
2323 total_len += len + 1;
2325 ret = -ENAMETOOLONG;
2330 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2332 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2335 btrfs_release_path(path);
2336 key.objectid = key.offset;
2337 key.offset = (u64)-1;
2338 dirid = key.objectid;
2340 memmove(name, ptr, total_len);
2341 name[total_len] = '\0';
2344 btrfs_free_path(path);
2348 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2351 struct btrfs_ioctl_ino_lookup_args *args;
2352 struct inode *inode;
2355 args = memdup_user(argp, sizeof(*args));
2357 return PTR_ERR(args);
2359 inode = file_inode(file);
2362 * Unprivileged query to obtain the containing subvolume root id. The
2363 * path is reset so it's consistent with btrfs_search_path_in_tree.
2365 if (args->treeid == 0)
2366 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2368 if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2373 if (!capable(CAP_SYS_ADMIN)) {
2378 ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2379 args->treeid, args->objectid,
2383 if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2390 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2393 struct dentry *parent = file->f_path.dentry;
2394 struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2395 struct dentry *dentry;
2396 struct inode *dir = d_inode(parent);
2397 struct inode *inode;
2398 struct btrfs_root *root = BTRFS_I(dir)->root;
2399 struct btrfs_root *dest = NULL;
2400 struct btrfs_ioctl_vol_args *vol_args;
2404 if (!S_ISDIR(dir->i_mode))
2407 vol_args = memdup_user(arg, sizeof(*vol_args));
2408 if (IS_ERR(vol_args))
2409 return PTR_ERR(vol_args);
2411 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2412 namelen = strlen(vol_args->name);
2413 if (strchr(vol_args->name, '/') ||
2414 strncmp(vol_args->name, "..", namelen) == 0) {
2419 err = mnt_want_write_file(file);
2424 err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
2426 goto out_drop_write;
2427 dentry = lookup_one_len(vol_args->name, parent, namelen);
2428 if (IS_ERR(dentry)) {
2429 err = PTR_ERR(dentry);
2430 goto out_unlock_dir;
2433 if (d_really_is_negative(dentry)) {
2438 inode = d_inode(dentry);
2439 dest = BTRFS_I(inode)->root;
2440 if (!capable(CAP_SYS_ADMIN)) {
2442 * Regular user. Only allow this with a special mount
2443 * option, when the user has write+exec access to the
2444 * subvol root, and when rmdir(2) would have been
2447 * Note that this is _not_ check that the subvol is
2448 * empty or doesn't contain data that we wouldn't
2449 * otherwise be able to delete.
2451 * Users who want to delete empty subvols should try
2455 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
2459 * Do not allow deletion if the parent dir is the same
2460 * as the dir to be deleted. That means the ioctl
2461 * must be called on the dentry referencing the root
2462 * of the subvol, not a random directory contained
2469 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2474 /* check if subvolume may be deleted by a user */
2475 err = btrfs_may_delete(dir, dentry, 1);
2479 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2485 err = btrfs_delete_subvolume(dir, dentry);
2486 inode_unlock(inode);
2495 mnt_drop_write_file(file);
2501 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2503 struct inode *inode = file_inode(file);
2504 struct btrfs_root *root = BTRFS_I(inode)->root;
2505 struct btrfs_ioctl_defrag_range_args *range;
2508 ret = mnt_want_write_file(file);
2512 if (btrfs_root_readonly(root)) {
2517 switch (inode->i_mode & S_IFMT) {
2519 if (!capable(CAP_SYS_ADMIN)) {
2523 ret = btrfs_defrag_root(root);
2526 if (!(file->f_mode & FMODE_WRITE)) {
2531 range = kzalloc(sizeof(*range), GFP_KERNEL);
2538 if (copy_from_user(range, argp,
2544 /* compression requires us to start the IO */
2545 if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2546 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2547 range->extent_thresh = (u32)-1;
2550 /* the rest are all set to zero by kzalloc */
2551 range->len = (u64)-1;
2553 ret = btrfs_defrag_file(file_inode(file), file,
2554 range, BTRFS_OLDEST_GENERATION, 0);
2563 mnt_drop_write_file(file);
2567 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
2569 struct btrfs_ioctl_vol_args *vol_args;
2572 if (!capable(CAP_SYS_ADMIN))
2575 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
2576 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2578 vol_args = memdup_user(arg, sizeof(*vol_args));
2579 if (IS_ERR(vol_args)) {
2580 ret = PTR_ERR(vol_args);
2584 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2585 ret = btrfs_init_new_device(fs_info, vol_args->name);
2588 btrfs_info(fs_info, "disk added %s", vol_args->name);
2592 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2596 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
2598 struct inode *inode = file_inode(file);
2599 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2600 struct btrfs_ioctl_vol_args_v2 *vol_args;
2603 if (!capable(CAP_SYS_ADMIN))
2606 ret = mnt_want_write_file(file);
2610 vol_args = memdup_user(arg, sizeof(*vol_args));
2611 if (IS_ERR(vol_args)) {
2612 ret = PTR_ERR(vol_args);
2616 /* Check for compatibility reject unknown flags */
2617 if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED)
2620 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2621 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2625 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
2626 ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
2628 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
2629 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
2631 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2634 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
2635 btrfs_info(fs_info, "device deleted: id %llu",
2638 btrfs_info(fs_info, "device deleted: %s",
2644 mnt_drop_write_file(file);
2648 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2650 struct inode *inode = file_inode(file);
2651 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2652 struct btrfs_ioctl_vol_args *vol_args;
2655 if (!capable(CAP_SYS_ADMIN))
2658 ret = mnt_want_write_file(file);
2662 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
2663 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2664 goto out_drop_write;
2667 vol_args = memdup_user(arg, sizeof(*vol_args));
2668 if (IS_ERR(vol_args)) {
2669 ret = PTR_ERR(vol_args);
2673 vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2674 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
2677 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
2680 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
2682 mnt_drop_write_file(file);
2687 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
2690 struct btrfs_ioctl_fs_info_args *fi_args;
2691 struct btrfs_device *device;
2692 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2695 fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2700 fi_args->num_devices = fs_devices->num_devices;
2702 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2703 if (device->devid > fi_args->max_id)
2704 fi_args->max_id = device->devid;
2708 memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
2709 fi_args->nodesize = fs_info->nodesize;
2710 fi_args->sectorsize = fs_info->sectorsize;
2711 fi_args->clone_alignment = fs_info->sectorsize;
2713 if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2720 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
2723 struct btrfs_ioctl_dev_info_args *di_args;
2724 struct btrfs_device *dev;
2726 char *s_uuid = NULL;
2728 di_args = memdup_user(arg, sizeof(*di_args));
2729 if (IS_ERR(di_args))
2730 return PTR_ERR(di_args);
2732 if (!btrfs_is_empty_uuid(di_args->uuid))
2733 s_uuid = di_args->uuid;
2736 dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
2743 di_args->devid = dev->devid;
2744 di_args->bytes_used = btrfs_device_get_bytes_used(dev);
2745 di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2746 memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2748 struct rcu_string *name;
2750 name = rcu_dereference(dev->name);
2751 strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
2752 di_args->path[sizeof(di_args->path) - 1] = 0;
2754 di_args->path[0] = '\0';
2759 if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2766 static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2770 page = grab_cache_page(inode->i_mapping, index);
2772 return ERR_PTR(-ENOMEM);
2774 if (!PageUptodate(page)) {
2777 ret = btrfs_readpage(NULL, page);
2779 return ERR_PTR(ret);
2781 if (!PageUptodate(page)) {
2784 return ERR_PTR(-EIO);
2786 if (page->mapping != inode->i_mapping) {
2789 return ERR_PTR(-EAGAIN);
2796 static int gather_extent_pages(struct inode *inode, struct page **pages,
2797 int num_pages, u64 off)
2800 pgoff_t index = off >> PAGE_SHIFT;
2802 for (i = 0; i < num_pages; i++) {
2804 pages[i] = extent_same_get_page(inode, index + i);
2805 if (IS_ERR(pages[i])) {
2806 int err = PTR_ERR(pages[i]);
2817 static int lock_extent_range(struct inode *inode, u64 off, u64 len,
2818 bool retry_range_locking)
2821 * Do any pending delalloc/csum calculations on inode, one way or
2822 * another, and lock file content.
2823 * The locking order is:
2826 * 2) range in the inode's io tree
2829 struct btrfs_ordered_extent *ordered;
2830 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2831 ordered = btrfs_lookup_first_ordered_extent(inode,
2834 ordered->file_offset + ordered->len <= off ||
2835 ordered->file_offset >= off + len) &&
2836 !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2837 off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2839 btrfs_put_ordered_extent(ordered);
2842 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2844 btrfs_put_ordered_extent(ordered);
2845 if (!retry_range_locking)
2847 btrfs_wait_ordered_range(inode, off, len);
2852 static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2854 inode_unlock(inode1);
2855 inode_unlock(inode2);
2858 static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2860 if (inode1 < inode2)
2861 swap(inode1, inode2);
2863 inode_lock_nested(inode1, I_MUTEX_PARENT);
2864 inode_lock_nested(inode2, I_MUTEX_CHILD);
2867 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2868 struct inode *inode2, u64 loff2, u64 len)
2870 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2871 unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2874 static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2875 struct inode *inode2, u64 loff2, u64 len,
2876 bool retry_range_locking)
2880 if (inode1 < inode2) {
2881 swap(inode1, inode2);
2884 ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
2887 ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
2889 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
2896 struct page **src_pages;
2897 struct page **dst_pages;
2900 static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2905 for (i = 0; i < cmp->num_pages; i++) {
2906 pg = cmp->src_pages[i];
2911 pg = cmp->dst_pages[i];
2917 kfree(cmp->src_pages);
2918 kfree(cmp->dst_pages);
2921 static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2922 struct inode *dst, u64 dst_loff,
2923 u64 len, struct cmp_pages *cmp)
2926 int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
2927 struct page **src_pgarr, **dst_pgarr;
2930 * We must gather up all the pages before we initiate our
2931 * extent locking. We use an array for the page pointers. Size
2932 * of the array is bounded by len, which is in turn bounded by
2933 * BTRFS_MAX_DEDUPE_LEN.
2935 src_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
2936 dst_pgarr = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
2937 if (!src_pgarr || !dst_pgarr) {
2942 cmp->num_pages = num_pages;
2943 cmp->src_pages = src_pgarr;
2944 cmp->dst_pages = dst_pgarr;
2947 * If deduping ranges in the same inode, locking rules make it mandatory
2948 * to always lock pages in ascending order to avoid deadlocks with
2949 * concurrent tasks (such as starting writeback/delalloc).
2951 if (src == dst && dst_loff < loff) {
2952 swap(src_pgarr, dst_pgarr);
2953 swap(loff, dst_loff);
2956 ret = gather_extent_pages(src, src_pgarr, cmp->num_pages, loff);
2960 ret = gather_extent_pages(dst, dst_pgarr, cmp->num_pages, dst_loff);
2964 btrfs_cmp_data_free(cmp);
2968 static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
2972 struct page *src_page, *dst_page;
2973 unsigned int cmp_len = PAGE_SIZE;
2974 void *addr, *dst_addr;
2978 if (len < PAGE_SIZE)
2981 BUG_ON(i >= cmp->num_pages);
2983 src_page = cmp->src_pages[i];
2984 dst_page = cmp->dst_pages[i];
2985 ASSERT(PageLocked(src_page));
2986 ASSERT(PageLocked(dst_page));
2988 addr = kmap_atomic(src_page);
2989 dst_addr = kmap_atomic(dst_page);
2991 flush_dcache_page(src_page);
2992 flush_dcache_page(dst_page);
2994 if (memcmp(addr, dst_addr, cmp_len))
2997 kunmap_atomic(addr);
2998 kunmap_atomic(dst_addr);
3010 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3014 u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3016 if (off + olen > inode->i_size || off + olen < off)
3019 /* if we extend to eof, continue to block boundary */
3020 if (off + len == inode->i_size)
3021 *plen = len = ALIGN(inode->i_size, bs) - off;
3023 /* Check that we are block aligned - btrfs_clone() requires this */
3024 if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3030 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3031 struct inode *dst, u64 dst_loff)
3035 struct cmp_pages cmp;
3036 bool same_inode = (src == dst);
3037 u64 same_lock_start = 0;
3038 u64 same_lock_len = 0;
3046 btrfs_double_inode_lock(src, dst);
3048 ret = extent_same_check_offsets(src, loff, &len, olen);
3052 ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3058 * Single inode case wants the same checks, except we
3059 * don't want our length pushed out past i_size as
3060 * comparing that data range makes no sense.
3062 * extent_same_check_offsets() will do this for an
3063 * unaligned length at i_size, so catch it here and
3064 * reject the request.
3066 * This effectively means we require aligned extents
3067 * for the single-inode case, whereas the other cases
3068 * allow an unaligned length so long as it ends at
3076 /* Check for overlapping ranges */
3077 if (dst_loff + len > loff && dst_loff < loff + len) {
3082 same_lock_start = min_t(u64, loff, dst_loff);
3083 same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
3086 /* don't make the dst file partly checksummed */
3087 if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3088 (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3094 ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3099 ret = lock_extent_range(src, same_lock_start, same_lock_len,
3102 ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3105 * If one of the inodes has dirty pages in the respective range or
3106 * ordered extents, we need to flush dellaloc and wait for all ordered
3107 * extents in the range. We must unlock the pages and the ranges in the
3108 * io trees to avoid deadlocks when flushing delalloc (requires locking
3109 * pages) and when waiting for ordered extents to complete (they require
3112 if (ret == -EAGAIN) {
3114 * Ranges in the io trees already unlocked. Now unlock all
3115 * pages before waiting for all IO to complete.
3117 btrfs_cmp_data_free(&cmp);
3119 btrfs_wait_ordered_range(src, same_lock_start,
3122 btrfs_wait_ordered_range(src, loff, len);
3123 btrfs_wait_ordered_range(dst, dst_loff, len);
3129 /* ranges in the io trees already unlocked */
3130 btrfs_cmp_data_free(&cmp);
3134 /* pass original length for comparison so we stay within i_size */
3135 ret = btrfs_cmp_data(olen, &cmp);
3137 ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3140 unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
3141 same_lock_start + same_lock_len - 1);
3143 btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3145 btrfs_cmp_data_free(&cmp);
3150 btrfs_double_inode_unlock(src, dst);
3155 #define BTRFS_MAX_DEDUPE_LEN SZ_16M
3157 ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
3158 struct file *dst_file, u64 dst_loff)
3160 struct inode *src = file_inode(src_file);
3161 struct inode *dst = file_inode(dst_file);
3162 u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3165 if (olen > BTRFS_MAX_DEDUPE_LEN)
3166 olen = BTRFS_MAX_DEDUPE_LEN;
3168 if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3170 * Btrfs does not support blocksize < page_size. As a
3171 * result, btrfs_cmp_data() won't correctly handle
3172 * this situation without an update.
3177 res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
3183 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3184 struct inode *inode,
3190 struct btrfs_root *root = BTRFS_I(inode)->root;
3193 inode_inc_iversion(inode);
3194 if (!no_time_update)
3195 inode->i_mtime = inode->i_ctime = current_time(inode);
3197 * We round up to the block size at eof when determining which
3198 * extents to clone above, but shouldn't round up the file size.
3200 if (endoff > destoff + olen)
3201 endoff = destoff + olen;
3202 if (endoff > inode->i_size)
3203 btrfs_i_size_write(BTRFS_I(inode), endoff);
3205 ret = btrfs_update_inode(trans, root, inode);
3207 btrfs_abort_transaction(trans, ret);
3208 btrfs_end_transaction(trans);
3211 ret = btrfs_end_transaction(trans);
3216 static void clone_update_extent_map(struct btrfs_inode *inode,
3217 const struct btrfs_trans_handle *trans,
3218 const struct btrfs_path *path,
3219 const u64 hole_offset,
3222 struct extent_map_tree *em_tree = &inode->extent_tree;
3223 struct extent_map *em;
3226 em = alloc_extent_map();
3228 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3233 struct btrfs_file_extent_item *fi;
3235 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
3236 struct btrfs_file_extent_item);
3237 btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
3238 em->generation = -1;
3239 if (btrfs_file_extent_type(path->nodes[0], fi) ==
3240 BTRFS_FILE_EXTENT_INLINE)
3241 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3242 &inode->runtime_flags);
3244 em->start = hole_offset;
3246 em->ram_bytes = em->len;
3247 em->orig_start = hole_offset;
3248 em->block_start = EXTENT_MAP_HOLE;
3250 em->orig_block_len = 0;
3251 em->compress_type = BTRFS_COMPRESS_NONE;
3252 em->generation = trans->transid;
3256 write_lock(&em_tree->lock);
3257 ret = add_extent_mapping(em_tree, em, 1);
3258 write_unlock(&em_tree->lock);
3259 if (ret != -EEXIST) {
3260 free_extent_map(em);
3263 btrfs_drop_extent_cache(inode, em->start,
3264 em->start + em->len - 1, 0);
3268 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3272 * Make sure we do not end up inserting an inline extent into a file that has
3273 * already other (non-inline) extents. If a file has an inline extent it can